fix(goal): make cancellation a user-only control (#6667)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-14 23:48:13 +08:00
1 parent c927808aff
commit 12a86eaa86
33 files changed
+641 -63

No files matched your search

+8 -3
View File
@@ -52,7 +52,7 @@ import { AttachmentLayoutFixture } from "./attachment-layout-fixture";
import { LoadedSessionSearchFixture } from "./loaded-session-search-fixture";
import { AppearanceFixture } from "./appearance-fixture";
import { ContinuityFixture } from "./continuity-fixture";
import { SessionTransitionFixture } from "./session-transition-fixture";
import { installSessionTransitionPreviewApi, SessionTransitionFixture } from "./session-transition-fixture";
import { installSubagentDockApi, SubagentDockFixture } from "./subagent-dock-fixture";
const history: UIMessage[] = [
@@ -236,13 +236,18 @@ if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi()
if (parameters.get("case") === "tools-catalog") installToolsCatalogPreviewApi();
if (parameters.get("case") === "idle-compaction") installIdleCompactionApi();
if (parameters.get("case") === "subagent-dock") installSubagentDockApi();
if (parameters.get("case") === "session-transition" && parameters.has("preview")) installSessionTransitionPreviewApi();
await initializeI18n();
if (parameters.get("case") === "activity-wheel") await setAppLanguage("zh-CN");
if ((parameters.get("case") === "appearance" || historyPreview) && parameters.has("lang")) {
if ((["appearance", "session-transition"].includes(parameters.get("case") ?? "") || historyPreview) && parameters.has("lang")) {
await setAppLanguage(normalizeLocale(parameters.get("lang")));
}
const widePreview = new URL(location.href);
widePreview.searchParams.delete("narrow");
createRoot(document.getElementById("root")!).render(<TooltipProvider>
{parameters.get("case") === "session-transition"
{parameters.get("case") === "session-transition" && parameters.has("narrow")
? <iframe title="Narrow goal preview" src={widePreview.href} style={{ display: "block", margin: "0 auto", height: "100dvh", width: "100%", maxWidth: 390, border: 0 }} />
: parameters.get("case") === "session-transition"
? <SessionTransitionFixture />
: parameters.get("case") === "continuity"
? <ContinuityFixture />
+61 -9
View File
@@ -9,22 +9,65 @@ import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { ClientProvider } from "@/providers/ClientProvider";
import { createStreamClient } from "@/tests/stream-client";
const { client, receive } = createStreamClient();
const goalSummary = new URLSearchParams(location.search).has("long-goal")
? "完成会话切换和目标状态界面的优化,统一明暗主题下的布局、文字、图标与交互,验证桌面和窄屏体验后提交代码并更新发布说明"
: "Keep the composer stable";
for (const topic of ["goal", "together", "blocked"]) {
receive({ event: "goal_state", chat_id: topic, goal_state: {
active: topic !== "blocked", status: topic === "blocked" ? "blocked" : "active",
ui_summary: goalSummary,
objective: "Verify session navigation with real components.\n\n" + "- Preserve drafts, reading position and usable header controls.\n".repeat(6),
...(topic === "blocked" ? { recap: "Waiting for a workspace permission decision." } : {}),
} });
export function installSessionTransitionPreviewApi() {
const original = window.fetch.bind(window);
window.fetch = async (input, init) => {
const url = new URL(input instanceof Request ? input.url : String(input), location.href);
if (url.origin !== location.origin || !url.pathname.startsWith("/api/")) return original(input, init);
if (url.pathname === "/api/commands") return Response.json({ commands: [
{ command: "/cancel_goal", title: "Cancel goal", description: "Cancel the goal", icon: "square", lifecycle: "side_channel", accepts_args: false },
] });
if (url.pathname.endsWith("/subagents")) return Response.json({ tasks: [] });
if (url.pathname.endsWith("/webui-thread")) {
const topic = decodeURIComponent(url.pathname.split("/")[3]).split(":")[1];
return Response.json({ schemaVersion: 3, projection: "events", events: [
{ event: "user_message", chat_id: topic, projection_id: `${topic}-prompt`, turn_id: "fixture-turn", starts_turn: true, text: `Question for ${topic}` },
{ event: "message", chat_id: topic, projection_id: `${topic}-answer`, turn_id: "fixture-turn", text: `Answer for ${topic}\n\n` + "A long conversation stays at its reading position.\n\n".repeat(25) },
] });
}
return Response.json({}, { status: 404 });
};
}
export function SessionTransitionFixture() {
const [pendingCancel, setPendingCancel] = useState<{ chat_id: string; turn_id: string } | null>(null);
const [{ client, receive, socket }] = useState(() => {
const preview = createStreamClient((data) => {
const frame = JSON.parse(data);
if (frame.content === "/cancel_goal") setPendingCancel({ chat_id: frame.chat_id, turn_id: frame.turn_id });
});
for (const topic of ["goal", "together", "blocked"]) {
preview.receive({ event: "goal_state", chat_id: topic, goal_state: {
active: topic !== "blocked", status: topic === "blocked" ? "blocked" : "active",
ui_summary: goalSummary,
objective: "Verify session navigation with real components.\n\n" + "- Preserve drafts, reading position and usable header controls.\n".repeat(6),
...(topic === "blocked" ? { recap: "Waiting for a workspace permission decision." } : {}),
} });
}
if (new URLSearchParams(location.search).has("preview")) {
const send = preview.client.sendSystemCommand.bind(preview.client);
preview.client.sendSystemCommand = (chatId, command) => send(chatId, command, 600_000);
}
return preview;
});
const [online, setOnline] = useState(true);
const cancelPreview = new URLSearchParams(location.search).has("cancel-goal");
const finishCancel = (success: boolean) => {
if (!pendingCancel) return;
if (success) {
if (client.getGoalState(pendingCancel.chat_id)?.active) {
receive({ event: "turn_end", chat_id: pendingCancel.chat_id, turn_id: "live-turn" });
}
receive({ event: "goal_state", chat_id: pendingCancel.chat_id, goal_state: { active: false } });
}
receive({ event: "message", ...pendingCancel, text: success ? "Goal cancelled." : "Could not save goal cancellation." });
setPendingCancel(null);
};
const workbench = new URLSearchParams(location.search).has("workbench");
const [topic, setTopic] = useState(workbench ? "goal" : "plain");
const [topic, setTopic] = useState(new URLSearchParams(location.search).get("topic") ?? (workbench ? "goal" : "plain"));
const [cache] = useState(() => new ThreadMessageCache(() => false));
const [drafts] = useState(() => new ComposerDraftStore());
const dark = new URLSearchParams(location.search).has("dark");
@@ -41,6 +84,15 @@ export function SessionTransitionFixture() {
receive({ event: "goal_status", chat_id: topic, turn_id: "live-turn", status: "running", started_at: Date.now() / 1000 });
receive({ event: "delta", chat_id: topic, turn_id: "live-turn", stream_id: "live", text: "Live reply continues" });
}}>Stream reply</button>
{cancelPreview ? <>
<button disabled={!pendingCancel} onClick={() => finishCancel(true)}>Confirm cancellation</button>
<button disabled={!pendingCancel} onClick={() => finishCancel(false)}>Fail cancellation</button>
<button onClick={() => {
if (online) client.close();
else { client.connect(); socket.onopen?.(); }
setOnline(!online);
}}>{online ? "Disconnect" : "Reconnect"}</button>
</> : null}
</nav>
{workbench ? <PaneWorkbench
panes={["goal", "blocked"].map(key => ({ key, title: key }))} activePaneKey={topic} layout="columns"
+26
View File
@@ -67,6 +67,32 @@ test("blocked goal remains visible until cleared and survives session switching"
await expect(page.locator(".goal-island")).toHaveCount(0);
});
for (const { width, topic } of [{ width: 1440, topic: "goal" }, { width: 390, topic: "blocked" }]) {
test(`goal cancellation is reachable at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 844 });
await installPreview(page);
await page.goto("/browser/fixture.html?case=session-transition&cancel-goal");
await select(page, topic);
await page.getByRole("textbox").fill("Keep this draft");
await page.getByRole("button", { name: "Show full goal" }).click();
const dialog = page.getByRole("dialog", { name: "Goal", exact: true });
await dialog.evaluate(async el => { await Promise.all(el.getAnimations({ subtree: true }).map(animation => animation.finished)); });
const cancel = dialog.getByRole("button", { name: "Cancel goal", exact: true });
const panelBounds = await dialog.boundingBox();
const buttonBounds = await cancel.boundingBox();
expect(buttonBounds!.y).toBeGreaterThanOrEqual(panelBounds!.y);
expect(buttonBounds!.y + buttonBounds!.height).toBeLessThanOrEqual(panelBounds!.y + panelBounds!.height);
await cancel.focus();
await page.keyboard.press("Enter");
const confirm = page.getByRole("button", { name: "Confirm cancellation", exact: true });
await expect(confirm).toBeEnabled();
await confirm.click();
await expect(page.locator(".goal-island")).toHaveCount(0);
await expect(page.getByRole("textbox")).toHaveValue("Keep this draft");
expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
});
}
for (const viewport of [{ width: 390, height: 844 }, { width: 844, height: 390 }]) {
test(`long goal summaries leave the objective readable at ${viewport.width}x${viewport.height}`, async ({ page }) => {
await page.setViewportSize(viewport);
+37 -5
View File
@@ -3,15 +3,22 @@ import { useLayoutEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { MarkdownText, preloadMarkdownText } from "@/components/MarkdownText";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useOverlayEscapeFocus } from "@/hooks/useOverlayEscapeFocus";
import type { GoalStateWsPayload } from "@/lib/types";
import "./goal-island.css";
export function GoalIsland({ goal }: { goal: GoalStateWsPayload }) {
export function GoalIsland({ goal, cancelDisabled, onCancel }: {
goal: GoalStateWsPayload;
cancelDisabled: boolean;
onCancel: () => Promise<void>;
}) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const [cancelling, setCancelling] = useState(false);
const [cancelFailed, setCancelFailed] = useState(false);
const [scrollBody, setScrollBody] = useState<HTMLDivElement | null>(null);
const panelRef = useRef<HTMLDivElement>(null);
const escapeFocus = useOverlayEscapeFocus();
@@ -36,10 +43,30 @@ export function GoalIsland({ goal }: { goal: GoalStateWsPayload }) {
const status = goal.status === "blocked" ? "blocked" : "active";
const recap = goal.recap?.trim() ?? "";
const collapsedLabel = status === "blocked" ? recap : label;
const cancelButton = <Button
type="button"
variant="ghost"
size="sm"
className="ml-auto h-7 shrink-0 px-2 text-caption text-muted-foreground"
disabled={cancelDisabled || cancelling}
aria-busy={cancelling}
title={cancelDisabled ? t("thread.composer.cancelGoalOffline") : undefined}
onClick={async () => {
setCancelling(true);
setCancelFailed(false);
try {
await onCancel();
} catch {
setCancelFailed(true);
} finally {
setCancelling(false);
}
}}
>{t("thread.composer.cancelGoal")}</Button>;
useLayoutEffect(() => {
if (!scrollBody) return;
if (status === "blocked") scrollBody.scrollTop = 0;
if (status === "blocked" || cancelFailed) scrollBody.scrollTop = 0;
const measure = () => {
scrollBody.toggleAttribute("data-overflow-top", scrollBody.scrollTop > 1);
scrollBody.toggleAttribute("data-overflow-bottom", scrollBody.scrollHeight - scrollBody.clientHeight - scrollBody.scrollTop > 1);
@@ -53,7 +80,7 @@ export function GoalIsland({ goal }: { goal: GoalStateWsPayload }) {
observer.disconnect();
scrollBody.removeEventListener("scroll", measure);
};
}, [scrollBody, status]);
}, [scrollBody, status, cancelFailed]);
return (
<div className="goal-island-position">
@@ -87,13 +114,18 @@ export function GoalIsland({ goal }: { goal: GoalStateWsPayload }) {
>
<div className="goal-island-surface" aria-hidden />
<div className="goal-island-panel-content">
{status !== "blocked" && summary ? <div className="goal-island-summary markdown-content"><h2>{summary}</h2></div> : null}
{status !== "blocked" ? <div className="goal-island-summary flex items-start gap-3">
{summary ? <div className="markdown-content min-w-0 flex-1"><h2>{summary}</h2></div> : null}
{cancelButton}
</div> : null}
<div ref={setScrollBody} className="goal-island-body">
<div className="goal-island-document">
{cancelFailed ? <p role="alert" className="mb-2 text-caption text-destructive">{t("thread.composer.cancelGoalFailed")}</p> : null}
{status === "blocked" ? <div className="goal-island-blocked">
<CircleAlert className="goal-island-status-icon" strokeWidth={2.5} aria-hidden="true" />
<span className="sr-only">{t("thread.composer.goalBlocked")}</span>
{recap ? <MarkdownText className="goal-island-reason">{recap}</MarkdownText> : null}
{recap ? <MarkdownText className="goal-island-reason flex-1">{recap}</MarkdownText> : null}
{cancelButton}
</div> : null}
{objective ? <MarkdownText className={status === "blocked" ? "mt-4" : undefined}>{objective}</MarkdownText> : null}
{status !== "blocked" && recap ? <MarkdownText className="mt-4 text-muted-foreground">{recap}</MarkdownText> : null}
+17 -2
View File
@@ -426,6 +426,18 @@ export function ThreadShell({
[historyKey, sessions, titleOverrides],
);
const { client, getToken, ingressLimits, modelName, token, webuiCapabilities } = useClient();
const [online, setOnline] = useState(client.status === "open");
useEffect(() => client.onStatus((status) => setOnline(status === "open")), [client]);
const cancelGoal = useCallback(async () => {
if (!chatId || client.status !== "open") throw new Error(t("thread.composer.cancelGoalOffline"));
await client.sendSystemCommand(chatId, "/cancel_goal").catch(() => {
throw new Error(t("thread.composer.cancelGoalFailed"));
});
const remainingGoal = client.getGoalState(chatId);
if (remainingGoal?.active || remainingGoal?.status === "blocked") {
throw new Error(t("thread.composer.cancelGoalFailed"));
}
}, [chatId, client, t]);
const favoriteWorkspaceProject = useCallback(
async (path: string, pinned: boolean) => {
const response = await client.requestMutation<{ favorite_projects: ProjectDirectory[] }>("workspace.favorite", { path, pinned });
@@ -1060,6 +1072,9 @@ export function ThreadShell({
const handleThreadSend = useCallback(
(content: string, images?: SendAttachment[], options?: SendOptions) => {
if (content.trim() === "/cancel_goal" && options?.sideChannel) {
return cancelGoal().then(() => true);
}
setRestoredFirstDraft((current) => current?.chatId === chatId ? { ...current, error: "" } : current);
const submitted = send(content, images, withWorkspaceScope(options));
if (
@@ -1073,7 +1088,7 @@ export function ThreadShell({
}
return submitted?.delivery ? submitted.delivery.then(() => true) : submitted !== null;
},
[chatId, send, withWorkspaceScope],
[cancelGoal, chatId, send, withWorkspaceScope],
);
const loadTemporaryFilePreview = useCallback((path: string) =>
@@ -1429,7 +1444,7 @@ export function ThreadShell({
className={previewOpen ? "h-10" : undefined}
title={title}
goal={currentGoalState && (currentGoalState.active || currentGoalState.status === "blocked")
? <GoalIsland key={historyKey} goal={currentGoalState} /> : undefined}
? <GoalIsland key={historyKey} goal={currentGoalState} cancelDisabled={!online} onCancel={cancelGoal} /> : undefined}
onToggleSidebar={onToggleSidebar}
theme={theme}
onToggleTheme={onToggleTheme}
+4 -3
View File
@@ -93,11 +93,12 @@ function ComposerPreview() {
function GoalPreview() {
const { t } = useGalleryTranslation();
const [status, setStatus] = useState<"active" | "blocked">("active");
const [cancelled, setCancelled] = useState(false);
return <div>
<StatePicker label={t("previews.goal.state")} value={status} options={["active", "blocked"]} onChange={setStatus} />
<StatePicker label={t("previews.goal.state")} value={status} options={["active", "blocked"]} onChange={(next) => { setStatus(next); setCancelled(false); }} />
<div className="thread-header-container relative h-56 overflow-hidden rounded-control border bg-background">
<GoalIsland goal={{ active: status === "active", status, ui_summary: t("previews.goal.summary"), objective: t("previews.goal.objective"),
...(status === "blocked" ? { recap: t("previews.goal.recap") } : {}) }} />
{!cancelled && <GoalIsland goal={{ active: status === "active", status, ui_summary: t("previews.goal.summary"), objective: t("previews.goal.objective"),
...(status === "blocked" ? { recap: t("previews.goal.recap") } : {}) }} cancelDisabled={false} onCancel={async () => setCancelled(true)} />}
</div>
</div>;
}
+7
View File
@@ -2120,6 +2120,9 @@
"goalStateExpandAria": "Show full goal",
"goalBlocked": "Blocked",
"goalStateSheetTitle": "Goal",
"cancelGoal": "Cancel goal",
"cancelGoalFailed": "Could not cancel goal. Try again.",
"cancelGoalOffline": "Reconnect to cancel the goal.",
"send": "Send message",
"stop": "Stop response",
"quotedContext": "Quoted context",
@@ -2262,6 +2265,10 @@
"title": "Long-running goal",
"description": "Have the assistant keep working toward this goal."
},
"cancel_goal": {
"title": "Cancel goal",
"description": "Cancel the active or blocked goal in this chat."
},
"trigger": {
"title": "CLI trigger",
"description": "Create a CLI trigger for this chat."
+7
View File
@@ -1938,6 +1938,9 @@
"goalStateExpandAria": "Ver objetivo completo",
"goalBlocked": "Bloqueado",
"goalStateSheetTitle": "Objetivo",
"cancelGoal": "Cancelar objetivo",
"cancelGoalFailed": "No se pudo cancelar. Inténtalo de nuevo.",
"cancelGoalOffline": "Vuelve a conectarte para cancelar el objetivo.",
"send": "Enviar mensaje",
"stop": "Detener respuesta",
"quotedContext": "Contexto citado",
@@ -2071,6 +2074,10 @@
"title": "Objetivo a largo plazo",
"description": "Haz que el asistente siga trabajando en este objetivo."
},
"cancel_goal": {
"title": "Cancelar objetivo",
"description": "Cancela el objetivo activo o bloqueado de este chat."
},
"trigger": {
"title": "Activador CLI",
"description": "Crea un activador CLI para este chat."
+7
View File
@@ -1938,6 +1938,9 @@
"goalStateExpandAria": "Afficher l’objectif complet",
"goalBlocked": "Bloqué",
"goalStateSheetTitle": "Objectif",
"cancelGoal": "Annuler l’objectif",
"cancelGoalFailed": "Échec de l’annulation. Réessayez.",
"cancelGoalOffline": "Reconnectez-vous pour annuler l’objectif.",
"send": "Envoyer le message",
"stop": "Arrêter la réponse",
"quotedContext": "Contexte cité",
@@ -2071,6 +2074,10 @@
"title": "Objectif long terme",
"description": "Demandez à l’assistant de poursuivre cet objectif."
},
"cancel_goal": {
"title": "Annuler l’objectif",
"description": "Annuler l’objectif actif ou bloqué de cette conversation."
},
"trigger": {
"title": "Déclencheur CLI",
"description": "Créez un déclencheur CLI pour cette discussion."
+7
View File
@@ -1938,6 +1938,9 @@
"goalStateExpandAria": "Lihat tujuan lengkap",
"goalBlocked": "Terhambat",
"goalStateSheetTitle": "Tujuan",
"cancelGoal": "Batalkan tujuan",
"cancelGoalFailed": "Tujuan gagal dibatalkan. Coba lagi.",
"cancelGoalOffline": "Hubungkan kembali untuk membatalkan tujuan.",
"send": "Kirim pesan",
"stop": "Hentikan respons",
"quotedContext": "Konteks kutipan",
@@ -2071,6 +2074,10 @@
"title": "Tujuan jangka panjang",
"description": "Minta asisten terus mengerjakan tujuan ini."
},
"cancel_goal": {
"title": "Batalkan tujuan",
"description": "Batalkan tujuan aktif atau terblokir di chat ini."
},
"trigger": {
"title": "Pemicu CLI",
"description": "Buat pemicu CLI untuk chat ini."
+7
View File
@@ -1938,6 +1938,9 @@
"goalStateExpandAria": "目標の全文を表示",
"goalBlocked": "進行不可",
"goalStateSheetTitle": "目標",
"cancelGoal": "目標を取り消す",
"cancelGoalFailed": "取り消せませんでした。再試行してください。",
"cancelGoalOffline": "再接続してから目標を取り消してください。",
"send": "メッセージを送信",
"stop": "応答を停止",
"quotedContext": "引用したコンテキスト",
@@ -2071,6 +2074,10 @@
"title": "長期目標",
"description": "アシスタントがこの目標に向けて作業を続けます。"
},
"cancel_goal": {
"title": "目標を取り消す",
"description": "このチャットの実行中またはブロック中の目標を取り消します。"
},
"trigger": {
"title": "CLI トリガー",
"description": "このチャット用の CLI トリガーを作成します。"
+7
View File
@@ -1938,6 +1938,9 @@
"goalStateExpandAria": "전체 목표 보기",
"goalBlocked": "진행 막힘",
"goalStateSheetTitle": "목표",
"cancelGoal": "목표 취소",
"cancelGoalFailed": "목표를 취소하지 못했습니다. 다시 시도하세요.",
"cancelGoalOffline": "다시 연결한 후 목표를 취소하세요.",
"send": "메시지 보내기",
"stop": "응답 중지",
"quotedContext": "인용한 문맥",
@@ -2071,6 +2074,10 @@
"title": "장기 목표",
"description": "어시스턴트가 이 목표를 향해 계속 작업하게 합니다."
},
"cancel_goal": {
"title": "목표 취소",
"description": "이 채팅에서 진행 중이거나 차단된 목표를 취소합니다."
},
"trigger": {
"title": "CLI 트리거",
"description": "이 채팅의 CLI 트리거를 만듭니다."
+7
View File
@@ -1940,6 +1940,9 @@
"goalStateExpandAria": "Mostrar objetivo completo",
"goalBlocked": "Bloqueado",
"goalStateSheetTitle": "Objetivo",
"cancelGoal": "Cancelar objetivo",
"cancelGoalFailed": "Não foi possível cancelar. Tente novamente.",
"cancelGoalOffline": "Reconecte-se para cancelar o objetivo.",
"send": "Enviar mensagem",
"stop": "Parar resposta",
"quotedContext": "Contexto citado",
@@ -2082,6 +2085,10 @@
"title": "Objetivo de longa duração",
"description": "Peça ao assistente para continuar trabalhando neste objetivo."
},
"cancel_goal": {
"title": "Cancelar objetivo",
"description": "Cancela o objetivo ativo ou bloqueado desta conversa."
},
"trigger": {
"title": "Gatilho CLI",
"description": "Crie um gatilho CLI para esta conversa."
+7
View File
@@ -1938,6 +1938,9 @@
"goalStateExpandAria": "Xem đầy đủ mục tiêu",
"goalBlocked": "Bị chặn",
"goalStateSheetTitle": "Mục tiêu",
"cancelGoal": "Hủy mục tiêu",
"cancelGoalFailed": "Không thể hủy mục tiêu. Hãy thử lại.",
"cancelGoalOffline": "Kết nối lại để hủy mục tiêu.",
"send": "Gửi tin nhắn",
"stop": "Dừng phản hồi",
"quotedContext": "Ngữ cảnh được trích dẫn",
@@ -2071,6 +2074,10 @@
"title": "Mục tiêu dài hạn",
"description": "Để trợ lý tiếp tục làm việc hướng đến mục tiêu này."
},
"cancel_goal": {
"title": "Hủy mục tiêu",
"description": "Hủy mục tiêu đang chạy hoặc bị chặn trong cuộc trò chuyện này."
},
"trigger": {
"title": "Kích hoạt CLI",
"description": "Tạo kích hoạt CLI cho trò chuyện này."
+7
View File
@@ -2120,6 +2120,9 @@
"goalStateExpandAria": "查看完整目标",
"goalBlocked": "已阻塞",
"goalStateSheetTitle": "目标",
"cancelGoal": "取消目标",
"cancelGoalFailed": "取消失败,请重试。",
"cancelGoalOffline": "请重新连接后取消目标。",
"send": "发送消息",
"stop": "停止响应",
"quotedContext": "引用内容",
@@ -2262,6 +2265,10 @@
"title": "长期目标",
"description": "让助手持续推进当前目标"
},
"cancel_goal": {
"title": "取消目标",
"description": "取消当前对话中执行或阻塞的目标"
},
"trigger": {
"title": "CLI 触发器",
"description": "创建绑定当前对话的 CLI 触发器"
+7
View File
@@ -1938,6 +1938,9 @@
"goalStateExpandAria": "檢視完整目標",
"goalBlocked": "已受阻",
"goalStateSheetTitle": "目標",
"cancelGoal": "取消目標",
"cancelGoalFailed": "取消失敗,請重試。",
"cancelGoalOffline": "請重新連線後取消目標。",
"send": "送出訊息",
"stop": "停止回覆",
"quotedContext": "引用內容",
@@ -2071,6 +2074,10 @@
"title": "長期目標",
"description": "讓助手持續推進當前目標"
},
"cancel_goal": {
"title": "取消目標",
"description": "取消目前對話中執行或受阻的目標"
},
"trigger": {
"title": "CLI 觸發器",
"description": "建立繫結當前對話的 CLI 觸發器"
+1 -1
View File
@@ -11,7 +11,7 @@ const goal = { active: true, ui_summary: "Ship the release", objective: "Verify
function Conversation({ blocked = false }: { blocked?: boolean }) {
return <>
<ThreadHeader title="Release planning" onToggleSidebar={vi.fn()} theme="light" onToggleTheme={vi.fn()}
goal={<GoalIsland goal={{ ...goal, active: !blocked, status: blocked ? "blocked" : "active", ...(blocked ? { recap: "Waiting for approval." } : {}) }} />} />
goal={<GoalIsland goal={{ ...goal, active: !blocked, status: blocked ? "blocked" : "active", ...(blocked ? { recap: "Waiting for approval." } : {}) }} cancelDisabled={false} onCancel={async () => {}} />} />
<ThreadComposer onSend={vi.fn()} persistDraft={false} goalState={goal} />
</>;
}
+3 -2
View File
@@ -1,12 +1,12 @@
import { NanobotClient } from "@/lib/nanobot-client";
import type { InboundEvent } from "@/lib/types";
export function createStreamClient() {
export function createStreamClient(onSend: (frame: string) => void = () => {}) {
const socket = {
readyState: 1,
onopen: null as (() => void) | null,
onmessage: null as ((event: MessageEvent) => void) | null,
send() {},
send: onSend,
close() {},
};
const client = new NanobotClient({
@@ -17,6 +17,7 @@ export function createStreamClient() {
socket.onopen?.();
return {
client,
socket,
receive(event: InboundEvent) {
socket.onmessage?.({ data: JSON.stringify(event) } as MessageEvent);
},
+110
View File
@@ -5468,6 +5468,116 @@ describe("ThreadShell", () => {
await waitFor(() => expect(scroller.scrollTop).toBe(1800));
});
it.each(["active", "blocked"] as const)("cancels the %s goal through a system command and waits for goal_state", async (status) => {
const client = makeClient();
const chatId = `cancel-${status}`;
let complete!: () => void;
client.sendSystemCommand.mockImplementation(() => new Promise<void>((resolve) => { complete = resolve; }));
render(wrap(client, <ThreadShell session={session(chatId)} title="Goal" onToggleSidebar={() => {}} />));
await act(async () => {});
act(() => {
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: status === "active", status, objective: "Ship the release" } });
client._emitChat(chatId, { event: "goal_status", chat_id: chatId, turn_id: "running-turn", status: "running", started_at: 100 });
client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: "running-turn", stream_id: "live", text: "Still responding" });
});
await screen.findByText("Still responding");
expect(screen.getByRole("button", { name: "Stop response" })).toBeVisible();
const input = screen.getByRole("textbox", { name: "Message input" });
fireEvent.change(input, { target: { value: "Keep my draft" } });
fireEvent.click(await screen.findByRole("button", { name: "Show full goal" }));
const button = screen.getByRole("button", { name: "Cancel goal" });
fireEvent.click(button);
expect(button).toBeDisabled();
fireEvent.click(button);
expect(client.sendSystemCommand).toHaveBeenCalledTimes(1);
expect(client.sendSystemCommand).toHaveBeenCalledWith(chatId, "/cancel_goal");
expect(screen.getByRole("dialog", { name: "Goal" })).toBeVisible();
expect(input).toHaveValue("Keep my draft");
expect(client.sendMessage).not.toHaveBeenCalled();
expect(client.finishRunLocally).not.toHaveBeenCalled();
expect(client.getRunState(chatId).active).toBe(true);
act(() => {
if (status === "active") client._emitChat(chatId, { event: "turn_end", chat_id: chatId, turn_id: "running-turn" });
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false } });
});
await waitFor(() => expect(screen.queryByRole("button", { name: "Show full goal" })).not.toBeInTheDocument());
await act(async () => complete());
expect(input).toHaveValue("Keep my draft");
expect(within(screen.getByTestId("thread-message-region")).queryByText("/cancel_goal")).not.toBeInTheDocument();
fireEvent.change(input, { target: { value: "" } });
if (status === "blocked") {
act(() => client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: "running-turn", stream_id: "live", text: " after goal cancellation" }));
expect(await screen.findByText("Still responding after goal cancellation")).toBeVisible();
expect(screen.getByRole("button", { name: "Stop response" })).toBeVisible();
} else {
expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument();
}
});
it("disables offline goal cancellation and treats an unchanged goal after a control reply as a retryable failure", async () => {
const client = makeClient();
const chatId = "cancel-failure";
render(wrap(client, <ThreadShell session={session(chatId)} title="Goal" onToggleSidebar={() => {}} />));
await act(async () => {});
act(() => {
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false, status: "blocked", objective: "Ship the release" } });
client._emitStatus("closed");
});
fireEvent.click(await screen.findByRole("button", { name: "Show full goal" }));
const button = screen.getByRole("button", { name: "Cancel goal" });
expect(button).toBeDisabled();
fireEvent.click(button);
expect(client.sendSystemCommand).not.toHaveBeenCalled();
act(() => client._emitStatus("open"));
fireEvent.click(button);
expect(await screen.findByRole("alert")).toHaveTextContent("Could not cancel goal. Try again.");
expect(button).toBeEnabled();
expect(screen.getByRole("dialog", { name: "Goal" })).toBeVisible();
client.sendSystemCommand.mockImplementationOnce(async () => {
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false } });
});
fireEvent.click(button);
await waitFor(() => expect(screen.queryByRole("button", { name: "Show full goal" })).not.toBeInTheDocument());
expect(client.sendSystemCommand).toHaveBeenCalledTimes(2);
});
it("sends /cancel_goal directly while streaming without a transcript entry, /stop, or offline replay", async () => {
const client = makeClient();
const chatId = "cancel-slash";
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => String(input).endsWith("/api/commands")
? httpJson({ commands: [{ command: "/cancel_goal", title: "Cancel goal", description: "Cancel the goal", icon: "square", lifecycle: "side_channel", accepts_args: false }] })
: new Response(null, { status: 404 })));
render(wrap(client, <ThreadShell session={session(chatId)} title="Goal" onToggleSidebar={() => {}} />));
await act(async () => {});
act(() => {
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false, status: "blocked", objective: "Ship the release" } });
client._emitChat(chatId, { event: "goal_status", chat_id: chatId, turn_id: "unrelated", status: "running", started_at: 100 });
client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: "unrelated", stream_id: "live", text: "Unrelated reply" });
client._emitStatus("closed");
});
const input = screen.getByRole("textbox", { name: "Message input" });
fireEvent.change(input, { target: { value: "/cancel_goal" } });
expect(await screen.findByRole("option", { name: /Cancel goal/ })).toBeVisible();
fireEvent.keyDown(input, { key: "Escape" });
fireEvent.keyDown(input, { key: "Enter" });
expect(await screen.findByText("Reconnect to cancel the goal.")).toBeVisible();
expect(client.sendSystemCommand).not.toHaveBeenCalled();
expect(input).toHaveValue("/cancel_goal");
act(() => client._emitStatus("open"));
expect(client.sendSystemCommand).not.toHaveBeenCalled();
client.sendSystemCommand.mockImplementationOnce(async () => {
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false } });
});
fireEvent.keyDown(input, { key: "Enter" });
await waitFor(() => expect(input).toHaveValue(""));
expect(client.sendSystemCommand).toHaveBeenCalledTimes(1);
expect(client.sendSystemCommand).toHaveBeenCalledWith(chatId, "/cancel_goal");
expect(client.sendMessage).not.toHaveBeenCalled();
expect(client.finishRunLocally).not.toHaveBeenCalled();
expect(within(screen.getByTestId("thread-message-region")).queryByText("/cancel_goal")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Stop response" })).toBeVisible();
});
it("opens slash commands on the blank welcome page", async () => {
const client = makeClient();
vi.stubGlobal(