deer-flow/frontend/tests/e2e/goal-status.spec.ts
Totoro 0fe6e63a68
feat(goal): show why a chat goal stopped and when it was met, and redact the goal evaluator and continuation input (#6556)
* feat(goal): record the met goal and keep goal state on the history head

- Add a goal_outcome LastValue channel (GoalOutcomeState). Only the
  guarded clear of a satisfied ordinary goal writes it, in the same
  checkpoint as the clear; the reply anchor is the latest visible AI
  message with text, the reply the visible signature keys on. A goal
  stored without created_at still clears and gets a record.
- write_thread_goal removes the record on every other goal write and
  lists it in channel_versions, new_versions and metadata writes when
  it changes. Threads that never had a record keep their checkpoint
  shape. The sync-only SqliteSaver and CachedHistorySaver, which take
  the #6448 sync fallback, store and drop it the same way.
- goal_outcome is server-owned: POST /state and non-internal run input
  that carry it get 400. A POST /state goal write, or a goal in
  external run input, clears it.
- A branch head written onto its replay base resets the channels the
  head lacks, so a goal or record that write_thread_goal removed does
  not come back. Branching from the met turn keeps the record without
  the met goal.
- The POST /history head now carries an active goal and an achieved
  goal_outcome, also before any message exists, so the post-run
  history refetch keeps them. Older entries stay title/thread_data.
- contracts/thread_goal_contract.json pins the chat stand-down and
  check-failure codes, the record shape and status, the head keys and
  the host-written reasons.

* feat(frontend): show why a goal stopped and when it was met

- The goal bar derives its state from the active goal, the goal_outcome
  record and the messages: set, in progress, continuing, stopped (limit,
  auto-continue off, no progress, token budget, missing evidence, failed
  run, unknown code), waiting for you, waiting, couldn't check the goal,
  paused and goal met. An 8/8 stand-down now reads "Stopped" with the
  next step instead of "Continuing 8/8", and a count-0 stand-down no
  longer looks like a fresh goal.
- "Goal met" shows while its anchor reply is the latest visible message
  (a visible human message, or a visible AI message with text, moves the
  chat on), so a reload agrees with the live view. An active goal wins
  over the record, and this tab's /goal set or clear hides it.
- useActiveGoal drops the optimistic goal when the record of that same
  goal arrives, which fixes the bar that stayed after a goal met on the
  first run (the clear frame has no goal key), also for a goal stored
  without created_at. Server goal values pass through isGoalState; a
  /goal status read uses the backend's own active check, so the bar, the
  toast and the edit lock agree with the server.
- Row 2 gives the reason and what to do next; Details holds the full
  goal, the checker's own note (never host-written text, a check failure
  or a paused goal's older check), the assumption note and an unknown
  code, and starts collapsed in each new state. The bar is a labelled
  section with a live region that announces state changes only (another
  goal's same state counts) and re-reads its text after a language switch.
- The edit pencil on the latest turn is shown disabled with "Editing is
  off while a goal is set" instead of hidden; the message toolbar shows
  on focus-within, so keyboard users can reach it.
- A /goal set or clear rejected with 409 keeps the draft and says a run
  is still going; other failures keep the server's message and the draft.
  A /goal request replaced by a newer one leaves the composer alone, so
  a double submit no longer empties it before the second one fails.
- Copy lives in inputBox.goalBar (en-US, zh-CN); a contract test reads
  contracts/thread_goal_contract.json, and the raw-identifier guard now
  catches stand-down codes and goal field names.

* test(frontend): cover the goal bar on both chat pages

- tests/e2e/goal-status.spec.ts runs every case on the chat page and the
  agent chat page, since each wires the goal bar and the edit lock itself:
  a goal stopped at 8/8, one waiting for details and one waiting on an
  open question card show their reason and next step, also after a
  reload; the locked edit pencil gets keyboard focus, shows its toolbar
  and tooltip, does not open the editor, and hides while a file uploads;
  Goal met after one automatic follow-up (In progress, Continuing 1/8,
  then "Auto-continued once") survives a reload and hides after the next
  visible message; a goal met on the first run of a new chat replaces the
  set bar and frees the pencil, and a new /goal replaces Goal met while
  its own run goes on; a /goal set or clear refused with 409 keeps the
  draft for the retry and shows its own busy toast.
- The mock POST /history head carries only the contract's
  history_head_keys, with goal only while active and goal_outcome only
  when achieved; thread state and run values omit an unset goal instead
  of sending goal: null. PUT and DELETE /goal drop the met record,
  setGoalWritesBusy returns the Gateway's 409, and a repeat create of a
  requested thread id returns the thread as is, like the Gateway.
- The raw-identifier guard also catches checker blockers and the met
  record's field names.
- frontend/src/AGENTS.md: the GoalStatus sentence now names goal,
  goal_outcome and useActiveGoal, reworded in place.

* test(frontend): keep the draft through a failed upload and a busy /goal

#6412 fires onSent only once a send is dispatched, so a failed upload
keeps the text, files and stored draft. A /goal the Gateway refuses with
409 never reaches sendMessage, and the composer rejects it so PromptInput
keeps the text. Drive both through the real sendMessage in one composer:
a failed upload keeps "summarize it" stored, a busy /goal keeps its text
and stored draft with no run, and the retry saves the goal and starts
one run with the objective, not the "/goal" text. After that run the
composer is empty and no stored draft comes back.

* fix(frontend): drop the stop condition's closing period before the pause clause

A stored stop condition often ends with a period, so the schedule card
read "…remain)., pauses itself" (and "…。,满足后自动暂停" in Chinese).
Trim the condition's closing sentence punctuation before the clause that
follows it. The event line, where the condition ends the sentence, is
unchanged.

* fix(frontend): point "evidence missing" at the agent, not a user reply

"Evidence missing" asked the user to reply with what's left, which is
the push a goal is meant to save. It now asks the agent to show the
result or explain what's missing, and offers /goal clear only for a goal that
no longer applies: clearing drops the met record, so work that is right
would never show "Goal met".

zh-CN follows. Copy only: no key, state or mapping changes, and the
scheduled page's reason labels are untouched.

tests/unit/components/workspace/goal-status-next-steps.test.ts checks
the row in en-US and zh-CN, and that no stop row offers /goal clear
without that condition. goal-status.dom.test.tsx and
goal-stream.dom.test.tsx now expect the new copy.

* fix(frontend): say "Couldn't check the goal" once in the goal bar

After a goal check that could not run, the bar's second line borrowed
the scheduled page's whole reason, so it repeated the chip: "Couldn't
check the goal · Couldn't check the goal; the run itself may be fine.
It's checked again after your next message." Chinese had the same
repeat.

The line now gives only why the check failed ("The run itself may be
fine", "No final reply was saved" or "The chat changed during the
check"), then when it is checked again. The screen-reader announcement
follows. The chip and the scheduled page's reason labels are unchanged.

tests/unit/components/workspace/goal-status-unchecked.test.ts checks
every check-failure code in en-US and zh-CN: the label appears once,
and the line still says why the check failed.

* feat(goal): redact the evaluator input when pii_redaction is enabled

The goal evaluator calls its model directly, outside
PiiRedactionMiddleware, so it sent raw user lines, tool arguments, tool
results and Human Input Card answers even with pii_redaction enabled.

With pii_redaction enabled:
- the messages in the evidence window are redacted whole before the
  evidence caps can cut an identifier in two, as TitleMiddleware does.
  This reuses redact_queued_messages, which already covers content,
  call arguments and card answers. Earlier messages are left alone: the
  evaluator never sees them, and the pass is synchronous work on the
  event loop (0.84 s for an 800-message, 4 MB thread, 0.06 s for its
  window);
- the assembled input, the goal objective included, is redacted again.

A redaction error fails the check with evaluator_failed; raw text is
never sent instead. When redaction is off, the input is byte-identical.
Thread state keeps the raw text. README.md, config.example.yaml and the
middleware docstring list the evaluator with the other redacted inputs.

tests/test_goal_pii.py puts an address where the evidence caps cut a
tool argument, a tool result and a card answer, and checks the
objective, the unchanged input when redaction is off, that only the
evidence window reaches the redactor and gives the same evidence as
redacting the whole thread, that a redaction error stands down with
evaluator_failed before the model is called, and the worker path.

* fix(goal): redact the hidden continuation when pii_redaction is enabled

The hidden /goal continuation repeats the goal objective and the
evaluator's reason and evidence summary. PiiRedactionMiddleware skips
it, since it is a framework message and not a user message, so with
pii_redaction enabled each continuation turn sent them raw to the
agent's model, and the message stayed in the thread for later model
calls. The durable-context block and the evaluator input already redact
the objective.

With pii_redaction enabled, make_goal_continuation_message now redacts
the objective, the reason and the evidence summary with redact_text
before the message is built. The thread keeps the redacted message,
which the UI hides; the goal state keeps the raw objective.

The worker builds the message before it counts the continuation. A
redaction error fails the check the way an evaluator redaction error
does: run_failed with stand_down_reason evaluator_failed, the goal stays
active, nothing is sent and the continuation budget is not spent. Only
the exception type is stored. With redaction off, the message is
byte-identical.

README.md, config.example.yaml and the middleware docstring list the
continuation with the other redacted inputs.

tests/test_goal_continuation_pii.py checks the redacted objective,
reason and evidence summary against the tokens redact_text gives, the
unchanged message with redaction off or no config, the worker path
under the run config, and a redaction error.

* docs(changelog): link the goal outcome entries to #6556

Fill the four ([#PR]) placeholders in CHANGELOG.md and CHANGELOG_zh.md with this PR's number and add the matching link references.

* fix(frontend): keep an active goal stored without timestamps visible

POST /threads/{id}/state and run input can store an active goal without
created_at or updated_at. The backend still evaluates it and rejects an
edit with 409 (is_active_goal checks only status "active"), but
isGoalState required both timestamps, so history and live values
dropped it: both chat pages hid the goal bar and unlocked the last-turn
pencil, and only a /goal status read, which used a looser predicate,
brought them back.

isGoalState now accepts any record with a string objective and status
"active", and normalizeGoalStatusRead uses it, so thread values, live
updates and status reads share one rule. Malformed or inactive values
are still dropped.

Tests cover a sparse active goal from the history head and from a live
update before the post-run refetch (bar shown, hasGoal true), and a
malformed goal that stays hidden.

* test(goal): check the outcome write metadata the same way on every saver

PostgresSaver stores checkpoint metadata through
get_serializable_checkpoint_metadata, which drops "writes", so the
[postgres] case of test_goal_outcome_round_trips_through_the_sync_fallback
failed with KeyError: 'writes' when CI ran it against a live database.

The test now records the metadata write_thread_goal passes to put and
asserts the clear's and the next goal's "writes" there, for every saver.
The stored channel values are checked as before, and on sqlite and
cached-sqlite the stored "writes" must still equal what was passed.

* docs(agents): keep goal_outcome out of the agents guidance chain

The middlewares AGENTS.md chain is already over the 98,304-byte AG002
hard limit on main, and the PR-mode check fails any chain a PR touches,
so adding goal_outcome to the ThreadState field list in
deerflow/agents/AGENTS.md failed the agent-guidance job. goal_outcome
stays documented in runtime/AGENTS.md and backend/app/gateway/AGENTS.md,
which are outside that chain.

* refactor(goal): read the evaluator's evidence and redaction from one window

format_visible_conversation recomputed the window start that the redaction
pass takes from _evidence_window. Both now use _evidence_window, so a later
change to the cap or to what counts as visible moves both.

The window test now fills the window with tool-only replies and tool results.
Before, it caught a cap change in one copy but not a change to what counts
as visible.

---------

Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
2026-10-10 00:20:45 +08:00

667 lines
22 KiB
TypeScript

import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { expect, test, type Page, type Route } from "@playwright/test";
import type { GoalState, ThreadGoalOutcome } from "@/core/threads/types";
import {
MOCK_RUN_ID,
mockGoal,
mockGoalOutcome,
mockLangGraphAPI,
runStreamThreadId,
visibleRunInputMessages,
type MockAPIOptions,
type MockThread,
} from "./utils/mock-api";
import { expectNoRawIdentifiers } from "./utils/readable";
/**
* A Gateway-like run stream. The response names the created run
* (`Content-Location`, which moves a new chat to its own URL), and each
* `values` frame is written `gapMs` after the previous one, so the goal bar
* renders every state a live goal run passes through. As elsewhere in these
* mocks, messages ride the `values` frames. The Gateway streams a chat run's
* messages as message events and sends `values` only for goal writes, so a
* frame that adds messages and leaves the goal as it was stands in for those
* events. `saved` runs before the last frame: by then the backend has stored
* the run's final state for the post-run history refetch.
*/
async function startRunStream(gapMs: number) {
let run: {
threadId: string;
steps: Record<string, unknown>[];
saved: () => void;
} = { threadId: "", steps: [], saved: () => undefined };
const server = createServer((_request, response) => {
const { threadId, steps, saved } = run;
response.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Expose-Headers": "Content-Location",
"Cache-Control": "no-cache",
"Content-Location": `/threads/${threadId}/runs/${MOCK_RUN_ID}`,
"Content-Type": "text/event-stream",
});
const frame = (event: string, data: unknown) =>
`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
response.write(
frame("metadata", { run_id: MOCK_RUN_ID, thread_id: threadId }),
);
const timers = steps.map((values, index) =>
setTimeout(() => {
if (index < steps.length - 1) {
response.write(frame("values", values));
return;
}
saved();
response.end(frame("values", values) + frame("end", {}));
}, index * gapMs),
);
response.once("close", () => timers.forEach(clearTimeout));
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
server.off("error", reject);
resolve();
});
});
const { port } = server.address() as AddressInfo;
return {
/** Answer the run `route` starts with these `values` frames. */
serve(route: Route, steps: Record<string, unknown>[], saved: () => void) {
run = { threadId: runStreamThreadId(route), steps, saved };
return route.continue({ url: `http://127.0.0.1:${port}/runs/stream` });
},
async close() {
server.closeAllConnections();
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
},
};
}
// Both chat pages wire the goal bar and the edit lock themselves, so every
// case runs on each of them.
const CHAT_PAGES: {
name: string;
path: string;
options: MockAPIOptions;
agentName?: string;
}[] = [
{ name: "chat", path: "/workspace/chats", options: {} },
{
name: "agent chat",
path: "/workspace/agents/test-agent/chats",
options: {
agents: [
{
name: "test-agent",
description: "A test agent for E2E tests",
system_prompt: "You are a test agent.",
},
],
},
agentName: "test-agent",
},
];
const THREAD_ID = "00000000-0000-0000-0000-000000000601";
const BUSY = "A run is still going in this chat. Try again when it finishes.";
function goalBar(page: Page) {
return page.getByRole("region", { name: "Goal status" });
}
function composer(page: Page) {
return page.getByPlaceholder(/how can i assist you/i);
}
/** A question card the agent left open (`ask_clarification`). */
const OPEN_QUESTION = [
{
type: "ai",
id: "goal-ask",
content: "",
tool_calls: [
{
id: "call-room",
name: "ask_clarification",
args: {
question: "Which time works for you?",
clarification_type: "missing_info",
options: ["10:00", "14:00"],
},
},
],
},
{
type: "tool",
id: "goal-question",
name: "ask_clarification",
tool_call_id: "call-room",
content: "Which time works for you?",
artifact: {
human_input: {
version: 1,
kind: "human_input_request",
source: "ask_clarification",
request_id: "clarification:call-room",
tool_call_id: "call-room",
clarification_type: "missing_info",
question: "Which time works for you?",
input_mode: "choice_with_other",
options: [
{ id: "option-1", label: "10:00", value: "10:00" },
{ id: "option-2", label: "14:00", value: "14:00" },
],
},
},
},
];
const STOOD_DOWN = [
{
name: "a goal that used every automatic follow-up",
objective: "Make every test in the suite pass",
goal: {
continuation_count: 8,
last_evaluation: {
satisfied: false,
blocker: "goal_not_met_yet",
reason: "Two tests still fail.",
stand_down_reason: "max_continuations_reached",
},
},
reply: [
{
type: "ai",
id: "goal-ai",
content: "Six of the eight tests pass now.",
},
],
chip: "Stopped",
detail:
"Continuation limit reached · 8/8. It won't auto-continue again. Reply to keep going, or set the goal again with /goal <condition> to start a fresh count (this also starts a new run).",
note: "Two tests still fail.",
},
{
name: "a goal that needs details before any follow-up",
objective: "Book a meeting room for Friday",
goal: {
last_evaluation: {
satisfied: false,
blocker: "needs_user_input",
reason: "The user has to pick a time first.",
stand_down_reason: "blocked:needs_user_input",
},
},
reply: [
{ type: "ai", id: "goal-ai", content: "Which time works for you?" },
],
chip: "Waiting for you",
detail: "Reply with the missing details to continue.",
note: "The user has to pick a time first.",
},
{
name: "a goal waiting on an open question",
objective: "Book a meeting room for Friday",
goal: {
// The host writes this reason itself; it is not the checker's note.
last_evaluation: {
satisfied: false,
blocker: "needs_user_input",
reason:
"The turn ended on a question to the user that has not been answered.",
stand_down_reason: "blocked:needs_user_input",
},
},
reply: OPEN_QUESTION,
chip: "Waiting for you",
detail: "Answer the question above to continue.",
note: null,
},
] satisfies {
name: string;
objective: string;
goal: Partial<GoalState>;
reply: unknown[];
chip: string;
detail: string;
note: string | null;
}[];
for (const chatPage of CHAT_PAGES) {
const threadUrl = `${chatPage.path}/${THREAD_ID}`;
/** A chat with one finished turn, optionally under a stood-down goal. */
function chatThread({
objective = "Summarize the README",
goal,
reply = [
{ type: "ai", id: "goal-ai", content: "The README covers setup." },
],
}: {
objective?: string;
goal?: Partial<GoalState>;
reply?: unknown[];
} = {}): MockThread {
return {
thread_id: THREAD_ID,
title: "Goal chat",
agent_name: chatPage.agentName,
messages: [
{
type: "human",
id: "goal-human",
content: [{ type: "text", text: objective }],
},
...reply,
],
...(goal ? { goal: mockGoal(objective, goal) } : {}),
};
}
test.describe(`Goal bar on the ${chatPage.name} page`, () => {
for (const scenario of STOOD_DOWN) {
test(`explains ${scenario.name}, also after a reload`, async ({
page,
}) => {
mockLangGraphAPI(page, {
...chatPage.options,
threads: [chatThread(scenario)],
});
await page.goto(threadUrl);
const bar = goalBar(page);
for (const reload of [false, true]) {
if (reload) {
await page.reload();
}
await expect(bar.getByTestId("goal-status-chip")).toHaveText(
scenario.chip,
{ timeout: 15_000 },
);
await expect(bar.getByTestId("goal-status-detail")).toHaveText(
scenario.detail,
);
await expect(bar).not.toContainText("Continuing");
await expectNoRawIdentifiers(bar);
}
await bar.getByRole("button", { name: "Details" }).click();
const details = bar.getByTestId("goal-status-details");
await expect(details).toContainText(scenario.objective);
if (scenario.note) {
await expect(bar.getByTestId("goal-status-note")).toHaveText(
scenario.note,
);
} else {
await expect(details).not.toContainText("Goal check note");
}
});
}
test("keeps the locked edit pencil visible to the keyboard, and hides it during an upload", async ({
page,
}) => {
mockLangGraphAPI(page, {
...chatPage.options,
threads: [chatThread(STOOD_DOWN[0])],
});
await page.goto(threadUrl);
await expect(goalBar(page).getByTestId("goal-status-chip")).toHaveText(
"Stopped",
{ timeout: 15_000 },
);
// No pointer over the message: only keyboard focus can show its toolbar.
await page.mouse.move(0, 0);
const toolbar = page
.getByTestId("message-toolbar")
.filter({ has: page.getByTestId("message-edit-locked") });
const pencil = toolbar.getByRole("button", { name: "Edit and rerun" });
await toolbar.getByRole("button", { name: "Copy to clipboard" }).focus();
await page.keyboard.press("Tab");
await expect(pencil).toBeFocused();
await expect(pencil).toBeDisabled();
await expect(toolbar).toHaveCSS("opacity", "1");
await expect(
page.getByRole("tooltip").filter({
hasText:
"Editing is off while a goal is set. Run /goal clear to edit.",
}),
).toBeVisible();
await page.keyboard.press("Enter");
await expect(
page.getByRole("button", { name: "Update and rerun" }),
).toBeHidden();
// No turn can be edited while a file uploads, so no pencil shows, not
// even the goal's locked one.
let releaseUpload!: () => void;
const uploadHeld = new Promise<void>((resolve) => {
releaseUpload = resolve;
});
await page.route("**/api/threads/*/uploads", async (route) => {
await uploadHeld;
return route.fulfill({
status: 500,
contentType: "application/json",
body: JSON.stringify({ detail: "Upload failed." }),
});
});
await page.getByLabel("Upload files").setInputFiles({
name: "notes.txt",
mimeType: "text/plain",
buffer: Buffer.from("notes"),
});
await composer(page).fill("Summarize these notes");
await composer(page).press("Enter");
await expect(page.getByTestId("message-edit-locked")).toHaveCount(0);
releaseUpload();
await expect(page.getByTestId("message-edit-locked")).toHaveCount(1);
});
test("shows Goal met after one automatic follow-up until the chat moves on", async ({
page,
}) => {
const objective = "Write a three-line summary of the README";
const stream = await startRunStream(600);
let runs = 0;
const api = mockLangGraphAPI(page, {
...chatPage.options,
threads: [chatThread()],
runStreamHandler: async (route) => {
runs += 1;
const thread = api.getThread(runStreamThreadId(route))!;
const turn = [
...(thread.messages ?? []),
...visibleRunInputMessages(route),
];
if (runs > 1) {
// A later turn: the backend keeps the record and adds the turn.
const messages = [
...turn,
{ type: "ai", id: "goal-ai-3", content: "Glad it helps." },
];
return stream.serve(
route,
[{ messages, goal_outcome: thread.goal_outcome }],
() => api.upsertThread({ ...thread, messages }),
);
}
const goal = thread.goal as GoalState;
const draft = {
type: "ai",
id: "goal-ai-1",
content: "Draft: the summary has two lines so far.",
};
const continuation = {
type: "human",
id: "goal-continuation-1",
content: `<goal_continuation>\nActive goal: ${objective}\n</goal_continuation>`,
additional_kwargs: {
hide_from_ui: true,
deerflow_goal_continuation: true,
},
};
const reply = {
type: "ai",
id: "goal-ai-2",
content: "Done: the summary now has three lines.",
};
const continuing: GoalState = {
...goal,
continuation_count: 1,
last_evaluation: {
satisfied: false,
blocker: "goal_not_met_yet",
reason: "The summary has two lines, not three.",
run_id: MOCK_RUN_ID,
},
};
const record = mockGoalOutcome(continuing, reply.id, {
reason: "The summary has three lines.",
});
const messages = [...turn, draft, continuation, reply];
// The checkpoint has the submitted turn while the run goes on.
api.upsertThread({ ...thread, messages: turn });
return stream.serve(
route,
[
{ messages: [...turn, draft], goal },
{ messages: [...turn, draft, continuation], goal: continuing },
{ messages, goal: continuing },
// The clear of the met goal: the record, and no `goal` key.
{ messages, goal_outcome: record },
],
() =>
api.upsertThread({
...thread,
goal: null,
goal_outcome: record,
messages,
}),
);
},
});
try {
await page.goto(threadUrl);
const textarea = composer(page);
await expect(page.getByText("The README covers setup.")).toBeVisible({
timeout: 15_000,
});
await textarea.fill(`/goal ${objective}`);
await textarea.press("Enter");
const bar = goalBar(page);
await expect(bar).toContainText("In progress");
await expect(bar).toContainText("Continuing 1/8");
await expect(bar).toHaveAttribute("data-goal-state", "met");
await expect(bar).toContainText(`Goal met${objective}`);
await expect(bar).toContainText("Auto-continued once");
await expect(bar).not.toContainText("Continuing");
await expect(
page.getByText("Done: the summary now has three lines."),
).toBeVisible();
// The goal is no longer active, so edit-and-rerun is back.
await expect(
page.getByRole("button", { name: "Edit and rerun" }),
).toBeEnabled();
await expect(page.getByTestId("message-edit-locked")).toHaveCount(0);
await expectNoRawIdentifiers(bar);
await page.reload();
await expect(bar).toContainText("Goal met", { timeout: 15_000 });
await expect(bar).toContainText("Auto-continued once");
await textarea.fill("Thanks, that works.");
await textarea.press("Enter");
await expect(page.getByText("Glad it helps.")).toBeVisible();
await expect(bar).toBeHidden();
await page.reload();
await expect(page.getByText("Glad it helps.")).toBeVisible({
timeout: 15_000,
});
await expect(bar).toBeHidden();
expect(runs).toBe(2);
} finally {
await stream.close();
}
});
test("replaces the set goal with Goal met when the first run meets it, and Goal met with a new goal", async ({
page,
}) => {
const objective = "Summarize the README in three lines";
const next = "List the README's sections";
const nextReply = "Sections: Setup, Usage, License.";
const stream = await startRunStream(600);
let runs = 0;
let lastRecord: ThreadGoalOutcome | undefined;
const api = mockLangGraphAPI(page, {
...chatPage.options,
// The goal PUT and the run share the chat's own id, as on the Gateway.
honorRequestedThreadId: true,
createdThreadMessages: [],
// Each goal is met on its own first run.
runStreamHandler: async (route) => {
runs += 1;
const thread = api.getThread(runStreamThreadId(route))!;
const turn = [
...(thread.messages ?? []),
...visibleRunInputMessages(route),
];
const reply = {
type: "ai",
id: `goal-ai-${runs}`,
content:
runs === 1 ? "README: setup, usage and license." : nextReply,
};
const messages = [...turn, reply];
const record = mockGoalOutcome(thread.goal as GoalState, reply.id);
const earlier = lastRecord;
lastRecord = record;
return stream.serve(
route,
[
// The turn's message events: the tab keeps the values it had,
// an earlier goal's record included.
{ messages: turn, ...(earlier ? { goal_outcome: earlier } : {}) },
// The clear of the met goal: the record, and no `goal` key at all.
{ messages, goal_outcome: record },
],
() =>
api.upsertThread({
...thread,
goal: null,
goal_outcome: record,
messages,
}),
);
},
});
try {
await page.goto(`${chatPage.path}/new`);
const textarea = composer(page);
await expect(textarea).toBeVisible({ timeout: 15_000 });
await textarea.fill(`/goal ${objective}`);
await textarea.press("Enter");
const bar = goalBar(page);
await expect(bar).toHaveAttribute("data-goal-state", "met");
await expect(bar).toContainText(`Goal met${objective}`);
await expect(bar).not.toContainText("Auto-continued");
await expect(
page.getByText("README: setup, usage and license."),
).toBeVisible();
await expect(page).not.toHaveURL(/\/new$/);
await expect(
page.getByRole("button", { name: "Edit and rerun" }),
).toBeEnabled();
await page.reload();
await expect(bar).toHaveAttribute("data-goal-state", "met", {
timeout: 15_000,
});
await expect(bar).toContainText(`Goal met${objective}`);
// A new goal replaces Goal met at once, and its own run meets it.
await textarea.fill(`/goal ${next}`);
await textarea.press("Enter");
await expect(bar).toHaveAttribute("data-goal-state", "inProgress");
await expect(bar).toContainText(next);
await expect(bar).toHaveAttribute("data-goal-state", "met");
await expect(bar).toContainText(`Goal met${next}`);
await expect(bar).not.toContainText(objective);
await textarea.fill("/goal clear");
await textarea.press("Enter");
await expect(page.getByText("Goal cleared.")).toBeVisible();
await expect(bar).toBeHidden();
await page.reload();
await expect(page.getByText(nextReply)).toBeVisible({
timeout: 15_000,
});
await expect(bar).toBeHidden();
expect(runs).toBe(2);
} finally {
await stream.close();
}
});
test("keeps the /goal draft when a run is still going", async ({
page,
}) => {
const objective = "Finish the quarterly report";
const api = mockLangGraphAPI(page, {
...chatPage.options,
threads: [chatThread()],
});
let runStreams = 0;
page.on("request", (request) => {
if (
request.method() === "POST" &&
request.url().includes("/runs/stream")
) {
runStreams += 1;
}
});
await page.goto(threadUrl);
const textarea = composer(page);
const bar = goalBar(page);
await expect(page.getByText("The README covers setup.")).toBeVisible({
timeout: 15_000,
});
// Setting the goal: the Gateway's 409 keeps the draft for a retry.
api.setGoalWritesBusy(true);
await textarea.fill(`/goal ${objective}`);
await textarea.press("Enter");
await expect(page.getByText(BUSY)).toBeVisible();
await expect(textarea).toHaveValue(`/goal ${objective}`);
await expect(bar).toBeHidden();
expect(runStreams).toBe(0);
api.setGoalWritesBusy(false);
await textarea.press("Enter");
await expect(bar).toContainText(objective);
await expect(textarea).toHaveValue("");
await expect(page.getByText("Hello from DeerFlow!")).toBeVisible();
expect(runStreams).toBe(1);
// Clearing it: the same. The set half's toast closes first, so the busy
// toast below can only be the clear's own.
await expect(page.getByText(BUSY)).toHaveCount(0, { timeout: 10_000 });
api.setGoalWritesBusy(true);
await textarea.fill("/goal clear");
const refused = page.waitForResponse(
(response) =>
response.request().method() === "DELETE" &&
response.url().endsWith("/goal"),
);
await textarea.press("Enter");
expect((await refused).status()).toBe(409);
await expect(page.getByText(BUSY)).toBeVisible();
await expect(textarea).toHaveValue("/goal clear");
await expect(bar).toContainText(objective);
api.setGoalWritesBusy(false);
await textarea.press("Enter");
await expect(page.getByText("Goal cleared.")).toBeVisible();
await expect(bar).toBeHidden();
await expect(textarea).toHaveValue("");
expect(runStreams).toBe(1);
});
});
}