Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(backend): route Linear resolver conversations to claimed org workspaces (#13804)

Hiep Led6a0dd7fe4a7
diff --git a/enterprise/integrations/linear/linear_view.py b/enterprise/integrations/linear/linear_view.py
index dabe80cf60..9a62ac762f 100644
--- a/enterprise/integrations/linear/linear_view.py
+++ b/enterprise/integrations/linear/linear_view.py
@@ -1,25 +1,34 @@
from dataclasses import dataclass
+from uuid import uuid4
from integrations.linear.linear_types import LinearViewInterface, StartingConvoException
from integrations.models import JobContext
+from integrations.resolver_org_router import resolve_org_for_repo
from integrations.utils import CONVERSATION_URL, get_final_agent_observation
from jinja2 import Environment
+from server.config import get_config
from storage.linear_conversation import LinearConversation
from storage.linear_integration_store import LinearIntegrationStore
from storage.linear_user import LinearUser
from storage.linear_workspace import LinearWorkspace
+from storage.saas_conversation_store import SaasConversationStore
from openhands.core.logger import openhands_logger as logger
from openhands.core.schema.agent import AgentState
from openhands.events.action import MessageAction
from openhands.events.serialization.event import event_to_dict
+from openhands.integrations.provider import ProviderHandler
from openhands.server.services.conversation_service import (
- create_new_conversation,
setup_init_conversation_settings,
+ start_conversation,
)
from openhands.server.shared import ConversationStoreImpl, config, conversation_manager
from openhands.server.user_auth.user_auth import UserAuth
-from openhands.storage.data_models.conversation_metadata import ConversationTrigger
+from openhands.storage.data_models.conversation_metadata import (
+ ConversationMetadata,
+ ConversationTrigger,
+)
+from openhands.utils.conversation_summary import get_default_conversation_title
integration_store = LinearIntegrationStore.get_instance()
@@ -61,20 +70,70 @@ class LinearNewConversationView(LinearViewInterface):
instructions, user_msg = await self._get_instructions(jinja_env)
try:
- agent_loop_info = await create_new_conversation(
- user_id=self.linear_user.keycloak_user_id,
- git_provider_tokens=provider_tokens,
+ user_id = self.linear_user.keycloak_user_id
+
+ # Resolve git provider from repository
+ resolved_git_provider = None
+ if provider_tokens:
+ try:
+ provider_handler = ProviderHandler(provider_tokens)
+ repository = await provider_handler.verify_repo_provider(
+ self.selected_repo
+ )
+ resolved_git_provider = repository.git_provider
+ except Exception as e:
+ logger.warning(
+ f'[Linear] Failed to resolve git provider for {self.selected_repo}: {e}'
+ )
+
+ # Resolve target org based on claimed git organizations
+ resolved_org_id = None
+ if resolved_git_provider and self.selected_repo:
+ try:
+ resolved_org_id = await resolve_org_for_repo(
+ provider=resolved_git_provider.value,
+ full_repo_name=self.selected_repo,
+ keycloak_user_id=user_id,
+ )
+ except Exception as e:
+ logger.warning(
+ f'[Linear] Failed to resolve org for {self.selected_repo}: {e}'
+ )
+
+ # Create the conversation store with resolver org routing
+ # (bypasses initialize_conversation to avoid threading enterprise-only
+ # resolver_org_id through the generic OSS interface)
+ store = await SaasConversationStore.get_resolver_instance(
+ get_config(),
+ user_id,
+ resolved_org_id,
+ )
+
+ conversation_id = uuid4().hex
+ conversation_metadata = ConversationMetadata(
+ trigger=ConversationTrigger.LINEAR,
+ conversation_id=conversation_id,
+ title=get_default_conversation_title(conversation_id),
+ user_id=user_id,
selected_repository=self.selected_repo,
selected_branch=None,
+ git_provider=resolved_git_provider,
+ )
+ await store.save_metadata(conversation_metadata)
+
+ await start_conversation(
+ user_id=user_id,
+ git_provider_tokens=provider_tokens,
+ custom_secrets=user_secrets.custom_secrets if user_secrets else None,
initial_user_msg=user_msg,
- conversation_instructions=instructions,
image_urls=None,
replay_json=None,
- conversation_trigger=ConversationTrigger.LINEAR,
- custom_secrets=user_secrets.custom_secrets if user_secrets else None,
+ conversation_id=conversation_id,
+ conversation_metadata=conversation_metadata,
+ conversation_instructions=instructions,
)
- self.conversation_id = agent_loop_info.conversation_id
+ self.conversation_id = conversation_id
logger.info(f'[Linear] Created conversation {self.conversation_id}')
diff --git a/enterprise/tests/unit/integrations/linear/conftest.py b/enterprise/tests/unit/integrations/linear/conftest.py
index 14189cc569..158fa5f8f0 100644
--- a/enterprise/tests/unit/integrations/linear/conftest.py
+++ b/enterprise/tests/unit/integrations/linear/conftest.py
@@ -73,6 +73,7 @@ def sample_user_auth():
"""Create a mock UserAuth for testing."""
user_auth = MagicMock(spec=UserAuth)
user_auth.get_provider_tokens = AsyncMock(return_value={})
+ user_auth.get_secrets = AsyncMock(return_value=MagicMock(custom_secrets={}))
user_auth.get_access_token = AsyncMock(return_value='test_token')
user_auth.get_user_id = AsyncMock(return_value='test_user_id')
return user_auth
diff --git a/enterprise/tests/unit/integrations/linear/test_linear_view.py b/enterprise/tests/unit/integrations/linear/test_linear_view.py
index 09505aa3fc..537f31dd97 100644
--- a/enterprise/tests/unit/integrations/linear/test_linear_view.py
+++ b/enterprise/tests/unit/integrations/linear/test_linear_view.py
@@ -29,27 +29,33 @@ class TestLinearNewConversationView:
assert 'Test Issue' in user_msg
assert 'Fix this bug @openhands' in user_msg
- @patch('integrations.linear.linear_view.create_new_conversation')
+ @patch(
+ 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
+ new_callable=AsyncMock,
+ )
+ @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
@patch('integrations.linear.linear_view.integration_store')
async def test_create_or_update_conversation_success(
self,
- mock_store,
- mock_create_conversation,
+ mock_integration_store,
+ mock_start_convo,
+ mock_get_resolver_instance,
new_conversation_view,
mock_jinja_env,
- mock_agent_loop_info,
):
"""Test successful conversation creation"""
- mock_create_conversation.return_value = mock_agent_loop_info
- mock_store.create_conversation = AsyncMock()
+ mock_store = MagicMock()
+ mock_store.save_metadata = AsyncMock()
+ mock_get_resolver_instance.return_value = mock_store
+ mock_integration_store.create_conversation = AsyncMock()
result = await new_conversation_view.create_or_update_conversation(
mock_jinja_env
)
- assert result == 'conv-123'
- mock_create_conversation.assert_called_once()
- mock_store.create_conversation.assert_called_once()
+ assert result is not None
+ mock_start_convo.assert_called_once()
+ mock_integration_store.create_conversation.assert_called_once()
async def test_create_or_update_conversation_no_repo(
self, new_conversation_view, mock_jinja_env
@@ -60,12 +66,23 @@ class TestLinearNewConversationView:
with pytest.raises(StartingConvoException, match='No repository selected'):
await new_conversation_view.create_or_update_conversation(mock_jinja_env)
- @patch('integrations.linear.linear_view.create_new_conversation')
+ @patch(
+ 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
+ new_callable=AsyncMock,
+ )
+ @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
async def test_create_or_update_conversation_failure(
- self, mock_create_conversation, new_conversation_view, mock_jinja_env
+ self,
+ mock_start_convo,
+ mock_get_resolver_instance,
+ new_conversation_view,
+ mock_jinja_env,
):
"""Test conversation creation failure"""
- mock_create_conversation.side_effect = Exception('Creation failed')
+ mock_store = MagicMock()
+ mock_store.save_metadata = AsyncMock()
+ mock_get_resolver_instance.return_value = mock_store
+ mock_start_convo.side_effect = Exception('Creation failed')
with pytest.raises(
StartingConvoException, match='Failed to create conversation'
@@ -300,43 +317,57 @@ class TestLinearFactory:
class TestLinearViewEdgeCases:
"""Tests for edge cases and error scenarios"""
- @patch('integrations.linear.linear_view.create_new_conversation')
+ @patch(
+ 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
+ new_callable=AsyncMock,
+ )
+ @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
@patch('integrations.linear.linear_view.integration_store')
async def test_conversation_creation_with_no_user_secrets(
self,
- mock_store,
- mock_create_conversation,
+ mock_integration_store,
+ mock_start_convo,
+ mock_get_resolver_instance,
new_conversation_view,
mock_jinja_env,
- mock_agent_loop_info,
):
"""Test conversation creation when user has no secrets"""
- new_conversation_view.saas_user_auth.get_secrets.return_value = None
- mock_create_conversation.return_value = mock_agent_loop_info
- mock_store.create_conversation = AsyncMock()
+ new_conversation_view.saas_user_auth.get_secrets = AsyncMock(return_value=None)
+ mock_store = MagicMock()
+ mock_store.save_metadata = AsyncMock()
+ mock_get_resolver_instance.return_value = mock_store
+ mock_integration_store.create_conversation = AsyncMock()
result = await new_conversation_view.create_or_update_conversation(
mock_jinja_env
)
- assert result == 'conv-123'
- # Verify create_new_conversation was called with custom_secrets=None
- call_kwargs = mock_create_conversation.call_args[1]
+ assert result is not None
+ # Verify start_conversation was called with custom_secrets=None
+ call_kwargs = mock_start_convo.call_args[1]
assert call_kwargs['custom_secrets'] is None
- @patch('integrations.linear.linear_view.create_new_conversation')
+ @patch(
+ 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
+ new_callable=AsyncMock,
+ )
+ @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
@patch('integrations.linear.linear_view.integration_store')
async def test_conversation_creation_store_failure(
self,
- mock_store,
- mock_create_conversation,
+ mock_integration_store,
+ mock_start_convo,
+ mock_get_resolver_instance,
new_conversation_view,
mock_jinja_env,
- mock_agent_loop_info,
):
"""Test conversation creation when store creation fails"""
- mock_create_conversation.return_value = mock_agent_loop_info
- mock_store.create_conversation = AsyncMock(side_effect=Exception('Store error'))
+ mock_store = MagicMock()
+ mock_store.save_metadata = AsyncMock()
+ mock_get_resolver_instance.return_value = mock_store
+ mock_integration_store.create_conversation = AsyncMock(
+ side_effect=Exception('Store error')
+ )
with pytest.raises(
StartingConvoException, match='Failed to create conversation'
diff --git a/enterprise/tests/unit/test_linear_view.py b/enterprise/tests/unit/test_linear_view.py
new file mode 100644
index 0000000000..3eb0dfbfa2
--- /dev/null
+++ b/enterprise/tests/unit/test_linear_view.py
@@ -0,0 +1,347 @@
+"""Tests for Linear resolver org routing logic.
+
+Tests that the LinearNewConversationView correctly resolves the target
+organization and passes resolver_org_id through the V0 conversation path.
+"""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+from uuid import UUID
+
+import pytest
+from integrations.linear.linear_view import LinearNewConversationView
+from integrations.models import JobContext
+from storage.linear_user import LinearUser
+from storage.linear_workspace import LinearWorkspace
+
+from openhands.integrations.service_types import ProviderType
+from openhands.server.user_auth.user_auth import UserAuth
+from openhands.storage.data_models.conversation_metadata import ConversationTrigger
+
+CLAIMING_ORG_ID = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
+KEYCLOAK_USER_ID = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'
+
+
+def mock_linear_user():
+ user = LinearUser()
+ user.id = 1
+ user.keycloak_user_id = KEYCLOAK_USER_ID
+ user.linear_user_id = 'linear-user-123'
+ user.linear_workspace_id = 1
+ user.status = 'active'
+ return user
+
+
+def mock_linear_workspace():
+ workspace = LinearWorkspace()
+ workspace.id = 1
+ workspace.name = 'test-workspace'
+ workspace.linear_org_id = 'linear-org-123'
+ workspace.admin_user_id = 'admin-123'
+ workspace.webhook_secret = 'secret'
+ workspace.svc_acc_email = '[email protected]'
+ workspace.svc_acc_api_key = 'api-key'
+ workspace.status = 'active'
+ return workspace
+
+
+def mock_user_auth():
+ auth = MagicMock(spec=UserAuth)
+ auth.get_provider_tokens = AsyncMock(
+ return_value={ProviderType.GITHUB: MagicMock()}
+ )
+ auth.get_secrets = AsyncMock(return_value=MagicMock(custom_secrets={}))
+ return auth
+
+
+def job_context():
+ return JobContext(
+ issue_id='issue-123',
+ issue_key='PROJ-42',
+ issue_title='Test issue',
+ issue_description='Test description',
+ user_msg='@openhands fix this',
+ user_email='[email protected]',
+ platform_user_id='linear-user-123',
+ workspace_name='test-workspace',
+ display_name='Test User',
+ )
+
+
+def linear_view(job_context, mock_user_auth, mock_linear_user, mock_linear_workspace):
+ return LinearNewConversationView(
+ job_context=job_context,
+ saas_user_auth=mock_user_auth,
+ linear_user=mock_linear_user,
+ linear_workspace=mock_linear_workspace,
+ selected_repo='OpenHands/foo',
+ conversation_id='',
+ )
+
+
+class TestLinearV0OrgRouting:
+ """Test V0 conversation routing logic for Linear resolver."""
+
+ @pytest.mark.asyncio
+ @patch(
+ 'integrations.linear.linear_view.resolve_org_for_repo', new_callable=AsyncMock
+ )
+ @patch('integrations.linear.linear_view.ProviderHandler')
+ @patch(
+ 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
+ new_callable=AsyncMock,
+ )
+ @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
+ @patch(
+ 'integrations.linear.linear_view.integration_store',
+ )
+ async def test_v0_passes_resolver_org_id_to_get_resolver_instance(
+ self,
+ mock_integration_store,
+ mock_start_convo,
+ mock_get_resolver_instance,
+ mock_provider_handler_cls,
+ mock_resolve_org,
+ linear_view,
+ ):
+ """V0 path should resolve org and pass resolver_org_id to get_resolver_instance."""
+ # Arrange
+ mock_repo = MagicMock()
+ mock_repo.git_provider = ProviderType.GITHUB
+ mock_handler = MagicMock()
+ mock_handler.verify_repo_provider = AsyncMock(return_value=mock_repo)
+ mock_provider_handler_cls.return_value = mock_handler
+
+ mock_resolve_org.return_value = CLAIMING_ORG_ID
+ mock_store = MagicMock()
+ mock_store.save_metadata = AsyncMock()
+ mock_get_resolver_instance.return_value = mock_store
+ mock_integration_store.create_conversation = AsyncMock()
+
+ mock_jinja = MagicMock()
+
+ # Act
+ with patch.object(
+ linear_view,
+ '_get_instructions',
+ new_callable=AsyncMock,
+ return_value=('instructions', 'user_msg'),
+ ):
+ await linear_view.create_or_update_conversation(mock_jinja)
+
+ # Assert
+ mock_resolve_org.assert_called_once_with(
+ provider='github',
+ full_repo_name='OpenHands/foo',
+ keycloak_user_id=KEYCLOAK_USER_ID,
+ )
+ call_args = mock_get_resolver_instance.call_args
+ assert call_args[0][1] == KEYCLOAK_USER_ID
+ assert call_args[0][2] == CLAIMING_ORG_ID
+ saved_metadata = mock_store.save_metadata.call_args[0][0]
+ assert saved_metadata.trigger == ConversationTrigger.LINEAR
+ assert saved_metadata.git_provider == ProviderType.GITHUB
+
+ @pytest.mark.asyncio
+ @patch(
+ 'integrations.linear.linear_view.resolve_org_for_repo', new_callable=AsyncMock
+ )
+ @patch('integrations.linear.linear_view.ProviderHandler')
+ @patch(
+ 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
+ new_callable=AsyncMock,
+ )
+ @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
+ @patch(
+ 'integrations.linear.linear_view.integration_store',
+ )
+ async def test_v0_passes_none_when_no_claim(
+ self,
+ mock_integration_store,
+ mock_start_convo,
+ mock_get_resolver_instance,
+ mock_provider_handler_cls,
+ mock_resolve_org,
+ linear_view,
+ ):
+ """When no claim exists, resolver_org_id should be None (personal workspace)."""
+ # Arrange
+ mock_repo = MagicMock()
+ mock_repo.git_provider = ProviderType.GITHUB
+ mock_handler = MagicMock()
+ mock_handler.verify_repo_provider = AsyncMock(return_value=mock_repo)
+ mock_provider_handler_cls.return_value = mock_handler
+
+ mock_resolve_org.return_value = None
+ mock_store = MagicMock()
+ mock_store.save_metadata = AsyncMock()
+ mock_get_resolver_instance.return_value = mock_store
+ mock_integration_store.create_conversation = AsyncMock()
+
+ mock_jinja = MagicMock()
+
+ # Act
+ with patch.object(
+ linear_view,
+ '_get_instructions',
+ new_callable=AsyncMock,
+ return_value=('instructions', 'user_msg'),
+ ):
+ await linear_view.create_or_update_conversation(mock_jinja)
+
+ # Assert
+ call_args = mock_get_resolver_instance.call_args
+ assert call_args[0][2] is None
+
+ @pytest.mark.asyncio
+ @patch(
+ 'integrations.linear.linear_view.resolve_org_for_repo', new_callable=AsyncMock
+ )
+ @patch(
+ 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
+ new_callable=AsyncMock,
+ )
+ @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
+ @patch(
+ 'integrations.linear.linear_view.integration_store',
+ )
+ async def test_no_provider_tokens_skips_org_resolution(
+ self,
+ mock_integration_store,
+ mock_start_convo,
+ mock_get_resolver_instance,
+ mock_resolve_org,
+ linear_view,
+ mock_user_auth,
+ ):
+ """When provider tokens are None, org resolution should be skipped."""
+ # Arrange
+ mock_user_auth.get_provider_tokens = AsyncMock(return_value=None)
+ mock_store = MagicMock()
+ mock_store.save_metadata = AsyncMock()
+ mock_get_resolver_instance.return_value = mock_store
+ mock_integration_store.create_conversation = AsyncMock()
+
+ mock_jinja = MagicMock()
+
+ # Act
+ with patch.object(
+ linear_view,
+ '_get_instructions',
+ new_callable=AsyncMock,
+ return_value=('instructions', 'user_msg'),
+ ):
+ await linear_view.create_or_update_conversation(mock_jinja)
+
+ # Assert
+ mock_resolve_org.assert_not_called()
+ call_args = mock_get_resolver_instance.call_args
+ assert call_args[0][2] is None
+ saved_metadata = mock_store.save_metadata.call_args[0][0]
+ assert saved_metadata.git_provider is None
+
+ @pytest.mark.asyncio
+ @patch(
+ 'integrations.linear.linear_view.resolve_org_for_repo', new_callable=AsyncMock
+ )
+ @patch('integrations.linear.linear_view.ProviderHandler')
+ @patch(
+ 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
+ new_callable=AsyncMock,
+ )
+ @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
+ @patch(
+ 'integrations.linear.linear_view.integration_store',
+ )
+ async def test_verify_repo_provider_failure_falls_back_to_personal_workspace(
+ self,
+ mock_integration_store,
+ mock_start_convo,
+ mock_get_resolver_instance,
+ mock_provider_handler_cls,
+ mock_resolve_org,
+ linear_view,
+ ):
+ """When verify_repo_provider fails, should fall back to personal workspace."""
+ # Arrange
+ mock_handler = MagicMock()
+ mock_handler.verify_repo_provider = AsyncMock(
+ side_effect=Exception('Repository not found')
+ )
+ mock_provider_handler_cls.return_value = mock_handler
+
+ mock_store = MagicMock()
+ mock_store.save_metadata = AsyncMock()
+ mock_get_resolver_instance.return_value = mock_store
+ mock_integration_store.create_conversation = AsyncMock()
+
+ mock_jinja = MagicMock()
+
+ # Act
+ with patch.object(
+ linear_view,
+ '_get_instructions',
+ new_callable=AsyncMock,
+ return_value=('instructions', 'user_msg'),
+ ):
+ await linear_view.create_or_update_conversation(mock_jinja)
+
+ # Assert - org resolution should be skipped, conversation created in personal workspace
+ mock_resolve_org.assert_not_called()
+ call_args = mock_get_resolver_instance.call_args
+ assert call_args[0][2] is None
+
+ @pytest.mark.asyncio
+ @patch(
+ 'integrations.linear.linear_view.resolve_org_for_repo', new_callable=AsyncMock
+ )
+ @patch('integrations.linear.linear_view.ProviderHandler')
+ @patch(
+ 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
+ new_callable=AsyncMock,
+ )
+ @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
+ @patch(
+ 'integrations.linear.linear_view.integration_store',
+ )
+ async def test_resolve_org_failure_falls_back_to_personal_workspace(
+ self,
+ mock_integration_store,
+ mock_start_convo,
+ mock_get_resolver_instance,
+ mock_provider_handler_cls,
+ mock_resolve_org,
+ linear_view,
+ ):
+ """When resolve_org_for_repo fails, should fall back to personal workspace."""
+ # Arrange
+ mock_repo = MagicMock()
+ mock_repo.git_provider = ProviderType.GITHUB
+ mock_handler = MagicMock()
+ mock_handler.verify_repo_provider = AsyncMock(return_value=mock_repo)
+ mock_provider_handler_cls.return_value = mock_handler
+
+ mock_resolve_org.side_effect = Exception('Database connection failed')
+ mock_store = MagicMock()
+ mock_store.save_metadata = AsyncMock()
+ mock_get_resolver_instance.return_value = mock_store
+ mock_integration_store.create_conversation = AsyncMock()
+
+ mock_jinja = MagicMock()
+
+ # Act
+ with patch.object(
+ linear_view,
+ '_get_instructions',
+ new_callable=AsyncMock,
+ return_value=('instructions', 'user_msg'),
+ ):
+ await linear_view.create_or_update_conversation(mock_jinja)
+
+ # Assert - conversation should be created with resolver_org_id=None
+ call_args = mock_get_resolver_instance.call_args
+ assert call_args[0][2] is None