deer-flow/frontend/tests/e2e-record/record-write-read-file.spec.ts
Xinmin Zeng 799bef6d9d
fix(replay-e2e): match by conversation, not the living system prompt (#3436)
* fix(replay-e2e): match by conversation, not the living system prompt

The model-replay match key hashed the full input including the lead-agent
system prompt. That prompt is edited frequently (e.g. #3195 added a "File
Editing Workflow" section), so the committed fixture went stale the moment
the prompt changed on main — turning the Layer-2 render gate RED on every
unrelated PR (#3430, #3432, ...). This was a self-inflicted false positive.

Root-cause fix:
- replay_provider._canonical_messages now EXCLUDES the system message from
  the hash. The conversation (human/ai/tool) is the stable contract that
  identifies a recorded turn; the system prompt is an internal detail not
  part of the front-back contract under test. (Mirrors how open-design keys
  its mock picker on the user prompt, not the system internals.) Proven
  robust: injecting a prompt edit no longer causes a replay miss.
- Layer-1 golden was BLIND to replay misses: the gateway swallows a miss
  into an assistant error message, so the shape-only golden stayed green on
  a stale fixture. It now inspects replay_provider.replay_misses() and fails
  loud. (Layer-2 already fails on a miss.)
- Re-recorded write_read_file.ultra fixture + regenerated golden under the
  new conversation-only hash.
- Layer-2 render spec: assert the in-graph auto-title (deterministic); the
  follow-up suggestion is fired async and depends on a clean JSON model
  output, so assert it only when the fixture captured one — never gate on
  its absence (recording flakiness must not block CI).
- docs: REPLAY_E2E.md updated.

Verified: Layer-1 golden green (no miss), Layer-2 both specs green,
CI=true make test 4033 passed / 0 failed, frontend pnpm check clean.

* test(replay-e2e): restore suggestions coverage with a reliable capture

Addresses review feedback (the suggestion path was dropped from Layer-2):

- record spec now waits for the `/suggestions` response before checking
  capture stability, so the recorded fixture reliably includes the
  frontend-fired suggestions turn (previously the stability window could
  return before suggestions fired, yielding a fixture without it).
- Re-recorded write_read_file.ultra: 5 turns (write_file, auto-title,
  read_file, answer, suggestions). Golden unchanged — suggestions is a
  separate /suggestions call, not part of the /runs/stream SSE sequence.
- Layer-2 spec: restore the hard `EXPECTED_SUGGESTION` assertion. With the
  record spec now waiting for /suggestions, a fixture missing the suggestion
  turn means a broken recording and must fail loud, not pass silently.

Verified: Layer-1 golden green (no miss), Layer-2 both specs green
(auto-title + suggestion render), frontend pnpm check clean.

* ci: re-trigger (flaky Docker Hub image pull in sandbox e2e, unrelated)

backend-unit-tests failed only in test_sandbox_orphan_reconciliation_e2e.py
with 'docker pull busybox:latest ... context deadline exceeded' — a CI-runner
network flake reaching Docker Hub, not related to this docs/tests-only change.
Empty commit to re-run CI.

---------

Co-authored-by: DanielWalnut <45447813+hetaoBackend@users.noreply.github.com>
2026-06-08 17:32:41 +08:00

126 lines
4.2 KiB
TypeScript

import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { expect, test } from "@playwright/test";
/**
* RECORD driver (Plan A): drive the real frontend through the write/read-file
* scenario against the real-model gateway. The gateway captures every model
* call to DEERFLOW_RECORD_OUT; this just needs to drive the flow and wait until
* the captures stop arriving (main turns + in-graph title + follow-up
* suggestions all fired). It asserts nothing about content — it produces the
* fixture, it doesn't verify it.
*/
const APP = "http://localhost:3000";
const SCENARIO = "write_read_file";
const MODE = "ultra";
const PROMPT =
"Using your own file tools directly, create the file /mnt/user-data/outputs/note.txt " +
"with exactly this content: hi from replay. Then read that same file back and reply with its " +
"exact contents. Do NOT delegate to a subagent and do NOT use the task tool — do it yourself. " +
"Do not ask any clarifying questions.";
function countLines(path: string): number {
return existsSync(path)
? readFileSync(path, "utf-8")
.split("\n")
.filter((l) => l.trim()).length
: 0;
}
async function waitForCaptureStable(
path: string,
{ stableMs = 12_000, maxMs = 160_000 } = {},
): Promise<number> {
const start = Date.now();
let last = -1;
let lastChange = Date.now();
while (Date.now() - start < maxMs) {
const n = countLines(path);
if (n !== last) {
last = n;
lastChange = Date.now();
} else if (n > 0 && Date.now() - lastChange > stableMs) {
return n;
}
await new Promise((r) => setTimeout(r, 1000));
}
// Hard failure on timeout: returning the last count here would let a
// truncated/partial recording pass silently (captured > 0). A recording must
// stabilize, or it is not trustworthy.
throw new Error(
`[record] captures never stabilized within ${maxMs}ms (last count=${last}); ` +
`the recording may be truncated — raise maxMs or check the record gateway.`,
);
}
test.describe.configure({ timeout: 220_000 });
test("record write/read-file run through the real frontend", async ({
page,
context,
}) => {
const out = process.env.DEERFLOW_RECORD_OUT;
expect(out, "DEERFLOW_RECORD_OUT must be set").toBeTruthy();
// The context the frontend derives for ultra mode (core/threads/hooks.ts). The
// backend-direct golden test (Layer 1) POSTs this so its prompt — hence the
// recorded input hashes — matches the browser run. thinking/reasoning don't
// affect the prompt; is_plan_mode + subagent_enabled add the todo/task tools.
const CONTEXT = {
is_bootstrap: false,
mode: MODE,
thinking_enabled: true,
is_plan_mode: true,
subagent_enabled: true,
};
writeFileSync(
`${out}.meta.json`,
JSON.stringify({
scenario: SCENARIO,
mode: MODE,
prompt: PROMPT,
context: CONTEXT,
}),
"utf-8",
);
const reg = await context.request.post(`${APP}/api/v1/auth/register`, {
data: {
email: `rec-${Date.now()}@example.com`,
password: "very-strong-password-123",
},
});
expect(reg.status(), await reg.text()).toBe(201);
await page.addInitScript(() => {
window.localStorage.setItem(
"deerflow.local-settings",
JSON.stringify({ context: { mode: "ultra" } }),
);
});
await page.goto("/workspace/chats/new");
const textarea = page.getByPlaceholder(/how can i assist you/i);
await expect(textarea).toBeVisible({ timeout: 30_000 });
await textarea.fill(PROMPT);
await textarea.press("Enter");
// Suggestions fire only AFTER the run completes (input-box.tsx POSTs
// /suggestions). Wait for that response so its model call lands in the capture
// before we check for stability — otherwise the stability window can return
// first and the recorded fixture would be missing the suggestions turn.
await page
.waitForResponse((r) => r.url().includes("/suggestions"), {
timeout: 90_000,
})
.catch(() => undefined);
const captured = await waitForCaptureStable(out!);
console.log(
`[record] captures stabilized at ${captured} model call(s) -> ${out}`,
);
expect(
captured,
"expected at least the agent turns to be captured",
).toBeGreaterThan(0);
});