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
@@ -22,3 +22,24 @@ class TestCreateAppPayloadMode:
|
||||
def test_rejects_unknown_mode(self):
|
||||
with pytest.raises(ValidationError):
|
||||
CreateAppPayload.model_validate({"name": "X", "mode": "not-a-mode"})
|
||||
|
||||
|
||||
class TestCreateAppPayloadNaming:
|
||||
"""App Builder creates from a prompt, so the client may send no name."""
|
||||
|
||||
def test_accepts_a_prompt_without_a_name(self):
|
||||
payload = CreateAppPayload.model_validate(
|
||||
{"mode": "workflow", "prompt": "Refund approval for ecommerce orders"}
|
||||
)
|
||||
assert payload.name is None
|
||||
assert payload.prompt == "Refund approval for ecommerce orders"
|
||||
|
||||
def test_accepts_neither_name_nor_prompt(self):
|
||||
payload = CreateAppPayload.model_validate({"mode": "workflow"})
|
||||
assert payload.name is None
|
||||
assert payload.prompt is None
|
||||
|
||||
def test_still_rejects_an_empty_name(self):
|
||||
# Omitting the name asks the server to derive one; sending "" is a bug.
|
||||
with pytest.raises(ValidationError):
|
||||
CreateAppPayload.model_validate({"name": "", "mode": "workflow"})
|
||||
@@ -127,7 +127,7 @@ def test_conversation_get_rejects_competing_cursors(monkeypatch):
|
||||
(
|
||||
{"scenario": "build", "app_id": "a1", "goal_text": "Build it"},
|
||||
"create_build_session_stream",
|
||||
{"app_id": "a1", "goal_text": "Build it", "model_config": None},
|
||||
{"app_id": "a1", "goal_text": "Build it", "model_config": None, "derive_app_name": False},
|
||||
),
|
||||
(
|
||||
{"scenario": "edit", "app_id": "a1", "goal_text": "Tighten risk"},
|
||||
@@ -543,3 +543,64 @@ def test_decorator_stack_gate_blocks_when_feature_off(monkeypatch):
|
||||
def test_session_routes_require_legacy_edit_permission(method):
|
||||
gate = unwrap(method, stop=lambda wrapper: "edit_permission_required" in wrapper.__code__.co_qualname)
|
||||
assert "edit_permission_required" in gate.__code__.co_qualname
|
||||
|
||||
|
||||
def test_create_build_defaults_to_not_renaming_the_app(monkeypatch):
|
||||
service = MagicMock()
|
||||
service.create_build_session_stream.return_value = _frames()
|
||||
monkeypatch.setattr(mod, "build_service", lambda: service)
|
||||
|
||||
mod._create({"scenario": "build", "app_id": "a1", "goal_text": "Build it"}, _actor())
|
||||
|
||||
assert service.create_build_session_stream.call_args.kwargs["derive_app_name"] is False
|
||||
|
||||
|
||||
def test_create_build_forwards_the_rename_opt_in(monkeypatch):
|
||||
service = MagicMock()
|
||||
service.create_build_session_stream.return_value = _frames()
|
||||
monkeypatch.setattr(mod, "build_service", lambda: service)
|
||||
|
||||
mod._create(
|
||||
{"scenario": "build", "app_id": "a1", "goal_text": "Build it", "derive_app_name": True},
|
||||
_actor(),
|
||||
)
|
||||
|
||||
assert service.create_build_session_stream.call_args.kwargs["derive_app_name"] is True
|
||||
|
||||
|
||||
def test_action_resolves_confirm_through_the_option_the_client_chose(monkeypatch):
|
||||
service = MagicMock()
|
||||
service.submit_action_stream.return_value = _frames()
|
||||
monkeypatch.setattr(mod, "build_service", lambda: service)
|
||||
|
||||
response = mod._action(
|
||||
"s1",
|
||||
{
|
||||
"action_id": "confirm",
|
||||
"payload": {"option_id": "run_validation", "free_text": ""},
|
||||
"base_version": 1,
|
||||
"base_app_revision": "hash-1",
|
||||
},
|
||||
_actor(),
|
||||
)
|
||||
|
||||
_assert_event_stream(response)
|
||||
|
||||
action = service.submit_action_stream.call_args.args[2]
|
||||
assert action.kind == "run_verify"
|
||||
# The chosen option and any free text travel on to the handler untouched.
|
||||
assert action.payload == {"option_id": "run_validation", "free_text": ""}
|
||||
|
||||
|
||||
def test_action_still_accepts_a_client_posting_the_bare_action_id(monkeypatch):
|
||||
service = MagicMock()
|
||||
service.submit_action_stream.return_value = _frames()
|
||||
monkeypatch.setattr(mod, "build_service", lambda: service)
|
||||
|
||||
mod._action(
|
||||
"s1",
|
||||
{"action_id": "run_validation", "payload": {}, "base_version": 1, "base_app_revision": "hash-1"},
|
||||
_actor(),
|
||||
)
|
||||
|
||||
assert service.submit_action_stream.call_args.args[2].kind == "run_verify"
|
||||
@@ -409,6 +409,9 @@ class StubAgent:
|
||||
def analyze_goal(self, _goal_text):
|
||||
return {}
|
||||
|
||||
def propose_app_name(self, _goal_text, _requirements):
|
||||
return ""
|
||||
|
||||
def propose_plan_v1(self, _requirements):
|
||||
return []
|
||||
|
||||
|
||||
@@ -1332,3 +1332,68 @@ def test_recovery_restart_resets_interrupted_step_to_entry_state():
|
||||
reloaded, fc = repo.get_session(s.id)
|
||||
assert reloaded.current_state == entry_state_for(EntryMode.BUILD) # back at the flow entry
|
||||
assert fc.staged_repair == [] # working fields reset
|
||||
|
||||
|
||||
class _NamingAgent(PlaceholderAgent):
|
||||
"""Placeholder cognition plus a model that has an opinion about the name."""
|
||||
|
||||
def __init__(self, proposal: str = "Expense reimbursement approval") -> None:
|
||||
self.proposal = proposal
|
||||
self.calls: list[tuple[str, dict]] = []
|
||||
|
||||
def propose_app_name(self, goal_text, requirements):
|
||||
self.calls.append((goal_text, dict(requirements)))
|
||||
return self.proposal
|
||||
|
||||
|
||||
def _run_capability_check(agent, *, app_name_auto: bool, rename_app=None):
|
||||
from core.dify_builder.handlers_build import build_registry
|
||||
|
||||
env, repo = _new_env(agent=agent)
|
||||
env.rename_app = rename_app
|
||||
s = _seed_build_session(repo, PcState.BUILD_CAPABILITY_CHECK, app_name_auto=app_name_auto)
|
||||
runner = Runner(env, build_registry())
|
||||
runner.advance(s.id, Turn(action=Action(kind="send_goal", payload={"text": "x"}, base_version=1), actor=_actor()))
|
||||
_session_after, fc = repo.get_session(s.id)
|
||||
return fc
|
||||
|
||||
|
||||
def test_goal_analysis_renames_an_app_still_carrying_its_derived_name():
|
||||
agent = _NamingAgent()
|
||||
renamed: list[str] = []
|
||||
fc = _run_capability_check(agent, app_name_auto=True, rename_app=renamed.append)
|
||||
|
||||
assert renamed == ["Expense reimbursement approval"]
|
||||
# The goal and the just-analyzed requirements are both handed to the model.
|
||||
assert agent.calls[0][0] == "x"
|
||||
assert agent.calls[0][1] == fc.requirements
|
||||
# Cleared, so a later advance through this state never renames again.
|
||||
assert fc.app_name_auto is False
|
||||
|
||||
|
||||
def test_an_app_named_by_its_user_is_never_renamed():
|
||||
agent = _NamingAgent()
|
||||
renamed: list[str] = []
|
||||
fc = _run_capability_check(agent, app_name_auto=False, rename_app=renamed.append)
|
||||
|
||||
assert renamed == []
|
||||
assert agent.calls == []
|
||||
assert fc.app_name_auto is False
|
||||
|
||||
|
||||
def test_a_model_with_no_proposal_leaves_the_derived_name_alone():
|
||||
agent = _NamingAgent(proposal=" ")
|
||||
renamed: list[str] = []
|
||||
fc = _run_capability_check(agent, app_name_auto=True, rename_app=renamed.append)
|
||||
|
||||
assert renamed == []
|
||||
# Still consumed: one shot per session, whether or not it produced anything.
|
||||
assert fc.app_name_auto is False
|
||||
|
||||
|
||||
def test_no_rename_callback_wired_costs_no_model_call():
|
||||
agent = _NamingAgent()
|
||||
fc = _run_capability_check(agent, app_name_auto=True, rename_app=None)
|
||||
|
||||
assert agent.calls == []
|
||||
assert fc.app_name_auto is False
|
||||
@@ -0,0 +1,113 @@
|
||||
"""App names derived from the creating prompt (App Builder spec, board N)."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from core.dify_builder import naming
|
||||
|
||||
NOW = datetime(2026, 9, 7, 14, 2)
|
||||
|
||||
|
||||
def test_derives_the_name_from_the_first_clause():
|
||||
# The spec's own example: the trailing noun is dropped at the word boundary
|
||||
# that keeps the name inside MAX_NAME_LENGTH.
|
||||
assert naming.derive_app_name("Refund approval for ecommerce orders", now=NOW) == "Refund approval for ecommerce"
|
||||
|
||||
|
||||
def test_drops_an_imperative_lead_in_and_recases_the_fragment():
|
||||
assert (
|
||||
naming.derive_app_name(
|
||||
"Set up an expense reimbursement process — check claims against our policy",
|
||||
now=NOW,
|
||||
)
|
||||
== "Expense reimbursement process"
|
||||
)
|
||||
|
||||
|
||||
def test_peels_nested_lead_ins():
|
||||
assert naming.derive_app_name("Please help me build an expense report app", now=NOW) == "Expense report app"
|
||||
|
||||
|
||||
def test_keeps_a_name_that_is_already_a_noun_phrase():
|
||||
assert naming.derive_app_name("Daily ticket summary", now=NOW) == "Daily ticket summary"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("prompt", "expected"),
|
||||
[
|
||||
("帮我创建一个报销审批流程。检查金额并通知经理", "报销审批流程"),
|
||||
("请设计一份文章摘要生成器", "文章摘要生成器"),
|
||||
# A quantifier left behind by the pronoun is peeled like an article.
|
||||
("我要一个报销审批流程", "报销审批流程"),
|
||||
("我想要一套客服机器人", "客服机器人"),
|
||||
],
|
||||
)
|
||||
def test_chinese_prompts_keep_their_own_language(prompt: str, expected: str):
|
||||
# The name is cut out of the prompt, so it needs no translation.
|
||||
assert naming.derive_app_name(prompt, now=NOW) == expected
|
||||
|
||||
|
||||
def test_a_version_or_model_string_is_not_a_clause_boundary():
|
||||
assert naming.derive_app_name("Build a workflow using gpt-4o-mini. Classify tickets.", now=NOW) == (
|
||||
"Workflow using gpt-4o-mini"
|
||||
)
|
||||
|
||||
|
||||
def test_a_cjk_terminator_ends_the_clause_without_a_trailing_space():
|
||||
assert naming.derive_app_name("文章摘要生成器。它读取网页", now=NOW) == "文章摘要生成器"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prompt", ["", " ", "??? !!!", "123 456"])
|
||||
def test_a_prompt_with_nothing_nameable_falls_back(prompt: str):
|
||||
assert naming.derive_app_name(prompt, now=NOW) == "New app · Sep 7, 14:02"
|
||||
|
||||
|
||||
def test_peeling_never_empties_the_name():
|
||||
# "app" is all that is left; peeling the article too would leave nothing.
|
||||
assert naming.derive_app_name("Build me an app", now=NOW) == "App"
|
||||
|
||||
|
||||
def test_a_long_unspaced_name_is_cut_at_the_character():
|
||||
# CJK has no word boundary to back off to, so the cut lands on the limit.
|
||||
prompt = "报" * 50
|
||||
assert naming.derive_app_name(prompt, now=NOW) == "报" * naming.MAX_NAME_LENGTH
|
||||
|
||||
|
||||
def test_the_cut_never_severs_a_word_in_a_spaced_script():
|
||||
name = naming.derive_app_name("Invoices to spreadsheet for my daily expense in company", now=NOW)
|
||||
assert len(name) <= naming.MAX_NAME_LENGTH
|
||||
assert not name.endswith(" ")
|
||||
assert name == "Invoices to spreadsheet for my"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("language", "expected"),
|
||||
[
|
||||
("en-US", "New app · Sep 7, 14:02"),
|
||||
("zh-Hans", "新应用 · 9月7日 14:02"),
|
||||
("ja-JP", "新しいアプリ · 9月7日 14:02"),
|
||||
("ko-KR", "새 앱 · 9월 7일 14:02"),
|
||||
("fr-FR", "Nouvelle application · Sep 7, 14:02"),
|
||||
# An unknown locale takes the English stem rather than raising.
|
||||
("xx-YY", "New app · Sep 7, 14:02"),
|
||||
],
|
||||
)
|
||||
def test_the_fallback_is_localized(language: str, expected: str):
|
||||
assert naming.fallback_app_name(NOW, language) == expected
|
||||
|
||||
|
||||
def test_every_console_locale_has_a_fallback_stem():
|
||||
from constants.languages import languages
|
||||
|
||||
assert set(languages) <= set(naming._FALLBACK_STEM)
|
||||
|
||||
|
||||
def test_normalize_proposed_name_unwraps_and_caps_a_model_answer():
|
||||
assert naming.normalize_proposed_name(' "Expense Reimbursement Approval" ') == "Expense Reimbursement Approval"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proposal", ["", " ", '""', "!!!"])
|
||||
def test_normalize_proposed_name_yields_nothing_for_an_unusable_answer(proposal: str):
|
||||
# "" tells the caller to keep the name already derived from the prompt.
|
||||
assert naming.normalize_proposed_name(proposal) == ""
|
||||
@@ -116,6 +116,9 @@ class _StubAgent:
|
||||
def analyze_goal(self, _goal_text):
|
||||
return {}
|
||||
|
||||
def propose_app_name(self, _goal_text, _requirements):
|
||||
return ""
|
||||
|
||||
def propose_plan_v1(self, _requirements):
|
||||
return []
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1038,3 +1038,49 @@ class TestAgentAppType:
|
||||
assert exc_info.value is error
|
||||
retire_unowned.assert_not_called()
|
||||
enqueue_collection.assert_not_called()
|
||||
|
||||
|
||||
class TestResolveAppName:
|
||||
"""Naming an app created from a goal prompt (App Builder spec, board N)."""
|
||||
|
||||
@staticmethod
|
||||
def _account(*, timezone: str | None = "UTC", language: str | None = "en-US") -> Account:
|
||||
account = Account(name="Namer", email=f"namer-{uuid4()}@example.com")
|
||||
account.timezone = timezone
|
||||
account.interface_language = language
|
||||
return account
|
||||
|
||||
def test_a_user_supplied_name_wins_over_the_prompt(self):
|
||||
# Create-from-blank: the user names the app and Builder only inherits it.
|
||||
params = CreateAppParams(name="Refund approval", prompt="Something else entirely", mode="workflow")
|
||||
assert AppService._resolve_app_name(params, self._account()) == "Refund approval"
|
||||
|
||||
def test_the_name_is_derived_from_the_prompt_when_omitted(self):
|
||||
params = CreateAppParams(prompt="Refund approval for ecommerce orders", mode="workflow")
|
||||
assert AppService._resolve_app_name(params, self._account()) == "Refund approval for ecommerce"
|
||||
|
||||
def test_a_prompt_with_nothing_nameable_falls_back_in_the_console_language(self):
|
||||
params = CreateAppParams(prompt="???", mode="workflow")
|
||||
name = AppService._resolve_app_name(params, self._account(language="zh-Hans"))
|
||||
assert name.startswith("新应用 · ")
|
||||
|
||||
def test_neither_name_nor_prompt_still_names_the_app(self):
|
||||
# Creation must never fail for want of a name.
|
||||
params = CreateAppParams(mode="workflow")
|
||||
assert AppService._resolve_app_name(params, self._account()).startswith("New app · ")
|
||||
|
||||
def test_an_unparseable_account_timezone_does_not_break_creation(self):
|
||||
params = CreateAppParams(prompt=" ", mode="workflow")
|
||||
name = AppService._resolve_app_name(params, self._account(timezone="Mars/Olympus_Mons"))
|
||||
assert name.startswith("New app · ")
|
||||
|
||||
def test_the_fallback_stamp_uses_the_account_timezone(self):
|
||||
params = CreateAppParams(prompt="!!!", mode="workflow")
|
||||
tokyo = AppService._resolve_app_name(params, self._account(timezone="Asia/Tokyo"))
|
||||
honolulu = AppService._resolve_app_name(params, self._account(timezone="Pacific/Honolulu"))
|
||||
# 19 hours apart: the two stamps can never render the same clock time.
|
||||
assert tokyo != honolulu
|
||||
|
||||
def test_only_the_opening_clause_of_a_long_prompt_is_scanned(self):
|
||||
params = CreateAppParams(prompt="Refund approval for ecommerce orders. " + "x" * 50_000, mode="workflow")
|
||||
assert AppService._resolve_app_name(params, self._account()) == "Refund approval for ecommerce"
|
||||
Reference in new issue
Block a user