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:
Charles YaoandClaude Opus 5 committed 2026-09-17 17:55:38 -07:00
1 parent cc9ca8b1dd
commit aa2b4fe4ab
30 files changed
+1163 -18

No files matched your search

@@ -0,0 +1,80 @@
"""Builder-driven app rename: usable proposals only, and never fatal."""
import contextlib
from unittest.mock import MagicMock, patch
import pytest
from services.dify_builder import app_naming
@pytest.fixture
def db_stubbed():
"""Stub the engine so nothing here needs a Flask app context.
Without it the real ``db.engine`` raises, ``rename_app_from_proposal``
swallows that, and every assertion below passes for the wrong reason.
"""
with (
patch.object(app_naming, "db", MagicMock()),
patch.object(app_naming, "sessionmaker") as factory,
):
factory.return_value.return_value = contextlib.nullcontext(MagicMock(name="session"))
yield factory
def test_an_unusable_proposal_never_touches_the_database(db_stubbed):
# No session is opened at all -- the derived name simply stands.
app_naming.rename_app_from_proposal(app_id="a", tenant_id="t", account_id="acc", proposed=' "" ')
db_stubbed.assert_not_called()
@pytest.mark.usefixtures("db_stubbed")
def test_a_usable_proposal_is_normalized_before_it_is_stored():
app = MagicMock()
app.name = "Set up an expense"
with (
patch.object(app_naming, "AppService") as app_service,
patch.object(app_naming, "_load_app", return_value=app),
):
app_naming.rename_app_from_proposal(
app_id="app-1", tenant_id="tenant-1", account_id="acc-1", proposed=' "Expense approval"\n'
)
app_service.return_value.rename_app.assert_called_once()
args, kwargs = app_service.return_value.rename_app.call_args
assert args[1] == "Expense approval"
assert kwargs["account_id"] == "acc-1"
@pytest.mark.usefixtures("db_stubbed")
def test_a_proposal_equal_to_the_current_name_is_not_written():
app = MagicMock()
app.name = "Expense approval"
with (
patch.object(app_naming, "AppService") as app_service,
patch.object(app_naming, "_load_app", return_value=app),
):
app_naming.rename_app_from_proposal(
app_id="app-1", tenant_id="tenant-1", account_id="acc-1", proposed="Expense approval"
)
app_service.return_value.rename_app.assert_not_called()
@pytest.mark.usefixtures("db_stubbed")
def test_a_missing_app_is_not_an_error():
with (
patch.object(app_naming, "AppService") as app_service,
patch.object(app_naming, "_load_app", return_value=None),
):
app_naming.rename_app_from_proposal(app_id="gone", tenant_id="t", account_id="acc", proposed="Anything")
app_service.return_value.rename_app.assert_not_called()
@pytest.mark.usefixtures("db_stubbed")
def test_a_failing_rename_is_swallowed():
# A cosmetic rename must never take the build down with it.
with (
patch.object(app_naming, "AppService", side_effect=RuntimeError("boom")),
patch.object(app_naming, "_load_app", return_value=MagicMock()),
):
app_naming.rename_app_from_proposal(app_id="a", tenant_id="t", account_id="acc", proposed="Expense approval")
@@ -0,0 +1,137 @@
"""A gate's choice as card options plus one fixed button pair.
The action bar used to change shape per gate -- four buttons at review, one at
plan approval. These project the same choice, identically everywhere.
"""
import pytest
from core.dify_builder.contract import CANCEL_ACTION_ID, CONFIRM_ACTION_ID, ActionKind
from core.dify_builder.state import PcState
from services.dify_builder.service import (
_actions_for,
_decision_for,
resolve_action_kind,
resolve_submitted_action,
)
def _decision(state: PcState):
return _decision_for(_actions_for(state))
def test_a_gate_offers_its_actions_as_options_not_buttons():
decision = _decision(PcState.BUILD_REVIEW)
assert [o.id for o in decision.options] == [
"publish_workflow",
"keep_draft",
"continue_adjusting",
"revert",
]
# Whatever the gate, the buttons are the same two.
assert decision.confirm.id == CONFIRM_ACTION_ID
assert decision.cancel.id == CANCEL_ACTION_ID
def test_exactly_one_option_carries_the_default_badge():
decision = _decision(PcState.BUILD_REVIEW)
defaults = [o.id for o in decision.options if o.is_default]
assert defaults == ["publish_workflow"]
assert decision.default_option_id == "publish_workflow"
def test_a_destructive_action_keeps_its_tone_as_an_option():
decision = _decision(PcState.BUILD_REVIEW)
tones = {o.id: o.tone for o in decision.options}
assert tones["revert"] == "destructive"
assert tones["keep_draft"] == "neutral"
def test_an_option_carries_the_state_map_hints_its_action_had():
decision = _decision(PcState.BUILD_REVIEW)
publish = next(o for o in decision.options if o.id == "publish_workflow")
assert publish.next_state == "build.publish"
assert publish.canvas_event == "publish_workflow"
def test_a_single_action_gate_still_becomes_an_option():
decision = _decision(PcState.BUILD_PLAN_APPROVAL)
assert [o.id for o in decision.options] == ["approve_plan"]
assert decision.options[0].is_default is True
def test_a_gate_offering_nothing_has_no_decision():
# Nothing to choose means no card options and no buttons -- not an empty row.
assert _decision_for([]) is None
def test_rejecting_a_repair_asks_for_a_reason():
decision = _decision(PcState.FIX_AWAIT_APPROVAL)
reject = next(o for o in decision.options if o.id == "reject_repair")
assert reject.input is not None
assert (reject.input.min_length, reject.input.max_length) == (10, 200)
assert reject.input.required is True
def test_options_without_free_text_declare_none():
decision = _decision(PcState.FIX_AWAIT_APPROVAL)
approve = next(o for o in decision.options if o.id == "approve_plan")
assert approve.input is None
def test_an_automatic_action_is_never_offered_as_an_option():
from core.dify_builder.contract import Action as UiAction
decision = _decision_for(
[
UiAction(id="visible", label="Visible", kind=ActionKind.PRIMARY),
UiAction(id="auto", label="Auto", kind=ActionKind.AUTOMATIC),
]
)
assert [o.id for o in decision.options] == ["visible"]
def test_only_the_first_primary_is_the_default():
from core.dify_builder.contract import Action as UiAction
decision = _decision_for(
[
UiAction(id="first", label="First", kind=ActionKind.PRIMARY),
UiAction(id="second", label="Second", kind=ActionKind.PRIMARY),
]
)
# Two recommendations is no recommendation.
assert [o.id for o in decision.options if o.is_default] == ["first"]
class TestResolvingWhatTheClientPosted:
def test_confirm_resolves_through_the_named_option(self):
# "publish_fix" is renamed to the handler kind "publish"; the option id
# goes through exactly the map the button id used to.
assert resolve_submitted_action(CONFIRM_ACTION_ID, {"option_id": "publish_fix"}) == "publish"
def test_an_option_id_that_is_already_a_kind_passes_through(self):
assert resolve_submitted_action(CONFIRM_ACTION_ID, {"option_id": "publish_workflow"}) == "publish_workflow"
def test_a_legacy_client_posting_the_action_id_still_resolves(self):
assert resolve_submitted_action("publish_fix", {}) == "publish"
def test_both_contracts_land_on_the_same_kind(self):
for action_id in ("publish_fix", "run_validation", "revert", "restart"):
assert resolve_submitted_action(CONFIRM_ACTION_ID, {"option_id": action_id}) == resolve_action_kind(
action_id
)
@pytest.mark.parametrize("payload", [{}, None, {"option_id": ""}, {"option_id": None}, "not-a-dict"])
def test_confirm_naming_no_option_resolves_to_nothing(self, payload):
# "" is not legal in any state, so the existing per-state check rejects it.
assert resolve_submitted_action(CONFIRM_ACTION_ID, payload) == ""
@@ -0,0 +1,19 @@
"""The one-shot app-name refine flag survives the commit round-trip."""
from core.dify_builder.models import DifyBuilderContext
from services.dify_builder.serde import context_from_dict, context_to_dict
def test_app_name_auto_defaults_off():
# Off by default: an app is only renamed when its creator asked for it.
assert DifyBuilderContext().app_name_auto is False
def test_app_name_auto_round_trips():
fc = DifyBuilderContext(app_name_auto=True)
assert context_from_dict(context_to_dict(fc)).app_name_auto is True
def test_app_name_auto_absent_in_an_older_row_defaults_off():
# Sessions started before this field must not suddenly rename their apps.
assert context_from_dict({"goal_text": "x"}).app_name_auto is False
@@ -238,6 +238,27 @@ def test_create_build_session_rejects_blank_goal(service: DifyBuilderService, en
assert enqueued == []
@pytest.mark.parametrize(("derive", "expected"), [(True, True), (False, False)])
def test_create_build_session_records_whether_builder_may_rename_the_app(
service: DifyBuilderService, repo: SqlDifyBuilderRepository, derive: bool, expected: bool
) -> None:
# The client knows which entry it came from: the homepage prompt (Builder
# renames once) or create-from-blank (the user already named it).
view = service.create_build_session(APP_ID, _actor(), goal_text="Build it", derive_app_name=derive)
_session, fc = repo.get_session(view.session_id)
assert fc.app_name_auto is expected
def test_create_build_session_does_not_rename_by_default(
service: DifyBuilderService, repo: SqlDifyBuilderRepository
) -> None:
view = service.create_build_session(APP_ID, _actor(), goal_text="Build it")
_session, fc = repo.get_session(view.session_id)
assert fc.app_name_auto is False
def test_create_fix_session_converts_valid_checklist_dicts_before_persisting(
service: DifyBuilderService, repo: SqlDifyBuilderRepository
) -> None:
@@ -772,6 +793,32 @@ def test_get_session_view_actions_for_fix_await_decision(
]
def test_session_view_carries_the_same_choice_as_options_and_as_actions(
service: DifyBuilderService, repo: SqlDifyBuilderRepository
) -> None:
s = _seed_session_at(repo, PcState.FIX_AWAIT_DECISION)
view = service.get_session_view(s.id, _actor())
# Both contracts are live while the web client migrates, and they must never
# disagree about what this gate is asking.
assert [o.id for o in view.decision.options] == [a.id for a in view.actions]
assert view.decision.default_option_id == "publish_fix"
assert (view.decision.confirm.id, view.decision.cancel.id) == ("confirm", "cancel")
def test_a_session_view_with_nothing_to_decide_has_no_decision(
service: DifyBuilderService, repo: SqlDifyBuilderRepository
) -> None:
s = _seed_session_at(repo, PcState.BUILD_COMPLETE)
view = service.get_session_view(s.id, _actor())
# A finished session asks nothing, so there is no card to put options in.
assert view.actions == []
assert view.decision is None
def test_get_session_view_actions_for_fix_await_verify(
service: DifyBuilderService, repo: SqlDifyBuilderRepository
) -> None:
@@ -39,6 +39,7 @@ def test_session_view_to_dict_round_trips_fields():
"entry_mode": "fix",
"phase": "understand",
"actions": [],
"decision": None,
"active_interaction": None,
"checkpoint": None,
"recovery": None,