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

117 lines
3.9 KiB
Python

"""Slash-command registry for the DeerFlow TUI (pure).
Normalizes two command sources into one searchable list:
* **Built-ins** — TUI-owned affordances (``/help``, ``/model``, ``/threads`` …).
* **Skills** — one ``/<skill-name>`` per enabled skill, preserving DeerFlow's
existing slash-skill activation semantics.
The picker filters this list; :func:`resolve` classifies a submitted line as a
built-in command, a skill activation, an unknown command, or a plain message.
No Textual dependency.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal
@dataclass(frozen=True)
class Command:
name: str # without leading slash
description: str
category: Literal["builtin", "skill"] = "builtin"
@dataclass(frozen=True)
class Resolution:
kind: Literal["builtin", "skill", "unknown", "message"]
name: str = ""
args: str = ""
text: str = ""
# Built-in commands, ordered for display in /help and the picker.
BUILTIN_COMMANDS: tuple[Command, ...] = (
Command("help", "Show commands and keybindings"),
Command("new", "Start a fresh thread"),
Command("threads", "Open the thread switcher"),
Command("switch", "Open the thread switcher"),
Command("resume", "Resume a thread by id or title"),
Command("goal", "Set, show or clear the active goal"),
Command("model", "Open the model picker"),
Command("skills", "Browse enabled and available skills"),
Command("tools", "Show built-in, MCP and sandbox tools"),
Command("mcp", "Show MCP server status"),
Command("memory", "Show memory status and injected facts"),
Command("uploads", "Show uploaded files for this thread"),
Command("artifacts", "Show generated artifacts"),
Command("details", "Toggle verbose activity rendering"),
Command("usage", "Show token usage and context"),
Command("config", "Show resolved config paths and overrides"),
Command("quit", "Exit the TUI"),
)
_BUILTIN_NAMES = frozenset(c.name for c in BUILTIN_COMMANDS)
def build_registry(skills: list[dict]) -> list[Command]:
"""Merge built-ins with one command per enabled skill."""
commands = list(BUILTIN_COMMANDS)
for skill in skills:
if not skill.get("enabled", False):
continue
name = skill.get("name")
if not name or name in _BUILTIN_NAMES:
continue
commands.append(Command(name=name, description=skill.get("description", "") or "", category="skill"))
return commands
def filter_commands(commands: list[Command], query: str) -> list[Command]:
"""Filter + rank commands for the picker.
Ranking: name-prefix matches first, then name-substring, then
description-substring. Original order is preserved within a rank tier.
"""
q = query.strip().lower()
if not q:
return commands
prefix: list[Command] = []
substring: list[Command] = []
description: list[Command] = []
for command in commands:
name = command.name.lower()
if name.startswith(q):
prefix.append(command)
elif q in name:
substring.append(command)
elif q in command.description.lower():
description.append(command)
return prefix + substring + description
def resolve(text: str, skills: list[str] | None = None) -> Resolution:
"""Classify a submitted input line."""
stripped = text.strip()
if not stripped.startswith("/"):
return Resolution(kind="message", text=text)
body = stripped[1:]
name, _, args = body.partition(" ")
name = name.strip()
args = args.strip()
if not name:
return Resolution(kind="unknown", name="")
if name in _BUILTIN_NAMES:
return Resolution(kind="builtin", name=name, args=args)
if skills and name in skills:
return Resolution(kind="skill", name=name, args=args)
return Resolution(kind="unknown", name=name, args=args)