mirror of
https://github.com/langgenius/dify.git
synced 2026-10-04 13:47:55 +08:00
feat(dify-builder): name apps from their prompt, and turn gate actions into card options
Two App Builder spec changes that share the Builder session contract.
Naming (spec N1-N3): an app created from the homepage prompt is no longer named
by the user. core/dify_builder/naming.py cuts the prompt's opening clause at
create time -- instant and infallible, since it runs inside POST /apps -- and
CreateAppPayload.name becomes optional alongside a new prompt field. The Builder
then refines that name once during goal analysis, where a model and the detected
reply language are already in hand, so the judgement calls that are
English-shaped in pure Python (dropping an imperative lead-in, spotting a
contentless prompt) work in any language. Plan approval freezes the name.
Card options: SessionView gains a Decision carrying the gate's choice as options
inside the card plus a fixed confirm/cancel pair, replacing a button row whose
shape changed at every state. Option ids are the old action ids untouched, so
resolve_action_kind and the per-state legality check are unchanged, and
SessionView.actions keeps being populated -- the deployed web client goes on
working until it reads decision instead.
The regenerated console OpenAPI doc also picks up ErrorCard.diagnostics, missed
when cc9ca8b1dd landed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
cc9ca8b1dd
commit
aa2b4fe4ab
30 files changed
+1163
-18
No files matched your search
@@ -168,6 +168,69 @@ class Action:
|
||||
canvas_event: str | None = None
|
||||
|
||||
|
||||
# The only two buttons an interactive card shows; every real choice is an option
|
||||
# inside it. One interaction shape at every gate, not one per state.
|
||||
CONFIRM_ACTION_ID = "confirm"
|
||||
CANCEL_ACTION_ID = "cancel"
|
||||
|
||||
|
||||
@dataclass
|
||||
class OptionInput:
|
||||
"""Free text an option reveals once selected ("Something else", "Reject with a reason").
|
||||
|
||||
Bounds are declared for the client to enforce; see ``Decision`` for why the
|
||||
server does not reject on them yet.
|
||||
"""
|
||||
|
||||
placeholder: str = ""
|
||||
min_length: int = 0
|
||||
max_length: int = 100
|
||||
required: bool = True
|
||||
|
||||
|
||||
@dataclass
|
||||
class CardOption:
|
||||
"""One answer a gate offers, inside the card instead of as a button.
|
||||
|
||||
``id`` is the former standalone action id, unchanged, so an option resolves
|
||||
to exactly the handler kind its button used to.
|
||||
"""
|
||||
|
||||
id: str
|
||||
label: str
|
||||
# The second line under an option. Empty for now: the per-state action table
|
||||
# carries labels only, and writing the copy here is a product decision.
|
||||
description: str = ""
|
||||
# Shown as a DEFAULT badge. Advisory only -- these gates have side effects,
|
||||
# so declining to choose must never apply anything.
|
||||
is_default: bool = False
|
||||
tone: str = "neutral" # neutral | destructive
|
||||
input: OptionInput | None = None
|
||||
next_state: str | None = None
|
||||
canvas_event: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Decision:
|
||||
"""What the current gate asks: card options plus the fixed button pair.
|
||||
|
||||
Replaces the per-state action bar. The client renders ``options`` in the
|
||||
active card, shows only ``confirm`` and ``cancel``, and on confirm posts
|
||||
``confirm`` with ``{"option_id": ..., "free_text": ...}``. ``cancel`` is
|
||||
presentational -- it dismisses without posting and the gate stays open.
|
||||
|
||||
While ``SessionView.actions`` is still populated, the server accepts the old
|
||||
per-action ids too and does not enforce ``OptionInput`` bounds, so a client
|
||||
posting a bare action id keeps working. Enforcement moves server-side when
|
||||
``actions`` goes.
|
||||
"""
|
||||
|
||||
options: list[CardOption] = field(default_factory=list)
|
||||
confirm: Action | None = None
|
||||
cancel: Action | None = None
|
||||
default_option_id: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class CheckpointRef:
|
||||
"""Active restore point on the SessionView (spec §8)."""
|
||||
@@ -320,7 +383,10 @@ class SessionView:
|
||||
conversation_last_seq: int
|
||||
entry_mode: EntryMode = EntryMode.FIX
|
||||
phase: Phase = Phase.UNDERSTAND
|
||||
# DEPRECATED until the web client reads ``decision``: the same choice, in
|
||||
# the standalone-button shape.
|
||||
actions: list[Action] = field(default_factory=list)
|
||||
decision: Decision | None = None
|
||||
active_interaction: ActiveInteraction | None = None
|
||||
checkpoint: CheckpointRef | None = None
|
||||
recovery: RecoveryRef | None = None
|
||||
|
||||
@@ -98,6 +98,30 @@ def _emit_completion(fc: DifyBuilderContext) -> list[ConversationItem]:
|
||||
return append_card(fc, SummaryCard(variant="completion", title="Build complete", rows=rows))
|
||||
|
||||
|
||||
def _refine_app_name(env: Env, fc: DifyBuilderContext) -> None:
|
||||
"""Replace the prompt-derived app name with a model-written one, once (spec N1).
|
||||
|
||||
Creation named the app by cutting the prompt's opening clause -- mechanical,
|
||||
and English-shaped where it has to judge. The goal has just been understood
|
||||
here and a model is in hand, so the name can be rewritten properly, in
|
||||
whatever language the user wrote. Plan approval then freezes it (spec N3).
|
||||
|
||||
The flag is cleared whether or not the proposal was usable, so a session
|
||||
never renames twice and never retries a model that gave nothing. It is
|
||||
committed with the transition while the rename commits on its own, so an
|
||||
advance that fails after this point proposes again next attempt and
|
||||
overwrites with an equivalent title.
|
||||
"""
|
||||
if not fc.app_name_auto:
|
||||
return
|
||||
fc.app_name_auto = False
|
||||
if env.rename_app is None:
|
||||
return
|
||||
proposed = env.agent.propose_app_name(fc.goal_text, fc.requirements)
|
||||
if proposed and proposed.strip():
|
||||
env.rename_app(proposed)
|
||||
|
||||
|
||||
def handle_capability_check(env: Env, turn: Turn, s: Session, fc: DifyBuilderContext) -> StepResult:
|
||||
"""(waiting) Entry state. On ``send_goal`` reset the canvas, analyze the
|
||||
goal into requirements, and transition to build.goal_analysis emitting its
|
||||
@@ -125,6 +149,7 @@ def handle_capability_check(env: Env, turn: Turn, s: Session, fc: DifyBuilderCon
|
||||
analysis = env.agent.analyze_goal(fc.goal_text)
|
||||
fc.form_fields = list(analysis.get("fields") or [])
|
||||
fc.requirements = dict(analysis.get("values") or {})
|
||||
_refine_app_name(env, fc)
|
||||
|
||||
progress.activate("build-prepare-requirements")
|
||||
form_items = append_card(
|
||||
|
||||
@@ -266,6 +266,10 @@ class DifyBuilderContext:
|
||||
resource_selection: dict[str, Any] = field(default_factory=dict)
|
||||
built_node_ids: list[str] = field(default_factory=list)
|
||||
form_fields: list[dict] = field(default_factory=list)
|
||||
# True while the app still carries the name cut from its creating prompt, so
|
||||
# Builder may refine it once (spec N1); cleared the moment it does. Plan
|
||||
# approval freezes the name for good (spec N3, 批准即定名).
|
||||
app_name_auto: bool = False
|
||||
|
||||
# -- Edit fields (Slice 3, additive) --
|
||||
edit_rules: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Name an app after the goal prompt it was created from (App Builder spec, N1).
|
||||
|
||||
Pure stdlib, so the console create path and the Builder engine can both use it.
|
||||
|
||||
Extraction runs inside ``POST /apps``, so it is a clause cut rather than an
|
||||
understanding of the sentence: instant and infallible. Anything needing
|
||||
judgement is left to the Builder's goal-analysis pass, which has a model and the
|
||||
detected reply language -- dropping an imperative lead-in is seeded for English
|
||||
and Chinese only here, and a contentless prompt still yields a literal name
|
||||
rather than the fallback. N3 freezes whatever name approval lands on.
|
||||
"""
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
# Long enough to stay meaningful, short enough for a sidebar card. The spec's
|
||||
# example cut ("Refund approval for ecommerce orders" -> "Refund approval for
|
||||
# ecommerce") is this limit applied at the preceding word boundary.
|
||||
MAX_NAME_LENGTH = 30
|
||||
|
||||
# Where the first clause ends; the rest is elaboration. ASCII terminators count
|
||||
# only at a word break so "v1.5" and "gpt-4o-mini" survive, while CJK ones are
|
||||
# unambiguous alone because CJK text puts no space after them.
|
||||
_CLAUSE_BOUNDARY = re.compile(r"[—–;;\n\r]|[。!?…]|[.!?]+(?=\s|$)")
|
||||
|
||||
# Imperative lead-ins, dropped so the name reads as a thing rather than an
|
||||
# instruction. An unlisted language keeps its lead-in until the Builder renames.
|
||||
_LEAD_INS = (
|
||||
r"i\s+(?:want|need|would\s+like)\s+(?:to\s+)?",
|
||||
r"(?:can|could|would)\s+you\s+(?:please\s+)?",
|
||||
r"please\s+",
|
||||
r"help\s+me\s+(?:to\s+)?",
|
||||
r"let'?s\s+",
|
||||
r"(?:set\s+up|build|create|make|design|generate|write|add|implement)\s+(?:me\s+)?",
|
||||
r"(?:a|an|the)\s+",
|
||||
r"(?:请|帮我|帮忙|我想要|我想|我需要|我要)\s*",
|
||||
r"(?:创建|新建|搭建|生成|设计|编写|做)(?:一个|一份|一套|个)?\s*",
|
||||
r"(?:一个|一份|一套)\s*", # the Chinese article, once a pronoun above is gone
|
||||
)
|
||||
_LEAD_IN_RE = re.compile(r"^(?:" + "|".join(_LEAD_INS) + r")", re.IGNORECASE)
|
||||
|
||||
# Lead-ins nest ("Please help me build an expense report app"); bound the peeling.
|
||||
_MAX_LEAD_IN_PEELS = 6
|
||||
|
||||
# Any Unicode letter or ideograph. Without one there is no name to be had.
|
||||
_HAS_LETTER = re.compile(r"[^\W\d_]")
|
||||
|
||||
# "New app" per console locale (api/constants/languages.py). The fallback fires
|
||||
# when the prompt had no words, so it speaks the console's language.
|
||||
_FALLBACK_STEM: dict[str, str] = {
|
||||
"en-US": "New app",
|
||||
"zh-Hans": "新应用",
|
||||
"zh-Hant": "新應用",
|
||||
"pt-BR": "Novo app",
|
||||
"es-ES": "Nueva aplicación",
|
||||
"fr-FR": "Nouvelle application",
|
||||
"de-DE": "Neue App",
|
||||
"ja-JP": "新しいアプリ",
|
||||
"ko-KR": "새 앱",
|
||||
"lo-LA": "ແອັບໃໝ່",
|
||||
"ru-RU": "Новое приложение",
|
||||
"it-IT": "Nuova app",
|
||||
"uk-UA": "Новий застосунок",
|
||||
"vi-VN": "Ứng dụng mới",
|
||||
"ro-RO": "Aplicație nouă",
|
||||
"pl-PL": "Nowa aplikacja",
|
||||
"hi-IN": "नया ऐप",
|
||||
"tr-TR": "Yeni uygulama",
|
||||
"fa-IR": "برنامه جدید",
|
||||
"sl-SI": "Nova aplikacija",
|
||||
"th-TH": "แอปใหม่",
|
||||
"id-ID": "Aplikasi baru",
|
||||
"ar-TN": "تطبيق جديد",
|
||||
"nl-NL": "Nieuwe app",
|
||||
}
|
||||
_DEFAULT_LANGUAGE = "en-US"
|
||||
|
||||
# Only the stamp's shape varies. Other locales take the English month
|
||||
# abbreviation: unambiguous everywhere, and cheaper to keep right than 24 month
|
||||
# tables for a name meant to be replaced.
|
||||
_CJK_STAMP = frozenset({"zh-Hans", "zh-Hant", "ja-JP"})
|
||||
_MONTH_ABBR = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
|
||||
|
||||
|
||||
def fallback_app_name(now: datetime, language: str = _DEFAULT_LANGUAGE) -> str:
|
||||
"""The name for a prompt with nothing nameable in it: ``New app · Sep 7, 14:02``.
|
||||
|
||||
``now`` is used as given -- pass it in the account's own timezone, since the
|
||||
stamp exists to be recognised by the person who just typed.
|
||||
"""
|
||||
stem = _FALLBACK_STEM.get(language, _FALLBACK_STEM[_DEFAULT_LANGUAGE])
|
||||
if language in _CJK_STAMP:
|
||||
stamp = f"{now.month}月{now.day}日 {now:%H:%M}"
|
||||
elif language == "ko-KR":
|
||||
stamp = f"{now.month}월 {now.day}일 {now:%H:%M}"
|
||||
else:
|
||||
stamp = f"{_MONTH_ABBR[now.month - 1]} {now.day}, {now:%H:%M}"
|
||||
return f"{stem} · {stamp}"
|
||||
|
||||
|
||||
def _first_clause(prompt: str) -> str:
|
||||
return _CLAUSE_BOUNDARY.split(prompt.strip(), maxsplit=1)[0]
|
||||
|
||||
|
||||
def _strip_lead_ins(text: str) -> str:
|
||||
for _ in range(_MAX_LEAD_IN_PEELS):
|
||||
peeled = _LEAD_IN_RE.sub("", text, count=1)
|
||||
# Stop before peeling the name away entirely ("Build me an app" -> "app").
|
||||
if peeled == text or not _HAS_LETTER.search(peeled):
|
||||
return text
|
||||
text = peeled
|
||||
return text
|
||||
|
||||
|
||||
def _truncate(text: str) -> str:
|
||||
if len(text) <= MAX_NAME_LENGTH:
|
||||
return text
|
||||
head = text[:MAX_NAME_LENGTH]
|
||||
# Back off to the preceding word boundary when the cut landed inside a word.
|
||||
# Scripts without spaces (CJK, Thai) have none, and cutting at the character
|
||||
# is already right there.
|
||||
if not text[MAX_NAME_LENGTH].isspace() and (boundary := head.rfind(" ")) > 0:
|
||||
head = head[:boundary]
|
||||
return head.rstrip()
|
||||
|
||||
|
||||
def derive_app_name(prompt: str, *, now: datetime, language: str = _DEFAULT_LANGUAGE) -> str:
|
||||
"""Name an app after the prompt that created it. Never raises."""
|
||||
clause = re.sub(r"\s+", " ", _first_clause(prompt or "")).strip()
|
||||
candidate = _strip_lead_ins(clause)
|
||||
peeled = candidate != clause
|
||||
candidate = _truncate(candidate).strip(" ,.:;·-—–、,。")
|
||||
if not _HAS_LETTER.search(candidate):
|
||||
return fallback_app_name(now, language)
|
||||
if peeled and candidate[:1].islower():
|
||||
# Peeling "Set up an " leaves a fragment mid-sentence-case. Scripts
|
||||
# without case are unaffected.
|
||||
candidate = candidate[0].upper() + candidate[1:]
|
||||
return candidate
|
||||
|
||||
|
||||
def normalize_proposed_name(name: str) -> str:
|
||||
"""Make a model-proposed name safe to store, or "" to keep the derived one.
|
||||
|
||||
The model is asked for a short title but not trusted to have produced one.
|
||||
A refinement that cannot improve on the derived name must not replace it.
|
||||
"""
|
||||
candidate = re.sub(r"\s+", " ", name or "").strip().strip("\"'“”‘’「」『』")
|
||||
candidate = _truncate(candidate).strip()
|
||||
return candidate if _HAS_LETTER.search(candidate) else ""
|
||||
@@ -103,6 +103,11 @@ class PlaceholderAgent:
|
||||
},
|
||||
}
|
||||
|
||||
def propose_app_name(self, goal_text: str, requirements: dict[str, Any]) -> str:
|
||||
# No model, so nothing better than what the create path already cut out
|
||||
# of the prompt. Returning "" leaves that derived name in place.
|
||||
return ""
|
||||
|
||||
def propose_plan_v1(self, requirements: dict[str, Any]) -> list[str]:
|
||||
return [
|
||||
"Ingest source documents",
|
||||
|
||||
@@ -77,6 +77,10 @@ class DifyBuilderAgent(Protocol):
|
||||
|
||||
def analyze_goal(self, goal_text: str) -> dict[str, Any]: ...
|
||||
|
||||
# Short human title for a prompt-created app. Returns the raw proposal; the
|
||||
# service layer normalizes and stores it.
|
||||
def propose_app_name(self, goal_text: str, requirements: dict[str, Any]) -> str: ...
|
||||
|
||||
def propose_plan_v1(self, requirements: dict[str, Any]) -> list[str]: ...
|
||||
|
||||
def discover_resources(self, plan_items: list[str]) -> list[ResourceOption]: ...
|
||||
|
||||
@@ -115,6 +115,11 @@ class Env:
|
||||
# MUST NOT raise: the engine does not guard this call, so the service-layer
|
||||
# implementation is responsible for swallowing its own errors and returning a safe fallback.
|
||||
localize_items: Callable[[list["ConversationItem"], str], list["ConversationItem"]] | None = None
|
||||
# Renames the session's app to a model-proposed title (spec N1). None -> no-op.
|
||||
# MUST NOT raise: the engine does not guard this call, so the service-layer
|
||||
# implementation swallows its own errors -- a failed rename leaves the
|
||||
# derived name in place and never blocks the build.
|
||||
rename_app: Callable[[str], None] | None = None
|
||||
# Correlation metadata for the handler transition currently running.
|
||||
# The runner resets it before every independently committed step.
|
||||
session_id: str = ""
|
||||
|
||||
Reference in new issue
Block a user