deer-flow/frontend/tests/unit/components/workspace/input-box-helpers.test.ts
DanielWalnut 25ea6970a6
feat(runtime): implement goal continuations (#3858)
* implement goal continuations

* fix(goal): address review findings for goal continuations

- goal: key the no-progress breaker on a signature of the latest visible
  assistant evidence instead of the evaluator's volatile free-text, so it
  actually fires on stalled turns; thread the signature through every
  worker persist / no-progress call site
- goal: align _stand_down_reason default caps with should_continue_goal
  (8 / 2) so the two gate functions agree on goals missing the fields
- runtime: offload the synchronous checkpointer fallback via
  asyncio.to_thread (goal.py + worker.py) to keep blocking IO off the loop
- frontend: i18n the GoalStatus "Goal" label (goalLabel in en/zh/types)
- frontend: extract pure composer helpers into input-box-helpers.ts with
  unit tests (parseGoalCommand, readGoalResponseError, skill suggestions)
- tests: cover the evidence-based no-progress and default-cap behavior
- docs: align backend/AGENTS.md goal paragraph with actual behavior
- e2e: prettier-format chat.spec.ts (fixes the lint-frontend CI failure)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(frontend): hide goal continuation counter until the agent continues

The goal status bar rendered a raw "0/8" before any auto-continuation, which
read as a mysterious score. Now the counter is hidden until
continuation_count > 0, then shows "Continuing N/M" with a tooltip explaining
the auto-continuation cap.

- Extract getGoalContinuationDisplay into a pure helper (hides at 0) + unit tests
- Add goalContinuing / goalContinuationTooltip i18n keys (en/zh/types)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(goal): address review findings for goal continuations

Frontend correctness
- Fix the optimistic /goal result permanently shadowing server goal state:
  the streamed continuation counter never surfaced for a goal set in-session.
  Extract a shared useActiveGoal hook (used by both chat pages) that reconciles
  the optimistic copy with server state via a goalReconciliationKey, de-duping
  the copy-pasted goal block across the two pages.
- Stop /goal status|clear failures from escaping handleSubmit as unhandled
  rejections (handleGoalCommand now returns success; the run only starts when a
  goal was actually saved).
- Use a function replacer for the goal-status toast so an objective containing
  $&/$1 isn't treated as a replacement pattern.

Backend cleanliness / correctness
- De-duplicate four byte-identical helpers (_call_checkpointer_method,
  _message_type, _additional_kwargs, _is_visible_message) by importing them
  from runtime.goal instead of re-defining them in the run worker.
- Remove the dead `checkpoint_tuple.tasks` durability guard (CheckpointTuple has
  no tasks field) and document that pending_writes is the durability signal.
- Decompose the 176-line _prepare_goal_continuation_input: extract
  _reread_goal_and_checkpoint and a _persist closure so the thread-unchanged
  guard and stand-down persistence aren't open-coded three times. Document the
  last-writer-wins write-window limitation as a follow-up.
- Add a shared parse_goal_command helper and use it from the TUI and IM-channel
  /goal handlers (one place for the status/clear/set semantics).

Tests
- Restore the 11 command-registry tests dropped by the previous goal change
  (filter_commands ranking/description, build_registry builtins/skills, resolve
  cases) alongside the new goal tests.
- Add coverage for the IM-channel _handle_goal_command, the TUI _handle_goal
  handler, parse_goal_command, and goalReconciliationKey.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix goal review feedback

* fix goal continuation checkpoint races

* prioritize goal commands while streaming

Route composer submits through a shared helper so /goal commands can be handled before the streaming stop shortcut, while ordinary streaming submits still stop the active run.

Testing: cd frontend && pnpm exec rstest run tests/unit/components/workspace/input-box-helpers.test.ts tests/unit/components/workspace/goal-status-helpers.test.ts; cd frontend && pnpm check

* preserve goal status during clarification

Keep omitted stream goal fields distinct from explicit null clears so clarification interrupts do not hide an active thread goal that is still present in the checkpoint.

Testing: pnpm exec rstest run tests/unit/components/workspace/use-active-goal.test.ts tests/unit/components/workspace/input-box-helpers.test.ts tests/unit/components/workspace/goal-status-helpers.test.ts; pnpm check; git diff --check

* style: format active goal hook

Run Prettier on use-active-goal.ts to satisfy the frontend lint workflow formatting gate.

Testing: pnpm format; pnpm exec rstest run tests/unit/components/workspace/use-active-goal.test.ts tests/unit/components/workspace/input-box-helpers.test.ts tests/unit/components/workspace/goal-status-helpers.test.ts; pnpm check; git diff --check

* fix goal review followups

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 08:49:33 +08:00

261 lines
7.6 KiB
TypeScript

import { describe, expect, it } from "@rstest/core";
import {
abortGoalRequest,
beginGoalRequest,
createGoalRequestState,
findSuggestionTemplatePlaceholder,
finishGoalRequest,
getInputSubmitAction,
getLeadingSlashSkillQuery,
getMatchingSkillSuggestions,
isAbortError,
isCurrentGoalRequest,
parseGoalCommand,
readGoalResponseError,
type SlashSuggestion,
} from "@/components/workspace/input-box-helpers";
import type { Skill } from "@/core/skills";
function makeSkill(name: string, enabled = true): Skill {
return {
name,
description: `${name} description`,
enabled,
} as Skill;
}
// Builtin command names are bare (no leading slash); the composer renders them
// as `/${name}`. Mirror that shape here.
const builtins: SlashSuggestion[] = [
{
name: "goal",
description: "Set, show, or clear an active goal",
kind: "builtin",
},
{ name: "new", description: "Start a new thread", kind: "builtin" },
];
describe("parseGoalCommand", () => {
it("returns status for a bare /goal", () => {
expect(parseGoalCommand("/goal")).toEqual({ kind: "status" });
expect(parseGoalCommand(" /goal ")).toEqual({ kind: "status" });
});
it("treats clear/reset/off as clear (case-insensitive)", () => {
expect(parseGoalCommand("/goal clear")).toEqual({ kind: "clear" });
expect(parseGoalCommand("/GOAL Reset")).toEqual({ kind: "clear" });
expect(parseGoalCommand("/goal off")).toEqual({ kind: "clear" });
});
it("captures the objective for /goal <text>", () => {
expect(parseGoalCommand("/goal ship the feature")).toEqual({
kind: "set",
objective: "ship the feature",
});
});
it("returns null when the input is not a /goal command", () => {
expect(parseGoalCommand("/goalkeeper do thing")).toBeNull();
expect(parseGoalCommand("hello")).toBeNull();
expect(parseGoalCommand("/new")).toBeNull();
});
});
describe("getInputSubmitAction", () => {
it("handles /goal commands before the streaming stop shortcut", () => {
expect(
getInputSubmitAction({
text: "/goal ",
fileCount: 0,
status: "streaming",
}),
).toEqual({ kind: "goal", command: { kind: "status" } });
});
it("handles /goal set commands before the streaming stop shortcut", () => {
expect(
getInputSubmitAction({
text: "/goal finish the work",
fileCount: 0,
status: "streaming",
}),
).toEqual({
kind: "goal",
command: { kind: "set", objective: "finish the work" },
});
});
it("keeps ordinary streaming submits as stop", () => {
expect(
getInputSubmitAction({
text: "hello",
fileCount: 0,
status: "streaming",
}),
).toEqual({ kind: "stop" });
});
it("does not treat /goal text with attachments as a goal command", () => {
expect(
getInputSubmitAction({
text: "/goal ",
fileCount: 1,
status: "ready",
}),
).toEqual({ kind: "message" });
});
it("ignores empty ready submits", () => {
expect(
getInputSubmitAction({
text: " ",
fileCount: 0,
status: "ready",
}),
).toEqual({ kind: "empty" });
});
});
describe("getLeadingSlashSkillQuery", () => {
it("returns the query for a leading slash token", () => {
expect(getLeadingSlashSkillQuery("/rev")).toBe("rev");
expect(getLeadingSlashSkillQuery("/")).toBe("");
});
it("returns null when there is no leading slash or the token is not bare", () => {
expect(getLeadingSlashSkillQuery("rev")).toBeNull();
expect(getLeadingSlashSkillQuery("/rev now")).toBeNull();
expect(getLeadingSlashSkillQuery("/a/b")).toBeNull();
});
});
describe("getMatchingSkillSuggestions", () => {
it("excludes disabled skills and ranks prefix matches first", () => {
const skills = [
makeSkill("deep-research"),
makeSkill("review"),
makeSkill("reviewer-disabled", false),
];
const result = getMatchingSkillSuggestions(skills, "rev", []);
expect(result.map((s) => s.name)).toEqual(["review"]);
expect(result.every((s) => s.kind === "skill")).toBe(true);
});
it("includes matching builtin commands after skills", () => {
const result = getMatchingSkillSuggestions(
[makeSkill("goal-helper")],
"goal",
builtins,
);
expect(result.map((s) => s.name)).toContain("goal-helper");
expect(result.map((s) => s.name)).toContain("goal");
});
it("excludes skills that collide with builtin command names", () => {
const result = getMatchingSkillSuggestions(
[makeSkill("goal"), makeSkill("goal-helper")],
"goal",
builtins,
);
expect(result.map((s) => `${s.kind}:${s.name}`)).toEqual([
"skill:goal-helper",
"builtin:goal",
]);
});
it("caps the number of suggestions", () => {
const skills = Array.from({ length: 10 }, (_, i) =>
makeSkill(`skill-${i}`),
);
const result = getMatchingSkillSuggestions(skills, "", []);
expect(result.length).toBeLessThanOrEqual(6);
});
});
describe("readGoalResponseError", () => {
it("returns the detail string when present", async () => {
const response = {
status: 422,
json: async () => ({ detail: "Goal objective must not be empty." }),
} as unknown as Response;
expect(await readGoalResponseError(response)).toBe(
"Goal objective must not be empty.",
);
});
it("falls back to the HTTP status when detail is missing or unparseable", async () => {
const noDetail = {
status: 500,
json: async () => ({}),
} as unknown as Response;
expect(await readGoalResponseError(noDetail)).toBe("HTTP 500");
const broken = {
status: 503,
json: async () => {
throw new Error("not json");
},
} as unknown as Response;
expect(await readGoalResponseError(broken)).toBe("HTTP 503");
});
});
describe("goal request lifecycle", () => {
it("aborts a pending goal request when the thread changes and blocks stale updates", () => {
const state = createGoalRequestState();
const first = beginGoalRequest(state, "thread-1");
const updates: string[] = [];
abortGoalRequest(state);
const second = beginGoalRequest(state, "thread-2");
if (isCurrentGoalRequest(state, first, "thread-1")) {
updates.push("thread-1");
}
if (isCurrentGoalRequest(state, second, "thread-2")) {
updates.push("thread-2");
}
expect(first.controller.signal.aborted).toBe(true);
expect(second.controller.signal.aborted).toBe(false);
expect(updates).toEqual(["thread-2"]);
});
it("does not let an older request finish a newer one", () => {
const state = createGoalRequestState();
const first = beginGoalRequest(state, "thread-1");
const second = beginGoalRequest(state, "thread-1");
finishGoalRequest(state, first);
expect(isCurrentGoalRequest(state, second, "thread-1")).toBe(true);
});
it("recognizes abort-shaped errors", () => {
expect(isAbortError(new DOMException("aborted", "AbortError"))).toBe(true);
expect(
isAbortError(Object.assign(new Error("aborted"), { name: "AbortError" })),
).toBe(true);
expect(isAbortError(new Error("other"))).toBe(false);
});
});
describe("findSuggestionTemplatePlaceholder", () => {
it("locates a topic/source placeholder", () => {
const found = findSuggestionTemplatePlaceholder("Research [topic] deeply");
expect(found).not.toBeNull();
expect(
found && "Research [topic] deeply".slice(found.start, found.end),
).toBe("[topic]");
});
it("returns null when no placeholder is present", () => {
expect(findSuggestionTemplatePlaceholder("no placeholder here")).toBeNull();
});
});