fix: 修复独立环境登录 404 与「添加第一个模型」500(4.11 回归) (#2755)

* fix(space): keep dedicated-environment Space login working

A dedicated environment runs the OSS runtime with system.edition=cloud. The
process-level 'LangBot Models' compatibility provider is part of the OSS
single-Workspace contract, but write_space_model_providers() skipped creating it
for every non-community edition. The Space OAuth callback then unconditionally
rewarded the provider row by api key, so provider_service raised
WorkspaceNotFoundError('Provider not found') and the whole callback returned 404
-- after the Account and its Workspace had already been created. Every retry
failed the same way, making dedicated-environment login impossible on 4.11.x.

Gate the compatibility provider on the deployment shape instead of the edition
(genuine multi-tenant Cloud runs in CLOUD_RUNTIME persistence and never reaches
this path), and treat a missing provider row as a model-routing warning rather
than an authentication failure so a data anomaly can never block login.

* fix(agent): bind the first model to the 4.11 runner config

create_llm_model() still wrote the auto-selected model into the pre-4.11
ai['local-agent'] container. On a 4.11 Workspace that key does not exist, so the
assignment raised KeyError and POST /provider/models/llm returned 500 the first
time a user added a model -- and the default pipeline kept primary='', so every
Agent run failed with 'No authorized model for local-agent'.

Delegate to RunnerDefaultConfigService, which resolves the selected runner and
writes the schema-defined model selector into ai.runner_config[<runner id>].

Also default the NOT NULL description column on pipeline and bot creation:
omitting an optional description returned a 500 from the constraint instead of
creating the resource.

* fix(agent): keep seeding the model for pipelines that never migrated

set_pipeline_llm_model_if_empty() returns False when a pipeline has no 4.11
runner selected -- that is exactly the un-migrated shape, which still carries
ai.local-agent. Seed that container, but only when it exists, so the legacy path
keeps its old behaviour without the KeyError.
This commit is contained in:
RockChinQ
2026-10-22 23:26:30 +08:00
committed by GitHub
parent da508f9603
commit 7fa9c0e426
9 changed files with 326 additions and 14 deletions
@@ -0,0 +1,106 @@
import json
import sys
import types
from unittest.mock import AsyncMock, Mock
import pytest
from langbot.pkg.api.http.service.model import LLMModelsService
def _service(default_pipeline, runner_service):
app = Mock()
app.persistence_mgr = Mock()
app.persistence_mgr.execute_async = AsyncMock()
result = Mock()
result.first.return_value = default_pipeline
app.persistence_mgr.execute_async.return_value = result
app.runner_default_config_service = runner_service
app.model_mgr = Mock()
app.model_mgr.load_llm_model_with_provider = AsyncMock(return_value=Mock())
app.model_mgr.cache_llm_model = AsyncMock()
app.provider_service = Mock()
app.pipeline_service = Mock()
app.pipeline_service.update_pipeline = AsyncMock()
return LLMModelsService(app)
@pytest.mark.asyncio
async def test_model_creation_delegates_default_pipeline_binding_to_runner_schema(monkeypatch):
"""The pre-4.11 ai['local-agent'] container must never be touched directly.
Assigning into ai['local-agent'] raised KeyError on 4.11 Workspaces, which
turned "add the first model" into a 500 -- and the model never reached the
default pipeline, so every agent run failed with "No authorized model".
"""
pipeline = types.SimpleNamespace(
uuid='pipeline-a', config={'ai': {'runner': {'id': 'plugin:langbot-team/LocalAgent/default'}}}
)
runner_service = Mock()
runner_service.set_pipeline_llm_model_if_empty = AsyncMock(return_value=True)
service = _service(pipeline, runner_service)
monkeypatch.setattr(sys.modules['langbot.pkg.api.http.service.model'], '_require_workspace_provider', AsyncMock())
monkeypatch.setattr(
sys.modules['langbot.pkg.api.http.service.model'], '_assert_cloud_managed_provider_mutable', AsyncMock()
)
monkeypatch.setattr(sys.modules['langbot.pkg.api.http.service.model'], '_validate_provider_supports', AsyncMock())
monkeypatch.setattr(sys.modules['langbot.pkg.api.http.service.model'], '_require_runtime_provider', AsyncMock())
monkeypatch.setattr(
sys.modules['langbot.pkg.api.http.service.model'], '_normalize_llm_reasoning', lambda data: None
)
monkeypatch.setattr(
sys.modules['langbot.pkg.api.http.service.model'], '_validate_llm_reasoning_capability', lambda *a, **k: None
)
uuid_value = await service.create_llm_model(
'workspace-a',
{
'name': 'deepseek-chat',
'provider_uuid': 'provider-a',
'abilities': ['func_call'],
},
)
assert uuid_value
runner_service.set_pipeline_llm_model_if_empty.assert_awaited_once()
args = runner_service.set_pipeline_llm_model_if_empty.await_args.args
assert args[0] == 'workspace-a'
assert args[1] is pipeline
assert args[2] == uuid_value
# No legacy write path should remain.
assert 'local-agent' not in json.dumps(pipeline.config)
@pytest.mark.asyncio
async def test_unmigrated_pipeline_still_gets_a_legacy_model(monkeypatch):
"""A pipeline that has not run the 4.11 migration keeps its old shape."""
pipeline = types.SimpleNamespace(
uuid='pipeline-b',
config={'ai': {'local-agent': {'model': {'primary': '', 'fallbacks': []}}}},
)
runner_service = Mock()
runner_service.set_pipeline_llm_model_if_empty = AsyncMock(return_value=False)
service = _service(pipeline, runner_service)
monkeypatch.setattr(sys.modules['langbot.pkg.api.http.service.model'], '_require_workspace_provider', AsyncMock())
monkeypatch.setattr(
sys.modules['langbot.pkg.api.http.service.model'], '_assert_cloud_managed_provider_mutable', AsyncMock()
)
monkeypatch.setattr(sys.modules['langbot.pkg.api.http.service.model'], '_validate_provider_supports', AsyncMock())
monkeypatch.setattr(sys.modules['langbot.pkg.api.http.service.model'], '_require_runtime_provider', AsyncMock())
monkeypatch.setattr(
sys.modules['langbot.pkg.api.http.service.model'], '_normalize_llm_reasoning', lambda data: None
)
monkeypatch.setattr(
sys.modules['langbot.pkg.api.http.service.model'], '_validate_llm_reasoning_capability', lambda *a, **k: None
)
uuid_value = await service.create_llm_model(
'workspace-a',
{'name': 'deepseek-chat', 'provider_uuid': 'provider-a', 'abilities': ['func_call']},
)
assert pipeline.config['ai']['local-agent']['model']['primary'] == uuid_value
service.ap.pipeline_service.update_pipeline.assert_awaited_once()
@@ -0,0 +1,56 @@
import types
import pytest
from langbot.pkg.api.http.service.pipeline import PipelineService
async def _noop(*args, **kwargs):
return None
@pytest.mark.asyncio
async def test_create_pipeline_defaults_missing_description(monkeypatch):
"""legacy_pipelines.description is NOT NULL; omitting it must not 500."""
captured = {}
app = types.SimpleNamespace()
app.persistence_mgr = types.SimpleNamespace()
app.pipeline_mgr = types.SimpleNamespace(load_pipeline=_noop)
app.ver_mgr = types.SimpleNamespace(get_current_version=lambda: 'v4.11.1')
service = PipelineService.__new__(PipelineService)
service.ap = app
async def fake_get_default_config(context):
runner_id = 'plugin:langbot-team/LocalAgent/default'
return {
'ai': {
'runner': {'id': runner_id},
'runner_config': {runner_id: {'model': {'primary': '', 'fallbacks': []}}},
}
}
async def fake_get_pipelines(context, *args, **kwargs):
return []
async def fake_get_pipeline(context, uuid_value, include_secret=True):
return {'uuid': uuid_value}
async def fake_insert(statement):
captured['statement'] = statement
async def fake_limits(*args, **kwargs):
return {'max_pipelines': -1}
monkeypatch.setattr(service, 'get_default_pipeline_config', fake_get_default_config)
monkeypatch.setattr(service, 'get_pipelines', fake_get_pipelines)
monkeypatch.setattr(service, 'get_pipeline', fake_get_pipeline)
monkeypatch.setattr('langbot.pkg.api.http.service.workspace_limits.workspace_limits', fake_limits)
app.persistence_mgr.execute_async = fake_insert
await service.create_pipeline('workspace-a', {'name': 'de-agent-test'})
params = captured['statement'].compile().params
assert params.get('description') == ''
assert params.get('workspace_uuid') == 'workspace-a'
@@ -925,6 +925,32 @@ class TestUserServiceCreateOrUpdateSpaceUser:
provider_service.update_space_model_provider_api_keys.assert_awaited_once_with('workspace-a', 'owner-api-key')
async def test_oss_space_provider_refresh_tolerates_missing_provider_row(self):
"""A missing provider row must not abort the Space OAuth login."""
from langbot.pkg.workspace.errors import WorkspaceNotFoundError
owner_account = _create_mock_user(email='[email protected]', space_account_uuid='space-owner')
access = SimpleNamespace(
workspace=SimpleNamespace(uuid='workspace-a'),
membership=SimpleNamespace(role='owner'),
)
provider_service = SimpleNamespace(
update_space_model_provider_api_keys=AsyncMock(side_effect=WorkspaceNotFoundError('Provider not found'))
)
logger = SimpleNamespace(warning=Mock())
ap = SimpleNamespace(
workspace_service=SimpleNamespace(policy=SimpleNamespace(multi_workspace_enabled=False)),
workspace_collaboration_service=SimpleNamespace(list_account_workspaces=AsyncMock(return_value=[access])),
provider_service=provider_service,
logger=logger,
)
# Must not raise: authentication already succeeded by this point.
await UserService(ap)._update_space_provider_for_account(owner_account, 'owner-api-key')
provider_service.update_space_model_provider_api_keys.assert_awaited_once_with('workspace-a', 'owner-api-key')
logger.warning.assert_called_once()
async def test_create_or_update_space_user_no_expiry(self):
"""Creates Space user without token expiry."""
# Setup