mirror of
https://github.com/All-Hands-AI/OpenHands.git
synced 2026-04-29 03:00:45 -04:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5e0de8ecd | ||
|
|
2209a0713a | ||
|
|
72048be1f3 | ||
|
|
2d65d3517b | ||
|
|
bbaa86b8b7 | ||
|
|
93c567faf0 |
8
.github/CODEOWNERS
vendored
Normal file
8
.github/CODEOWNERS
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
# CODEOWNERS file for OpenHands repository
|
||||
# See https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners
|
||||
|
||||
/frontend/ @amanape @hieptl
|
||||
/openhands-ui/ @amanape @hieptl
|
||||
/openhands/ @tofarr @malhotra5 @hieptl
|
||||
/enterprise/ @chuckbutkus @tofarr @malhotra5
|
||||
/evaluation/ @xingyaoww @neubig
|
||||
62
.github/pull_request_template.md
vendored
62
.github/pull_request_template.md
vendored
@@ -1,46 +1,38 @@
|
||||
<!-- Keep this PR as draft until it is ready for review. -->
|
||||
<!-- If you are still working on the PR, please mark it as draft. Maintainers will review PRs marked ready for review, which leads to lost time if your PR is actually not ready yet. Keep the PR marked as draft until it is finally ready for review -->
|
||||
|
||||
<!-- AI/LLM agents: be concise and specific. Do not check the box below. -->
|
||||
## Summary of PR
|
||||
|
||||
- [ ] A human has tested these changes.
|
||||
<!-- Summarize what the PR does -->
|
||||
|
||||
---
|
||||
## Demo Screenshots/Videos
|
||||
|
||||
## Why
|
||||
<!-- AI/LLM AGENTS: This section is intended for a human author to add screenshots or videos demonstrating the PR in action (optional). While many pull requests may be generated by AI/LLM agents, we are fine with this as long as a human author has reviewed and tested the changes to ensure accuracy and functionality. -->
|
||||
|
||||
<!-- Describe problem, motivation, etc.-->
|
||||
## Change Type
|
||||
|
||||
## Summary
|
||||
|
||||
<!-- 1-3 bullets describing what changed. -->
|
||||
-
|
||||
|
||||
## Issue Number
|
||||
<!-- Required if there is a relevant issue to this PR. -->
|
||||
|
||||
## How to Test
|
||||
|
||||
<!--
|
||||
Required. Share the steps for the reviewer to be able to test your PR. e.g. You can test by running `npm install` then `npm build dev`.
|
||||
|
||||
If you could not test this, say why.
|
||||
-->
|
||||
|
||||
## Video/Screenshots
|
||||
|
||||
<!--
|
||||
Provide a video or screenshots of testing your PR. e.g. you added a new feature to the gui, show us the video of you testing it successfully.
|
||||
|
||||
-->
|
||||
|
||||
## Type
|
||||
<!-- Choose the types that apply to your PR -->
|
||||
|
||||
- [ ] Bug fix
|
||||
- [ ] Feature
|
||||
- [ ] Refactor
|
||||
- [ ] New feature
|
||||
- [ ] Breaking change
|
||||
- [ ] Docs / chore
|
||||
- [ ] Refactor
|
||||
- [ ] Other (dependency update, docs, typo fixes, etc.)
|
||||
|
||||
## Notes
|
||||
## Checklist
|
||||
<!-- AI/LLM AGENTS: This checklist is for a human author to complete. Do NOT check either of the two boxes below. Leave them unchecked until a human has personally reviewed and tested the changes. -->
|
||||
|
||||
<!-- Optional: migrations, config changes, rollout concerns, follow-ups, or anything reviewers should know. -->
|
||||
- [ ] I have read and reviewed the code and I understand what the code is doing.
|
||||
- [ ] I have tested the code to the best of my ability and ensured it works as expected.
|
||||
|
||||
## Fixes
|
||||
|
||||
<!-- If this resolves an issue, link it here so it will close automatically upon merge. -->
|
||||
|
||||
Resolves #(issue)
|
||||
|
||||
## Release Notes
|
||||
|
||||
<!-- Check the box if this change is worth adding to the release notes. If checked, you must provide an
|
||||
end-user friendly description for your change below the checkbox. -->
|
||||
|
||||
- [ ] Include this change in the Release Notes.
|
||||
|
||||
2
.github/workflows/check-package-versions.yml
vendored
2
.github/workflows/check-package-versions.yml
vendored
@@ -12,7 +12,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
|
||||
2
.github/workflows/e2e-tests.yml
vendored
2
.github/workflows/e2e-tests.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install poetry via pipx
|
||||
uses: abatilo/actions-poetry@v4
|
||||
|
||||
@@ -10,7 +10,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout PR branch
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
fetch-depth: 0
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Find Comment
|
||||
uses: peter-evans/find-comment@v4
|
||||
uses: peter-evans/find-comment@v3
|
||||
id: find-comment
|
||||
with:
|
||||
issue-number: ${{ github.event.pull_request.number }}
|
||||
|
||||
8
.github/workflows/fe-e2e-tests.yml
vendored
8
.github/workflows/fe-e2e-tests.yml
vendored
@@ -17,20 +17,18 @@ concurrency:
|
||||
jobs:
|
||||
fe-e2e-test:
|
||||
name: FE E2E Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [22]
|
||||
fail-fast: true
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: useblacksmith/setup-node@v5
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- name: Install dependencies
|
||||
working-directory: ./frontend
|
||||
run: npm ci
|
||||
|
||||
8
.github/workflows/fe-unit-tests.yml
vendored
8
.github/workflows/fe-unit-tests.yml
vendored
@@ -21,20 +21,18 @@ jobs:
|
||||
# Run frontend unit tests
|
||||
fe-test:
|
||||
name: FE Unit Tests
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [22]
|
||||
fail-fast: true
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: useblacksmith/setup-node@v5
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- name: Install dependencies
|
||||
working-directory: ./frontend
|
||||
run: npm ci
|
||||
|
||||
29
.github/workflows/ghcr-build.yml
vendored
29
.github/workflows/ghcr-build.yml
vendored
@@ -30,7 +30,7 @@ env:
|
||||
|
||||
jobs:
|
||||
define-matrix:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: blacksmith
|
||||
outputs:
|
||||
base_image: ${{ steps.define-base-images.outputs.base_image }}
|
||||
platforms: ${{ steps.define-base-images.outputs.platforms }}
|
||||
@@ -57,7 +57,7 @@ jobs:
|
||||
# Builds the OpenHands Docker images
|
||||
ghcr_build_app:
|
||||
name: Build App Image
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
if: "!(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/ext-v'))"
|
||||
needs: define-matrix
|
||||
permissions:
|
||||
@@ -65,7 +65,7 @@ jobs:
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
- name: Set up QEMU
|
||||
@@ -92,7 +92,7 @@ jobs:
|
||||
# Builds the runtime Docker images
|
||||
ghcr_build_runtime:
|
||||
name: Build Runtime Image
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2204
|
||||
if: "!(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/ext-v'))"
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -103,7 +103,7 @@ jobs:
|
||||
base_image: ${{ fromJson(needs.define-matrix.outputs.base_image) }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
- name: Set up QEMU
|
||||
@@ -122,7 +122,7 @@ jobs:
|
||||
- name: Install poetry via pipx
|
||||
run: pipx install poetry
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
uses: useblacksmith/setup-python@v6
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: poetry
|
||||
@@ -149,7 +149,7 @@ jobs:
|
||||
echo "DOCKER_BUILD_ARGS=$(echo "$DOCKER_BUILD_JSON" | jq -r '.build_args | join(",")')" >> $GITHUB_ENV
|
||||
- name: Build and push runtime image ${{ matrix.base_image.image }}
|
||||
if: github.event.pull_request.head.repo.fork != true
|
||||
uses: docker/build-push-action@v6
|
||||
uses: useblacksmith/build-push-action@v1
|
||||
with:
|
||||
push: true
|
||||
tags: ${{ env.DOCKER_TAGS }}
|
||||
@@ -163,7 +163,7 @@ jobs:
|
||||
# Forked repos can't push to GHCR, so we just build in order to populate the cache for rebuilding
|
||||
- name: Build runtime image ${{ matrix.base_image.image }} for fork
|
||||
if: github.event.pull_request.head.repo.fork
|
||||
uses: docker/build-push-action@v6
|
||||
uses: useblacksmith/build-push-action@v1
|
||||
with:
|
||||
tags: ghcr.io/${{ env.REPO_OWNER }}/runtime:${{ env.RELEVANT_SHA }}-${{ matrix.base_image.tag }}
|
||||
context: containers/runtime
|
||||
@@ -176,7 +176,7 @@ jobs:
|
||||
|
||||
ghcr_build_enterprise:
|
||||
name: Push Enterprise Image
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2204
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
@@ -185,7 +185,7 @@ jobs:
|
||||
if: github.event.pull_request.head.repo.fork != true
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
|
||||
@@ -215,7 +215,6 @@ jobs:
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=semver,pattern={{major}}
|
||||
type=match,pattern=cloud-\d+\.\d+\.\d+
|
||||
flavor: |
|
||||
latest=auto
|
||||
prefix=
|
||||
@@ -229,7 +228,7 @@ jobs:
|
||||
# rather than a mutable branch tag like "main" which can serve stale cached layers.
|
||||
echo "OPENHANDS_DOCKER_TAG=${RELEVANT_SHA}" >> $GITHUB_ENV
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
uses: useblacksmith/build-push-action@v1
|
||||
with:
|
||||
context: .
|
||||
file: enterprise/Dockerfile
|
||||
@@ -248,7 +247,7 @@ jobs:
|
||||
# We can remove this once the config changes
|
||||
runtime_tests_check_success:
|
||||
name: All Runtime Tests Passed
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
steps:
|
||||
- name: All tests passed
|
||||
run: echo "All runtime tests have passed successfully!"
|
||||
@@ -257,10 +256,10 @@ jobs:
|
||||
name: Update PR Description
|
||||
if: github.event_name == 'pull_request' && !github.event.pull_request.head.repo.fork && github.actor != 'dependabot[bot]'
|
||||
needs: [ghcr_build_runtime]
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Get short SHA
|
||||
id: short_sha
|
||||
|
||||
19
.github/workflows/lint-fix.yml
vendored
19
.github/workflows/lint-fix.yml
vendored
@@ -9,12 +9,12 @@ jobs:
|
||||
lint-fix-frontend:
|
||||
if: github.event.label.name == 'lint-fix'
|
||||
name: Fix frontend linting issues
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.head_ref }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
@@ -22,14 +22,13 @@ jobs:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install Node.js 22
|
||||
uses: actions/setup-node@v4
|
||||
uses: useblacksmith/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- name: Install frontend dependencies
|
||||
working-directory: ./frontend
|
||||
run: npm ci
|
||||
run: |
|
||||
cd frontend
|
||||
npm install --frozen-lockfile
|
||||
- name: Generate i18n and route types
|
||||
run: |
|
||||
cd frontend
|
||||
@@ -59,12 +58,12 @@ jobs:
|
||||
lint-fix-python:
|
||||
if: github.event.label.name == 'lint-fix'
|
||||
name: Fix Python linting issues
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.head_ref }}
|
||||
repository: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
@@ -72,7 +71,7 @@ jobs:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Set up python
|
||||
uses: actions/setup-python@v5
|
||||
uses: useblacksmith/setup-python@v6
|
||||
with:
|
||||
python-version: 3.12
|
||||
cache: "pip"
|
||||
|
||||
27
.github/workflows/lint.yml
vendored
27
.github/workflows/lint.yml
vendored
@@ -19,35 +19,34 @@ jobs:
|
||||
# Run lint on the frontend code
|
||||
lint-frontend:
|
||||
name: Lint frontend
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Node.js 22
|
||||
uses: actions/setup-node@v4
|
||||
uses: useblacksmith/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- name: Install dependencies
|
||||
working-directory: ./frontend
|
||||
run: npm ci
|
||||
run: |
|
||||
cd frontend
|
||||
npm install --frozen-lockfile
|
||||
- name: Lint, TypeScript compilation, and translation checks
|
||||
run: |
|
||||
cd frontend
|
||||
npm run lint
|
||||
npm run make-i18n && npx tsc
|
||||
npm run make-i18n && tsc
|
||||
npm run check-translation-completeness
|
||||
|
||||
# Run lint on the python code
|
||||
lint-python:
|
||||
name: Lint python
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Set up python
|
||||
uses: actions/setup-python@v5
|
||||
uses: useblacksmith/setup-python@v6
|
||||
with:
|
||||
python-version: 3.12
|
||||
cache: "pip"
|
||||
@@ -58,13 +57,13 @@ jobs:
|
||||
|
||||
lint-enterprise-python:
|
||||
name: Lint enterprise python
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Set up python
|
||||
uses: actions/setup-python@v5
|
||||
uses: useblacksmith/setup-python@v6
|
||||
with:
|
||||
python-version: 3.12
|
||||
cache: "pip"
|
||||
|
||||
8
.github/workflows/npm-publish-ui.yml
vendored
8
.github/workflows/npm-publish-ui.yml
vendored
@@ -18,7 +18,7 @@ concurrency:
|
||||
jobs:
|
||||
check-version:
|
||||
name: Check if version has changed
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
current-version: ${{ steps.version-check.outputs.current-version }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 2 # Need previous commit to compare
|
||||
|
||||
@@ -55,7 +55,7 @@ jobs:
|
||||
|
||||
publish:
|
||||
name: Publish to npm
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
needs: check-version
|
||||
if: needs.check-version.outputs.should-publish == 'true'
|
||||
defaults:
|
||||
@@ -63,7 +63,7 @@ jobs:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
|
||||
2
.github/workflows/openhands-resolver.yml
vendored
2
.github/workflows/openhands-resolver.yml
vendored
@@ -86,7 +86,7 @@ jobs:
|
||||
runs-on: "${{ inputs.runner || 'ubuntu-latest' }}"
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
|
||||
2
.github/workflows/pr-review-evaluation.yml
vendored
2
.github/workflows/pr-review-evaluation.yml
vendored
@@ -28,7 +28,7 @@ jobs:
|
||||
steps:
|
||||
- name: Download review trace artifact
|
||||
id: download-trace
|
||||
uses: dawidd6/action-download-artifact@v15
|
||||
uses: dawidd6/action-download-artifact@v6
|
||||
continue-on-error: true
|
||||
with:
|
||||
workflow: pr-review-by-openhands.yml
|
||||
|
||||
20
.github/workflows/py-tests.yml
vendored
20
.github/workflows/py-tests.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
# Run python tests on Linux
|
||||
test-on-linux:
|
||||
name: Python Tests on Linux
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
env:
|
||||
INSTALL_DOCKER: "0" # Set to '0' to skip Docker installation
|
||||
strategy:
|
||||
@@ -30,22 +30,20 @@ jobs:
|
||||
pull-requests: write
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Install tmux
|
||||
run: sudo apt-get update && sudo apt-get install -y tmux
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: useblacksmith/setup-node@v5
|
||||
with:
|
||||
node-version: "22.x"
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- name: Install poetry via pipx
|
||||
run: pipx install poetry
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
uses: useblacksmith/setup-python@v6
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: "poetry"
|
||||
@@ -75,16 +73,16 @@ jobs:
|
||||
|
||||
test-enterprise:
|
||||
name: Enterprise Python Unit Tests
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.12"]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install poetry via pipx
|
||||
run: pipx install poetry
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
uses: useblacksmith/setup-python@v6
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: "poetry"
|
||||
@@ -113,9 +111,9 @@ jobs:
|
||||
pull-requests: write
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/download-artifact@v7
|
||||
- uses: actions/download-artifact@v6
|
||||
id: download
|
||||
with:
|
||||
pattern: coverage-*
|
||||
|
||||
10
.github/workflows/pypi-release.yml
vendored
10
.github/workflows/pypi-release.yml
vendored
@@ -17,14 +17,14 @@ on:
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-22.04
|
||||
# Run when manually dispatched for "app server" OR for tag pushes that don't contain '-cli' and don't start with 'cloud-'
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
# Run when manually dispatched for "app server" OR for tag pushes that don't contain '-cli'
|
||||
if: |
|
||||
(github.event_name == 'workflow_dispatch' && github.event.inputs.reason == 'app server')
|
||||
|| (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') && !contains(github.ref, '-cli') && !startsWith(github.ref, 'refs/tags/cloud-'))
|
||||
|| (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') && !contains(github.ref, '-cli'))
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/checkout@v4
|
||||
- uses: useblacksmith/setup-python@v6
|
||||
with:
|
||||
python-version: 3.12
|
||||
- name: Install Poetry
|
||||
|
||||
4
.github/workflows/stale.yml
vendored
4
.github/workflows/stale.yml
vendored
@@ -8,10 +8,10 @@ on:
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
if: github.repository == 'OpenHands/OpenHands'
|
||||
steps:
|
||||
- uses: actions/stale@v10
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
stale-issue-message: 'This issue is stale because it has been open for 40 days with no activity. Remove the stale label or leave a comment, otherwise it will be closed in 10 days.'
|
||||
stale-pr-message: 'This PR is stale because it has been open for 40 days with no activity. Remove the stale label or leave a comment, otherwise it will be closed in 10 days.'
|
||||
|
||||
4
.github/workflows/ui-build.yml
vendored
4
.github/workflows/ui-build.yml
vendored
@@ -19,10 +19,10 @@ concurrency:
|
||||
jobs:
|
||||
ui-build:
|
||||
name: Build openhands-ui
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2204
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: "openhands-ui/.bun-version"
|
||||
|
||||
36
AGENTS.md
36
AGENTS.md
@@ -36,42 +36,6 @@ then re-run the command to ensure it passes. Common issues include:
|
||||
- Be especially careful with `git reset --hard` after staging files, as it will remove accidentally staged files
|
||||
- When remote has new changes, use `git fetch upstream && git rebase upstream/<branch>` on the same branch
|
||||
|
||||
## Lockfile Regeneration (Preserve Original Tool Versions)
|
||||
|
||||
When regenerating lockfiles (poetry.lock, uv.lock, etc.), you MUST use the same tool version that originally generated the lockfile to avoid unnecessary diff noise. Each lockfile contains a version header indicating which tool version was used.
|
||||
|
||||
### Poetry (poetry.lock)
|
||||
|
||||
1. Extract the version from the lockfile header:
|
||||
```bash
|
||||
POETRY_VERSION=$(grep -m1 "^# This file is automatically @generated by Poetry" poetry.lock | sed 's/.*Poetry \([0-9.]*\).*/\1/')
|
||||
```
|
||||
2. If a version is found, install that specific version:
|
||||
```bash
|
||||
pipx install poetry==$POETRY_VERSION --force
|
||||
```
|
||||
3. Then regenerate the lockfile:
|
||||
```bash
|
||||
poetry lock --no-update
|
||||
```
|
||||
|
||||
### uv (uv.lock)
|
||||
|
||||
1. Extract the version from the lockfile header:
|
||||
```bash
|
||||
UV_VERSION=$(grep -m1 "^# This file was autogenerated by uv" uv.lock | sed 's/.*uv version \([0-9.]*\).*/\1/')
|
||||
```
|
||||
2. If a version is found, install that specific version:
|
||||
```bash
|
||||
pipx install uv==$UV_VERSION --force
|
||||
```
|
||||
3. Then regenerate the lockfile:
|
||||
```bash
|
||||
uv lock
|
||||
```
|
||||
|
||||
This ensures that lockfile updates only contain actual dependency changes, not tool version migration artifacts.
|
||||
|
||||
## PR-Specific Artifacts (`.pr/` directory)
|
||||
|
||||
When working on a PR that requires design documents, scripts meant for development-only, or other temporary artifacts that should NOT be merged to main, store them in a `.pr/` directory at the repository root.
|
||||
|
||||
@@ -127,14 +127,14 @@ For example, a PR title could be:
|
||||
|
||||
## Becoming a Maintainer
|
||||
|
||||
For contributors who have made significant and sustained contributions to the project, there is a possibility of joining the maintainer team.
|
||||
Contributors who have opened three meaningful PRs to the project may be eligible to join the maintainer team.
|
||||
The process for this is as follows:
|
||||
|
||||
1. Any contributor who has made sustained and high-quality contributions to the codebase can be nominated by any maintainer. If you feel that you may qualify you can reach out to any of the maintainers that have reviewed your PRs and ask if you can be nominated.
|
||||
1. Any contributor who has opened three meaningful PRs to the codebase can be nominated by any maintainer. If you feel that you may qualify, you can reach out to any of the maintainers that have reviewed your PRs and ask if you can be nominated.
|
||||
2. Once a maintainer nominates a new maintainer, there will be a discussion period among the maintainers for at least 3 days.
|
||||
3. If no concerns are raised the nomination will be accepted by acclamation, and if concerns are raised there will be a discussion and possible vote.
|
||||
|
||||
Note that just making many PRs does not immediately imply that you will become a maintainer. We will be looking at sustained high-quality contributions over a period of time, as well as good teamwork and adherence to our [Code of Conduct](./CODE_OF_CONDUCT.md).
|
||||
Note that opening three meaningful PRs does not automatically mean that you will become a maintainer. We will also be looking at good teamwork and adherence to our [Code of Conduct](./CODE_OF_CONDUCT.md).
|
||||
|
||||
## Need Help?
|
||||
|
||||
|
||||
77
README.md
77
README.md
@@ -26,7 +26,6 @@
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
|
||||
🙌 Welcome to OpenHands, a [community](COMMUNITY.md) focused on AI-driven development. We’d love for you to [join us on Slack](https://dub.sh/openhands).
|
||||
|
||||
There are a few ways to work with OpenHands:
|
||||
@@ -86,68 +85,20 @@ If you need help with anything, or just want to chat, [come find us on Slack](ht
|
||||
|
||||
<hr>
|
||||
|
||||
### Thank You to Our Contributors
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](https://github.com/OpenHands/OpenHands/graphs/contributors)
|
||||
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
|
||||
### Trusted by Engineers at
|
||||
|
||||
<div align="center">
|
||||
<strong>Trusted by engineers at</strong>
|
||||
<br/><br/>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/tiktok.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/tiktok.svg" alt="TikTok" height="17" hspace="5">
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/vmware.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/vmware.svg" alt="VMware" height="17" hspace="5">
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/roche.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/roche.svg" alt="Roche" height="17" hspace="5">
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/amazon.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/amazon.svg" alt="Amazon" height="17" hspace="5">
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/c3-ai.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/c3-ai.svg" alt="C3 AI" height="17" hspace="5">
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/netflix.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/netflix.svg" alt="Netflix" height="17" hspace="5">
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/mastercard.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/mastercard.svg" alt="Mastercard" height="17" hspace="5">
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/red-hat.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/red-hat.svg" alt="Red Hat" height="17" hspace="5">
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/mongodb.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/mongodb.svg" alt="MongoDB" height="17" hspace="5">
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/apple.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/apple.svg" alt="Apple" height="17" hspace="5">
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/nvidia.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/nvidia.svg" alt="NVIDIA" height="17" hspace="5">
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://assets.openhands.dev/logos/external/white/google.svg">
|
||||
<img src="https://assets.openhands.dev/logos/external/black/google.svg" alt="Google" height="17" hspace="5">
|
||||
</picture>
|
||||
</div>
|
||||
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137f6974b71a1a4a932f82_TikTok_logo.svg" alt="TikTok" height="40">
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137f523b08f91a5aa905b9_Vmware.svg" alt="VMware" height="40">
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137f2cb537758796a9dba1_Roche_Logo.svg" alt="Roche" height="40">
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137f10c3975e28b3932320_Amazon_logo%201.svg" alt="Amazon" height="40">
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137ec5a6f77dd174e557ce_C3ai_logo%201.svg" alt="C3 AI" height="40">
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137eac8f27ca27f5e48420_Netflix_2015_logo%201.svg" alt="Netflix" height="40">
|
||||
<br/>
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137e8df2c028b9e1506ede_mastercard%201.svg" alt="Mastercard" height="40">
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137e783790933dd06f9d59_Red_Hat_Logo_2019%201.svg" alt="Red Hat" height="40">
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137e5fa006d963a1d1904d_mongodb-ar21%201.svg" alt="MongoDB" height="40">
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137e47b45195da10c50f49_apple-11%201.svg" alt="Apple" height="40">
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137e34e3a5ab71e37082a7_NVIDIA_logo%201.svg" alt="NVIDIA" height="40">
|
||||
<img src="https://cdn.prod.website-files.com/68ff4058b35616cdd47d5b59/69137e199ce2cb594b0210ab_google-ar21%201.svg" alt="Google" height="40">
|
||||
</div>
|
||||
|
||||
@@ -20,11 +20,9 @@ ENV POETRY_NO_INTERACTION=1 \
|
||||
POETRY_VIRTUALENVS_CREATE=1 \
|
||||
POETRY_CACHE_DIR=/tmp/poetry_cache
|
||||
|
||||
# Pin Poetry version to match the version used to generate poetry.lock
|
||||
ARG POETRY_VERSION=2.3.3
|
||||
RUN apt-get update -y \
|
||||
&& apt-get install -y curl make git build-essential jq gettext \
|
||||
&& python3 -m pip install "poetry==${POETRY_VERSION}" --break-system-packages
|
||||
&& python3 -m pip install poetry --break-system-packages
|
||||
|
||||
COPY pyproject.toml poetry.lock ./
|
||||
RUN touch README.md
|
||||
@@ -52,7 +50,7 @@ RUN mkdir -p $FILE_STORE_PATH
|
||||
RUN mkdir -p $WORKSPACE_BASE
|
||||
|
||||
RUN apt-get update -y \
|
||||
&& apt-get install -y curl git ssh sudo \
|
||||
&& apt-get install -y curl ssh sudo \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Default is 1000, but OSX is often 501
|
||||
@@ -75,17 +73,6 @@ ENV VIRTUAL_ENV=/app/.venv \
|
||||
|
||||
COPY --chown=openhands:openhands --chmod=770 --from=backend-builder ${VIRTUAL_ENV} ${VIRTUAL_ENV}
|
||||
|
||||
# Pin pip to a known-good version (reproducible builds) and fix CVE-2025-8869
|
||||
# Pin both venv pip and system pip (Trivy scans both)
|
||||
# - `python -m pip` uses the venv because `PATH` is prefixed with `${VIRTUAL_ENV}/bin`
|
||||
# - `/usr/local/bin/python3 -m pip` uses the system interpreter regardless of `PATH`
|
||||
ARG PIP_VERSION=26.0.1
|
||||
RUN python -m pip install --no-cache-dir "pip==${PIP_VERSION}"
|
||||
|
||||
USER root
|
||||
RUN /usr/local/bin/python3 -m pip install --no-cache-dir "pip==${PIP_VERSION}" --break-system-packages
|
||||
USER openhands
|
||||
|
||||
COPY --chown=openhands:openhands --chmod=770 ./skills ./skills
|
||||
COPY --chown=openhands:openhands --chmod=770 ./openhands ./openhands
|
||||
COPY --chown=openhands:openhands --chmod=777 ./openhands/runtime/plugins ./openhands/runtime/plugins
|
||||
|
||||
@@ -58,8 +58,6 @@ repos:
|
||||
types-Markdown,
|
||||
pydantic,
|
||||
lxml,
|
||||
"openhands-sdk==1.14",
|
||||
"openhands-tools==1.14",
|
||||
]
|
||||
# To see gaps add `--html-report mypy-report/`
|
||||
entry: mypy --config-file dev_config/python/mypy.ini openhands/
|
||||
|
||||
@@ -14,11 +14,3 @@ exclude = (third_party/|enterprise/)
|
||||
|
||||
[mypy-openhands.memory.condenser.impl.*]
|
||||
disable_error_code = override
|
||||
|
||||
[mypy-openai.*]
|
||||
follow_imports = skip
|
||||
ignore_missing_imports = True
|
||||
|
||||
[mypy-litellm.*]
|
||||
follow_imports = skip
|
||||
ignore_missing_imports = True
|
||||
|
||||
@@ -723,13 +723,11 @@
|
||||
"https://$WEB_HOST/slack/keycloak-callback",
|
||||
"https://$WEB_HOST/oauth/device/keycloak-callback",
|
||||
"https://$WEB_HOST/api/email/verified",
|
||||
"/realms/$KEYCLOAK_REALM_NAME/$KEYCLOAK_CLIENT_ID/*",
|
||||
"https://laminar.$WEB_HOST/api/auth/callback/keycloak"
|
||||
"/realms/$KEYCLOAK_REALM_NAME/$KEYCLOAK_CLIENT_ID/*"
|
||||
],
|
||||
"webOrigins": [
|
||||
"https://$WEB_HOST",
|
||||
"https://$AUTH_WEB_HOST",
|
||||
"https://laminar.$WEB_HOST"
|
||||
"https://$AUTH_WEB_HOST"
|
||||
],
|
||||
"notBefore": 0,
|
||||
"bearerOnly": false,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from types import MappingProxyType
|
||||
|
||||
from github import Auth, Github, GithubIntegration
|
||||
from lmnr import Laminar
|
||||
from integrations.github.data_collector import GitHubDataCollector
|
||||
from integrations.github.github_solvability import summarize_issue_solvability
|
||||
from integrations.github.github_view import (
|
||||
@@ -38,7 +37,6 @@ from server.utils.conversation_callback_utils import register_callback_processor
|
||||
from openhands.core.logger import openhands_logger as logger
|
||||
from openhands.integrations.provider import ProviderToken, ProviderType
|
||||
from openhands.integrations.service_types import AuthenticationError
|
||||
from openhands.sdk.observability import init_laminar_for_external
|
||||
from openhands.server.types import (
|
||||
LLMAuthenticationError,
|
||||
MissingSettingsError,
|
||||
@@ -331,9 +329,6 @@ class GithubManager(Manager[GithubViewType]):
|
||||
GithubCallbackProcessor,
|
||||
)
|
||||
|
||||
# Initialize Laminar for external caller (webhook) and get parent span context
|
||||
laminar_span_context = init_laminar_for_external()
|
||||
|
||||
try:
|
||||
msg_info: str = ''
|
||||
|
||||
@@ -394,42 +389,12 @@ class GithubManager(Manager[GithubViewType]):
|
||||
github_view.user_info.keycloak_user_id, self.token_manager
|
||||
)
|
||||
|
||||
# Set up Laminar tracing if enabled (laminar_span_context is None if disabled)
|
||||
if laminar_span_context:
|
||||
try:
|
||||
with Laminar.start_as_current_span(
|
||||
name='github-resolver',
|
||||
parent_span_context=laminar_span_context,
|
||||
):
|
||||
Laminar.set_trace_metadata({
|
||||
'source': 'github',
|
||||
'repo': github_view.full_repo_name,
|
||||
'issue_number': str(github_view.issue_number),
|
||||
'username': user_info.username,
|
||||
'conversation_id': github_view.conversation_id,
|
||||
})
|
||||
await github_view.create_new_conversation(
|
||||
self.jinja_env,
|
||||
secret_store.provider_tokens,
|
||||
convo_metadata,
|
||||
saas_user_auth,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f'[Github] Laminar span error: {e}')
|
||||
# Fall back to non-Laminar execution
|
||||
await github_view.create_new_conversation(
|
||||
self.jinja_env,
|
||||
secret_store.provider_tokens,
|
||||
convo_metadata,
|
||||
saas_user_auth,
|
||||
)
|
||||
else:
|
||||
await github_view.create_new_conversation(
|
||||
self.jinja_env,
|
||||
secret_store.provider_tokens,
|
||||
convo_metadata,
|
||||
saas_user_auth,
|
||||
)
|
||||
await github_view.create_new_conversation(
|
||||
self.jinja_env,
|
||||
secret_store.provider_tokens,
|
||||
convo_metadata,
|
||||
saas_user_auth,
|
||||
)
|
||||
|
||||
conversation_id = github_view.conversation_id
|
||||
|
||||
@@ -493,10 +458,3 @@ class GithubManager(Manager[GithubViewType]):
|
||||
await self.data_collector.save_data(github_view)
|
||||
except Exception:
|
||||
logger.warning('[Github]: Error saving interaction data', exc_info=True)
|
||||
|
||||
# Flush Laminar traces if enabled (laminar_span_context is None if disabled)
|
||||
if laminar_span_context:
|
||||
try:
|
||||
Laminar.flush()
|
||||
except Exception as e:
|
||||
logger.warning(f'[Github] Error flushing Laminar traces: {e}')
|
||||
|
||||
@@ -10,7 +10,6 @@ from integrations.github.github_types import (
|
||||
)
|
||||
from integrations.models import Message
|
||||
from integrations.resolver_context import ResolverUserContext
|
||||
from integrations.resolver_org_router import resolve_org_for_repo
|
||||
from integrations.types import ResolverViewInterface, UserData
|
||||
from integrations.utils import (
|
||||
ENABLE_PROACTIVE_CONVERSATION_STARTERS,
|
||||
@@ -27,7 +26,6 @@ from server.auth.token_manager import TokenManager
|
||||
from server.config import get_config
|
||||
from storage.org_store import OrgStore
|
||||
from storage.proactive_conversation_store import ProactiveConversationStore
|
||||
from storage.saas_conversation_store import SaasConversationStore
|
||||
from storage.saas_secrets_store import SaasSecretsStore
|
||||
|
||||
from openhands.agent_server.models import SendMessageRequest
|
||||
@@ -43,14 +41,16 @@ from openhands.integrations.github.github_service import GithubServiceImpl
|
||||
from openhands.integrations.provider import PROVIDER_TOKEN_TYPE, ProviderType
|
||||
from openhands.integrations.service_types import Comment
|
||||
from openhands.sdk import TextContent
|
||||
from openhands.server.services.conversation_service import start_conversation
|
||||
from openhands.server.services.conversation_service import (
|
||||
initialize_conversation,
|
||||
start_conversation,
|
||||
)
|
||||
from openhands.server.user_auth.user_auth import UserAuth
|
||||
from openhands.storage.data_models.conversation_metadata import (
|
||||
ConversationMetadata,
|
||||
ConversationTrigger,
|
||||
)
|
||||
from openhands.utils.async_utils import call_sync_from_async
|
||||
from openhands.utils.conversation_summary import get_default_conversation_title
|
||||
|
||||
OH_LABEL, INLINE_OH_LABEL = get_oh_labels(HOST)
|
||||
|
||||
@@ -154,17 +154,12 @@ class GithubIssue(ResolverViewInterface):
|
||||
return user_secrets.custom_secrets if user_secrets else None
|
||||
|
||||
async def initialize_new_conversation(self) -> ConversationMetadata:
|
||||
# FIXME: Handle if initialize_conversation returns None
|
||||
|
||||
self.v1_enabled = await is_v1_enabled_for_github_resolver(
|
||||
self.user_info.keycloak_user_id
|
||||
)
|
||||
|
||||
# Resolve target org based on claimed git organizations
|
||||
self.resolved_org_id = await resolve_org_for_repo(
|
||||
provider='github',
|
||||
full_repo_name=self.full_repo_name,
|
||||
keycloak_user_id=self.user_info.keycloak_user_id,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f'[GitHub V1]: User flag found for {self.user_info.keycloak_user_id} is {self.v1_enabled}'
|
||||
)
|
||||
@@ -178,28 +173,16 @@ class GithubIssue(ResolverViewInterface):
|
||||
selected_repository=self.full_repo_name,
|
||||
)
|
||||
|
||||
# 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(),
|
||||
self.user_info.keycloak_user_id,
|
||||
self.resolved_org_id,
|
||||
)
|
||||
|
||||
conversation_id = uuid4().hex
|
||||
conversation_metadata = ConversationMetadata(
|
||||
trigger=ConversationTrigger.RESOLVER,
|
||||
conversation_id=conversation_id,
|
||||
title=get_default_conversation_title(conversation_id),
|
||||
conversation_metadata: ConversationMetadata = await initialize_conversation( # type: ignore[assignment]
|
||||
user_id=self.user_info.keycloak_user_id,
|
||||
conversation_id=None,
|
||||
selected_repository=self.full_repo_name,
|
||||
selected_branch=self._get_branch_name(),
|
||||
conversation_trigger=ConversationTrigger.RESOLVER,
|
||||
git_provider=ProviderType.GITHUB,
|
||||
)
|
||||
await store.save_metadata(conversation_metadata)
|
||||
|
||||
self.conversation_id = conversation_id
|
||||
self.conversation_id = conversation_metadata.conversation_id
|
||||
return conversation_metadata
|
||||
|
||||
async def create_new_conversation(
|
||||
@@ -311,10 +294,7 @@ class GithubIssue(ResolverViewInterface):
|
||||
)
|
||||
|
||||
# Set up the GitHub user context for the V1 system
|
||||
github_user_context = ResolverUserContext(
|
||||
saas_user_auth=saas_user_auth,
|
||||
resolver_org_id=self.resolved_org_id,
|
||||
)
|
||||
github_user_context = ResolverUserContext(saas_user_auth=saas_user_auth)
|
||||
setattr(injector_state, USER_CONTEXT_ATTR, github_user_context)
|
||||
|
||||
async with get_app_conversation_service(
|
||||
@@ -342,7 +322,7 @@ class GithubIssue(ResolverViewInterface):
|
||||
'full_repo_name': self.full_repo_name,
|
||||
'installation_id': self.installation_id,
|
||||
},
|
||||
should_request_summary=self.send_summary_instruction,
|
||||
send_summary_instruction=self.send_summary_instruction,
|
||||
)
|
||||
|
||||
|
||||
@@ -496,7 +476,7 @@ class GithubInlinePRComment(GithubPRComment):
|
||||
'comment_id': self.comment_id,
|
||||
},
|
||||
inline_pr_comment=True,
|
||||
should_request_summary=self.send_summary_instruction,
|
||||
send_summary_instruction=self.send_summary_instruction,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ from uuid import UUID, uuid4
|
||||
|
||||
from integrations.models import Message
|
||||
from integrations.resolver_context import ResolverUserContext
|
||||
from integrations.resolver_org_router import resolve_org_for_repo
|
||||
from integrations.types import ResolverViewInterface, UserData
|
||||
from integrations.utils import (
|
||||
ENABLE_V1_GITLAB_RESOLVER,
|
||||
@@ -15,7 +14,6 @@ from integrations.utils import (
|
||||
from jinja2 import Environment
|
||||
from server.auth.token_manager import TokenManager
|
||||
from server.config import get_config
|
||||
from storage.saas_conversation_store import SaasConversationStore
|
||||
from storage.saas_secrets_store import SaasSecretsStore
|
||||
|
||||
from openhands.agent_server.models import SendMessageRequest
|
||||
@@ -31,13 +29,15 @@ from openhands.integrations.gitlab.gitlab_service import GitLabServiceImpl
|
||||
from openhands.integrations.provider import PROVIDER_TOKEN_TYPE, ProviderType
|
||||
from openhands.integrations.service_types import Comment
|
||||
from openhands.sdk import TextContent
|
||||
from openhands.server.services.conversation_service import start_conversation
|
||||
from openhands.server.services.conversation_service import (
|
||||
initialize_conversation,
|
||||
start_conversation,
|
||||
)
|
||||
from openhands.server.user_auth.user_auth import UserAuth
|
||||
from openhands.storage.data_models.conversation_metadata import (
|
||||
ConversationMetadata,
|
||||
ConversationTrigger,
|
||||
)
|
||||
from openhands.utils.conversation_summary import get_default_conversation_title
|
||||
|
||||
OH_LABEL, INLINE_OH_LABEL = get_oh_labels(HOST)
|
||||
CONFIDENTIAL_NOTE = 'confidential_note'
|
||||
@@ -118,14 +118,6 @@ class GitlabIssue(ResolverViewInterface):
|
||||
async def initialize_new_conversation(self) -> ConversationMetadata:
|
||||
# v1_enabled is already set at construction time in the factory method
|
||||
# This is the source of truth for the conversation type
|
||||
|
||||
# Resolve target org based on claimed git organizations
|
||||
self.resolved_org_id = await resolve_org_for_repo(
|
||||
provider='gitlab',
|
||||
full_repo_name=self.full_repo_name,
|
||||
keycloak_user_id=self.user_info.keycloak_user_id,
|
||||
)
|
||||
|
||||
if self.v1_enabled:
|
||||
# Create dummy conversation metadata
|
||||
# Don't save to conversation store
|
||||
@@ -136,28 +128,16 @@ class GitlabIssue(ResolverViewInterface):
|
||||
selected_repository=self.full_repo_name,
|
||||
)
|
||||
|
||||
# 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(),
|
||||
self.user_info.keycloak_user_id,
|
||||
self.resolved_org_id,
|
||||
)
|
||||
|
||||
conversation_id = uuid4().hex
|
||||
conversation_metadata = ConversationMetadata(
|
||||
trigger=ConversationTrigger.RESOLVER,
|
||||
conversation_id=conversation_id,
|
||||
title=get_default_conversation_title(conversation_id),
|
||||
conversation_metadata: ConversationMetadata = await initialize_conversation( # type: ignore[assignment]
|
||||
user_id=self.user_info.keycloak_user_id,
|
||||
conversation_id=None,
|
||||
selected_repository=self.full_repo_name,
|
||||
selected_branch=self._get_branch_name(),
|
||||
conversation_trigger=ConversationTrigger.RESOLVER,
|
||||
git_provider=ProviderType.GITLAB,
|
||||
)
|
||||
await store.save_metadata(conversation_metadata)
|
||||
|
||||
self.conversation_id = conversation_id
|
||||
self.conversation_id = conversation_metadata.conversation_id
|
||||
return conversation_metadata
|
||||
|
||||
async def create_new_conversation(
|
||||
@@ -248,10 +228,7 @@ class GitlabIssue(ResolverViewInterface):
|
||||
)
|
||||
|
||||
# Set up the GitLab user context for the V1 system
|
||||
gitlab_user_context = ResolverUserContext(
|
||||
saas_user_auth=saas_user_auth,
|
||||
resolver_org_id=self.resolved_org_id,
|
||||
)
|
||||
gitlab_user_context = ResolverUserContext(saas_user_auth=saas_user_auth)
|
||||
setattr(injector_state, USER_CONTEXT_ATTR, gitlab_user_context)
|
||||
|
||||
async with get_app_conversation_service(
|
||||
@@ -283,7 +260,7 @@ class GitlabIssue(ResolverViewInterface):
|
||||
'is_mr': self.is_mr,
|
||||
'discussion_id': getattr(self, 'discussion_id', None),
|
||||
},
|
||||
should_request_summary=self.send_summary_instruction,
|
||||
send_summary_instruction=self.send_summary_instruction,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ Views are responsible for:
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
from integrations.jira.jira_payload import JiraWebhookPayload
|
||||
@@ -16,25 +15,18 @@ from integrations.jira.jira_types import (
|
||||
RepositoryNotFoundError,
|
||||
StartingConvoException,
|
||||
)
|
||||
from integrations.resolver_org_router import resolve_org_for_repo
|
||||
from integrations.utils import CONVERSATION_URL, infer_repo_from_message
|
||||
from jinja2 import Environment
|
||||
from server.config import get_config
|
||||
from storage.jira_conversation import JiraConversation
|
||||
from storage.jira_integration_store import JiraIntegrationStore
|
||||
from storage.jira_user import JiraUser
|
||||
from storage.jira_workspace import JiraWorkspace
|
||||
from storage.saas_conversation_store import SaasConversationStore
|
||||
|
||||
from openhands.core.logger import openhands_logger as logger
|
||||
from openhands.integrations.provider import ProviderHandler
|
||||
from openhands.server.services.conversation_service import start_conversation
|
||||
from openhands.server.services.conversation_service import create_new_conversation
|
||||
from openhands.server.user_auth.user_auth import UserAuth
|
||||
from openhands.storage.data_models.conversation_metadata import (
|
||||
ConversationMetadata,
|
||||
ConversationTrigger,
|
||||
)
|
||||
from openhands.utils.conversation_summary import get_default_conversation_title
|
||||
from openhands.storage.data_models.conversation_metadata import ConversationTrigger
|
||||
from openhands.utils.http_session import httpx_verify_option
|
||||
|
||||
JIRA_CLOUD_API_URL = 'https://api.atlassian.com/ex/jira'
|
||||
@@ -174,68 +166,20 @@ class JiraNewConversationView(JiraViewInterface):
|
||||
instructions, user_msg = await self._get_instructions(jinja_env)
|
||||
|
||||
try:
|
||||
user_id = self.jira_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'[Jira] 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'[Jira] Failed to resolve org for {self.selected_repo}: {e}'
|
||||
)
|
||||
|
||||
# Create the conversation store with resolver org routing
|
||||
store = await SaasConversationStore.get_resolver_instance(
|
||||
get_config(),
|
||||
user_id,
|
||||
resolved_org_id,
|
||||
)
|
||||
|
||||
conversation_id = uuid4().hex
|
||||
conversation_metadata = ConversationMetadata(
|
||||
trigger=ConversationTrigger.JIRA,
|
||||
conversation_id=conversation_id,
|
||||
title=get_default_conversation_title(conversation_id),
|
||||
user_id=user_id,
|
||||
agent_loop_info = await create_new_conversation(
|
||||
user_id=self.jira_user.keycloak_user_id,
|
||||
git_provider_tokens=provider_tokens,
|
||||
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_id=conversation_id,
|
||||
conversation_metadata=conversation_metadata,
|
||||
conversation_instructions=instructions,
|
||||
conversation_trigger=ConversationTrigger.JIRA,
|
||||
custom_secrets=user_secrets.custom_secrets if user_secrets else None,
|
||||
)
|
||||
|
||||
self.conversation_id = conversation_id
|
||||
self.conversation_id = agent_loop_info.conversation_id
|
||||
|
||||
logger.info(
|
||||
'[Jira] Created conversation',
|
||||
@@ -243,9 +187,6 @@ class JiraNewConversationView(JiraViewInterface):
|
||||
'conversation_id': self.conversation_id,
|
||||
'issue_key': self.payload.issue_key,
|
||||
'selected_repo': self.selected_repo,
|
||||
'resolved_org_id': str(resolved_org_id)
|
||||
if resolved_org_id
|
||||
else None,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -1,34 +1,25 @@
|
||||
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 (
|
||||
ConversationMetadata,
|
||||
ConversationTrigger,
|
||||
)
|
||||
from openhands.utils.conversation_summary import get_default_conversation_title
|
||||
from openhands.storage.data_models.conversation_metadata import ConversationTrigger
|
||||
|
||||
integration_store = LinearIntegrationStore.get_instance()
|
||||
|
||||
@@ -70,70 +61,20 @@ class LinearNewConversationView(LinearViewInterface):
|
||||
instructions, user_msg = await self._get_instructions(jinja_env)
|
||||
|
||||
try:
|
||||
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,
|
||||
agent_loop_info = await create_new_conversation(
|
||||
user_id=self.linear_user.keycloak_user_id,
|
||||
git_provider_tokens=provider_tokens,
|
||||
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_id=conversation_id,
|
||||
conversation_metadata=conversation_metadata,
|
||||
conversation_instructions=instructions,
|
||||
conversation_trigger=ConversationTrigger.LINEAR,
|
||||
custom_secrets=user_secrets.custom_secrets if user_secrets else None,
|
||||
)
|
||||
|
||||
self.conversation_id = conversation_id
|
||||
self.conversation_id = agent_loop_info.conversation_id
|
||||
|
||||
logger.info(f'[Linear] Created conversation {self.conversation_id}')
|
||||
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
from uuid import UUID
|
||||
|
||||
from openhands.app_server.user.user_context import UserContext
|
||||
from openhands.app_server.user.user_models import UserInfo
|
||||
from openhands.integrations.provider import PROVIDER_TOKEN_TYPE, ProviderHandler
|
||||
from openhands.integrations.service_types import ProviderType, UserGitInfo
|
||||
from openhands.integrations.service_types import ProviderType
|
||||
from openhands.sdk.secret import SecretSource, StaticSecret
|
||||
from openhands.server.user_auth.user_auth import UserAuth
|
||||
|
||||
@@ -14,10 +12,8 @@ class ResolverUserContext(UserContext):
|
||||
def __init__(
|
||||
self,
|
||||
saas_user_auth: UserAuth,
|
||||
resolver_org_id: UUID | None = None,
|
||||
):
|
||||
self.saas_user_auth = saas_user_auth
|
||||
self.resolver_org_id = resolver_org_id
|
||||
self._provider_handler: ProviderHandler | None = None
|
||||
|
||||
async def get_user_id(self) -> str | None:
|
||||
@@ -85,6 +81,3 @@ class ResolverUserContext(UserContext):
|
||||
|
||||
async def get_mcp_api_key(self) -> str | None:
|
||||
return await self.saas_user_auth.get_mcp_api_key()
|
||||
|
||||
async def get_user_git_info(self) -> UserGitInfo | None:
|
||||
return await self.saas_user_auth.get_user_git_info()
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
"""Resolve which OpenHands organization workspace a resolver conversation should be created in.
|
||||
|
||||
This module provides a reusable utility for routing resolver conversations
|
||||
(GitHub, GitLab, Bitbucket, Slack, etc.) to the correct OpenHands organization
|
||||
workspace based on claimed Git organizations.
|
||||
"""
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from storage.org_git_claim_store import OrgGitClaimStore
|
||||
from storage.org_member_store import OrgMemberStore
|
||||
|
||||
from openhands.core.logger import openhands_logger as logger
|
||||
|
||||
|
||||
async def resolve_org_for_repo(
|
||||
provider: str,
|
||||
full_repo_name: str,
|
||||
keycloak_user_id: str,
|
||||
) -> UUID | None:
|
||||
"""Determine the OpenHands org_id for a resolver conversation.
|
||||
|
||||
If the repo's git organization is claimed by an OpenHands org AND the user
|
||||
is a member of that org, returns the claiming org's ID. Otherwise returns
|
||||
None (caller should fall back to user.current_org_id / personal workspace).
|
||||
|
||||
Args:
|
||||
provider: Git provider name ("github", "gitlab", "bitbucket")
|
||||
full_repo_name: Full repository name (e.g., "OpenHands/foo")
|
||||
keycloak_user_id: The user's Keycloak UUID string
|
||||
|
||||
Returns:
|
||||
The org_id if the repo's org is claimed and user is a member, else None
|
||||
"""
|
||||
git_org = full_repo_name.split('/')[0].lower()
|
||||
|
||||
try:
|
||||
claim = await OrgGitClaimStore.get_claim_by_provider_and_git_org(
|
||||
provider, git_org
|
||||
)
|
||||
if not claim:
|
||||
logger.debug(
|
||||
f'[OrgResolver] No claim found for {provider}/{git_org}',
|
||||
)
|
||||
return None
|
||||
|
||||
member = await OrgMemberStore.get_org_member(
|
||||
claim.org_id, UUID(keycloak_user_id)
|
||||
)
|
||||
if not member:
|
||||
logger.debug(
|
||||
f'[OrgResolver] User {keycloak_user_id} is not a member of org '
|
||||
f'{claim.org_id} (claimed {provider}/{git_org}). '
|
||||
f'Falling back to personal workspace.',
|
||||
)
|
||||
return None
|
||||
|
||||
logger.info(
|
||||
f'[OrgResolver] Routing conversation to org {claim.org_id} '
|
||||
f'for {provider}/{git_org} (user {keycloak_user_id})',
|
||||
)
|
||||
return claim.org_id
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f'[OrgResolver] Error resolving org for {provider}/{git_org}: {e}',
|
||||
exc_info=True,
|
||||
)
|
||||
return None
|
||||
@@ -239,14 +239,12 @@ class SlackManager(Manager[SlackViewInterface]):
|
||||
def _generate_repo_selection_form(
|
||||
self, message_ts: str, thread_ts: str | None
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Generate a repo selection form with immediate "No Repository" button and search dropdown.
|
||||
"""Generate a repo selection form using external_select for dynamic loading.
|
||||
|
||||
This form provides two options side-by-side:
|
||||
1. A "No Repository" button - immediately clickable without any loading
|
||||
2. An external_select dropdown - for searching repositories dynamically
|
||||
|
||||
This design ensures "No Repository" is always immediately available while
|
||||
still providing full dynamic search capability for repositories.
|
||||
This uses Slack's external_select element which allows:
|
||||
- Type-ahead search for repositories
|
||||
- Dynamic loading of options from an external endpoint
|
||||
- Support for users with many repositories (no 100 option limit)
|
||||
|
||||
Args:
|
||||
message_ts: The message timestamp for tracking
|
||||
@@ -268,22 +266,12 @@ class SlackManager(Manager[SlackViewInterface]):
|
||||
'type': 'section',
|
||||
'text': {
|
||||
'type': 'mrkdwn',
|
||||
'text': 'Select a repository or continue without one:',
|
||||
'text': 'Type to search your repositories:',
|
||||
},
|
||||
},
|
||||
{
|
||||
'type': 'actions',
|
||||
'elements': [
|
||||
{
|
||||
'type': 'button',
|
||||
'action_id': f'no_repository:{message_ts}:{thread_ts}',
|
||||
'text': {
|
||||
'type': 'plain_text',
|
||||
'text': 'No Repository',
|
||||
'emoji': True,
|
||||
},
|
||||
'value': '-',
|
||||
},
|
||||
{
|
||||
'type': 'external_select',
|
||||
'action_id': f'repository_select:{message_ts}:{thread_ts}',
|
||||
@@ -291,8 +279,8 @@ class SlackManager(Manager[SlackViewInterface]):
|
||||
'type': 'plain_text',
|
||||
'text': 'Search repositories...',
|
||||
},
|
||||
'min_query_length': 0,
|
||||
},
|
||||
'min_query_length': 0, # Load initial options immediately
|
||||
}
|
||||
],
|
||||
},
|
||||
]
|
||||
@@ -300,11 +288,8 @@ class SlackManager(Manager[SlackViewInterface]):
|
||||
def _build_repo_options(self, repos: list[Repository]) -> list[dict[str, Any]]:
|
||||
"""Build Slack options list from repositories.
|
||||
|
||||
Returns up to 100 repositories formatted as Slack options
|
||||
(Slack has a 100 option limit for external_select).
|
||||
|
||||
Note: "No Repository" is handled by a separate button in the form,
|
||||
so it's not included in the dropdown options.
|
||||
Always includes a "No Repository" option at the top, followed by up to 99
|
||||
repositories (Slack has a 100 option limit for external_select).
|
||||
|
||||
Args:
|
||||
repos: List of Repository objects
|
||||
@@ -312,7 +297,13 @@ class SlackManager(Manager[SlackViewInterface]):
|
||||
Returns:
|
||||
List of Slack option objects
|
||||
"""
|
||||
return [
|
||||
options: list[dict[str, Any]] = [
|
||||
{
|
||||
'text': {'type': 'plain_text', 'text': 'No Repository'},
|
||||
'value': '-',
|
||||
}
|
||||
]
|
||||
options.extend(
|
||||
{
|
||||
'text': {
|
||||
'type': 'plain_text',
|
||||
@@ -320,8 +311,9 @@ class SlackManager(Manager[SlackViewInterface]):
|
||||
},
|
||||
'value': repo.full_name,
|
||||
}
|
||||
for repo in repos[:100]
|
||||
]
|
||||
for repo in repos[:99] # Leave room for "No Repository" option
|
||||
)
|
||||
return options
|
||||
|
||||
async def search_repos_for_slack(
|
||||
self, user_auth: UserAuth, query: str, per_page: int = 20
|
||||
@@ -371,69 +363,33 @@ class SlackManager(Manager[SlackViewInterface]):
|
||||
SlackError(SlackErrorCode.UNEXPECTED_ERROR),
|
||||
)
|
||||
|
||||
def _parse_form_action(self, action: dict) -> tuple[str, str | None, str] | None:
|
||||
"""Parse action payload and extract message_ts, thread_ts, and selected value.
|
||||
|
||||
This handles the different payload structures for button clicks vs dropdown
|
||||
selections in the repository selection form.
|
||||
|
||||
Args:
|
||||
action: The action object from the Slack payload
|
||||
|
||||
Returns:
|
||||
Tuple of (message_ts, thread_ts, selected_value) if action is recognized,
|
||||
None if the action_id is unknown.
|
||||
"""
|
||||
action_id = action['action_id']
|
||||
|
||||
if action_id.startswith('no_repository:'):
|
||||
# Button click - value is in 'value' field
|
||||
attribs = action_id.split('no_repository:')[-1]
|
||||
selected_value = action.get('value', '-')
|
||||
elif action_id.startswith('repository_select:'):
|
||||
# Dropdown selection - value is in 'selected_option'
|
||||
attribs = action_id.split('repository_select:')[-1]
|
||||
selected_value = action['selected_option']['value']
|
||||
else:
|
||||
return None
|
||||
|
||||
message_ts, thread_ts = attribs.split(':')
|
||||
thread_ts = None if thread_ts == 'None' else thread_ts
|
||||
|
||||
return message_ts, thread_ts, selected_value
|
||||
|
||||
async def receive_form_interaction(self, slack_payload: dict):
|
||||
"""Process a Slack form interaction (repository selection or button click).
|
||||
"""Process a Slack form interaction (repository selection).
|
||||
|
||||
This handles the block_actions payload when a user interacts with the
|
||||
repository selection form. It can handle:
|
||||
- "No Repository" button click: proceeds with conversation without a repo
|
||||
- Repository selection from dropdown: proceeds with the selected repo
|
||||
This handles the block_actions payload when a user selects a repository
|
||||
from the dropdown form. It retrieves the original user message from Redis
|
||||
and delegates to receive_message for processing.
|
||||
|
||||
Args:
|
||||
slack_payload: The raw Slack interaction payload
|
||||
"""
|
||||
# Extract fields from the Slack interaction payload
|
||||
action = slack_payload['actions'][0]
|
||||
selected_repository = slack_payload['actions'][0]['selected_option']['value']
|
||||
if selected_repository == '-':
|
||||
selected_repository = None
|
||||
|
||||
slack_user_id = slack_payload['user']['id']
|
||||
channel_id = slack_payload['container']['channel_id']
|
||||
team_id = slack_payload['team']['id']
|
||||
|
||||
# Parse the action to extract message_ts, thread_ts, and selected value
|
||||
parsed = self._parse_form_action(action)
|
||||
if parsed is None:
|
||||
logger.warning(
|
||||
'slack_unknown_action_id',
|
||||
extra={
|
||||
'action_id': action['action_id'],
|
||||
'slack_user_id': slack_user_id,
|
||||
},
|
||||
)
|
||||
return
|
||||
# Get original message_ts and thread_ts from action_id
|
||||
attribs = slack_payload['actions'][0]['action_id'].split('repository_select:')[
|
||||
-1
|
||||
]
|
||||
message_ts, thread_ts = attribs.split(':')
|
||||
thread_ts = None if thread_ts == 'None' else thread_ts
|
||||
|
||||
message_ts, thread_ts, selected_value = parsed
|
||||
|
||||
# Build partial payload for error handling
|
||||
# Build partial payload for error handling during Redis retrieval
|
||||
payload = {
|
||||
'team_id': team_id,
|
||||
'channel_id': channel_id,
|
||||
@@ -442,9 +398,6 @@ class SlackManager(Manager[SlackViewInterface]):
|
||||
'thread_ts': thread_ts,
|
||||
}
|
||||
|
||||
# Convert "-" (No Repository) to None
|
||||
selected_repository = None if selected_value == '-' else selected_value
|
||||
|
||||
# Retrieve the original user message from Redis
|
||||
try:
|
||||
user_msg = await self._retrieve_user_msg_for_form(message_ts, thread_ts)
|
||||
|
||||
@@ -4,7 +4,6 @@ from uuid import UUID, uuid4
|
||||
|
||||
from integrations.models import Message
|
||||
from integrations.resolver_context import ResolverUserContext
|
||||
from integrations.resolver_org_router import resolve_org_for_repo
|
||||
from integrations.slack.slack_types import (
|
||||
SlackMessageView,
|
||||
SlackViewInterface,
|
||||
@@ -18,9 +17,7 @@ from integrations.utils import (
|
||||
get_user_v1_enabled_setting,
|
||||
)
|
||||
from jinja2 import Environment
|
||||
from server.config import get_config
|
||||
from slack_sdk import WebClient
|
||||
from storage.saas_conversation_store import SaasConversationStore
|
||||
from storage.slack_conversation import SlackConversation
|
||||
from storage.slack_conversation_store import SlackConversationStore
|
||||
from storage.slack_team_store import SlackTeamStore
|
||||
@@ -39,20 +36,18 @@ 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.integrations.provider import ProviderHandler, ProviderType
|
||||
from openhands.sdk import TextContent
|
||||
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 (
|
||||
ConversationMetadata,
|
||||
ConversationTrigger,
|
||||
)
|
||||
from openhands.utils.async_utils import GENERAL_TIMEOUT
|
||||
from openhands.utils.conversation_summary import get_default_conversation_title
|
||||
|
||||
# =================================================
|
||||
# SECTION: Slack view types
|
||||
@@ -207,22 +202,6 @@ class SlackNewConversationView(SlackViewInterface):
|
||||
provider_tokens = await self.saas_user_auth.get_provider_tokens()
|
||||
user_secrets = await self.saas_user_auth.get_secrets()
|
||||
|
||||
# Determine git provider from repository (needed for both org routing and conversation creation)
|
||||
self._resolved_git_provider = None
|
||||
if self.selected_repo and provider_tokens:
|
||||
provider_handler = ProviderHandler(provider_tokens)
|
||||
repository = await provider_handler.verify_repo_provider(self.selected_repo)
|
||||
self._resolved_git_provider = repository.git_provider
|
||||
|
||||
# Resolve target org based on claimed git organizations
|
||||
self.resolved_org_id = None
|
||||
if self._resolved_git_provider and self.selected_repo:
|
||||
self.resolved_org_id = await resolve_org_for_repo(
|
||||
provider=self._resolved_git_provider.value,
|
||||
full_repo_name=self.selected_repo,
|
||||
keycloak_user_id=self.slack_to_openhands_user.keycloak_user_id,
|
||||
)
|
||||
|
||||
# Check if V1 conversations are enabled for this user
|
||||
self.v1_enabled = await is_v1_enabled_for_slack_resolver(
|
||||
self.slack_to_openhands_user.keycloak_user_id
|
||||
@@ -245,44 +224,30 @@ class SlackNewConversationView(SlackViewInterface):
|
||||
jinja
|
||||
)
|
||||
|
||||
user_id = self.slack_to_openhands_user.keycloak_user_id
|
||||
# Determine git provider from repository
|
||||
git_provider = None
|
||||
if self.selected_repo and provider_tokens:
|
||||
provider_handler = ProviderHandler(provider_tokens)
|
||||
repository = await provider_handler.verify_repo_provider(self.selected_repo)
|
||||
git_provider = repository.git_provider
|
||||
|
||||
# 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,
|
||||
self.resolved_org_id,
|
||||
)
|
||||
|
||||
conversation_id = uuid4().hex
|
||||
conversation_metadata = ConversationMetadata(
|
||||
trigger=ConversationTrigger.SLACK,
|
||||
conversation_id=conversation_id,
|
||||
title=get_default_conversation_title(conversation_id),
|
||||
user_id=user_id,
|
||||
agent_loop_info = await create_new_conversation(
|
||||
user_id=self.slack_to_openhands_user.keycloak_user_id,
|
||||
git_provider_tokens=provider_tokens,
|
||||
selected_repository=self.selected_repo,
|
||||
selected_branch=None,
|
||||
git_provider=self._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_instructions,
|
||||
image_urls=None,
|
||||
replay_json=None,
|
||||
conversation_id=conversation_id,
|
||||
conversation_metadata=conversation_metadata,
|
||||
conversation_instructions=(
|
||||
conversation_instructions if conversation_instructions else None
|
||||
),
|
||||
image_urls=None,
|
||||
replay_json=None,
|
||||
conversation_trigger=ConversationTrigger.SLACK,
|
||||
custom_secrets=user_secrets.custom_secrets if user_secrets else None,
|
||||
git_provider=git_provider,
|
||||
)
|
||||
|
||||
self.conversation_id = conversation_id
|
||||
self.conversation_id = agent_loop_info.conversation_id
|
||||
logger.info(f'[Slack]: Created V0 conversation: {self.conversation_id}')
|
||||
await self.save_slack_convo(v1_enabled=False)
|
||||
|
||||
@@ -300,8 +265,13 @@ class SlackNewConversationView(SlackViewInterface):
|
||||
# Create the Slack V1 callback processor
|
||||
slack_callback_processor = self._create_slack_v1_callback_processor()
|
||||
|
||||
# Use git provider resolved in create_or_update_conversation
|
||||
git_provider = self._resolved_git_provider
|
||||
# Determine git provider from repository
|
||||
git_provider = None
|
||||
provider_tokens = await self.saas_user_auth.get_provider_tokens()
|
||||
if self.selected_repo and provider_tokens:
|
||||
provider_handler = ProviderHandler(provider_tokens)
|
||||
repository = await provider_handler.verify_repo_provider(self.selected_repo)
|
||||
git_provider = ProviderType(repository.git_provider.value)
|
||||
|
||||
# Get the app conversation service and start the conversation
|
||||
injector_state = InjectorState()
|
||||
@@ -322,10 +292,7 @@ class SlackNewConversationView(SlackViewInterface):
|
||||
)
|
||||
|
||||
# Set up the Slack user context for the V1 system
|
||||
slack_user_context = ResolverUserContext(
|
||||
saas_user_auth=self.saas_user_auth,
|
||||
resolver_org_id=self.resolved_org_id,
|
||||
)
|
||||
slack_user_context = ResolverUserContext(saas_user_auth=self.saas_user_auth)
|
||||
setattr(injector_state, USER_CONTEXT_ATTR, slack_user_context)
|
||||
|
||||
async with get_app_conversation_service(
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
"""Add disabled_skills column to user table.
|
||||
|
||||
Migration 102 added disabled_skills to the legacy user_settings table,
|
||||
but the active SaaS flow (SaasSettingsStore) reads from/writes to the
|
||||
user table. This migration adds the column where it is actually needed.
|
||||
|
||||
Revision ID: 104
|
||||
Revises: 103
|
||||
Create Date: 2026-03-31
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '104'
|
||||
down_revision: Union[str, None] = '103'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column('user', sa.Column('disabled_skills', sa.JSON(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column('user', 'disabled_skills')
|
||||
@@ -1,37 +0,0 @@
|
||||
"""Create org_git_claim table for tracking Git organization claims.
|
||||
|
||||
Revision ID: 105
|
||||
Revises: 104
|
||||
Create Date: 2026-04-01
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '105'
|
||||
down_revision: Union[str, None] = '104'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
'org_git_claim',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('org_id', sa.UUID(), nullable=False),
|
||||
sa.Column('provider', sa.String(), nullable=False),
|
||||
sa.Column('git_organization', sa.String(), nullable=False),
|
||||
sa.Column('claimed_by', sa.UUID(), nullable=False),
|
||||
sa.Column('claimed_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['org_id'], ['org.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['claimed_by'], ['user.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('provider', 'git_organization', name='uq_provider_git_org'),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table('org_git_claim')
|
||||
@@ -1,32 +0,0 @@
|
||||
"""Add tags column to conversation_metadata table.
|
||||
|
||||
Tags store key-value pairs for automation context (trigger type, automation_id),
|
||||
skills used, and other metadata. This enables querying conversations by
|
||||
automation source and associating SDK-provided context with conversations.
|
||||
|
||||
Revision ID: 106
|
||||
Revises: 105
|
||||
Create Date: 2026-03-31
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '106'
|
||||
down_revision: Union[str, None] = '105'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
'conversation_metadata',
|
||||
sa.Column('tags', sa.JSON(), nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column('conversation_metadata', 'tags')
|
||||
4648
enterprise/poetry.lock
generated
4648
enterprise/poetry.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -49,9 +49,6 @@ from server.routes.readiness import readiness_router # noqa: E402
|
||||
from server.routes.service import service_router # noqa: E402
|
||||
from server.routes.user import saas_user_router # noqa: E402
|
||||
from server.routes.user_app_settings import user_app_settings_router # noqa: E402
|
||||
from server.routes.users_v1 import ( # noqa: E402
|
||||
override_users_me_endpoint,
|
||||
)
|
||||
from server.sharing.shared_conversation_router import ( # noqa: E402
|
||||
router as shared_conversation_router,
|
||||
)
|
||||
@@ -126,10 +123,6 @@ base_app.include_router(
|
||||
# This must happen after all routers are included
|
||||
override_llm_models_dependency(base_app)
|
||||
|
||||
# Override the /api/v1/users/me endpoint to include organization info
|
||||
# This replaces the OSS endpoint with a SAAS version that adds org_id, org_name, role, permissions
|
||||
override_users_me_endpoint(base_app)
|
||||
|
||||
base_app.include_router(invitation_router) # Add routes for org invitation management
|
||||
base_app.include_router(invitation_accept_router) # Add route for accepting invitations
|
||||
add_github_proxy_routes(base_app)
|
||||
|
||||
@@ -84,9 +84,6 @@ class Permission(str, Enum):
|
||||
# Temporary permissions until we finish the API updates.
|
||||
EDIT_ORG_SETTINGS = 'edit_org_settings'
|
||||
|
||||
# Git organization claims
|
||||
MANAGE_ORG_CLAIMS = 'manage_org_claims'
|
||||
|
||||
|
||||
class RoleName(str, Enum):
|
||||
"""Role names used in the system."""
|
||||
@@ -121,8 +118,6 @@ ROLE_PERMISSIONS: dict[RoleName, frozenset[Permission]] = {
|
||||
# Organization Management (Owner only)
|
||||
Permission.CHANGE_ORGANIZATION_NAME,
|
||||
Permission.DELETE_ORGANIZATION,
|
||||
# Git organization claims
|
||||
Permission.MANAGE_ORG_CLAIMS,
|
||||
]
|
||||
),
|
||||
RoleName.ADMIN: frozenset(
|
||||
@@ -144,8 +139,6 @@ ROLE_PERMISSIONS: dict[RoleName, frozenset[Permission]] = {
|
||||
# Organization Management
|
||||
Permission.VIEW_ORG_SETTINGS,
|
||||
Permission.EDIT_ORG_SETTINGS,
|
||||
# Git organization claims
|
||||
Permission.MANAGE_ORG_CLAIMS,
|
||||
]
|
||||
),
|
||||
RoleName.MEMBER: frozenset(
|
||||
|
||||
@@ -6,6 +6,7 @@ GITHUB_APP_WEBHOOK_SECRET = os.getenv('GITHUB_APP_WEBHOOK_SECRET', '')
|
||||
GITHUB_APP_PRIVATE_KEY = os.getenv('GITHUB_APP_PRIVATE_KEY', '').replace('\\n', '\n')
|
||||
KEYCLOAK_SERVER_URL = os.getenv('KEYCLOAK_SERVER_URL', '').rstrip('/')
|
||||
KEYCLOAK_REALM_NAME = os.getenv('KEYCLOAK_REALM_NAME', '')
|
||||
KEYCLOAK_PROVIDER_NAME = os.getenv('KEYCLOAK_PROVIDER_NAME', '')
|
||||
KEYCLOAK_CLIENT_ID = os.getenv('KEYCLOAK_CLIENT_ID', '')
|
||||
KEYCLOAK_CLIENT_SECRET = os.getenv('KEYCLOAK_CLIENT_SECRET', '')
|
||||
KEYCLOAK_SERVER_URL_EXT = os.getenv(
|
||||
|
||||
@@ -4,6 +4,7 @@ from server.auth.constants import (
|
||||
KEYCLOAK_ADMIN_PASSWORD,
|
||||
KEYCLOAK_CLIENT_ID,
|
||||
KEYCLOAK_CLIENT_SECRET,
|
||||
KEYCLOAK_PROVIDER_NAME,
|
||||
KEYCLOAK_REALM_NAME,
|
||||
KEYCLOAK_SERVER_URL,
|
||||
KEYCLOAK_SERVER_URL_EXT,
|
||||
@@ -11,7 +12,7 @@ from server.auth.constants import (
|
||||
from server.logger import logger
|
||||
|
||||
logger.debug(
|
||||
f'KEYCLOAK_SERVER_URL:{KEYCLOAK_SERVER_URL}, KEYCLOAK_SERVER_URL_EXT:{KEYCLOAK_SERVER_URL_EXT}, KEYCLOAK_CLIENT_ID:{KEYCLOAK_CLIENT_ID}'
|
||||
f'KEYCLOAK_SERVER_URL:{KEYCLOAK_SERVER_URL}, KEYCLOAK_SERVER_URL_EXT:{KEYCLOAK_SERVER_URL_EXT}, KEYCLOAK_PROVIDER_NAME:{KEYCLOAK_PROVIDER_NAME}, KEYCLOAK_CLIENT_ID:{KEYCLOAK_CLIENT_ID}'
|
||||
)
|
||||
|
||||
_keycloak_instances = {}
|
||||
|
||||
@@ -14,10 +14,6 @@ from server.auth.auth_error import (
|
||||
ExpiredError,
|
||||
NoCredentialsError,
|
||||
)
|
||||
from server.auth.authorization import (
|
||||
get_role_permissions,
|
||||
get_user_org_role,
|
||||
)
|
||||
from server.auth.constants import BITBUCKET_DATA_CENTER_HOST
|
||||
from server.auth.token_manager import TokenManager
|
||||
from server.config import get_config
|
||||
@@ -27,12 +23,10 @@ from sqlalchemy import delete, select
|
||||
from storage.api_key_store import ApiKeyStore
|
||||
from storage.auth_tokens import AuthTokens
|
||||
from storage.database import a_session_maker
|
||||
from storage.org_store import OrgStore
|
||||
from storage.saas_secrets_store import SaasSecretsStore
|
||||
from storage.saas_settings_store import SaasSettingsStore
|
||||
from storage.user_authorization import UserAuthorizationType
|
||||
from storage.user_authorization_store import UserAuthorizationStore
|
||||
from storage.user_store import UserStore
|
||||
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed
|
||||
|
||||
from openhands.integrations.provider import (
|
||||
@@ -70,12 +64,6 @@ class SaasUserAuth(UserAuth):
|
||||
api_key_org_id: UUID | None = None # Org bound to the API key used for auth
|
||||
api_key_id: int | None = None
|
||||
api_key_name: str | None = None
|
||||
# Organization context fields - populated lazily via get_org_info()
|
||||
_org_id: str | None = None
|
||||
_org_name: str | None = None
|
||||
_role: str | None = None
|
||||
_permissions: list[str] | None = None
|
||||
_org_info_loaded: bool = False
|
||||
|
||||
def get_api_key_org_id(self) -> UUID | None:
|
||||
"""Get the organization ID bound to the API key used for authentication.
|
||||
@@ -254,72 +242,6 @@ class SaasUserAuth(UserAuth):
|
||||
)
|
||||
return mcp_api_key
|
||||
|
||||
async def get_org_info(self) -> dict | None:
|
||||
"""Get organization info for the current user.
|
||||
|
||||
Lazily loads and caches organization data including:
|
||||
- org_id: Current organization ID
|
||||
- org_name: Current organization name
|
||||
- role: User's role in the organization
|
||||
- permissions: List of permission names for the role
|
||||
|
||||
Returns:
|
||||
dict with org_id, org_name, role, permissions or None if not available
|
||||
"""
|
||||
if self._org_info_loaded:
|
||||
if self._org_id is None:
|
||||
return None
|
||||
return {
|
||||
'org_id': self._org_id,
|
||||
'org_name': self._org_name,
|
||||
'role': self._role,
|
||||
'permissions': self._permissions,
|
||||
}
|
||||
|
||||
# Mark as loaded to avoid repeated attempts on failure
|
||||
self._org_info_loaded = True
|
||||
|
||||
try:
|
||||
# Get user and their current org
|
||||
user = await UserStore.get_user_by_id(self.user_id)
|
||||
if not user:
|
||||
logger.warning(f'User {self.user_id} not found for org info')
|
||||
return None
|
||||
|
||||
# Get the current org
|
||||
org = await OrgStore.get_org_by_id(user.current_org_id)
|
||||
if not org:
|
||||
logger.warning(
|
||||
f'Organization {user.current_org_id} not found for user {self.user_id}'
|
||||
)
|
||||
return None
|
||||
|
||||
# Get user's role in the current org
|
||||
role = await get_user_org_role(self.user_id, user.current_org_id)
|
||||
role_name = role.name if role else None
|
||||
|
||||
# Get permissions for the role
|
||||
permissions: list[str] = []
|
||||
if role_name:
|
||||
role_permissions = get_role_permissions(role_name)
|
||||
permissions = [p.value for p in role_permissions]
|
||||
|
||||
# Cache the results
|
||||
self._org_id = str(user.current_org_id)
|
||||
self._org_name = org.name
|
||||
self._role = role_name
|
||||
self._permissions = permissions
|
||||
|
||||
return {
|
||||
'org_id': self._org_id,
|
||||
'org_name': self._org_name,
|
||||
'role': self._role,
|
||||
'permissions': self._permissions,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f'Error fetching org info for user {self.user_id}: {e}')
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
async def get_instance(cls, request: Request) -> UserAuth:
|
||||
logger.debug('saas_user_auth_get_instance')
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
# Enterprise server models
|
||||
@@ -1,16 +0,0 @@
|
||||
"""SAAS-specific user models that extend OSS UserInfo with organization fields."""
|
||||
|
||||
from openhands.app_server.user.user_models import UserInfo
|
||||
|
||||
|
||||
class SaasUserInfo(UserInfo):
|
||||
"""User info model for SAAS mode with organization context.
|
||||
|
||||
Extends the base UserInfo with SAAS-specific fields for organization
|
||||
membership, role, and permissions.
|
||||
"""
|
||||
|
||||
org_id: str | None = None
|
||||
org_name: str | None = None
|
||||
role: str | None = None
|
||||
permissions: list[str] | None = None
|
||||
@@ -7,8 +7,8 @@ from storage.database import a_session_maker
|
||||
from storage.feedback import ConversationFeedback
|
||||
from storage.stored_conversation_metadata_saas import StoredConversationMetadataSaas
|
||||
|
||||
from openhands.app_server.utils.dependencies import get_dependencies
|
||||
from openhands.events.event_store import EventStore
|
||||
from openhands.server.dependencies import get_dependencies
|
||||
from openhands.server.shared import file_store
|
||||
from openhands.server.user_auth import get_user_id
|
||||
|
||||
|
||||
@@ -335,9 +335,6 @@ async def on_options_load(request: Request, background_tasks: BackgroundTasks):
|
||||
2. Searches for repositories matching the user's query
|
||||
3. Returns up to 100 options for the dropdown
|
||||
|
||||
Note: "No Repository" is handled by a separate button in the form, so it's
|
||||
not included in the dropdown options. Error cases return an empty list.
|
||||
|
||||
Configuration: Set the Options Load URL in Slack App settings to:
|
||||
https://your-domain/slack/on-options-load
|
||||
"""
|
||||
|
||||
@@ -485,56 +485,6 @@ class OrgAppSettingsUpdate(BaseModel):
|
||||
return v
|
||||
|
||||
|
||||
VALID_GIT_PROVIDERS = {'github', 'gitlab', 'bitbucket'}
|
||||
|
||||
|
||||
class GitOrgClaimRequest(BaseModel):
|
||||
"""Request model for claiming a Git organization."""
|
||||
|
||||
provider: str
|
||||
git_organization: str
|
||||
|
||||
@field_validator('provider')
|
||||
@classmethod
|
||||
def validate_provider(cls, v: str) -> str:
|
||||
v = v.lower().strip()
|
||||
if v not in VALID_GIT_PROVIDERS:
|
||||
raise ValueError(
|
||||
f'Invalid provider: "{v}". Must be one of: {", ".join(sorted(VALID_GIT_PROVIDERS))}'
|
||||
)
|
||||
return v
|
||||
|
||||
@field_validator('git_organization')
|
||||
@classmethod
|
||||
def validate_git_organization(cls, v: str) -> str:
|
||||
v = v.strip().lower()
|
||||
if not v:
|
||||
raise ValueError('git_organization must not be empty')
|
||||
return v
|
||||
|
||||
|
||||
class GitOrgClaimResponse(BaseModel):
|
||||
"""Response model for a Git organization claim."""
|
||||
|
||||
id: str
|
||||
org_id: str
|
||||
provider: str
|
||||
git_organization: str
|
||||
claimed_by: str
|
||||
claimed_at: str
|
||||
|
||||
|
||||
class GitOrgAlreadyClaimedError(Exception):
|
||||
"""Raised when a Git organization is already claimed by another OpenHands org."""
|
||||
|
||||
def __init__(self, provider: str, git_organization: str):
|
||||
self.provider = provider
|
||||
self.git_organization = git_organization
|
||||
super().__init__(
|
||||
f'Git organization "{git_organization}" on {provider} is already claimed by another organization'
|
||||
)
|
||||
|
||||
|
||||
class OrgMemberFinancialResponse(BaseModel):
|
||||
"""Financial data for a single organization member."""
|
||||
|
||||
|
||||
@@ -10,9 +10,6 @@ from server.auth.authorization import (
|
||||
from server.email_validation import get_admin_user_id
|
||||
from server.routes.org_models import (
|
||||
CannotModifySelfError,
|
||||
GitOrgAlreadyClaimedError,
|
||||
GitOrgClaimRequest,
|
||||
GitOrgClaimResponse,
|
||||
InsufficientPermissionError,
|
||||
InvalidRoleError,
|
||||
LastOwnerError,
|
||||
@@ -49,8 +46,6 @@ from server.services.org_llm_settings_service import (
|
||||
)
|
||||
from server.services.org_member_financial_service import OrgMemberFinancialService
|
||||
from server.services.org_member_service import OrgMemberService
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from storage.org_git_claim_store import OrgGitClaimStore
|
||||
from storage.org_service import OrgService
|
||||
from storage.user_store import UserStore
|
||||
|
||||
@@ -1217,181 +1212,3 @@ async def update_org_member(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to update member',
|
||||
)
|
||||
|
||||
|
||||
@org_router.get(
|
||||
'/{org_id}/git-claims',
|
||||
response_model=list[GitOrgClaimResponse],
|
||||
)
|
||||
async def get_git_claims(
|
||||
org_id: UUID,
|
||||
user_id: str = Depends(require_permission(Permission.MANAGE_ORG_CLAIMS)),
|
||||
) -> list[GitOrgClaimResponse]:
|
||||
"""Get all Git organization claims for an OpenHands organization.
|
||||
|
||||
Only admin and owner roles can view Git organization claims.
|
||||
|
||||
Args:
|
||||
org_id: OpenHands organization UUID
|
||||
user_id: Authenticated user ID (injected by permission check)
|
||||
|
||||
Returns:
|
||||
List of GitOrgClaimResponse with claim details
|
||||
"""
|
||||
try:
|
||||
claims = await OrgGitClaimStore.get_claims_by_org_id(org_id=org_id)
|
||||
return [
|
||||
GitOrgClaimResponse(
|
||||
id=str(claim.id),
|
||||
org_id=str(claim.org_id),
|
||||
provider=claim.provider,
|
||||
git_organization=claim.git_organization,
|
||||
claimed_by=str(claim.claimed_by),
|
||||
claimed_at=claim.claimed_at.isoformat(),
|
||||
)
|
||||
for claim in claims
|
||||
]
|
||||
except Exception:
|
||||
logger.exception('Error fetching Git organization claims')
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to fetch Git organization claims',
|
||||
)
|
||||
|
||||
|
||||
@org_router.post(
|
||||
'/{org_id}/git-claims',
|
||||
response_model=GitOrgClaimResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
async def claim_git_organization(
|
||||
org_id: UUID,
|
||||
request: GitOrgClaimRequest,
|
||||
user_id: str = Depends(require_permission(Permission.MANAGE_ORG_CLAIMS)),
|
||||
) -> GitOrgClaimResponse:
|
||||
"""Claim a Git organization for an OpenHands organization.
|
||||
|
||||
Only admin and owner roles can claim Git organizations.
|
||||
A Git organization can only be claimed by one OpenHands organization at a time.
|
||||
|
||||
Args:
|
||||
org_id: OpenHands organization UUID
|
||||
request: Claim request with provider and git_organization
|
||||
user_id: Authenticated user ID (injected by permission check)
|
||||
|
||||
Returns:
|
||||
GitOrgClaimResponse with the created claim details
|
||||
|
||||
Raises:
|
||||
HTTPException 409: If the Git organization is already claimed
|
||||
HTTPException 403: If user lacks permission
|
||||
"""
|
||||
try:
|
||||
# Check if this Git org is already claimed (early feedback for the common case)
|
||||
existing_claim = await OrgGitClaimStore.get_claim_by_provider_and_git_org(
|
||||
provider=request.provider,
|
||||
git_organization=request.git_organization,
|
||||
)
|
||||
|
||||
if existing_claim:
|
||||
raise GitOrgAlreadyClaimedError(
|
||||
provider=request.provider,
|
||||
git_organization=request.git_organization,
|
||||
)
|
||||
|
||||
# Create the claim — the DB unique constraint handles the race condition
|
||||
# where two concurrent requests both pass the check above.
|
||||
claim = await OrgGitClaimStore.create_claim(
|
||||
org_id=org_id,
|
||||
provider=request.provider,
|
||||
git_organization=request.git_organization,
|
||||
claimed_by=UUID(user_id),
|
||||
)
|
||||
|
||||
return GitOrgClaimResponse(
|
||||
id=str(claim.id),
|
||||
org_id=str(claim.org_id),
|
||||
provider=claim.provider,
|
||||
git_organization=claim.git_organization,
|
||||
claimed_by=str(claim.claimed_by),
|
||||
claimed_at=claim.claimed_at.isoformat(),
|
||||
)
|
||||
|
||||
except GitOrgAlreadyClaimedError as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=str(e),
|
||||
)
|
||||
except IntegrityError as e:
|
||||
# Only treat the unique constraint violation as a duplicate claim.
|
||||
# Other integrity errors (e.g. FK violations) should surface as 500s.
|
||||
if 'uq_provider_git_org' in str(e.orig):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=str(
|
||||
GitOrgAlreadyClaimedError(
|
||||
provider=request.provider,
|
||||
git_organization=request.git_organization,
|
||||
)
|
||||
),
|
||||
)
|
||||
logger.exception('Integrity error claiming Git organization')
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to claim Git organization',
|
||||
)
|
||||
except Exception:
|
||||
logger.exception('Error claiming Git organization')
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to claim Git organization',
|
||||
)
|
||||
|
||||
|
||||
@org_router.delete(
|
||||
'/{org_id}/git-claims/{claim_id}',
|
||||
status_code=status.HTTP_200_OK,
|
||||
)
|
||||
async def disconnect_git_organization(
|
||||
org_id: UUID,
|
||||
claim_id: UUID,
|
||||
user_id: str = Depends(require_permission(Permission.MANAGE_ORG_CLAIMS)),
|
||||
) -> dict:
|
||||
"""Remove a Git organization claim from an OpenHands organization.
|
||||
|
||||
Only admin and owner roles can disconnect Git organization claims.
|
||||
|
||||
Args:
|
||||
org_id: OpenHands organization UUID
|
||||
claim_id: Claim UUID to remove
|
||||
user_id: Authenticated user ID (injected by permission check)
|
||||
|
||||
Returns:
|
||||
dict: Confirmation message on successful deletion
|
||||
|
||||
Raises:
|
||||
HTTPException 404: If the claim is not found for this organization
|
||||
HTTPException 403: If user lacks permission
|
||||
"""
|
||||
try:
|
||||
deleted = await OrgGitClaimStore.delete_claim(
|
||||
claim_id=claim_id,
|
||||
org_id=org_id,
|
||||
)
|
||||
|
||||
if not deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Git organization claim not found',
|
||||
)
|
||||
|
||||
return {'message': 'Git organization claim removed successfully'}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception('Error disconnecting Git organization')
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to disconnect Git organization',
|
||||
)
|
||||
|
||||
@@ -7,10 +7,8 @@ from server.auth.token_manager import TokenManager
|
||||
from storage.user_store import UserStore
|
||||
from utils.identity import resolve_display_name
|
||||
|
||||
from openhands.app_server.utils.dependencies import get_dependencies
|
||||
from openhands.integrations.provider import (
|
||||
PROVIDER_TOKEN_TYPE,
|
||||
ProviderHandler,
|
||||
)
|
||||
from openhands.integrations.service_types import (
|
||||
Branch,
|
||||
@@ -24,6 +22,7 @@ from openhands.microagent.types import (
|
||||
MicroagentContentResponse,
|
||||
MicroagentResponse,
|
||||
)
|
||||
from openhands.server.dependencies import get_dependencies
|
||||
from openhands.server.routes.git import (
|
||||
get_repository_branches,
|
||||
get_repository_microagent_content,
|
||||
@@ -45,12 +44,7 @@ saas_user_router = APIRouter(prefix='/api/user', dependencies=get_dependencies()
|
||||
token_manager = TokenManager()
|
||||
|
||||
|
||||
@saas_user_router.get(
|
||||
'/installations',
|
||||
response_model=list[str],
|
||||
deprecated=True,
|
||||
description='Deprecated: Use `/api/v1/git/installations` instead.',
|
||||
)
|
||||
@saas_user_router.get('/installations', response_model=list[str])
|
||||
async def saas_get_user_installations(
|
||||
provider: ProviderType,
|
||||
provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
|
||||
@@ -73,59 +67,7 @@ async def saas_get_user_installations(
|
||||
)
|
||||
|
||||
|
||||
@saas_user_router.get('/git-organizations')
|
||||
async def saas_get_user_git_organizations(
|
||||
provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
|
||||
access_token: SecretStr | None = Depends(get_access_token),
|
||||
user_id: str | None = Depends(get_user_id),
|
||||
):
|
||||
if not provider_tokens:
|
||||
retval = await _check_idp(
|
||||
access_token=access_token,
|
||||
default_value={},
|
||||
)
|
||||
if retval is not None:
|
||||
return retval
|
||||
# _check_idp returned None (tokens refreshed on Keycloak side),
|
||||
# but provider_tokens is still None for this request.
|
||||
return JSONResponse(
|
||||
content='Git provider token required.',
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
)
|
||||
|
||||
client = ProviderHandler(
|
||||
provider_tokens=provider_tokens,
|
||||
external_auth_token=access_token,
|
||||
external_auth_id=user_id,
|
||||
)
|
||||
|
||||
# SaaS users sign in with one provider at a time
|
||||
provider = next(iter(provider_tokens))
|
||||
|
||||
if provider == ProviderType.GITHUB:
|
||||
orgs = await client.get_github_organizations()
|
||||
elif provider == ProviderType.GITLAB:
|
||||
orgs = await client.get_gitlab_groups()
|
||||
elif provider == ProviderType.BITBUCKET:
|
||||
orgs = await client.get_bitbucket_workspaces()
|
||||
else:
|
||||
return JSONResponse(
|
||||
content=f"Provider {provider.value} doesn't support git organizations",
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
return {
|
||||
'provider': provider.value,
|
||||
'organizations': orgs,
|
||||
}
|
||||
|
||||
|
||||
@saas_user_router.get(
|
||||
'/repositories',
|
||||
response_model=list[Repository],
|
||||
deprecated=True,
|
||||
description='Deprecated: Use `/api/v1/git/repositories` instead.',
|
||||
)
|
||||
@saas_user_router.get('/repositories', response_model=list[Repository])
|
||||
async def saas_get_user_repositories(
|
||||
sort: str = 'pushed',
|
||||
selected_provider: ProviderType | None = None,
|
||||
@@ -156,13 +98,12 @@ async def saas_get_user_repositories(
|
||||
)
|
||||
|
||||
|
||||
@saas_user_router.get('/info', response_model=User, deprecated=True)
|
||||
@saas_user_router.get('/info', response_model=User)
|
||||
async def saas_get_user(
|
||||
provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),
|
||||
access_token: SecretStr | None = Depends(get_access_token),
|
||||
user_id: str | None = Depends(get_user_id),
|
||||
) -> User | JSONResponse:
|
||||
"""Get the current user git info. Use GET /api/v1/users/git-info instead"""
|
||||
if not provider_tokens:
|
||||
if not access_token:
|
||||
return JSONResponse(
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
"""SAAS-specific extensions for the /api/v1/users endpoints.
|
||||
|
||||
This module provides SAAS-specific implementations that extend the OSS
|
||||
user endpoints with organization context (org_id, org_name, role, permissions).
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, FastAPI, Header, HTTPException, Query, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from server.auth.saas_user_auth import SaasUserAuth
|
||||
from server.models.user_models import SaasUserInfo
|
||||
|
||||
from openhands.app_server.config import depends_user_context
|
||||
from openhands.app_server.sandbox.session_auth import validate_session_key_ownership
|
||||
from openhands.app_server.user.auth_user_context import AuthUserContext
|
||||
from openhands.app_server.user.user_context import UserContext
|
||||
from openhands.app_server.utils.dependencies import get_dependencies
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
saas_users_v1_router = APIRouter(
|
||||
prefix='/api/v1/users', tags=['User'], dependencies=get_dependencies()
|
||||
)
|
||||
user_dependency = depends_user_context()
|
||||
|
||||
|
||||
@saas_users_v1_router.get('/me')
|
||||
async def get_current_user_saas(
|
||||
user_context: UserContext = user_dependency,
|
||||
expose_secrets: bool = Query(
|
||||
default=False,
|
||||
description='If true, return unmasked secret values (e.g. llm_api_key). '
|
||||
'Requires a valid X-Session-API-Key header for an active sandbox '
|
||||
'owned by the authenticated user.',
|
||||
),
|
||||
x_session_api_key: str | None = Header(default=None),
|
||||
) -> SaasUserInfo:
|
||||
"""Get the current authenticated user with SAAS-specific org info.
|
||||
|
||||
Returns user settings along with organization context:
|
||||
- org_id: Current organization ID
|
||||
- org_name: Current organization name
|
||||
- role: User's role in the organization
|
||||
- permissions: List of permission strings for the role
|
||||
"""
|
||||
# Get base user info from the context
|
||||
base_user_info = await user_context.get_user_info()
|
||||
if base_user_info is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail='Not authenticated')
|
||||
|
||||
# Build SAAS user info from base settings
|
||||
user_info_data = base_user_info.model_dump(
|
||||
mode='json', context={'expose_secrets': True}
|
||||
)
|
||||
|
||||
# Add org info if available (from SaasUserAuth)
|
||||
org_info = await _get_org_info_from_context(user_context)
|
||||
if org_info:
|
||||
user_info_data.update(org_info)
|
||||
|
||||
user_info = SaasUserInfo(**user_info_data)
|
||||
|
||||
if expose_secrets:
|
||||
await validate_session_key_ownership(user_context, x_session_api_key)
|
||||
return JSONResponse( # type: ignore[return-value]
|
||||
content=user_info.model_dump(mode='json', context={'expose_secrets': True})
|
||||
)
|
||||
return user_info
|
||||
|
||||
|
||||
async def _get_org_info_from_context(user_context: UserContext) -> dict | None:
|
||||
"""Extract org info from the user context if available.
|
||||
|
||||
This works by checking if the underlying user_auth is a SaasUserAuth
|
||||
instance that has the get_org_info method.
|
||||
"""
|
||||
# Check if this is an AuthUserContext with a SaasUserAuth
|
||||
if isinstance(user_context, AuthUserContext):
|
||||
user_auth = user_context.user_auth
|
||||
if isinstance(user_auth, SaasUserAuth):
|
||||
return await user_auth.get_org_info()
|
||||
return None
|
||||
|
||||
|
||||
def override_users_me_endpoint(app: FastAPI) -> None:
|
||||
"""Override the OSS /api/v1/users/me endpoint with SAAS version.
|
||||
|
||||
This removes the base OSS endpoint and registers the SAAS version
|
||||
which includes organization context (org_id, org_name, role, permissions).
|
||||
|
||||
Must be called after the app is created in saas_server.py.
|
||||
"""
|
||||
# Find and remove the OSS /api/v1/users/me route
|
||||
routes_to_remove = []
|
||||
for route in app.routes:
|
||||
if hasattr(route, 'path') and route.path == '/api/v1/users/me':
|
||||
routes_to_remove.append(route)
|
||||
|
||||
for route in routes_to_remove:
|
||||
app.routes.remove(route)
|
||||
_logger.debug('Removed OSS route: %s', route.path)
|
||||
|
||||
# Add the SAAS version
|
||||
app.include_router(saas_users_v1_router)
|
||||
_logger.debug('Added SAAS /api/v1/users/me endpoint')
|
||||
@@ -363,11 +363,6 @@ class SaasSQLAppConversationInfoService(SQLAppConversationInfoService):
|
||||
if api_key_org_id is not None:
|
||||
org_id = api_key_org_id
|
||||
|
||||
# Override with resolver org_id if set (from git org claim resolution)
|
||||
resolver_org_id = getattr(self.user_context, 'resolver_org_id', None)
|
||||
if resolver_org_id is not None:
|
||||
org_id = resolver_org_id
|
||||
|
||||
# Check if SAAS metadata already exists
|
||||
saas_query = select(StoredConversationMetadataSaas).where(
|
||||
StoredConversationMetadataSaas.conversation_id == str(info.id)
|
||||
|
||||
@@ -17,7 +17,7 @@ from server.verified_models.verified_model_service import (
|
||||
|
||||
from openhands.app_server.config import get_db_session
|
||||
from openhands.server.routes import public
|
||||
from openhands.utils.llm import ModelsResponse, get_supported_llm_models
|
||||
from openhands.utils.llm import get_supported_llm_models
|
||||
|
||||
api_router = APIRouter(prefix='/api/admin/verified-models', tags=['Verified Models'])
|
||||
|
||||
@@ -117,7 +117,7 @@ async def delete_verified_model(
|
||||
)
|
||||
|
||||
|
||||
async def get_saas_llm_models_dependency(request: Request) -> ModelsResponse:
|
||||
async def get_saas_llm_models_dependency(request: Request) -> list[str]:
|
||||
"""SaaS implementation for the LLM models endpoint."""
|
||||
async with get_db_session(request.state, request) as db_session:
|
||||
# Prevent circular import
|
||||
|
||||
@@ -19,7 +19,6 @@ from storage.linear_workspace import LinearWorkspace
|
||||
from storage.maintenance_task import MaintenanceTask, MaintenanceTaskStatus
|
||||
from storage.openhands_pr import OpenhandsPR
|
||||
from storage.org import Org
|
||||
from storage.org_git_claim import OrgGitClaim
|
||||
from storage.org_invitation import OrgInvitation
|
||||
from storage.org_member import OrgMember
|
||||
from storage.proactive_convos import ProactiveConversation
|
||||
@@ -66,7 +65,6 @@ __all__ = [
|
||||
'MaintenanceTaskStatus',
|
||||
'OpenhandsPR',
|
||||
'Org',
|
||||
'OrgGitClaim',
|
||||
'OrgInvitation',
|
||||
'OrgMember',
|
||||
'ProactiveConversation',
|
||||
|
||||
@@ -64,7 +64,6 @@ class Org(Base): # type: ignore
|
||||
slack_conversations = relationship('SlackConversation', back_populates='org')
|
||||
slack_users = relationship('SlackUser', back_populates='org')
|
||||
stripe_customers = relationship('StripeCustomer', back_populates='org')
|
||||
git_claims = relationship('OrgGitClaim', back_populates='org')
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
# Handle known SQLAlchemy columns directly
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
"""
|
||||
SQLAlchemy model for Git Organization Claims.
|
||||
"""
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import UUID, Column, DateTime, ForeignKey, String, UniqueConstraint
|
||||
from sqlalchemy.orm import relationship
|
||||
from storage.base import Base
|
||||
|
||||
|
||||
class OrgGitClaim(Base): # type: ignore
|
||||
"""Model for tracking which OpenHands org has claimed a Git organization."""
|
||||
|
||||
__tablename__ = 'org_git_claim'
|
||||
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
|
||||
org_id = Column(
|
||||
UUID(as_uuid=True), ForeignKey('org.id', ondelete='CASCADE'), nullable=False
|
||||
)
|
||||
provider = Column(String, nullable=False)
|
||||
git_organization = Column(String, nullable=False)
|
||||
claimed_by = Column(UUID(as_uuid=True), ForeignKey('user.id'), nullable=False)
|
||||
claimed_at = Column(DateTime(timezone=True), nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint('provider', 'git_organization', name='uq_provider_git_org'),
|
||||
)
|
||||
|
||||
org = relationship('Org', back_populates='git_claims')
|
||||
@@ -1,141 +0,0 @@
|
||||
"""
|
||||
Store class for managing Git organization claims.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import and_, select
|
||||
from storage.database import a_session_maker
|
||||
from storage.org_git_claim import OrgGitClaim
|
||||
|
||||
from openhands.core.logger import openhands_logger as logger
|
||||
|
||||
|
||||
class OrgGitClaimStore:
|
||||
"""Store for managing Git organization claims."""
|
||||
|
||||
@staticmethod
|
||||
async def create_claim(
|
||||
org_id: UUID,
|
||||
provider: str,
|
||||
git_organization: str,
|
||||
claimed_by: UUID,
|
||||
) -> OrgGitClaim:
|
||||
"""Create a new Git organization claim.
|
||||
|
||||
Args:
|
||||
org_id: OpenHands organization UUID
|
||||
provider: Git provider ('github', 'gitlab', 'bitbucket')
|
||||
git_organization: Name of the Git organization being claimed
|
||||
claimed_by: User UUID who is making the claim
|
||||
|
||||
Returns:
|
||||
OrgGitClaim: The created claim record
|
||||
"""
|
||||
async with a_session_maker() as session:
|
||||
claim = OrgGitClaim(
|
||||
org_id=org_id,
|
||||
provider=provider,
|
||||
git_organization=git_organization,
|
||||
claimed_by=claimed_by,
|
||||
claimed_at=datetime.now(timezone.utc),
|
||||
)
|
||||
session.add(claim)
|
||||
await session.commit()
|
||||
await session.refresh(claim)
|
||||
|
||||
logger.info(
|
||||
'Created Git organization claim',
|
||||
extra={
|
||||
'claim_id': str(claim.id),
|
||||
'org_id': str(org_id),
|
||||
'provider': provider,
|
||||
'git_organization': git_organization,
|
||||
'claimed_by': str(claimed_by),
|
||||
},
|
||||
)
|
||||
|
||||
return claim
|
||||
|
||||
@staticmethod
|
||||
async def get_claim_by_provider_and_git_org(
|
||||
provider: str,
|
||||
git_organization: str,
|
||||
) -> Optional[OrgGitClaim]:
|
||||
"""Check if a Git organization is already claimed.
|
||||
|
||||
Args:
|
||||
provider: Git provider name
|
||||
git_organization: Name of the Git organization
|
||||
|
||||
Returns:
|
||||
OrgGitClaim or None if not claimed
|
||||
"""
|
||||
async with a_session_maker() as session:
|
||||
result = await session.execute(
|
||||
select(OrgGitClaim).filter(
|
||||
and_(
|
||||
OrgGitClaim.provider == provider,
|
||||
OrgGitClaim.git_organization == git_organization,
|
||||
)
|
||||
)
|
||||
)
|
||||
return result.scalars().first()
|
||||
|
||||
@staticmethod
|
||||
async def get_claims_by_org_id(org_id: UUID) -> list[OrgGitClaim]:
|
||||
"""Get all Git organization claims for an OpenHands organization.
|
||||
|
||||
Args:
|
||||
org_id: OpenHands organization UUID
|
||||
|
||||
Returns:
|
||||
List of OrgGitClaim records
|
||||
"""
|
||||
async with a_session_maker() as session:
|
||||
result = await session.execute(
|
||||
select(OrgGitClaim).filter(OrgGitClaim.org_id == org_id)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
@staticmethod
|
||||
async def delete_claim(claim_id: UUID, org_id: UUID) -> bool:
|
||||
"""Delete a Git organization claim.
|
||||
|
||||
Args:
|
||||
claim_id: Claim UUID to delete
|
||||
org_id: OpenHands organization UUID (for ownership verification)
|
||||
|
||||
Returns:
|
||||
True if deleted, False if not found
|
||||
"""
|
||||
async with a_session_maker() as session:
|
||||
result = await session.execute(
|
||||
select(OrgGitClaim).filter(
|
||||
and_(
|
||||
OrgGitClaim.id == claim_id,
|
||||
OrgGitClaim.org_id == org_id,
|
||||
)
|
||||
)
|
||||
)
|
||||
claim = result.scalars().first()
|
||||
|
||||
if not claim:
|
||||
return False
|
||||
|
||||
await session.delete(claim)
|
||||
await session.commit()
|
||||
|
||||
logger.info(
|
||||
'Deleted Git organization claim',
|
||||
extra={
|
||||
'claim_id': str(claim_id),
|
||||
'org_id': str(org_id),
|
||||
'provider': claim.provider,
|
||||
'git_organization': claim.git_organization,
|
||||
},
|
||||
)
|
||||
|
||||
return True
|
||||
@@ -34,17 +34,10 @@ class SaasConversationStore(ConversationStore):
|
||||
session_maker: sessionmaker
|
||||
org_id: UUID | None = None # will be fetched automatically
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
user_id: str,
|
||||
org_id: UUID,
|
||||
session_maker: sessionmaker,
|
||||
resolver_org_id: UUID | None = None,
|
||||
):
|
||||
def __init__(self, user_id: str, org_id: UUID, session_maker: sessionmaker):
|
||||
self.user_id = user_id
|
||||
self.org_id = org_id
|
||||
self.session_maker = session_maker
|
||||
self.resolver_org_id = resolver_org_id
|
||||
|
||||
def _select_by_id(self, session, conversation_id: str):
|
||||
# Join StoredConversationMetadata with ConversationMetadataSaas to filter by user/org
|
||||
@@ -110,13 +103,6 @@ class SaasConversationStore(ConversationStore):
|
||||
|
||||
stored_metadata = StoredConversationMetadata(**kwargs)
|
||||
|
||||
# Override with resolver org_id if set (from git org claim resolution),
|
||||
# same pattern as V1's save_app_conversation_info in
|
||||
# saas_app_conversation_info_injector.py
|
||||
org_id = self.org_id
|
||||
if self.resolver_org_id is not None:
|
||||
org_id = self.resolver_org_id
|
||||
|
||||
def _save_metadata():
|
||||
with self.session_maker() as session:
|
||||
# Save the main conversation metadata
|
||||
@@ -136,13 +122,13 @@ class SaasConversationStore(ConversationStore):
|
||||
saas_metadata = StoredConversationMetadataSaas(
|
||||
conversation_id=stored_metadata.conversation_id,
|
||||
user_id=UUID(self.user_id),
|
||||
org_id=org_id,
|
||||
org_id=self.org_id,
|
||||
)
|
||||
session.add(saas_metadata)
|
||||
else:
|
||||
# Validate
|
||||
expected_user_id = UUID(self.user_id)
|
||||
expected_org_id = org_id
|
||||
expected_org_id = self.org_id
|
||||
|
||||
if saas_metadata.user_id != expected_user_id:
|
||||
raise ValueError(
|
||||
@@ -254,19 +240,3 @@ class SaasConversationStore(ConversationStore):
|
||||
user = await UserStore.get_user_by_id(user_id)
|
||||
org_id = user.current_org_id if user else None
|
||||
return SaasConversationStore(user_id, org_id, session_maker)
|
||||
|
||||
@classmethod
|
||||
async def get_resolver_instance(
|
||||
cls,
|
||||
config: OpenHandsConfig,
|
||||
user_id: str,
|
||||
resolver_org_id: UUID | None = None,
|
||||
) -> 'SaasConversationStore':
|
||||
"""Get a store for resolver conversations with explicit org routing.
|
||||
|
||||
Unlike get_instance, this accepts a resolver_org_id that overrides
|
||||
the user's default org when saving conversation metadata.
|
||||
"""
|
||||
user = await UserStore.get_user_by_id(user_id)
|
||||
org_id = user.current_org_id if user else None
|
||||
return SaasConversationStore(user_id, org_id, session_maker, resolver_org_id)
|
||||
|
||||
@@ -182,13 +182,7 @@ class SaasSettingsStore(SettingsStore):
|
||||
return None
|
||||
|
||||
# Check if we need to generate an LLM key.
|
||||
# Only generate/verify proxy keys when the base URL is explicitly the
|
||||
# LiteLLM proxy, or when it's unset and the model is an OpenHands model
|
||||
# (which always needs a proxy key). For non-OpenHands models with no
|
||||
# base URL (e.g. basic view BYOR), preserve the user's own API key.
|
||||
if item.llm_base_url == LITE_LLM_API_URL or (
|
||||
not item.llm_base_url and is_openhands_model(item.llm_model)
|
||||
):
|
||||
if not item.llm_base_url or item.llm_base_url == LITE_LLM_API_URL:
|
||||
await self._ensure_api_key(
|
||||
item, str(org_id), openhands_type=is_openhands_model(item.llm_model)
|
||||
)
|
||||
|
||||
@@ -5,7 +5,6 @@ SQLAlchemy model for User.
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import (
|
||||
JSON,
|
||||
UUID,
|
||||
Boolean,
|
||||
Column,
|
||||
@@ -35,7 +34,6 @@ class User(Base): # type: ignore
|
||||
git_user_name = Column(String, nullable=True)
|
||||
git_user_email = Column(String, nullable=True)
|
||||
sandbox_grouping_strategy = Column(String, nullable=True)
|
||||
disabled_skills = Column(JSON, nullable=True)
|
||||
|
||||
# Relationships
|
||||
role = relationship('Role', back_populates='users')
|
||||
|
||||
@@ -13,6 +13,7 @@ Required environment variables:
|
||||
- RESEND_AUDIENCE_ID: ID of the Resend audience to add users to
|
||||
|
||||
Optional environment variables:
|
||||
- KEYCLOAK_PROVIDER_NAME: Provider name for Keycloak
|
||||
- KEYCLOAK_CLIENT_ID: Client ID for Keycloak
|
||||
- KEYCLOAK_CLIENT_SECRET: Client secret for Keycloak
|
||||
- RESEND_FROM_EMAIL: Email address to use as the sender (default: "OpenHands Team <no-reply@welcome.openhands.dev>")
|
||||
@@ -48,6 +49,7 @@ from openhands.core.logger import openhands_logger as logger
|
||||
# Get Keycloak configuration from environment variables
|
||||
KEYCLOAK_SERVER_URL = os.environ.get('KEYCLOAK_SERVER_URL', '')
|
||||
KEYCLOAK_REALM_NAME = os.environ.get('KEYCLOAK_REALM_NAME', '')
|
||||
KEYCLOAK_PROVIDER_NAME = os.environ.get('KEYCLOAK_PROVIDER_NAME', '')
|
||||
KEYCLOAK_CLIENT_ID = os.environ.get('KEYCLOAK_CLIENT_ID', '')
|
||||
KEYCLOAK_CLIENT_SECRET = os.environ.get('KEYCLOAK_CLIENT_SECRET', '')
|
||||
KEYCLOAK_ADMIN_PASSWORD = os.environ.get('KEYCLOAK_ADMIN_PASSWORD', '')
|
||||
|
||||
@@ -25,7 +25,6 @@ from storage.device_code import DeviceCode # noqa: F401
|
||||
from storage.feedback import Feedback
|
||||
from storage.github_app_installation import GithubAppInstallation
|
||||
from storage.org import Org
|
||||
from storage.org_git_claim import OrgGitClaim # noqa: F401
|
||||
from storage.org_invitation import OrgInvitation # noqa: F401
|
||||
from storage.org_member import OrgMember
|
||||
from storage.role import Role
|
||||
|
||||
@@ -88,7 +88,6 @@ class TestGithubViewV1InitialUserMessage:
|
||||
view.previous_comments = [MagicMock(author='alice', body='old comment 1')]
|
||||
|
||||
view._load_resolver_context = AsyncMock(side_effect=_load_context) # type: ignore[method-assign]
|
||||
view.resolved_org_id = None
|
||||
|
||||
fake_service = _FakeAppConversationService()
|
||||
mock_get_app_conversation_service.return_value = (
|
||||
@@ -145,7 +144,6 @@ class TestGithubViewV1InitialUserMessage:
|
||||
]
|
||||
|
||||
view._load_resolver_context = AsyncMock(side_effect=_load_context) # type: ignore[method-assign]
|
||||
view.resolved_org_id = None
|
||||
|
||||
fake_service = _FakeAppConversationService()
|
||||
mock_get_app_conversation_service.return_value = (
|
||||
@@ -202,7 +200,6 @@ class TestGithubViewV1InitialUserMessage:
|
||||
view.previous_comments = []
|
||||
|
||||
view._load_resolver_context = AsyncMock(side_effect=_load_context) # type: ignore[method-assign]
|
||||
view.resolved_org_id = None
|
||||
|
||||
fake_service = _FakeAppConversationService()
|
||||
mock_get_service.return_value = _fake_app_conversation_service_ctx(fake_service)
|
||||
|
||||
@@ -3,7 +3,6 @@ Tests for Jira view classes and factory.
|
||||
"""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from integrations.jira.jira_payload import (
|
||||
@@ -19,9 +18,6 @@ from integrations.jira.jira_view import (
|
||||
JiraNewConversationView,
|
||||
)
|
||||
|
||||
from openhands.integrations.service_types import ProviderType
|
||||
from openhands.server.user_auth.user_auth import UserAuth
|
||||
|
||||
|
||||
class TestJiraNewConversationView:
|
||||
"""Tests for JiraNewConversationView"""
|
||||
@@ -90,49 +86,29 @@ class TestJiraNewConversationView:
|
||||
assert 'Test Issue' in user_msg
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('integrations.jira.jira_view.resolve_org_for_repo', new_callable=AsyncMock)
|
||||
@patch('integrations.jira.jira_view.ProviderHandler')
|
||||
@patch(
|
||||
'integrations.jira.jira_view.SaasConversationStore.get_resolver_instance',
|
||||
new_callable=AsyncMock,
|
||||
)
|
||||
@patch('integrations.jira.jira_view.start_conversation', new_callable=AsyncMock)
|
||||
@patch('integrations.jira.jira_view.create_new_conversation')
|
||||
@patch('integrations.jira.jira_view.integration_store')
|
||||
async def test_create_or_update_conversation_success(
|
||||
self,
|
||||
mock_integration_store,
|
||||
mock_start_convo,
|
||||
mock_get_resolver_instance,
|
||||
mock_provider_handler_cls,
|
||||
mock_resolve_org,
|
||||
mock_store,
|
||||
mock_create_conversation,
|
||||
new_conversation_view,
|
||||
mock_jinja_env,
|
||||
mock_agent_loop_info,
|
||||
):
|
||||
"""Test successful conversation creation"""
|
||||
new_conversation_view._issue_title = 'Test Issue'
|
||||
new_conversation_view._issue_description = 'Test description'
|
||||
|
||||
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_create_conversation.return_value = mock_agent_loop_info
|
||||
mock_store.create_conversation = AsyncMock()
|
||||
|
||||
result = await new_conversation_view.create_or_update_conversation(
|
||||
mock_jinja_env
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert isinstance(result, str)
|
||||
assert len(result) == 32 # uuid4().hex format
|
||||
mock_start_convo.assert_called_once()
|
||||
mock_integration_store.create_conversation.assert_called_once()
|
||||
assert result == 'conv-123'
|
||||
mock_create_conversation.assert_called_once()
|
||||
mock_store.create_conversation.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_or_update_conversation_no_repo(
|
||||
@@ -372,125 +348,6 @@ class TestJiraFactory:
|
||||
)
|
||||
|
||||
|
||||
CLAIMING_ORG_ID = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
|
||||
|
||||
|
||||
class TestJiraV0ConversationRouting:
|
||||
"""Test V0 conversation routing logic based on claimed git organizations."""
|
||||
|
||||
@pytest.fixture
|
||||
def routing_view(
|
||||
self,
|
||||
sample_webhook_payload,
|
||||
sample_jira_user,
|
||||
sample_jira_workspace,
|
||||
):
|
||||
"""View with non-empty provider tokens for routing tests."""
|
||||
user_auth = MagicMock(spec=UserAuth)
|
||||
user_auth.get_provider_tokens = AsyncMock(
|
||||
return_value={ProviderType.GITHUB: MagicMock()}
|
||||
)
|
||||
user_auth.get_secrets = AsyncMock(return_value=None)
|
||||
return JiraNewConversationView(
|
||||
payload=sample_webhook_payload,
|
||||
saas_user_auth=user_auth,
|
||||
jira_user=sample_jira_user,
|
||||
jira_workspace=sample_jira_workspace,
|
||||
selected_repo='test/repo1',
|
||||
_issue_title='Test Issue',
|
||||
_issue_description='Test description',
|
||||
_decrypted_api_key='decrypted_key',
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('integrations.jira.jira_view.resolve_org_for_repo', new_callable=AsyncMock)
|
||||
@patch('integrations.jira.jira_view.ProviderHandler')
|
||||
@patch(
|
||||
'integrations.jira.jira_view.SaasConversationStore.get_resolver_instance',
|
||||
new_callable=AsyncMock,
|
||||
)
|
||||
@patch('integrations.jira.jira_view.start_conversation', new_callable=AsyncMock)
|
||||
@patch('integrations.jira.jira_view.integration_store')
|
||||
async def test_routes_to_claimed_org_when_user_is_member(
|
||||
self,
|
||||
mock_integration_store,
|
||||
mock_start_convo,
|
||||
mock_get_resolver_instance,
|
||||
mock_provider_handler_cls,
|
||||
mock_resolve_org,
|
||||
routing_view,
|
||||
mock_jinja_env,
|
||||
):
|
||||
"""When repo belongs to a claimed org and user is a member, conversation is created in that org."""
|
||||
# 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()
|
||||
|
||||
# Act
|
||||
await routing_view.create_or_update_conversation(mock_jinja_env)
|
||||
|
||||
# Assert
|
||||
mock_resolve_org.assert_called_once_with(
|
||||
provider='github',
|
||||
full_repo_name='test/repo1',
|
||||
keycloak_user_id='test_keycloak_id',
|
||||
)
|
||||
call_args = mock_get_resolver_instance.call_args
|
||||
assert call_args[0][1] == 'test_keycloak_id' # user_id
|
||||
assert call_args[0][2] == CLAIMING_ORG_ID # resolver_org_id
|
||||
saved_metadata = mock_store.save_metadata.call_args[0][0]
|
||||
assert saved_metadata.git_provider == ProviderType.GITHUB
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('integrations.jira.jira_view.resolve_org_for_repo', new_callable=AsyncMock)
|
||||
@patch('integrations.jira.jira_view.ProviderHandler')
|
||||
@patch(
|
||||
'integrations.jira.jira_view.SaasConversationStore.get_resolver_instance',
|
||||
new_callable=AsyncMock,
|
||||
)
|
||||
@patch('integrations.jira.jira_view.start_conversation', new_callable=AsyncMock)
|
||||
@patch('integrations.jira.jira_view.integration_store')
|
||||
async def test_falls_back_to_personal_workspace_when_no_claim(
|
||||
self,
|
||||
mock_integration_store,
|
||||
mock_start_convo,
|
||||
mock_get_resolver_instance,
|
||||
mock_provider_handler_cls,
|
||||
mock_resolve_org,
|
||||
routing_view,
|
||||
mock_jinja_env,
|
||||
):
|
||||
"""When no org has claimed the git org, conversation goes 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.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()
|
||||
|
||||
# Act
|
||||
await routing_view.create_or_update_conversation(mock_jinja_env)
|
||||
|
||||
# Assert
|
||||
call_args = mock_get_resolver_instance.call_args
|
||||
assert call_args[0][2] is None # resolver_org_id is None
|
||||
|
||||
|
||||
class TestJiraPayloadParser:
|
||||
"""Tests for JiraPayloadParser"""
|
||||
|
||||
|
||||
@@ -73,7 +73,6 @@ 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
|
||||
|
||||
@@ -29,33 +29,27 @@ class TestLinearNewConversationView:
|
||||
assert 'Test Issue' in user_msg
|
||||
assert 'Fix this bug @openhands' in user_msg
|
||||
|
||||
@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.create_new_conversation')
|
||||
@patch('integrations.linear.linear_view.integration_store')
|
||||
async def test_create_or_update_conversation_success(
|
||||
self,
|
||||
mock_integration_store,
|
||||
mock_start_convo,
|
||||
mock_get_resolver_instance,
|
||||
mock_store,
|
||||
mock_create_conversation,
|
||||
new_conversation_view,
|
||||
mock_jinja_env,
|
||||
mock_agent_loop_info,
|
||||
):
|
||||
"""Test successful conversation creation"""
|
||||
mock_store = MagicMock()
|
||||
mock_store.save_metadata = AsyncMock()
|
||||
mock_get_resolver_instance.return_value = mock_store
|
||||
mock_integration_store.create_conversation = AsyncMock()
|
||||
mock_create_conversation.return_value = mock_agent_loop_info
|
||||
mock_store.create_conversation = AsyncMock()
|
||||
|
||||
result = await new_conversation_view.create_or_update_conversation(
|
||||
mock_jinja_env
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
mock_start_convo.assert_called_once()
|
||||
mock_integration_store.create_conversation.assert_called_once()
|
||||
assert result == 'conv-123'
|
||||
mock_create_conversation.assert_called_once()
|
||||
mock_store.create_conversation.assert_called_once()
|
||||
|
||||
async def test_create_or_update_conversation_no_repo(
|
||||
self, new_conversation_view, mock_jinja_env
|
||||
@@ -66,23 +60,12 @@ 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.SaasConversationStore.get_resolver_instance',
|
||||
new_callable=AsyncMock,
|
||||
)
|
||||
@patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
|
||||
@patch('integrations.linear.linear_view.create_new_conversation')
|
||||
async def test_create_or_update_conversation_failure(
|
||||
self,
|
||||
mock_start_convo,
|
||||
mock_get_resolver_instance,
|
||||
new_conversation_view,
|
||||
mock_jinja_env,
|
||||
self, mock_create_conversation, new_conversation_view, mock_jinja_env
|
||||
):
|
||||
"""Test conversation creation failure"""
|
||||
mock_store = MagicMock()
|
||||
mock_store.save_metadata = AsyncMock()
|
||||
mock_get_resolver_instance.return_value = mock_store
|
||||
mock_start_convo.side_effect = Exception('Creation failed')
|
||||
mock_create_conversation.side_effect = Exception('Creation failed')
|
||||
|
||||
with pytest.raises(
|
||||
StartingConvoException, match='Failed to create conversation'
|
||||
@@ -317,57 +300,43 @@ class TestLinearFactory:
|
||||
class TestLinearViewEdgeCases:
|
||||
"""Tests for edge cases and error scenarios"""
|
||||
|
||||
@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.create_new_conversation')
|
||||
@patch('integrations.linear.linear_view.integration_store')
|
||||
async def test_conversation_creation_with_no_user_secrets(
|
||||
self,
|
||||
mock_integration_store,
|
||||
mock_start_convo,
|
||||
mock_get_resolver_instance,
|
||||
mock_store,
|
||||
mock_create_conversation,
|
||||
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 = 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()
|
||||
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()
|
||||
|
||||
result = await new_conversation_view.create_or_update_conversation(
|
||||
mock_jinja_env
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
# Verify start_conversation was called with custom_secrets=None
|
||||
call_kwargs = mock_start_convo.call_args[1]
|
||||
assert result == 'conv-123'
|
||||
# Verify create_new_conversation was called with custom_secrets=None
|
||||
call_kwargs = mock_create_conversation.call_args[1]
|
||||
assert call_kwargs['custom_secrets'] is None
|
||||
|
||||
@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.create_new_conversation')
|
||||
@patch('integrations.linear.linear_view.integration_store')
|
||||
async def test_conversation_creation_store_failure(
|
||||
self,
|
||||
mock_integration_store,
|
||||
mock_start_convo,
|
||||
mock_get_resolver_instance,
|
||||
mock_store,
|
||||
mock_create_conversation,
|
||||
new_conversation_view,
|
||||
mock_jinja_env,
|
||||
mock_agent_loop_info,
|
||||
):
|
||||
"""Test conversation creation when store creation fails"""
|
||||
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')
|
||||
)
|
||||
mock_create_conversation.return_value = mock_agent_loop_info
|
||||
mock_store.create_conversation = AsyncMock(side_effect=Exception('Store error'))
|
||||
|
||||
with pytest.raises(
|
||||
StartingConvoException, match='Failed to create conversation'
|
||||
|
||||
@@ -32,28 +32,6 @@ def resolver_context(mock_saas_user_auth):
|
||||
return ResolverUserContext(saas_user_auth=mock_saas_user_auth)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests for resolver_org_id - org routing for resolver conversations
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_resolver_org_id_defaults_to_none(mock_saas_user_auth):
|
||||
"""Test that resolver_org_id defaults to None when not provided."""
|
||||
ctx = ResolverUserContext(saas_user_auth=mock_saas_user_auth)
|
||||
assert ctx.resolver_org_id is None
|
||||
|
||||
|
||||
def test_resolver_org_id_can_be_set_via_constructor(mock_saas_user_auth):
|
||||
"""Test that resolver_org_id can be set via constructor for org routing."""
|
||||
from uuid import UUID
|
||||
|
||||
org_id = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
|
||||
ctx = ResolverUserContext(
|
||||
saas_user_auth=mock_saas_user_auth, resolver_org_id=org_id
|
||||
)
|
||||
assert ctx.resolver_org_id == org_id
|
||||
|
||||
|
||||
def create_custom_secret(value: str, description: str = 'Test secret') -> CustomSecret:
|
||||
"""Helper to create CustomSecret instances."""
|
||||
return CustomSecret(secret=SecretStr(value), description=description)
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
"""Tests for resolver org routing logic.
|
||||
|
||||
Tests the resolve_org_for_repo function which determines which OpenHands
|
||||
organization workspace a resolver conversation should be created in.
|
||||
"""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
|
||||
CLAIMING_ORG_ID = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
|
||||
USER_ID = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'
|
||||
|
||||
# Patch at module level where the names are looked up
|
||||
_CLAIM_STORE = 'enterprise.integrations.resolver_org_router.OrgGitClaimStore'
|
||||
_MEMBER_STORE = 'enterprise.integrations.resolver_org_router.OrgMemberStore'
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_stores():
|
||||
"""Mock OrgGitClaimStore and OrgMemberStore for all tests."""
|
||||
with (
|
||||
patch(_CLAIM_STORE) as mock_claim_store,
|
||||
patch(_MEMBER_STORE) as mock_member_store,
|
||||
):
|
||||
mock_claim_store.get_claim_by_provider_and_git_org = AsyncMock(
|
||||
return_value=None
|
||||
)
|
||||
mock_member_store.get_org_member = AsyncMock(return_value=None)
|
||||
yield mock_claim_store, mock_member_store
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_org_id_when_claimed_and_user_is_member(mock_stores):
|
||||
"""When the git org is claimed and the user is a member, return the claiming org's ID."""
|
||||
from enterprise.integrations.resolver_org_router import resolve_org_for_repo
|
||||
|
||||
mock_claim_store, mock_member_store = mock_stores
|
||||
|
||||
# Arrange
|
||||
claim = MagicMock()
|
||||
claim.org_id = CLAIMING_ORG_ID
|
||||
mock_claim_store.get_claim_by_provider_and_git_org.return_value = claim
|
||||
mock_member_store.get_org_member.return_value = MagicMock() # member exists
|
||||
|
||||
# Act
|
||||
result = await resolve_org_for_repo('github', 'OpenHands/foo', USER_ID)
|
||||
|
||||
# Assert
|
||||
assert result == CLAIMING_ORG_ID
|
||||
mock_claim_store.get_claim_by_provider_and_git_org.assert_called_once_with(
|
||||
'github', 'openhands'
|
||||
)
|
||||
mock_member_store.get_org_member.assert_called_once_with(
|
||||
CLAIMING_ORG_ID, UUID(USER_ID)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_none_when_claimed_but_user_not_member(mock_stores):
|
||||
"""When the git org is claimed but user is not a member, return None."""
|
||||
from enterprise.integrations.resolver_org_router import resolve_org_for_repo
|
||||
|
||||
mock_claim_store, mock_member_store = mock_stores
|
||||
|
||||
# Arrange
|
||||
claim = MagicMock()
|
||||
claim.org_id = CLAIMING_ORG_ID
|
||||
mock_claim_store.get_claim_by_provider_and_git_org.return_value = claim
|
||||
mock_member_store.get_org_member.return_value = None
|
||||
|
||||
# Act
|
||||
result = await resolve_org_for_repo('github', 'OpenHands/foo', USER_ID)
|
||||
|
||||
# Assert
|
||||
assert result is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_none_when_no_claim_exists(mock_stores):
|
||||
"""When no org has claimed the git organization, return None."""
|
||||
from enterprise.integrations.resolver_org_router import resolve_org_for_repo
|
||||
|
||||
mock_claim_store, _ = mock_stores
|
||||
mock_claim_store.get_claim_by_provider_and_git_org.return_value = None
|
||||
|
||||
# Act
|
||||
result = await resolve_org_for_repo('github', 'UnclaimedOrg/repo', USER_ID)
|
||||
|
||||
# Assert
|
||||
assert result is None
|
||||
mock_claim_store.get_claim_by_provider_and_git_org.assert_called_once_with(
|
||||
'github', 'unclaimedorg'
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_extracts_git_org_lowercase_from_repo_name(mock_stores):
|
||||
"""The git org is extracted from repo name and lowercased for claim lookup."""
|
||||
from enterprise.integrations.resolver_org_router import resolve_org_for_repo
|
||||
|
||||
mock_claim_store, _ = mock_stores
|
||||
|
||||
# Act
|
||||
await resolve_org_for_repo('github', 'MyOrg/some-repo', USER_ID)
|
||||
|
||||
# Assert
|
||||
mock_claim_store.get_claim_by_provider_and_git_org.assert_called_once_with(
|
||||
'github', 'myorg'
|
||||
)
|
||||
@@ -1,351 +0,0 @@
|
||||
"""Unit tests for SaasUserAuth.get_org_info() using SQLite in-memory database.
|
||||
|
||||
These tests exercise the real `get_org_info()` implementation with actual DB queries
|
||||
to catch regressions in the SAAS org lookup logic.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from pydantic import SecretStr
|
||||
from server.auth.saas_user_auth import SaasUserAuth
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from storage.base import Base
|
||||
from storage.org import Org
|
||||
from storage.org_member import OrgMember
|
||||
from storage.role import Role
|
||||
from storage.user import User
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def async_engine():
|
||||
"""Create an async SQLite engine for testing."""
|
||||
engine = create_async_engine(
|
||||
'sqlite+aiosqlite:///:memory:',
|
||||
poolclass=StaticPool,
|
||||
connect_args={'check_same_thread': False},
|
||||
)
|
||||
return engine
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def async_session_maker(async_engine):
|
||||
"""Create an async session maker bound to the async engine."""
|
||||
session_maker = async_sessionmaker(
|
||||
bind=async_engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
async with async_engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
return session_maker
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_id():
|
||||
"""Generate a unique user ID for tests."""
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def org_id():
|
||||
"""Generate a unique org ID for tests."""
|
||||
return uuid.uuid4()
|
||||
|
||||
|
||||
async def create_role(session_maker, name: str, rank: int) -> Role:
|
||||
"""Helper to create a role in the test database."""
|
||||
async with session_maker() as session:
|
||||
role = Role(name=name, rank=rank)
|
||||
session.add(role)
|
||||
await session.commit()
|
||||
await session.refresh(role)
|
||||
return role
|
||||
|
||||
|
||||
async def create_org(session_maker, org_id: uuid.UUID, name: str) -> Org:
|
||||
"""Helper to create an org in the test database."""
|
||||
async with session_maker() as session:
|
||||
org = Org(
|
||||
id=org_id,
|
||||
name=name,
|
||||
org_version=1,
|
||||
enable_default_condenser=True,
|
||||
enable_proactive_conversation_starters=True,
|
||||
)
|
||||
session.add(org)
|
||||
await session.commit()
|
||||
await session.refresh(org)
|
||||
return org
|
||||
|
||||
|
||||
async def create_user(session_maker, user_id: str, current_org_id: uuid.UUID) -> User:
|
||||
"""Helper to create a user in the test database."""
|
||||
async with session_maker() as session:
|
||||
user = User(
|
||||
id=uuid.UUID(user_id),
|
||||
current_org_id=current_org_id,
|
||||
user_consents_to_analytics=True,
|
||||
)
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
await session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
async def create_org_member(
|
||||
session_maker,
|
||||
org_id: uuid.UUID,
|
||||
user_id: str,
|
||||
role_id: int,
|
||||
status: str = 'active',
|
||||
llm_api_key: str = 'test-api-key',
|
||||
) -> OrgMember:
|
||||
"""Helper to create an org member in the test database."""
|
||||
async with session_maker() as session:
|
||||
org_member = OrgMember(
|
||||
org_id=org_id,
|
||||
user_id=uuid.UUID(user_id),
|
||||
role_id=role_id,
|
||||
status=status,
|
||||
llm_api_key=llm_api_key,
|
||||
)
|
||||
session.add(org_member)
|
||||
await session.commit()
|
||||
await session.refresh(org_member)
|
||||
return org_member
|
||||
|
||||
|
||||
class TestGetOrgInfoWithRealDB:
|
||||
"""Tests for get_org_info() using in-memory SQLite database."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_org_info_returns_correct_data_for_owner(
|
||||
self, async_session_maker, user_id, org_id
|
||||
):
|
||||
"""Test that get_org_info returns correct data for an owner role."""
|
||||
# Set up test data
|
||||
owner_role = await create_role(async_session_maker, 'owner', 1)
|
||||
await create_org(async_session_maker, org_id, 'Test Organization')
|
||||
await create_user(async_session_maker, user_id, org_id)
|
||||
await create_org_member(async_session_maker, org_id, user_id, owner_role.id)
|
||||
|
||||
# Create SaasUserAuth instance
|
||||
user_auth = SaasUserAuth(
|
||||
user_id=user_id,
|
||||
refresh_token=SecretStr('mock_refresh_token'),
|
||||
)
|
||||
|
||||
# Patch the global a_session_maker in all stores that use it
|
||||
with patch('storage.user_store.a_session_maker', async_session_maker), patch(
|
||||
'storage.org_store.a_session_maker', async_session_maker
|
||||
), patch(
|
||||
'storage.org_member_store.a_session_maker', async_session_maker
|
||||
), patch('storage.role_store.a_session_maker', async_session_maker):
|
||||
org_info = await user_auth.get_org_info()
|
||||
|
||||
assert org_info is not None
|
||||
assert org_info['org_id'] == str(org_id)
|
||||
assert org_info['org_name'] == 'Test Organization'
|
||||
assert org_info['role'] == 'owner'
|
||||
assert isinstance(org_info['permissions'], list)
|
||||
# Owner should have many permissions
|
||||
assert len(org_info['permissions']) > 0
|
||||
assert 'manage_secrets' in org_info['permissions']
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_org_info_returns_correct_data_for_member(
|
||||
self, async_session_maker, user_id, org_id
|
||||
):
|
||||
"""Test that get_org_info returns correct data for a member role."""
|
||||
# Set up test data
|
||||
member_role = await create_role(async_session_maker, 'member', 3)
|
||||
await create_org(async_session_maker, org_id, 'Member Org')
|
||||
await create_user(async_session_maker, user_id, org_id)
|
||||
await create_org_member(async_session_maker, org_id, user_id, member_role.id)
|
||||
|
||||
user_auth = SaasUserAuth(
|
||||
user_id=user_id,
|
||||
refresh_token=SecretStr('mock_refresh_token'),
|
||||
)
|
||||
|
||||
with patch('storage.user_store.a_session_maker', async_session_maker), patch(
|
||||
'storage.org_store.a_session_maker', async_session_maker
|
||||
), patch(
|
||||
'storage.org_member_store.a_session_maker', async_session_maker
|
||||
), patch('storage.role_store.a_session_maker', async_session_maker):
|
||||
org_info = await user_auth.get_org_info()
|
||||
|
||||
assert org_info is not None
|
||||
assert org_info['org_id'] == str(org_id)
|
||||
assert org_info['org_name'] == 'Member Org'
|
||||
assert org_info['role'] == 'member'
|
||||
# Member should have limited permissions
|
||||
assert isinstance(org_info['permissions'], list)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_org_info_returns_correct_data_for_admin(
|
||||
self, async_session_maker, user_id, org_id
|
||||
):
|
||||
"""Test that get_org_info returns correct data for an admin role."""
|
||||
# Set up test data
|
||||
admin_role = await create_role(async_session_maker, 'admin', 2)
|
||||
await create_org(async_session_maker, org_id, 'Admin Org')
|
||||
await create_user(async_session_maker, user_id, org_id)
|
||||
await create_org_member(async_session_maker, org_id, user_id, admin_role.id)
|
||||
|
||||
user_auth = SaasUserAuth(
|
||||
user_id=user_id,
|
||||
refresh_token=SecretStr('mock_refresh_token'),
|
||||
)
|
||||
|
||||
with patch('storage.user_store.a_session_maker', async_session_maker), patch(
|
||||
'storage.org_store.a_session_maker', async_session_maker
|
||||
), patch(
|
||||
'storage.org_member_store.a_session_maker', async_session_maker
|
||||
), patch('storage.role_store.a_session_maker', async_session_maker):
|
||||
org_info = await user_auth.get_org_info()
|
||||
|
||||
assert org_info is not None
|
||||
assert org_info['org_id'] == str(org_id)
|
||||
assert org_info['org_name'] == 'Admin Org'
|
||||
assert org_info['role'] == 'admin'
|
||||
assert isinstance(org_info['permissions'], list)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_org_info_returns_none_when_user_not_found(
|
||||
self, async_session_maker
|
||||
):
|
||||
"""Test that get_org_info returns None when user doesn't exist."""
|
||||
nonexistent_user_id = str(uuid.uuid4())
|
||||
|
||||
user_auth = SaasUserAuth(
|
||||
user_id=nonexistent_user_id,
|
||||
refresh_token=SecretStr('mock_refresh_token'),
|
||||
)
|
||||
|
||||
with patch('storage.user_store.a_session_maker', async_session_maker), patch(
|
||||
'storage.org_store.a_session_maker', async_session_maker
|
||||
), patch(
|
||||
'storage.org_member_store.a_session_maker', async_session_maker
|
||||
), patch('storage.role_store.a_session_maker', async_session_maker):
|
||||
org_info = await user_auth.get_org_info()
|
||||
|
||||
assert org_info is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_org_info_returns_none_when_org_not_found(
|
||||
self, async_session_maker, user_id
|
||||
):
|
||||
"""Test that get_org_info returns None when user's org doesn't exist."""
|
||||
nonexistent_org_id = uuid.uuid4()
|
||||
|
||||
# Create user pointing to nonexistent org
|
||||
async with async_session_maker() as session:
|
||||
user = User(
|
||||
id=uuid.UUID(user_id),
|
||||
current_org_id=nonexistent_org_id,
|
||||
user_consents_to_analytics=True,
|
||||
)
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
|
||||
user_auth = SaasUserAuth(
|
||||
user_id=user_id,
|
||||
refresh_token=SecretStr('mock_refresh_token'),
|
||||
)
|
||||
|
||||
with patch('storage.user_store.a_session_maker', async_session_maker), patch(
|
||||
'storage.org_store.a_session_maker', async_session_maker
|
||||
), patch(
|
||||
'storage.org_member_store.a_session_maker', async_session_maker
|
||||
), patch('storage.role_store.a_session_maker', async_session_maker):
|
||||
org_info = await user_auth.get_org_info()
|
||||
|
||||
assert org_info is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_org_info_caches_result(
|
||||
self, async_session_maker, user_id, org_id
|
||||
):
|
||||
"""Test that get_org_info caches the result and doesn't hit DB twice."""
|
||||
# Set up test data
|
||||
owner_role = await create_role(async_session_maker, 'owner', 1)
|
||||
await create_org(async_session_maker, org_id, 'Cached Org')
|
||||
await create_user(async_session_maker, user_id, org_id)
|
||||
await create_org_member(async_session_maker, org_id, user_id, owner_role.id)
|
||||
|
||||
user_auth = SaasUserAuth(
|
||||
user_id=user_id,
|
||||
refresh_token=SecretStr('mock_refresh_token'),
|
||||
)
|
||||
|
||||
with patch('storage.user_store.a_session_maker', async_session_maker), patch(
|
||||
'storage.org_store.a_session_maker', async_session_maker
|
||||
), patch(
|
||||
'storage.org_member_store.a_session_maker', async_session_maker
|
||||
), patch('storage.role_store.a_session_maker', async_session_maker):
|
||||
# First call
|
||||
org_info1 = await user_auth.get_org_info()
|
||||
assert org_info1 is not None
|
||||
assert user_auth._org_info_loaded is True
|
||||
|
||||
# Second call should return cached result
|
||||
org_info2 = await user_auth.get_org_info()
|
||||
assert org_info2 is not None
|
||||
assert org_info1 == org_info2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_org_info_caches_none_result(self, async_session_maker):
|
||||
"""Test that get_org_info caches None result for nonexistent user."""
|
||||
nonexistent_user_id = str(uuid.uuid4())
|
||||
|
||||
user_auth = SaasUserAuth(
|
||||
user_id=nonexistent_user_id,
|
||||
refresh_token=SecretStr('mock_refresh_token'),
|
||||
)
|
||||
|
||||
with patch('storage.user_store.a_session_maker', async_session_maker), patch(
|
||||
'storage.org_store.a_session_maker', async_session_maker
|
||||
), patch(
|
||||
'storage.org_member_store.a_session_maker', async_session_maker
|
||||
), patch('storage.role_store.a_session_maker', async_session_maker):
|
||||
# First call
|
||||
org_info1 = await user_auth.get_org_info()
|
||||
assert org_info1 is None
|
||||
assert user_auth._org_info_loaded is True
|
||||
|
||||
# Second call should return cached None without hitting DB
|
||||
org_info2 = await user_auth.get_org_info()
|
||||
assert org_info2 is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_org_info_with_unknown_role_returns_empty_permissions(
|
||||
self, async_session_maker, user_id, org_id
|
||||
):
|
||||
"""Test that get_org_info returns empty permissions for unknown role."""
|
||||
# Create a custom role that isn't in the ROLE_PERMISSIONS mapping
|
||||
custom_role = await create_role(async_session_maker, 'custom_role', 99)
|
||||
await create_org(async_session_maker, org_id, 'Custom Org')
|
||||
await create_user(async_session_maker, user_id, org_id)
|
||||
await create_org_member(async_session_maker, org_id, user_id, custom_role.id)
|
||||
|
||||
user_auth = SaasUserAuth(
|
||||
user_id=user_id,
|
||||
refresh_token=SecretStr('mock_refresh_token'),
|
||||
)
|
||||
|
||||
with patch('storage.user_store.a_session_maker', async_session_maker), patch(
|
||||
'storage.org_store.a_session_maker', async_session_maker
|
||||
), patch(
|
||||
'storage.org_member_store.a_session_maker', async_session_maker
|
||||
), patch('storage.role_store.a_session_maker', async_session_maker):
|
||||
org_info = await user_auth.get_org_info()
|
||||
|
||||
assert org_info is not None
|
||||
assert org_info['org_id'] == str(org_id)
|
||||
assert org_info['role'] == 'custom_role'
|
||||
# Unknown roles should have empty permissions
|
||||
assert org_info['permissions'] == []
|
||||
@@ -1,603 +0,0 @@
|
||||
"""Tests for Git organization claim API endpoints.
|
||||
|
||||
Tests the following endpoints:
|
||||
- GET /api/organizations/{org_id}/git-claims (list claims)
|
||||
- POST /api/organizations/{org_id}/git-claims (claim)
|
||||
- DELETE /api/organizations/{org_id}/git-claims/{claim_id} (disconnect)
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI, status
|
||||
from fastapi.testclient import TestClient
|
||||
from server.routes.orgs import (
|
||||
claim_git_organization,
|
||||
disconnect_git_organization,
|
||||
get_git_claims,
|
||||
org_router,
|
||||
)
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from storage.org_git_claim import OrgGitClaim
|
||||
|
||||
from openhands.server.user_auth import get_user_id
|
||||
|
||||
TEST_USER_ID = str(uuid.uuid4())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def org_id():
|
||||
return uuid.uuid4()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_id():
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_claim():
|
||||
"""Factory to create mock OrgGitClaim objects."""
|
||||
|
||||
def _make(org_id, provider='github', git_organization='OpenHands', claimed_by=None):
|
||||
claim = MagicMock(spec=OrgGitClaim)
|
||||
claim.id = uuid.uuid4()
|
||||
claim.org_id = org_id
|
||||
claim.provider = provider
|
||||
claim.git_organization = git_organization
|
||||
claim.claimed_by = claimed_by or uuid.uuid4()
|
||||
claim.claimed_at = datetime(2026, 4, 1, 12, 0, 0)
|
||||
return claim
|
||||
|
||||
return _make
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# GET /api/organizations/{org_id}/git-claims
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestGetGitClaims:
|
||||
"""Tests for the get Git organization claims endpoint."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_empty_list_when_no_claims(self, org_id, user_id):
|
||||
"""
|
||||
GIVEN: An organization with no Git claims
|
||||
WHEN: GET /api/organizations/{org_id}/git-claims is called
|
||||
THEN: An empty list is returned
|
||||
"""
|
||||
with patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.get_claims_by_org_id',
|
||||
AsyncMock(return_value=[]),
|
||||
) as mock_get:
|
||||
result = await get_git_claims(org_id=org_id, user_id=user_id)
|
||||
|
||||
assert result == []
|
||||
mock_get.assert_called_once_with(org_id=org_id)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_claims_for_organization(self, org_id, user_id, make_claim):
|
||||
"""
|
||||
GIVEN: An organization with multiple Git claims
|
||||
WHEN: GET /api/organizations/{org_id}/git-claims is called
|
||||
THEN: All claims are returned with correct details
|
||||
"""
|
||||
claim1 = make_claim(org_id, provider='github', git_organization='OpenHands')
|
||||
claim2 = make_claim(org_id, provider='gitlab', git_organization='AcmeCo')
|
||||
|
||||
with patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.get_claims_by_org_id',
|
||||
AsyncMock(return_value=[claim1, claim2]),
|
||||
):
|
||||
result = await get_git_claims(org_id=org_id, user_id=user_id)
|
||||
|
||||
assert len(result) == 2
|
||||
assert result[0].id == str(claim1.id)
|
||||
assert result[0].org_id == str(org_id)
|
||||
assert result[0].provider == 'github'
|
||||
assert result[0].git_organization == 'OpenHands'
|
||||
assert result[0].claimed_by == str(claim1.claimed_by)
|
||||
assert result[0].claimed_at == '2026-04-01T12:00:00'
|
||||
assert result[1].id == str(claim2.id)
|
||||
assert result[1].provider == 'gitlab'
|
||||
assert result[1].git_organization == 'AcmeCo'
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_500_on_unexpected_error(self, org_id, user_id):
|
||||
"""
|
||||
GIVEN: An unexpected error occurs when fetching claims
|
||||
WHEN: GET /api/organizations/{org_id}/git-claims is called
|
||||
THEN: A 500 Internal Server Error is returned
|
||||
"""
|
||||
with patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.get_claims_by_org_id',
|
||||
AsyncMock(side_effect=RuntimeError('db connection failed')),
|
||||
):
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await get_git_claims(org_id=org_id, user_id=user_id)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# POST /api/organizations/{org_id}/git-claims
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestClaimGitOrganization:
|
||||
"""Tests for the claim Git organization endpoint."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_claim_succeeds_for_unclaimed_org(self, org_id, user_id, make_claim):
|
||||
"""
|
||||
GIVEN: A Git organization that has not been claimed
|
||||
WHEN: POST /api/organizations/{org_id}/git-claims is called
|
||||
THEN: The claim is created and returned with correct details
|
||||
"""
|
||||
# Arrange
|
||||
mock_claim = make_claim(org_id, claimed_by=uuid.UUID(user_id))
|
||||
request = MagicMock()
|
||||
request.provider = 'github'
|
||||
request.git_organization = 'OpenHands'
|
||||
|
||||
with (
|
||||
patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.get_claim_by_provider_and_git_org',
|
||||
AsyncMock(return_value=None),
|
||||
),
|
||||
patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.create_claim',
|
||||
AsyncMock(return_value=mock_claim),
|
||||
) as mock_create,
|
||||
):
|
||||
# Act
|
||||
response = await claim_git_organization(
|
||||
org_id=org_id, request=request, user_id=user_id
|
||||
)
|
||||
|
||||
# Assert
|
||||
assert response.id == str(mock_claim.id)
|
||||
assert response.org_id == str(org_id)
|
||||
assert response.provider == 'github'
|
||||
assert response.git_organization == 'OpenHands'
|
||||
assert response.claimed_by == user_id
|
||||
mock_create.assert_called_once_with(
|
||||
org_id=org_id,
|
||||
provider='github',
|
||||
git_organization='OpenHands',
|
||||
claimed_by=uuid.UUID(user_id),
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_claim_fails_when_already_claimed(self, org_id, user_id, make_claim):
|
||||
"""
|
||||
GIVEN: A Git organization already claimed by another OpenHands org
|
||||
WHEN: POST /api/organizations/{org_id}/git-claims is called
|
||||
THEN: A 409 Conflict error is returned
|
||||
"""
|
||||
# Arrange
|
||||
other_org_id = uuid.uuid4()
|
||||
existing_claim = make_claim(
|
||||
other_org_id, provider='github', git_organization='AlreadyClaimed'
|
||||
)
|
||||
request = MagicMock()
|
||||
request.provider = 'github'
|
||||
request.git_organization = 'AlreadyClaimed'
|
||||
|
||||
with patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.get_claim_by_provider_and_git_org',
|
||||
AsyncMock(return_value=existing_claim),
|
||||
):
|
||||
# Act & Assert
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await claim_git_organization(
|
||||
org_id=org_id, request=request, user_id=user_id
|
||||
)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_409_CONFLICT
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_claim_returns_500_on_unexpected_error(self, org_id, user_id):
|
||||
"""
|
||||
GIVEN: An unexpected error occurs during claim creation
|
||||
WHEN: POST /api/organizations/{org_id}/git-claims is called
|
||||
THEN: A 500 Internal Server Error is returned
|
||||
"""
|
||||
# Arrange
|
||||
request = MagicMock()
|
||||
request.provider = 'github'
|
||||
request.git_organization = 'OpenHands'
|
||||
|
||||
with patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.get_claim_by_provider_and_git_org',
|
||||
AsyncMock(side_effect=RuntimeError('db connection failed')),
|
||||
):
|
||||
# Act & Assert
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await claim_git_organization(
|
||||
org_id=org_id, request=request, user_id=user_id
|
||||
)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_claim_race_condition_returns_409(self, org_id, user_id):
|
||||
"""
|
||||
GIVEN: Pre-check passes but a concurrent request claims the org first
|
||||
WHEN: create_claim raises IntegrityError (DB unique constraint)
|
||||
THEN: A 409 Conflict error is returned instead of 500
|
||||
"""
|
||||
# Arrange
|
||||
request = MagicMock()
|
||||
request.provider = 'github'
|
||||
request.git_organization = 'RaceOrg'
|
||||
|
||||
with (
|
||||
patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.get_claim_by_provider_and_git_org',
|
||||
AsyncMock(return_value=None),
|
||||
),
|
||||
patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.create_claim',
|
||||
AsyncMock(
|
||||
side_effect=IntegrityError(
|
||||
'duplicate',
|
||||
'',
|
||||
Exception('uq_provider_git_org'),
|
||||
)
|
||||
),
|
||||
),
|
||||
):
|
||||
# Act & Assert
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await claim_git_organization(
|
||||
org_id=org_id, request=request, user_id=user_id
|
||||
)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_409_CONFLICT
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# DELETE /api/organizations/{org_id}/git-claims/{claim_id}
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestDisconnectGitOrganization:
|
||||
"""Tests for the disconnect Git organization endpoint."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disconnect_succeeds_for_existing_claim(self, org_id, user_id):
|
||||
"""
|
||||
GIVEN: A valid claim belonging to the organization
|
||||
WHEN: DELETE /api/organizations/{org_id}/git-claims/{claim_id} is called
|
||||
THEN: The claim is deleted and a success message is returned
|
||||
"""
|
||||
# Arrange
|
||||
claim_id = uuid.uuid4()
|
||||
|
||||
with patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.delete_claim',
|
||||
AsyncMock(return_value=True),
|
||||
) as mock_delete:
|
||||
# Act
|
||||
result = await disconnect_git_organization(
|
||||
org_id=org_id, claim_id=claim_id, user_id=user_id
|
||||
)
|
||||
|
||||
# Assert
|
||||
assert result == {'message': 'Git organization claim removed successfully'}
|
||||
mock_delete.assert_called_once_with(claim_id=claim_id, org_id=org_id)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disconnect_fails_when_claim_not_found(self, org_id, user_id):
|
||||
"""
|
||||
GIVEN: A claim_id that does not exist for this organization
|
||||
WHEN: DELETE /api/organizations/{org_id}/git-claims/{claim_id} is called
|
||||
THEN: A 404 Not Found error is returned
|
||||
"""
|
||||
# Arrange
|
||||
claim_id = uuid.uuid4()
|
||||
|
||||
with patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.delete_claim',
|
||||
AsyncMock(return_value=False),
|
||||
):
|
||||
# Act & Assert
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await disconnect_git_organization(
|
||||
org_id=org_id, claim_id=claim_id, user_id=user_id
|
||||
)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disconnect_returns_500_on_unexpected_error(self, org_id, user_id):
|
||||
"""
|
||||
GIVEN: An unexpected error occurs during claim deletion
|
||||
WHEN: DELETE /api/organizations/{org_id}/git-claims/{claim_id} is called
|
||||
THEN: A 500 Internal Server Error is returned
|
||||
"""
|
||||
# Arrange
|
||||
claim_id = uuid.uuid4()
|
||||
|
||||
with patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.delete_claim',
|
||||
AsyncMock(side_effect=RuntimeError('db connection failed')),
|
||||
):
|
||||
# Act & Assert
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await disconnect_git_organization(
|
||||
org_id=org_id, claim_id=claim_id, user_id=user_id
|
||||
)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Validation tests for GitOrgClaimRequest
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestGitOrgClaimRequestValidation:
|
||||
"""Tests for request model validation."""
|
||||
|
||||
def test_valid_providers_are_accepted(self):
|
||||
"""Each supported provider is accepted and normalized to lowercase."""
|
||||
from server.routes.org_models import GitOrgClaimRequest
|
||||
|
||||
for provider in ['github', 'GitLab', 'BITBUCKET']:
|
||||
req = GitOrgClaimRequest(provider=provider, git_organization='test-org')
|
||||
assert req.provider == provider.lower().strip()
|
||||
|
||||
def test_invalid_provider_is_rejected(self):
|
||||
"""An unsupported provider raises a validation error."""
|
||||
from pydantic import ValidationError
|
||||
from server.routes.org_models import GitOrgClaimRequest
|
||||
|
||||
with pytest.raises(ValidationError, match='Invalid provider'):
|
||||
GitOrgClaimRequest(provider='azure_devops', git_organization='test-org')
|
||||
|
||||
def test_empty_git_organization_is_rejected(self):
|
||||
"""An empty git_organization raises a validation error."""
|
||||
from pydantic import ValidationError
|
||||
from server.routes.org_models import GitOrgClaimRequest
|
||||
|
||||
with pytest.raises(ValidationError, match='git_organization must not be empty'):
|
||||
GitOrgClaimRequest(provider='github', git_organization=' ')
|
||||
|
||||
def test_git_organization_is_normalized_to_lowercase(self):
|
||||
"""git_organization is lowercased to prevent case-sensitive duplicates."""
|
||||
from server.routes.org_models import GitOrgClaimRequest
|
||||
|
||||
req = GitOrgClaimRequest(provider='github', git_organization='OpenHands')
|
||||
assert req.git_organization == 'openhands'
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Integration tests — TestClient with real HTTP, auth, and Pydantic validation
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_app():
|
||||
"""FastAPI app with org routes and mocked user authentication."""
|
||||
app = FastAPI()
|
||||
app.include_router(org_router)
|
||||
|
||||
app.dependency_overrides[get_user_id] = lambda: TEST_USER_ID
|
||||
return app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_owner_role():
|
||||
role = MagicMock()
|
||||
role.name = 'owner'
|
||||
return role
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_member_role():
|
||||
role = MagicMock()
|
||||
role.name = 'member'
|
||||
return role
|
||||
|
||||
|
||||
class TestGitClaimsAuthorization:
|
||||
"""Integration tests verifying authorization through the real HTTP cycle."""
|
||||
|
||||
def test_non_member_gets_403_on_get(self, mock_app):
|
||||
"""
|
||||
GIVEN: A user who is not a member of the target organization
|
||||
WHEN: GET /api/organizations/{org_id}/git-claims via HTTP
|
||||
THEN: 403 is returned by require_permission
|
||||
"""
|
||||
org_id = uuid.uuid4()
|
||||
|
||||
with patch(
|
||||
'server.auth.authorization.get_user_org_role',
|
||||
AsyncMock(return_value=None),
|
||||
):
|
||||
client = TestClient(mock_app)
|
||||
response = client.get(f'/api/organizations/{org_id}/git-claims')
|
||||
|
||||
assert response.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert 'not a member' in response.json()['detail']
|
||||
|
||||
def test_member_without_permission_gets_403_on_post(
|
||||
self, mock_app, mock_member_role
|
||||
):
|
||||
"""
|
||||
GIVEN: A user with member role (lacks MANAGE_ORG_CLAIMS)
|
||||
WHEN: POST /api/organizations/{org_id}/git-claims via HTTP
|
||||
THEN: 403 is returned by require_permission
|
||||
"""
|
||||
org_id = uuid.uuid4()
|
||||
|
||||
with patch(
|
||||
'server.auth.authorization.get_user_org_role',
|
||||
AsyncMock(return_value=mock_member_role),
|
||||
):
|
||||
client = TestClient(mock_app)
|
||||
response = client.post(
|
||||
f'/api/organizations/{org_id}/git-claims',
|
||||
json={'provider': 'github', 'git_organization': 'SomeOrg'},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert 'manage_org_claims' in response.json()['detail']
|
||||
|
||||
def test_member_without_permission_gets_403_on_delete(
|
||||
self, mock_app, mock_member_role
|
||||
):
|
||||
"""
|
||||
GIVEN: A user with member role (lacks MANAGE_ORG_CLAIMS)
|
||||
WHEN: DELETE /api/organizations/{org_id}/git-claims/{claim_id} via HTTP
|
||||
THEN: 403 is returned by require_permission
|
||||
"""
|
||||
org_id = uuid.uuid4()
|
||||
claim_id = uuid.uuid4()
|
||||
|
||||
with patch(
|
||||
'server.auth.authorization.get_user_org_role',
|
||||
AsyncMock(return_value=mock_member_role),
|
||||
):
|
||||
client = TestClient(mock_app)
|
||||
response = client.delete(
|
||||
f'/api/organizations/{org_id}/git-claims/{claim_id}'
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert 'manage_org_claims' in response.json()['detail']
|
||||
|
||||
|
||||
class TestGitClaimsHTTPIntegration:
|
||||
"""Integration tests for the full request/response cycle via TestClient."""
|
||||
|
||||
def test_post_claim_with_invalid_provider_returns_422(
|
||||
self, mock_app, mock_owner_role
|
||||
):
|
||||
"""
|
||||
GIVEN: A request with an unsupported provider
|
||||
WHEN: POST /api/organizations/{org_id}/git-claims via HTTP
|
||||
THEN: 422 is returned by Pydantic validation
|
||||
"""
|
||||
org_id = uuid.uuid4()
|
||||
|
||||
with patch(
|
||||
'server.auth.authorization.get_user_org_role',
|
||||
AsyncMock(return_value=mock_owner_role),
|
||||
):
|
||||
client = TestClient(mock_app)
|
||||
response = client.post(
|
||||
f'/api/organizations/{org_id}/git-claims',
|
||||
json={'provider': 'azure_devops', 'git_organization': 'test'},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
|
||||
|
||||
def test_post_claim_success_returns_201(self, mock_app, mock_owner_role):
|
||||
"""
|
||||
GIVEN: A valid claim request by an authorized admin/owner
|
||||
WHEN: POST /api/organizations/{org_id}/git-claims via HTTP
|
||||
THEN: 201 is returned with the claim details
|
||||
"""
|
||||
org_id = uuid.uuid4()
|
||||
mock_claim = MagicMock(spec=OrgGitClaim)
|
||||
mock_claim.id = uuid.uuid4()
|
||||
mock_claim.org_id = org_id
|
||||
mock_claim.provider = 'github'
|
||||
mock_claim.git_organization = 'openhands'
|
||||
mock_claim.claimed_by = uuid.UUID(TEST_USER_ID)
|
||||
mock_claim.claimed_at = datetime(2026, 4, 1, 12, 0, 0)
|
||||
|
||||
with (
|
||||
patch(
|
||||
'server.auth.authorization.get_user_org_role',
|
||||
AsyncMock(return_value=mock_owner_role),
|
||||
),
|
||||
patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.get_claim_by_provider_and_git_org',
|
||||
AsyncMock(return_value=None),
|
||||
),
|
||||
patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.create_claim',
|
||||
AsyncMock(return_value=mock_claim),
|
||||
),
|
||||
):
|
||||
client = TestClient(mock_app)
|
||||
response = client.post(
|
||||
f'/api/organizations/{org_id}/git-claims',
|
||||
json={'provider': 'github', 'git_organization': 'OpenHands'},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
data = response.json()
|
||||
assert data['org_id'] == str(org_id)
|
||||
assert data['provider'] == 'github'
|
||||
assert data['git_organization'] == 'openhands'
|
||||
|
||||
def test_delete_claim_success_returns_200(self, mock_app, mock_owner_role):
|
||||
"""
|
||||
GIVEN: A valid disconnect request by an authorized admin/owner
|
||||
WHEN: DELETE /api/organizations/{org_id}/git-claims/{claim_id} via HTTP
|
||||
THEN: 200 is returned with a success message
|
||||
"""
|
||||
org_id = uuid.uuid4()
|
||||
claim_id = uuid.uuid4()
|
||||
|
||||
with (
|
||||
patch(
|
||||
'server.auth.authorization.get_user_org_role',
|
||||
AsyncMock(return_value=mock_owner_role),
|
||||
),
|
||||
patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.delete_claim',
|
||||
AsyncMock(return_value=True),
|
||||
),
|
||||
):
|
||||
client = TestClient(mock_app)
|
||||
response = client.delete(
|
||||
f'/api/organizations/{org_id}/git-claims/{claim_id}'
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert (
|
||||
response.json()['message'] == 'Git organization claim removed successfully'
|
||||
)
|
||||
|
||||
def test_get_claims_success_returns_200(self, mock_app, mock_owner_role):
|
||||
"""
|
||||
GIVEN: An authorized user requests claims for their organization
|
||||
WHEN: GET /api/organizations/{org_id}/git-claims via HTTP
|
||||
THEN: 200 is returned with the list of claims
|
||||
"""
|
||||
org_id = uuid.uuid4()
|
||||
mock_claim = MagicMock(spec=OrgGitClaim)
|
||||
mock_claim.id = uuid.uuid4()
|
||||
mock_claim.org_id = org_id
|
||||
mock_claim.provider = 'github'
|
||||
mock_claim.git_organization = 'openhands'
|
||||
mock_claim.claimed_by = uuid.UUID(TEST_USER_ID)
|
||||
mock_claim.claimed_at = datetime(2026, 4, 1, 12, 0, 0)
|
||||
|
||||
with (
|
||||
patch(
|
||||
'server.auth.authorization.get_user_org_role',
|
||||
AsyncMock(return_value=mock_owner_role),
|
||||
),
|
||||
patch(
|
||||
'server.routes.orgs.OrgGitClaimStore.get_claims_by_org_id',
|
||||
AsyncMock(return_value=[mock_claim]),
|
||||
),
|
||||
):
|
||||
client = TestClient(mock_app)
|
||||
response = client.get(f'/api/organizations/{org_id}/git-claims')
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
data = response.json()
|
||||
assert len(data) == 1
|
||||
assert data[0]['provider'] == 'github'
|
||||
assert data[0]['git_organization'] == 'openhands'
|
||||
@@ -1,283 +0,0 @@
|
||||
"""Unit tests for SAAS-specific /api/v1/users endpoints.
|
||||
|
||||
Tests:
|
||||
- SaasUserInfo model with org fields
|
||||
- get_current_user_saas endpoint with org info
|
||||
- _get_org_info_from_context helper function
|
||||
"""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestSaasUserInfoModel:
|
||||
"""Test suite for SaasUserInfo model."""
|
||||
|
||||
def test_saas_user_info_with_all_org_fields(self):
|
||||
"""SaasUserInfo should accept all org-related fields."""
|
||||
from server.models.user_models import SaasUserInfo
|
||||
|
||||
user_info = SaasUserInfo(
|
||||
id='user-123',
|
||||
org_id='org-456',
|
||||
org_name='Test Organization',
|
||||
role='admin',
|
||||
permissions=['read', 'write', 'delete'],
|
||||
)
|
||||
|
||||
assert user_info.id == 'user-123'
|
||||
assert user_info.org_id == 'org-456'
|
||||
assert user_info.org_name == 'Test Organization'
|
||||
assert user_info.role == 'admin'
|
||||
assert user_info.permissions == ['read', 'write', 'delete']
|
||||
|
||||
def test_saas_user_info_without_org_fields(self):
|
||||
"""SaasUserInfo should work without org fields (fallback mode)."""
|
||||
from server.models.user_models import SaasUserInfo
|
||||
|
||||
user_info = SaasUserInfo(id='user-123')
|
||||
|
||||
assert user_info.id == 'user-123'
|
||||
assert user_info.org_id is None
|
||||
assert user_info.org_name is None
|
||||
assert user_info.role is None
|
||||
assert user_info.permissions is None
|
||||
|
||||
def test_saas_user_info_with_partial_org_fields(self):
|
||||
"""SaasUserInfo should handle partial org fields (e.g., role is None)."""
|
||||
from server.models.user_models import SaasUserInfo
|
||||
|
||||
user_info = SaasUserInfo(
|
||||
id='user-123',
|
||||
org_id='org-456',
|
||||
org_name='Test Organization',
|
||||
role=None,
|
||||
permissions=[],
|
||||
)
|
||||
|
||||
assert user_info.org_id == 'org-456'
|
||||
assert user_info.org_name == 'Test Organization'
|
||||
assert user_info.role is None
|
||||
assert user_info.permissions == []
|
||||
|
||||
def test_saas_user_info_model_dump_includes_org_fields(self):
|
||||
"""SaasUserInfo model_dump should include org fields."""
|
||||
from server.models.user_models import SaasUserInfo
|
||||
|
||||
user_info = SaasUserInfo(
|
||||
id='user-123',
|
||||
org_id='org-456',
|
||||
org_name='Test Organization',
|
||||
role='member',
|
||||
permissions=['read'],
|
||||
)
|
||||
|
||||
data = user_info.model_dump()
|
||||
assert data['org_id'] == 'org-456'
|
||||
assert data['org_name'] == 'Test Organization'
|
||||
assert data['role'] == 'member'
|
||||
assert data['permissions'] == ['read']
|
||||
|
||||
def test_saas_user_info_extends_base_user_info(self):
|
||||
"""SaasUserInfo should inherit from UserInfo base class."""
|
||||
from server.models.user_models import SaasUserInfo
|
||||
|
||||
from openhands.app_server.user.user_models import UserInfo
|
||||
|
||||
assert issubclass(SaasUserInfo, UserInfo)
|
||||
|
||||
|
||||
class TestGetOrgInfoFromContext:
|
||||
"""Test suite for _get_org_info_from_context helper function."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_org_info_from_saas_user_auth(self):
|
||||
"""Should return org info when context has SaasUserAuth."""
|
||||
from server.auth.saas_user_auth import SaasUserAuth
|
||||
from server.routes.users_v1 import _get_org_info_from_context
|
||||
|
||||
from openhands.app_server.user.auth_user_context import AuthUserContext
|
||||
|
||||
# Create a SaasUserAuth with mocked get_org_info
|
||||
mock_user_auth = MagicMock(spec=SaasUserAuth)
|
||||
mock_user_auth.get_org_info = AsyncMock(
|
||||
return_value={
|
||||
'org_id': 'org-456',
|
||||
'org_name': 'Test Organization',
|
||||
'role': 'admin',
|
||||
'permissions': ['read', 'write'],
|
||||
}
|
||||
)
|
||||
|
||||
# Create AuthUserContext with the mock
|
||||
context = MagicMock(spec=AuthUserContext)
|
||||
context.user_auth = mock_user_auth
|
||||
|
||||
org_info = await _get_org_info_from_context(context)
|
||||
|
||||
assert org_info is not None
|
||||
assert org_info['org_id'] == 'org-456'
|
||||
assert org_info['org_name'] == 'Test Organization'
|
||||
assert org_info['role'] == 'admin'
|
||||
mock_user_auth.get_org_info.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_none_for_non_auth_user_context(self):
|
||||
"""Should return None when context is not AuthUserContext."""
|
||||
from server.routes.users_v1 import _get_org_info_from_context
|
||||
|
||||
from openhands.app_server.user.user_context import UserContext
|
||||
|
||||
# Create a non-AuthUserContext
|
||||
mock_context = MagicMock(spec=UserContext)
|
||||
|
||||
org_info = await _get_org_info_from_context(mock_context)
|
||||
|
||||
assert org_info is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_none_for_non_saas_user_auth(self):
|
||||
"""Should return None when user_auth is not SaasUserAuth."""
|
||||
from server.routes.users_v1 import _get_org_info_from_context
|
||||
|
||||
from openhands.app_server.user.auth_user_context import AuthUserContext
|
||||
from openhands.server.user_auth.user_auth import UserAuth
|
||||
|
||||
# Create AuthUserContext with a non-SaasUserAuth
|
||||
mock_user_auth = MagicMock(spec=UserAuth)
|
||||
mock_context = MagicMock(spec=AuthUserContext)
|
||||
mock_context.user_auth = mock_user_auth
|
||||
|
||||
org_info = await _get_org_info_from_context(mock_context)
|
||||
|
||||
assert org_info is None
|
||||
|
||||
|
||||
class TestGetCurrentUserSaasEndpoint:
|
||||
"""Test suite for get_current_user_saas endpoint."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_context(self):
|
||||
"""Create a mock user context."""
|
||||
return AsyncMock()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_endpoint_returns_saas_user_info_with_org_fields(
|
||||
self, mock_user_context
|
||||
):
|
||||
"""Endpoint should return SaasUserInfo with org fields."""
|
||||
from unittest.mock import patch
|
||||
|
||||
from server.models.user_models import SaasUserInfo
|
||||
from server.routes.users_v1 import get_current_user_saas
|
||||
|
||||
from openhands.app_server.user.user_models import UserInfo
|
||||
|
||||
# Mock base user info
|
||||
base_user_info = UserInfo(id='user-123', llm_model='test-model')
|
||||
mock_user_context.get_user_info = AsyncMock(return_value=base_user_info)
|
||||
|
||||
# Mock _get_org_info_from_context to return org info
|
||||
org_info = {
|
||||
'org_id': 'org-456',
|
||||
'org_name': 'Test Organization',
|
||||
'role': 'member',
|
||||
'permissions': ['read', 'write'],
|
||||
}
|
||||
|
||||
with patch(
|
||||
'server.routes.users_v1._get_org_info_from_context',
|
||||
return_value=org_info,
|
||||
):
|
||||
result = await get_current_user_saas(
|
||||
user_context=mock_user_context, expose_secrets=False
|
||||
)
|
||||
|
||||
assert isinstance(result, SaasUserInfo)
|
||||
assert result.id == 'user-123'
|
||||
assert result.org_id == 'org-456'
|
||||
assert result.org_name == 'Test Organization'
|
||||
assert result.role == 'member'
|
||||
assert result.permissions == ['read', 'write']
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_endpoint_returns_saas_user_info_without_org_fields(
|
||||
self, mock_user_context
|
||||
):
|
||||
"""Endpoint should work when org info is not available."""
|
||||
from unittest.mock import patch
|
||||
|
||||
from server.models.user_models import SaasUserInfo
|
||||
from server.routes.users_v1 import get_current_user_saas
|
||||
|
||||
from openhands.app_server.user.user_models import UserInfo
|
||||
|
||||
# Mock base user info
|
||||
base_user_info = UserInfo(id='user-123', llm_model='test-model')
|
||||
mock_user_context.get_user_info = AsyncMock(return_value=base_user_info)
|
||||
|
||||
# Mock _get_org_info_from_context to return None
|
||||
with patch(
|
||||
'server.routes.users_v1._get_org_info_from_context',
|
||||
return_value=None,
|
||||
):
|
||||
result = await get_current_user_saas(
|
||||
user_context=mock_user_context, expose_secrets=False
|
||||
)
|
||||
|
||||
assert isinstance(result, SaasUserInfo)
|
||||
assert result.id == 'user-123'
|
||||
assert result.org_id is None
|
||||
assert result.org_name is None
|
||||
assert result.role is None
|
||||
assert result.permissions is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_endpoint_raises_401_when_user_info_is_none(self, mock_user_context):
|
||||
"""Endpoint should raise 401 when user info is None."""
|
||||
from fastapi import HTTPException
|
||||
from server.routes.users_v1 import get_current_user_saas
|
||||
|
||||
mock_user_context.get_user_info = AsyncMock(return_value=None)
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_current_user_saas(
|
||||
user_context=mock_user_context, expose_secrets=False
|
||||
)
|
||||
|
||||
assert exc_info.value.status_code == 401
|
||||
assert exc_info.value.detail == 'Not authenticated'
|
||||
|
||||
|
||||
class TestOverrideUsersEndpoint:
|
||||
"""Test suite for override_users_me_endpoint function."""
|
||||
|
||||
def test_override_removes_oss_route_and_adds_saas_route(self):
|
||||
"""override_users_me_endpoint should remove OSS route and add SAAS route."""
|
||||
from fastapi import FastAPI
|
||||
from server.routes.users_v1 import override_users_me_endpoint
|
||||
|
||||
# Create a minimal app with a mock OSS route
|
||||
app = FastAPI()
|
||||
|
||||
@app.get('/api/v1/users/me')
|
||||
def mock_oss_endpoint():
|
||||
return {'source': 'oss'}
|
||||
|
||||
# Verify OSS route exists
|
||||
oss_routes = [
|
||||
r for r in app.routes if hasattr(r, 'path') and r.path == '/api/v1/users/me'
|
||||
]
|
||||
assert len(oss_routes) == 1
|
||||
assert oss_routes[0].endpoint.__name__ == 'mock_oss_endpoint'
|
||||
|
||||
# Apply the override
|
||||
override_users_me_endpoint(app)
|
||||
|
||||
# Verify SAAS route exists and OSS route is gone
|
||||
saas_routes = [
|
||||
r for r in app.routes if hasattr(r, 'path') and r.path == '/api/v1/users/me'
|
||||
]
|
||||
assert len(saas_routes) == 1
|
||||
assert saas_routes[0].endpoint.__name__ == 'get_current_user_saas'
|
||||
@@ -1,210 +0,0 @@
|
||||
"""Tests for OrgGitClaimStore with real in-memory SQLite database.
|
||||
|
||||
Covers CRUD operations and unique constraint enforcement.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from storage.org import Org
|
||||
from storage.org_git_claim_store import OrgGitClaimStore
|
||||
from storage.org_member import OrgMember
|
||||
from storage.role import Role
|
||||
from storage.user import User
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def seed_org_and_user(async_session_maker):
|
||||
"""Create a minimal org, role, user, and org_member for FK satisfaction."""
|
||||
org_id = uuid.uuid4()
|
||||
user_id = uuid.uuid4()
|
||||
role_id = 1
|
||||
|
||||
async with async_session_maker() as session:
|
||||
session.add(Role(id=role_id, name='owner', rank=10))
|
||||
session.add(Org(id=org_id, name='test-org'))
|
||||
session.add(User(id=user_id, current_org_id=org_id, role_id=role_id))
|
||||
session.add(
|
||||
OrgMember(
|
||||
org_id=org_id,
|
||||
user_id=user_id,
|
||||
role_id=role_id,
|
||||
status='active',
|
||||
llm_api_key='test-key',
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
|
||||
return org_id, user_id
|
||||
|
||||
|
||||
class TestOrgGitClaimStoreCreate:
|
||||
"""Tests for OrgGitClaimStore.create_claim."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_claim_persists_and_returns(
|
||||
self, async_session_maker, seed_org_and_user
|
||||
):
|
||||
"""A new claim is persisted with correct fields and returned."""
|
||||
org_id, user_id = seed_org_and_user
|
||||
|
||||
with patch('storage.org_git_claim_store.a_session_maker', async_session_maker):
|
||||
claim = await OrgGitClaimStore.create_claim(
|
||||
org_id=org_id,
|
||||
provider='github',
|
||||
git_organization='OpenHands',
|
||||
claimed_by=user_id,
|
||||
)
|
||||
|
||||
assert claim.org_id == org_id
|
||||
assert claim.provider == 'github'
|
||||
assert claim.git_organization == 'OpenHands'
|
||||
assert claim.claimed_by == user_id
|
||||
assert claim.claimed_at is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_duplicate_raises_integrity_error(
|
||||
self, async_session_maker, seed_org_and_user
|
||||
):
|
||||
"""Creating a duplicate (provider, git_organization) violates the unique constraint."""
|
||||
org_id, user_id = seed_org_and_user
|
||||
|
||||
with patch('storage.org_git_claim_store.a_session_maker', async_session_maker):
|
||||
await OrgGitClaimStore.create_claim(
|
||||
org_id=org_id,
|
||||
provider='github',
|
||||
git_organization='DuplicateOrg',
|
||||
claimed_by=user_id,
|
||||
)
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
await OrgGitClaimStore.create_claim(
|
||||
org_id=org_id,
|
||||
provider='github',
|
||||
git_organization='DuplicateOrg',
|
||||
claimed_by=user_id,
|
||||
)
|
||||
|
||||
|
||||
class TestOrgGitClaimStoreLookup:
|
||||
"""Tests for OrgGitClaimStore lookup methods."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_claim_by_provider_and_git_org_found(
|
||||
self, async_session_maker, seed_org_and_user
|
||||
):
|
||||
"""Returns the claim when provider+git_organization exists."""
|
||||
org_id, user_id = seed_org_and_user
|
||||
|
||||
with patch('storage.org_git_claim_store.a_session_maker', async_session_maker):
|
||||
await OrgGitClaimStore.create_claim(
|
||||
org_id=org_id,
|
||||
provider='gitlab',
|
||||
git_organization='MyGroup',
|
||||
claimed_by=user_id,
|
||||
)
|
||||
|
||||
result = await OrgGitClaimStore.get_claim_by_provider_and_git_org(
|
||||
provider='gitlab', git_organization='MyGroup'
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result.provider == 'gitlab'
|
||||
assert result.git_organization == 'MyGroup'
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_claim_by_provider_and_git_org_not_found(
|
||||
self, async_session_maker
|
||||
):
|
||||
"""Returns None when no matching claim exists."""
|
||||
with patch('storage.org_git_claim_store.a_session_maker', async_session_maker):
|
||||
result = await OrgGitClaimStore.get_claim_by_provider_and_git_org(
|
||||
provider='github', git_organization='NonExistent'
|
||||
)
|
||||
|
||||
assert result is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_claims_by_org_id(self, async_session_maker, seed_org_and_user):
|
||||
"""Returns all claims belonging to the given org."""
|
||||
org_id, user_id = seed_org_and_user
|
||||
|
||||
with patch('storage.org_git_claim_store.a_session_maker', async_session_maker):
|
||||
await OrgGitClaimStore.create_claim(
|
||||
org_id=org_id,
|
||||
provider='github',
|
||||
git_organization='Org1',
|
||||
claimed_by=user_id,
|
||||
)
|
||||
await OrgGitClaimStore.create_claim(
|
||||
org_id=org_id,
|
||||
provider='gitlab',
|
||||
git_organization='Org2',
|
||||
claimed_by=user_id,
|
||||
)
|
||||
|
||||
claims = await OrgGitClaimStore.get_claims_by_org_id(org_id)
|
||||
|
||||
assert len(claims) == 2
|
||||
|
||||
|
||||
class TestOrgGitClaimStoreDelete:
|
||||
"""Tests for OrgGitClaimStore.delete_claim."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_existing_claim_returns_true(
|
||||
self, async_session_maker, seed_org_and_user
|
||||
):
|
||||
"""Deleting an existing claim returns True and removes it from the DB."""
|
||||
org_id, user_id = seed_org_and_user
|
||||
|
||||
with patch('storage.org_git_claim_store.a_session_maker', async_session_maker):
|
||||
claim = await OrgGitClaimStore.create_claim(
|
||||
org_id=org_id,
|
||||
provider='github',
|
||||
git_organization='ToDelete',
|
||||
claimed_by=user_id,
|
||||
)
|
||||
|
||||
result = await OrgGitClaimStore.delete_claim(
|
||||
claim_id=claim.id, org_id=org_id
|
||||
)
|
||||
|
||||
assert result is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_nonexistent_claim_returns_false(
|
||||
self, async_session_maker, seed_org_and_user
|
||||
):
|
||||
"""Deleting a claim that doesn't exist returns False."""
|
||||
org_id, _ = seed_org_and_user
|
||||
|
||||
with patch('storage.org_git_claim_store.a_session_maker', async_session_maker):
|
||||
result = await OrgGitClaimStore.delete_claim(
|
||||
claim_id=uuid.uuid4(), org_id=org_id
|
||||
)
|
||||
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_claim_wrong_org_returns_false(
|
||||
self, async_session_maker, seed_org_and_user
|
||||
):
|
||||
"""Deleting a claim with a mismatched org_id returns False."""
|
||||
org_id, user_id = seed_org_and_user
|
||||
|
||||
with patch('storage.org_git_claim_store.a_session_maker', async_session_maker):
|
||||
claim = await OrgGitClaimStore.create_claim(
|
||||
org_id=org_id,
|
||||
provider='github',
|
||||
git_organization='WrongOrg',
|
||||
claimed_by=user_id,
|
||||
)
|
||||
|
||||
result = await OrgGitClaimStore.delete_claim(
|
||||
claim_id=claim.id, org_id=uuid.uuid4()
|
||||
)
|
||||
|
||||
assert result is False
|
||||
@@ -280,8 +280,6 @@ class TestSaasSQLAppConversationInfoService:
|
||||
stored_metadata.reasoning_tokens = 0
|
||||
stored_metadata.context_window = 0
|
||||
stored_metadata.per_turn_token = 0
|
||||
stored_metadata.public = None
|
||||
stored_metadata.tags = {}
|
||||
|
||||
saas_metadata = MagicMock(spec=StoredConversationMetadataSaas)
|
||||
saas_metadata.user_id = UUID('a1111111-1111-1111-1111-111111111111')
|
||||
@@ -1306,100 +1304,3 @@ class TestApiKeyOrgIdHandling:
|
||||
conv_from_org1 = await user_service_org1.get_app_conversation_info(conv_id)
|
||||
assert conv_from_org1 is not None
|
||||
assert conv_from_org1.id == conv_id
|
||||
|
||||
|
||||
class TestResolverOrgIdRouting:
|
||||
"""Test that resolver_org_id on user_context overrides the default org_id."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_save_uses_resolver_org_id_when_set_on_context(
|
||||
self,
|
||||
async_session_with_users: AsyncSession,
|
||||
):
|
||||
"""When user_context has resolver_org_id, conversation is saved in that org."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from storage.stored_conversation_metadata_saas import (
|
||||
StoredConversationMetadataSaas,
|
||||
)
|
||||
|
||||
from enterprise.integrations.resolver_context import ResolverUserContext
|
||||
|
||||
# Arrange: user1 is in ORG1, but resolver routes to ORG2
|
||||
# Use spec to prevent MagicMock from auto-creating undefined attributes
|
||||
mock_context = MagicMock(spec=ResolverUserContext)
|
||||
mock_context.get_user_id = AsyncMock(return_value=str(USER1_ID))
|
||||
mock_context.resolver_org_id = ORG2_ID
|
||||
|
||||
service = SaasSQLAppConversationInfoService(
|
||||
db_session=async_session_with_users,
|
||||
user_context=mock_context,
|
||||
)
|
||||
|
||||
conv_id = uuid4()
|
||||
conv_info = AppConversationInfo(
|
||||
id=conv_id,
|
||||
created_by_user_id=str(USER1_ID),
|
||||
sandbox_id='sandbox_resolver',
|
||||
title='Resolver Routed Conversation',
|
||||
)
|
||||
|
||||
# Act
|
||||
await service.save_app_conversation_info(conv_info)
|
||||
|
||||
# Assert: conversation is stored in ORG2, not user's default ORG1
|
||||
saas_query = select(StoredConversationMetadataSaas).where(
|
||||
StoredConversationMetadataSaas.conversation_id == str(conv_id)
|
||||
)
|
||||
result = await async_session_with_users.execute(saas_query)
|
||||
saas_metadata = result.scalar_one_or_none()
|
||||
|
||||
assert saas_metadata is not None
|
||||
assert saas_metadata.org_id == ORG2_ID
|
||||
assert saas_metadata.user_id == USER1_ID
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_save_uses_default_org_when_resolver_org_id_is_none(
|
||||
self,
|
||||
async_session_with_users: AsyncSession,
|
||||
):
|
||||
"""When resolver_org_id is None, conversation uses user's default org."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from storage.stored_conversation_metadata_saas import (
|
||||
StoredConversationMetadataSaas,
|
||||
)
|
||||
|
||||
from enterprise.integrations.resolver_context import ResolverUserContext
|
||||
|
||||
# Arrange: user1 in ORG1 with no resolver override
|
||||
# Use spec to prevent MagicMock from auto-creating undefined attributes
|
||||
mock_context = MagicMock(spec=ResolverUserContext)
|
||||
mock_context.get_user_id = AsyncMock(return_value=str(USER1_ID))
|
||||
mock_context.resolver_org_id = None
|
||||
|
||||
service = SaasSQLAppConversationInfoService(
|
||||
db_session=async_session_with_users,
|
||||
user_context=mock_context,
|
||||
)
|
||||
|
||||
conv_id = uuid4()
|
||||
conv_info = AppConversationInfo(
|
||||
id=conv_id,
|
||||
created_by_user_id=str(USER1_ID),
|
||||
sandbox_id='sandbox_default',
|
||||
title='Default Org Conversation',
|
||||
)
|
||||
|
||||
# Act
|
||||
await service.save_app_conversation_info(conv_info)
|
||||
|
||||
# Assert: conversation stored in user's default ORG1
|
||||
saas_query = select(StoredConversationMetadataSaas).where(
|
||||
StoredConversationMetadataSaas.conversation_id == str(conv_id)
|
||||
)
|
||||
result = await async_session_with_users.execute(saas_query)
|
||||
saas_metadata = result.scalar_one_or_none()
|
||||
|
||||
assert saas_metadata is not None
|
||||
assert saas_metadata.org_id == ORG1_ID
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from unittest import TestCase, mock
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from uuid import UUID
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.github.github_view import GithubFactory, GithubIssue, get_oh_labels
|
||||
@@ -216,119 +215,3 @@ class TestGithubV1ConversationRouting(TestCase):
|
||||
jinja_env, saas_user_auth, conversation_metadata
|
||||
)
|
||||
mock_create_v0.assert_not_called()
|
||||
|
||||
|
||||
class TestGithubOrgRouting(TestCase):
|
||||
"""Test org routing for GitHub resolver conversations."""
|
||||
|
||||
def setUp(self):
|
||||
self.user_data = UserData(
|
||||
user_id=123, username='testuser', keycloak_user_id='test-keycloak-id'
|
||||
)
|
||||
self.raw_payload = Message(
|
||||
source=SourceType.GITHUB,
|
||||
message={
|
||||
'payload': {
|
||||
'action': 'opened',
|
||||
'issue': {'number': 42},
|
||||
}
|
||||
},
|
||||
)
|
||||
self.resolved_org_id = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
|
||||
|
||||
def _create_github_issue(self):
|
||||
return GithubIssue(
|
||||
user_info=self.user_data,
|
||||
full_repo_name='ClaimedOrg/repo',
|
||||
issue_number=42,
|
||||
installation_id=456,
|
||||
conversation_id='',
|
||||
should_extract=True,
|
||||
send_summary_instruction=False,
|
||||
is_public_repo=True,
|
||||
raw_payload=self.raw_payload,
|
||||
uuid='test-uuid',
|
||||
title='',
|
||||
description='',
|
||||
previous_comments=[],
|
||||
v1_enabled=False,
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch(
|
||||
'integrations.github.github_view.SaasConversationStore.get_resolver_instance'
|
||||
)
|
||||
@patch('integrations.github.github_view.resolve_org_for_repo')
|
||||
@patch('integrations.github.github_view.get_user_v1_enabled_setting')
|
||||
async def test_v0_passes_resolver_org_id_to_get_resolver_instance(
|
||||
self, mock_v1_setting, mock_resolve_org, mock_get_resolver
|
||||
):
|
||||
"""V0 path creates store via get_resolver_instance with resolver_org_id."""
|
||||
# Arrange
|
||||
mock_v1_setting.return_value = False
|
||||
mock_resolve_org.return_value = self.resolved_org_id
|
||||
mock_store = MagicMock()
|
||||
mock_store.save_metadata = AsyncMock()
|
||||
mock_get_resolver.return_value = mock_store
|
||||
|
||||
github_issue = self._create_github_issue()
|
||||
|
||||
# Act
|
||||
await github_issue.initialize_new_conversation()
|
||||
|
||||
# Assert
|
||||
mock_resolve_org.assert_called_once_with(
|
||||
provider='github',
|
||||
full_repo_name='ClaimedOrg/repo',
|
||||
keycloak_user_id='test-keycloak-id',
|
||||
)
|
||||
# get_resolver_instance(config, user_id, resolver_org_id)
|
||||
args, _ = mock_get_resolver.call_args
|
||||
assert args[1] == 'test-keycloak-id'
|
||||
assert args[2] == self.resolved_org_id
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('integrations.github.github_view.get_app_conversation_service')
|
||||
@patch('integrations.github.github_view.resolve_org_for_repo')
|
||||
@patch('integrations.github.github_view.get_user_v1_enabled_setting')
|
||||
async def test_v1_passes_resolver_org_id_to_resolver_user_context(
|
||||
self, mock_v1_setting, mock_resolve_org, mock_get_service
|
||||
):
|
||||
"""V1 path passes resolved org_id to ResolverUserContext."""
|
||||
# Arrange
|
||||
mock_v1_setting.return_value = True
|
||||
mock_resolve_org.return_value = self.resolved_org_id
|
||||
|
||||
github_issue = self._create_github_issue()
|
||||
|
||||
# Initialize to set resolved_org_id and v1_enabled
|
||||
await github_issue.initialize_new_conversation()
|
||||
|
||||
# Assert
|
||||
assert github_issue.resolved_org_id == self.resolved_org_id
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch(
|
||||
'integrations.github.github_view.SaasConversationStore.get_resolver_instance'
|
||||
)
|
||||
@patch('integrations.github.github_view.resolve_org_for_repo')
|
||||
@patch('integrations.github.github_view.get_user_v1_enabled_setting')
|
||||
async def test_no_claim_passes_none_resolver_org_id(
|
||||
self, mock_v1_setting, mock_resolve_org, mock_get_resolver
|
||||
):
|
||||
"""When no claim exists, resolver_org_id is None (falls back to personal workspace)."""
|
||||
# Arrange
|
||||
mock_v1_setting.return_value = False
|
||||
mock_resolve_org.return_value = None
|
||||
mock_store = MagicMock()
|
||||
mock_store.save_metadata = AsyncMock()
|
||||
mock_get_resolver.return_value = mock_store
|
||||
|
||||
github_issue = self._create_github_issue()
|
||||
|
||||
# Act
|
||||
await github_issue.initialize_new_conversation()
|
||||
|
||||
# Assert
|
||||
args, _ = mock_get_resolver.call_args
|
||||
assert args[2] is None
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
"""Tests for GitLab resolver org routing logic.
|
||||
|
||||
Tests that the GitLab resolver correctly resolves the target organization
|
||||
and passes resolver_org_id through V0 and V1 conversation paths.
|
||||
"""
|
||||
|
||||
from unittest import TestCase
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from integrations.gitlab.gitlab_view import GitlabIssue
|
||||
from integrations.models import Message, SourceType
|
||||
from integrations.types import UserData
|
||||
|
||||
|
||||
class TestGitlabOrgRouting(TestCase):
|
||||
"""Test org routing for GitLab resolver conversations."""
|
||||
|
||||
def setUp(self):
|
||||
self.user_data = UserData(
|
||||
user_id=123, username='testuser', keycloak_user_id='test-keycloak-id'
|
||||
)
|
||||
self.raw_payload = Message(
|
||||
source=SourceType.GITLAB,
|
||||
message={
|
||||
'payload': {
|
||||
'object_kind': 'issue',
|
||||
'object_attributes': {'action': 'open', 'iid': 42},
|
||||
}
|
||||
},
|
||||
)
|
||||
self.resolved_org_id = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
|
||||
|
||||
def _create_gitlab_issue(self):
|
||||
return GitlabIssue(
|
||||
user_info=self.user_data,
|
||||
full_repo_name='ClaimedOrg/repo',
|
||||
issue_number=42,
|
||||
project_id=100,
|
||||
installation_id='install-123',
|
||||
conversation_id='',
|
||||
should_extract=True,
|
||||
send_summary_instruction=False,
|
||||
is_public_repo=True,
|
||||
raw_payload=self.raw_payload,
|
||||
title='',
|
||||
description='',
|
||||
previous_comments=[],
|
||||
is_mr=False,
|
||||
v1_enabled=False,
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch(
|
||||
'integrations.gitlab.gitlab_view.SaasConversationStore.get_resolver_instance'
|
||||
)
|
||||
@patch('integrations.gitlab.gitlab_view.resolve_org_for_repo')
|
||||
async def test_v0_passes_resolver_org_id_to_get_resolver_instance(
|
||||
self, mock_resolve_org, mock_get_resolver
|
||||
):
|
||||
"""V0 path creates store via get_resolver_instance with resolver_org_id."""
|
||||
# Arrange
|
||||
mock_resolve_org.return_value = self.resolved_org_id
|
||||
mock_store = MagicMock()
|
||||
mock_store.save_metadata = AsyncMock()
|
||||
mock_get_resolver.return_value = mock_store
|
||||
|
||||
gitlab_issue = self._create_gitlab_issue()
|
||||
|
||||
# Act
|
||||
await gitlab_issue.initialize_new_conversation()
|
||||
|
||||
# Assert
|
||||
mock_resolve_org.assert_called_once_with(
|
||||
provider='gitlab',
|
||||
full_repo_name='ClaimedOrg/repo',
|
||||
keycloak_user_id='test-keycloak-id',
|
||||
)
|
||||
# get_resolver_instance(config, user_id, resolver_org_id)
|
||||
args, _ = mock_get_resolver.call_args
|
||||
assert args[1] == 'test-keycloak-id'
|
||||
assert args[2] == self.resolved_org_id
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('integrations.gitlab.gitlab_view.get_app_conversation_service')
|
||||
@patch('integrations.gitlab.gitlab_view.resolve_org_for_repo')
|
||||
async def test_v1_passes_resolver_org_id_to_resolver_user_context(
|
||||
self, mock_resolve_org, mock_get_service
|
||||
):
|
||||
"""V1 path passes resolved org_id to ResolverUserContext."""
|
||||
# Arrange
|
||||
mock_resolve_org.return_value = self.resolved_org_id
|
||||
|
||||
gitlab_issue = self._create_gitlab_issue()
|
||||
gitlab_issue.v1_enabled = True
|
||||
|
||||
# Initialize to set resolved_org_id
|
||||
await gitlab_issue.initialize_new_conversation()
|
||||
|
||||
# Assert
|
||||
assert gitlab_issue.resolved_org_id == self.resolved_org_id
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch(
|
||||
'integrations.gitlab.gitlab_view.SaasConversationStore.get_resolver_instance'
|
||||
)
|
||||
@patch('integrations.gitlab.gitlab_view.resolve_org_for_repo')
|
||||
async def test_no_claim_passes_none_resolver_org_id(
|
||||
self, mock_resolve_org, mock_get_resolver
|
||||
):
|
||||
"""When no claim exists, resolver_org_id is None (falls back to personal workspace)."""
|
||||
# Arrange
|
||||
mock_resolve_org.return_value = None
|
||||
mock_store = MagicMock()
|
||||
mock_store.save_metadata = AsyncMock()
|
||||
mock_get_resolver.return_value = mock_store
|
||||
|
||||
gitlab_issue = self._create_gitlab_issue()
|
||||
|
||||
# Act
|
||||
await gitlab_issue.initialize_new_conversation()
|
||||
|
||||
# Assert
|
||||
args, _ = mock_get_resolver.call_args
|
||||
assert args[2] is None
|
||||
@@ -1,347 +0,0 @@
|
||||
"""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'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
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
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
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 = 'svc@test.com'
|
||||
workspace.svc_acc_api_key = 'api-key'
|
||||
workspace.status = 'active'
|
||||
return workspace
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
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
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
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='user@test.com',
|
||||
platform_user_id='linear-user-123',
|
||||
workspace_name='test-workspace',
|
||||
display_name='Test User',
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
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
|
||||
@@ -214,125 +214,3 @@ class TestGetInstance:
|
||||
# Assert
|
||||
assert store.user_id == user_id
|
||||
assert store.org_id is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_resolver_instance_passes_resolver_org_id(self):
|
||||
"""Verify get_resolver_instance forwards resolver_org_id to the store."""
|
||||
# Arrange
|
||||
user_id = '5594c7b6-f959-4b81-92e9-b09c206f5081'
|
||||
resolver_org_id = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
|
||||
mock_user = MagicMock(spec=User)
|
||||
mock_user.current_org_id = UUID(user_id)
|
||||
mock_config = MagicMock(spec=OpenHandsConfig)
|
||||
|
||||
with patch(
|
||||
'storage.saas_conversation_store.UserStore.get_user_by_id',
|
||||
AsyncMock(return_value=mock_user),
|
||||
), patch('storage.saas_conversation_store.session_maker'):
|
||||
# Act
|
||||
store = await SaasConversationStore.get_resolver_instance(
|
||||
mock_config, user_id, resolver_org_id=resolver_org_id
|
||||
)
|
||||
|
||||
# Assert
|
||||
assert store.resolver_org_id == resolver_org_id
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_instance_does_not_have_resolver_org_id(self):
|
||||
"""Verify get_instance does not set resolver_org_id (it's not a resolver path)."""
|
||||
# Arrange
|
||||
user_id = '5594c7b6-f959-4b81-92e9-b09c206f5081'
|
||||
mock_user = MagicMock(spec=User)
|
||||
mock_user.current_org_id = UUID(user_id)
|
||||
mock_config = MagicMock(spec=OpenHandsConfig)
|
||||
|
||||
with patch(
|
||||
'storage.saas_conversation_store.UserStore.get_user_by_id',
|
||||
AsyncMock(return_value=mock_user),
|
||||
), patch('storage.saas_conversation_store.session_maker'):
|
||||
# Act
|
||||
store = await SaasConversationStore.get_instance(mock_config, user_id)
|
||||
|
||||
# Assert
|
||||
assert store.resolver_org_id is None
|
||||
|
||||
|
||||
class TestResolverOrgIdRouting:
|
||||
"""Tests for resolver_org_id overriding org_id in save_metadata."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_save_metadata_uses_resolver_org_id_over_default(self, session_maker):
|
||||
"""When resolver_org_id is set, save_metadata stores it instead of the default org_id."""
|
||||
# Arrange
|
||||
user_id = '5594c7b6-f959-4b81-92e9-b09c206f5081'
|
||||
default_org_id = UUID('5594c7b6-f959-4b81-92e9-b09c206f5081')
|
||||
resolver_org_id = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
|
||||
store = SaasConversationStore(
|
||||
user_id, default_org_id, session_maker, resolver_org_id=resolver_org_id
|
||||
)
|
||||
metadata = ConversationMetadata(
|
||||
conversation_id='resolver-routed-conv',
|
||||
user_id=user_id,
|
||||
selected_repository='ClaimedOrg/repo',
|
||||
selected_branch=None,
|
||||
created_at=datetime.now(UTC),
|
||||
last_updated_at=datetime.now(UTC),
|
||||
)
|
||||
|
||||
# Act
|
||||
await store.save_metadata(metadata)
|
||||
|
||||
# Assert - verify the SaaS metadata record has the resolver org, not the default
|
||||
from storage.stored_conversation_metadata_saas import (
|
||||
StoredConversationMetadataSaas,
|
||||
)
|
||||
|
||||
with session_maker() as session:
|
||||
saas_record = (
|
||||
session.query(StoredConversationMetadataSaas)
|
||||
.filter(
|
||||
StoredConversationMetadataSaas.conversation_id
|
||||
== 'resolver-routed-conv'
|
||||
)
|
||||
.first()
|
||||
)
|
||||
assert saas_record is not None
|
||||
assert saas_record.org_id == resolver_org_id
|
||||
assert saas_record.org_id != default_org_id
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_save_metadata_uses_default_org_when_no_resolver_org(
|
||||
self, session_maker
|
||||
):
|
||||
"""When resolver_org_id is None, save_metadata uses the default org_id."""
|
||||
# Arrange
|
||||
user_id = '5594c7b6-f959-4b81-92e9-b09c206f5081'
|
||||
default_org_id = UUID('5594c7b6-f959-4b81-92e9-b09c206f5081')
|
||||
store = SaasConversationStore(user_id, default_org_id, session_maker)
|
||||
metadata = ConversationMetadata(
|
||||
conversation_id='default-org-conv',
|
||||
user_id=user_id,
|
||||
selected_repository='PersonalOrg/repo',
|
||||
selected_branch=None,
|
||||
created_at=datetime.now(UTC),
|
||||
last_updated_at=datetime.now(UTC),
|
||||
)
|
||||
|
||||
# Act
|
||||
await store.save_metadata(metadata)
|
||||
|
||||
# Assert
|
||||
from storage.stored_conversation_metadata_saas import (
|
||||
StoredConversationMetadataSaas,
|
||||
)
|
||||
|
||||
with session_maker() as session:
|
||||
saas_record = (
|
||||
session.query(StoredConversationMetadataSaas)
|
||||
.filter(
|
||||
StoredConversationMetadataSaas.conversation_id == 'default-org-conv'
|
||||
)
|
||||
.first()
|
||||
)
|
||||
assert saas_record is not None
|
||||
assert saas_record.org_id == default_org_id
|
||||
|
||||
@@ -535,99 +535,6 @@ async def test_store_does_not_update_org_mcp_config(
|
||||
assert org.mcp_config is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_store_skips_ensure_api_key_for_non_openhands_model_without_base_url(
|
||||
session_maker, async_session_maker, mock_config, org_with_multiple_members_fixture
|
||||
):
|
||||
"""When saving a non-OpenHands model with no base URL (basic view BYOR),
|
||||
_ensure_api_key should NOT be called, preserving the user's custom API key.
|
||||
|
||||
This is the primary bug fix: users selecting e.g. OpenAI in basic view and
|
||||
providing their own API key should not have it overwritten by a proxy key.
|
||||
"""
|
||||
# Arrange
|
||||
fixture = org_with_multiple_members_fixture
|
||||
admin_user_id = str(fixture['admin_user_id'])
|
||||
store = SaasSettingsStore(admin_user_id, mock_config)
|
||||
|
||||
custom_api_key = 'sk-user-custom-openai-key'
|
||||
settings = DataSettings(
|
||||
llm_model='openai/gpt-5.2',
|
||||
llm_base_url=None, # Basic view: no base URL provided
|
||||
llm_api_key=SecretStr(custom_api_key),
|
||||
)
|
||||
|
||||
# Act
|
||||
with (
|
||||
patch('storage.saas_settings_store.a_session_maker', async_session_maker),
|
||||
patch.object(store, '_ensure_api_key', new_callable=AsyncMock) as mock_ensure,
|
||||
):
|
||||
await store.store(settings)
|
||||
|
||||
# Assert
|
||||
mock_ensure.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_store_calls_ensure_api_key_for_openhands_model_without_base_url(
|
||||
session_maker, async_session_maker, mock_config, org_with_multiple_members_fixture
|
||||
):
|
||||
"""When saving an OpenHands model with no base URL, _ensure_api_key should
|
||||
still be called to generate/verify the proxy key.
|
||||
|
||||
This guards the edge case of switching from a non-OpenHands provider to
|
||||
OpenHands in basic view, where a stale BYOR key needs to be replaced.
|
||||
"""
|
||||
# Arrange
|
||||
fixture = org_with_multiple_members_fixture
|
||||
admin_user_id = str(fixture['admin_user_id'])
|
||||
store = SaasSettingsStore(admin_user_id, mock_config)
|
||||
|
||||
settings = DataSettings(
|
||||
llm_model='openhands/claude-opus-4-5-20251101',
|
||||
llm_base_url=None,
|
||||
llm_api_key=SecretStr('sk-stale-openai-key'),
|
||||
)
|
||||
|
||||
# Act
|
||||
with (
|
||||
patch('storage.saas_settings_store.a_session_maker', async_session_maker),
|
||||
patch.object(store, '_ensure_api_key', new_callable=AsyncMock) as mock_ensure,
|
||||
):
|
||||
await store.store(settings)
|
||||
|
||||
# Assert
|
||||
mock_ensure.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_store_calls_ensure_api_key_when_base_url_is_litellm_proxy(
|
||||
session_maker, async_session_maker, mock_config, org_with_multiple_members_fixture
|
||||
):
|
||||
"""When the base URL is explicitly the LiteLLM proxy, _ensure_api_key should
|
||||
be called regardless of the model type."""
|
||||
# Arrange
|
||||
fixture = org_with_multiple_members_fixture
|
||||
admin_user_id = str(fixture['admin_user_id'])
|
||||
store = SaasSettingsStore(admin_user_id, mock_config)
|
||||
|
||||
settings = DataSettings(
|
||||
llm_model='openai/gpt-5.2',
|
||||
llm_base_url=LITE_LLM_API_URL,
|
||||
llm_api_key=SecretStr('sk-some-key'),
|
||||
)
|
||||
|
||||
# Act
|
||||
with (
|
||||
patch('storage.saas_settings_store.a_session_maker', async_session_maker),
|
||||
patch.object(store, '_ensure_api_key', new_callable=AsyncMock) as mock_ensure,
|
||||
):
|
||||
await store.store(settings)
|
||||
|
||||
# Assert
|
||||
mock_ensure.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_load_returns_user_specific_mcp_config(
|
||||
session_maker, async_session_maker, mock_config, org_with_multiple_members_fixture
|
||||
|
||||
@@ -135,19 +135,14 @@ class TestRepoVerificationHandling:
|
||||
|
||||
@patch('integrations.slack.slack_manager.sio')
|
||||
@patch.object(SlackManager, 'send_message', new_callable=AsyncMock)
|
||||
async def test_no_repo_mentioned_shows_button_and_dropdown(
|
||||
async def test_no_repo_mentioned_shows_external_selector(
|
||||
self,
|
||||
mock_send_message,
|
||||
mock_sio,
|
||||
slack_manager,
|
||||
slack_new_conversation_view,
|
||||
):
|
||||
"""Test that when no repo is mentioned, a button and dropdown are shown.
|
||||
|
||||
The form shows:
|
||||
1. A "No Repository" button - immediately clickable without loading
|
||||
2. An external_select dropdown - for searching repositories dynamically
|
||||
"""
|
||||
"""Test that when no repo is mentioned, external_select repo selector is shown."""
|
||||
# Setup Redis mock
|
||||
mock_redis = AsyncMock()
|
||||
mock_sio.manager.redis = mock_redis
|
||||
@@ -167,75 +162,17 @@ class TestRepoVerificationHandling:
|
||||
mock_send_message.assert_called_once()
|
||||
call_args = mock_send_message.call_args
|
||||
|
||||
# Should be the repo selection form with button + external_select
|
||||
# Should be the repo selection form with external_select
|
||||
message = call_args[0][0]
|
||||
assert isinstance(message, dict)
|
||||
assert message.get('text') == 'Choose a Repository:'
|
||||
|
||||
# Verify it's using external_select
|
||||
blocks = message.get('blocks', [])
|
||||
actions_block = next((b for b in blocks if b.get('type') == 'actions'), None)
|
||||
assert actions_block is not None
|
||||
elements = actions_block.get('elements', [])
|
||||
|
||||
# Should have 2 elements: button and external_select
|
||||
assert len(elements) == 2
|
||||
|
||||
# First element: "No Repository" button (immediately available)
|
||||
assert elements[0].get('type') == 'button'
|
||||
assert elements[0].get('action_id').startswith('no_repository:')
|
||||
assert elements[0].get('value') == '-'
|
||||
|
||||
# Second element: external_select for searching repos
|
||||
assert elements[1].get('type') == 'external_select'
|
||||
assert elements[1].get('action_id').startswith('repository_select:')
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('integrations.slack.slack_manager.sio')
|
||||
async def test_no_repository_button_click_processes_correctly(
|
||||
self,
|
||||
mock_sio,
|
||||
slack_manager,
|
||||
):
|
||||
"""Test that clicking 'No Repository' button correctly processes the interaction.
|
||||
|
||||
This verifies the button click path through receive_form_interaction, ensuring
|
||||
the no_repository: action_id is correctly parsed and processed.
|
||||
"""
|
||||
# Setup: Mock Redis to return a stored user message
|
||||
mock_redis = AsyncMock()
|
||||
mock_sio.manager.redis = mock_redis
|
||||
stored_msg = json.dumps({'text': 'Hello, help me with code', 'user': 'U123'})
|
||||
mock_redis.get = AsyncMock(return_value=stored_msg)
|
||||
|
||||
# Simulate button click payload (what Slack sends when button is clicked)
|
||||
button_payload = {
|
||||
'type': 'block_actions',
|
||||
'actions': [
|
||||
{
|
||||
'action_id': 'no_repository:1234567890.123456:None',
|
||||
'type': 'button',
|
||||
'value': '-',
|
||||
}
|
||||
],
|
||||
'user': {'id': 'U123'},
|
||||
'container': {'channel_id': 'C123'},
|
||||
'team': {'id': 'T123'},
|
||||
}
|
||||
|
||||
# Mock receive_message to capture what's passed to it
|
||||
with patch.object(
|
||||
slack_manager, 'receive_message', new_callable=AsyncMock
|
||||
) as mock_receive:
|
||||
await slack_manager.receive_form_interaction(button_payload)
|
||||
|
||||
# Verify receive_message was called
|
||||
mock_receive.assert_called_once()
|
||||
|
||||
# Verify the message payload has selected_repo as None
|
||||
call_args = mock_receive.call_args[0][0]
|
||||
assert call_args.message['selected_repo'] is None
|
||||
assert call_args.message['message_ts'] == '1234567890.123456'
|
||||
assert call_args.message['thread_ts'] is None
|
||||
assert len(elements) > 0
|
||||
assert elements[0].get('type') == 'external_select'
|
||||
|
||||
@patch('integrations.slack.slack_manager.sio')
|
||||
@patch('integrations.slack.slack_manager.ProviderHandler')
|
||||
@@ -286,8 +223,8 @@ class TestRepoVerificationHandling:
|
||||
class TestBuildRepoOptions:
|
||||
"""Test the _build_repo_options helper method.
|
||||
|
||||
Note: _build_repo_options returns only actual repositories. The "No Repository"
|
||||
option is now handled by a separate button in the form, not the dropdown.
|
||||
Note: _build_repo_options always includes the "No Repository" option at the top.
|
||||
This is by design for the external_select dropdown.
|
||||
"""
|
||||
|
||||
def test_build_options_with_repos(self, slack_manager):
|
||||
@@ -310,20 +247,21 @@ class TestBuildRepoOptions:
|
||||
|
||||
options = slack_manager._build_repo_options(repos)
|
||||
|
||||
# Should have 2 options (repos only - "No Repository" is now a button)
|
||||
assert len(options) == 2
|
||||
assert options[0]['value'] == 'owner/repo1'
|
||||
assert options[1]['value'] == 'owner/repo2'
|
||||
# Should have 3 options: "No Repository" + 2 repos
|
||||
assert len(options) == 3
|
||||
assert options[0]['value'] == '-'
|
||||
assert options[0]['text']['text'] == 'No Repository'
|
||||
assert options[1]['value'] == 'owner/repo1'
|
||||
assert options[2]['value'] == 'owner/repo2'
|
||||
|
||||
def test_build_options_empty_repos(self, slack_manager):
|
||||
"""Test building options with empty repo list returns empty list.
|
||||
|
||||
Note: "No Repository" is now handled by a separate button in the form.
|
||||
"""
|
||||
"""Test building options with empty repo list still includes No Repository."""
|
||||
options = slack_manager._build_repo_options([])
|
||||
|
||||
# Should have 0 options (empty list)
|
||||
assert len(options) == 0
|
||||
# Should have 1 option: just "No Repository"
|
||||
assert len(options) == 1
|
||||
assert options[0]['value'] == '-'
|
||||
assert options[0]['text']['text'] == 'No Repository'
|
||||
|
||||
def test_build_options_truncates_long_names(self, slack_manager):
|
||||
"""Test that repo names longer than 75 chars are truncated."""
|
||||
@@ -340,12 +278,12 @@ class TestBuildRepoOptions:
|
||||
|
||||
options = slack_manager._build_repo_options(repos)
|
||||
|
||||
# Should have 1 option (the repo only - "No Repository" is a button)
|
||||
assert len(options) == 1
|
||||
# First option is "No Repository", second is the repo
|
||||
assert len(options) == 2
|
||||
# Text should be truncated to 75 chars
|
||||
assert len(options[0]['text']['text']) == 75
|
||||
assert len(options[1]['text']['text']) == 75
|
||||
# But value should have full name
|
||||
assert options[0]['value'] == long_name
|
||||
assert options[1]['value'] == long_name
|
||||
|
||||
|
||||
class TestSearchRepositories:
|
||||
@@ -475,23 +413,23 @@ class TestSearchRepositories:
|
||||
options = slack_manager._build_repo_options(search_results)
|
||||
|
||||
# Verify: Options are correctly built from search results
|
||||
# Note: "No Repository" is now a button, not in the dropdown
|
||||
assert len(options) == 3 # 3 repos only
|
||||
assert len(options) == 4 # "No Repository" + 3 repos
|
||||
|
||||
# Options should be the repos in order
|
||||
assert options[0]['value'] == 'myorg/react-dashboard'
|
||||
assert options[0]['text']['text'] == 'myorg/react-dashboard'
|
||||
assert options[1]['value'] == 'myorg/python-api'
|
||||
assert options[2]['value'] == 'myorg/docs-site'
|
||||
# First option should be "No Repository"
|
||||
assert options[0]['value'] == '-'
|
||||
assert options[0]['text']['text'] == 'No Repository'
|
||||
|
||||
# Remaining options should be the repos in order
|
||||
assert options[1]['value'] == 'myorg/react-dashboard'
|
||||
assert options[1]['text']['text'] == 'myorg/react-dashboard'
|
||||
assert options[2]['value'] == 'myorg/python-api'
|
||||
assert options[3]['value'] == 'myorg/docs-site'
|
||||
|
||||
@patch('integrations.slack.slack_manager.ProviderHandler')
|
||||
async def test_search_with_empty_results_builds_empty_options(
|
||||
async def test_search_with_empty_results_builds_no_repo_only_option(
|
||||
self, mock_provider_handler_class, slack_manager, mock_user_auth
|
||||
):
|
||||
"""Test that when search returns no results, empty options list is returned.
|
||||
|
||||
Note: "No Repository" is now handled by a separate button in the form.
|
||||
"""
|
||||
"""Test that when search returns no results, only 'No Repository' option is shown."""
|
||||
# Setup: No matching repos
|
||||
mock_provider_handler = MagicMock()
|
||||
mock_provider_handler.search_repositories = AsyncMock(return_value=[])
|
||||
@@ -509,8 +447,10 @@ class TestSearchRepositories:
|
||||
)
|
||||
options = slack_manager._build_repo_options(search_results)
|
||||
|
||||
# Verify: Empty options list (button handles "No Repository")
|
||||
assert len(options) == 0
|
||||
# Verify: Only "No Repository" option
|
||||
assert len(options) == 1
|
||||
assert options[0]['value'] == '-'
|
||||
assert options[0]['text']['text'] == 'No Repository'
|
||||
|
||||
|
||||
class TestUserMsgStorage:
|
||||
@@ -729,10 +669,7 @@ class TestOnOptionsLoadEndpoint:
|
||||
async def test_on_options_load_disabled_returns_empty_options(
|
||||
self, mock_request, background_tasks
|
||||
):
|
||||
"""Test that when webhooks are disabled, empty options are returned.
|
||||
|
||||
Note: 'No Repository' is handled by a separate button in the form.
|
||||
"""
|
||||
"""Test that when webhooks are disabled, empty options are returned."""
|
||||
from server.routes.integration.slack import on_options_load
|
||||
|
||||
response = await on_options_load(mock_request, background_tasks)
|
||||
@@ -746,10 +683,7 @@ class TestOnOptionsLoadEndpoint:
|
||||
async def test_on_options_load_no_payload_returns_empty_options(
|
||||
self, mock_request, background_tasks
|
||||
):
|
||||
"""Test that when no payload is in request, empty options are returned.
|
||||
|
||||
Note: 'No Repository' is handled by a separate button in the form.
|
||||
"""
|
||||
"""Test that when no payload is in request, empty options are returned."""
|
||||
from server.routes.integration.slack import on_options_load
|
||||
|
||||
mock_request.body = AsyncMock(return_value=b'')
|
||||
@@ -797,10 +731,7 @@ class TestOnOptionsLoadEndpoint:
|
||||
async def test_on_options_load_wrong_payload_type_returns_empty_options(
|
||||
self, mock_signature_verifier, mock_request, background_tasks
|
||||
):
|
||||
"""Test that non-block_suggestion payload returns empty options.
|
||||
|
||||
Note: 'No Repository' is handled by a separate button in the form.
|
||||
"""
|
||||
"""Test that non-block_suggestion payload returns empty options."""
|
||||
from server.routes.integration.slack import on_options_load
|
||||
|
||||
payload = {
|
||||
@@ -833,10 +764,7 @@ class TestOnOptionsLoadEndpoint:
|
||||
background_tasks,
|
||||
valid_block_suggestion_payload,
|
||||
):
|
||||
"""Test that unauthenticated users get empty options and linking message is queued.
|
||||
|
||||
Note: 'No Repository' is handled by a separate button in the form.
|
||||
"""
|
||||
"""Test that unauthenticated users get empty options and linking message is queued."""
|
||||
from server.routes.integration.slack import on_options_load
|
||||
|
||||
payload_str = json.dumps(valid_block_suggestion_payload)
|
||||
@@ -889,8 +817,9 @@ class TestOnOptionsLoadEndpoint:
|
||||
return_value=(mock_slack_user, mock_user_auth)
|
||||
)
|
||||
|
||||
# Expected options from search_repos_for_slack (no "No Repository" - that's a button)
|
||||
# Expected options from search_repos_for_slack
|
||||
expected_options = [
|
||||
{'text': {'type': 'plain_text', 'text': 'No Repository'}, 'value': '-'},
|
||||
{
|
||||
'text': {'type': 'plain_text', 'text': 'owner/repo1'},
|
||||
'value': 'owner/repo1',
|
||||
@@ -949,8 +878,11 @@ class TestOnOptionsLoadEndpoint:
|
||||
mock_slack_manager.authenticate_user = AsyncMock(
|
||||
return_value=(mock_slack_user, mock_user_auth)
|
||||
)
|
||||
# Empty search returns empty list (no repos found, and "No Repository" is a button)
|
||||
mock_slack_manager.search_repos_for_slack = AsyncMock(return_value=[])
|
||||
mock_slack_manager.search_repos_for_slack = AsyncMock(
|
||||
return_value=[
|
||||
{'text': {'type': 'plain_text', 'text': 'No Repository'}, 'value': '-'}
|
||||
]
|
||||
)
|
||||
|
||||
response = await on_options_load(mock_request, background_tasks)
|
||||
|
||||
@@ -975,10 +907,7 @@ class TestOnOptionsLoadEndpoint:
|
||||
mock_slack_user,
|
||||
mock_user_auth,
|
||||
):
|
||||
"""Test that when search raises an exception, empty options are returned gracefully.
|
||||
|
||||
Note: 'No Repository' is handled by a separate button in the form.
|
||||
"""
|
||||
"""Test that when search raises an exception, empty options are returned gracefully."""
|
||||
from server.routes.integration.slack import on_options_load
|
||||
|
||||
payload_str = json.dumps(valid_block_suggestion_payload)
|
||||
|
||||
@@ -1,331 +0,0 @@
|
||||
"""Tests for Slack view org routing logic.
|
||||
|
||||
Tests that the SlackNewConversationView correctly resolves the target org
|
||||
based on claimed git organizations and passes it through V0/V1 paths.
|
||||
"""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from integrations.slack.slack_view import SlackNewConversationView
|
||||
from storage.slack_user import SlackUser
|
||||
|
||||
from openhands.integrations.service_types import ProviderType
|
||||
from openhands.server.user_auth.user_auth import UserAuth
|
||||
|
||||
CLAIMING_ORG_ID = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
|
||||
KEYCLOAK_USER_ID = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_slack_user():
|
||||
"""Create a mock SlackUser."""
|
||||
user = SlackUser()
|
||||
user.slack_user_id = 'U1234567890'
|
||||
user.keycloak_user_id = KEYCLOAK_USER_ID
|
||||
user.slack_display_name = 'Test User'
|
||||
user.org_id = UUID('cccccccc-cccc-cccc-cccc-cccccccccccc')
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_auth():
|
||||
"""Create a mock UserAuth."""
|
||||
auth = MagicMock(spec=UserAuth)
|
||||
auth.get_provider_tokens = AsyncMock(
|
||||
return_value={ProviderType.GITHUB: MagicMock()}
|
||||
)
|
||||
auth.get_secrets = AsyncMock(return_value=MagicMock(custom_secrets={}))
|
||||
auth.get_access_token = AsyncMock(return_value='access-token')
|
||||
auth.get_user_id = AsyncMock(return_value=KEYCLOAK_USER_ID)
|
||||
return auth
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def slack_view(mock_slack_user, mock_user_auth):
|
||||
"""Create a SlackNewConversationView instance for testing."""
|
||||
return SlackNewConversationView(
|
||||
bot_access_token='xoxb-test-token',
|
||||
user_msg='Hello OpenHands!',
|
||||
slack_user_id='U1234567890',
|
||||
slack_to_openhands_user=mock_slack_user,
|
||||
saas_user_auth=mock_user_auth,
|
||||
channel_id='C1234567890',
|
||||
message_ts='1234567890.123456',
|
||||
thread_ts=None,
|
||||
selected_repo='OpenHands/foo',
|
||||
should_extract=True,
|
||||
send_summary_instruction=True,
|
||||
conversation_id='',
|
||||
team_id='T1234567890',
|
||||
v1_enabled=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def slack_view_no_repo(mock_slack_user, mock_user_auth):
|
||||
"""Create a SlackNewConversationView with no selected repo."""
|
||||
return SlackNewConversationView(
|
||||
bot_access_token='xoxb-test-token',
|
||||
user_msg='Hello OpenHands!',
|
||||
slack_user_id='U1234567890',
|
||||
slack_to_openhands_user=mock_slack_user,
|
||||
saas_user_auth=mock_user_auth,
|
||||
channel_id='C1234567890',
|
||||
message_ts='1234567890.123456',
|
||||
thread_ts=None,
|
||||
selected_repo=None,
|
||||
should_extract=True,
|
||||
send_summary_instruction=True,
|
||||
conversation_id='',
|
||||
team_id='T1234567890',
|
||||
v1_enabled=False,
|
||||
)
|
||||
|
||||
|
||||
class TestSlackV0ConversationRouting:
|
||||
"""Test V0 conversation routing logic in Slack integration."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch(
|
||||
'integrations.slack.slack_view.is_v1_enabled_for_slack_resolver',
|
||||
new_callable=AsyncMock,
|
||||
return_value=False,
|
||||
)
|
||||
@patch('integrations.slack.slack_view.resolve_org_for_repo', new_callable=AsyncMock)
|
||||
@patch('integrations.slack.slack_view.ProviderHandler')
|
||||
@patch(
|
||||
'integrations.slack.slack_view.SaasConversationStore.get_resolver_instance',
|
||||
new_callable=AsyncMock,
|
||||
)
|
||||
@patch('integrations.slack.slack_view.start_conversation', new_callable=AsyncMock)
|
||||
async def test_v0_passes_resolver_org_id(
|
||||
self,
|
||||
mock_start_convo,
|
||||
mock_get_resolver_instance,
|
||||
mock_provider_handler_cls,
|
||||
mock_resolve_org,
|
||||
mock_v1_enabled,
|
||||
slack_view,
|
||||
):
|
||||
"""V0 path should pass resolver_org_id to SaasConversationStore.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_start_convo.return_value = MagicMock(conversation_id='test-conv-id')
|
||||
|
||||
mock_jinja = MagicMock()
|
||||
|
||||
# Act
|
||||
with (
|
||||
patch.object(
|
||||
slack_view,
|
||||
'_get_instructions',
|
||||
new_callable=AsyncMock,
|
||||
return_value=('msg', 'instructions'),
|
||||
),
|
||||
patch.object(slack_view, 'save_slack_convo', new_callable=AsyncMock),
|
||||
):
|
||||
await slack_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,
|
||||
)
|
||||
mock_get_resolver_instance.assert_called_once()
|
||||
call_args = mock_get_resolver_instance.call_args
|
||||
assert call_args[0][1] == KEYCLOAK_USER_ID # user_id
|
||||
assert call_args[0][2] == CLAIMING_ORG_ID # resolver_org_id
|
||||
mock_store.save_metadata.assert_called_once()
|
||||
saved_metadata = mock_store.save_metadata.call_args[0][0]
|
||||
assert saved_metadata.git_provider == ProviderType.GITHUB
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch(
|
||||
'integrations.slack.slack_view.is_v1_enabled_for_slack_resolver',
|
||||
new_callable=AsyncMock,
|
||||
return_value=False,
|
||||
)
|
||||
@patch('integrations.slack.slack_view.resolve_org_for_repo', new_callable=AsyncMock)
|
||||
@patch('integrations.slack.slack_view.ProviderHandler')
|
||||
@patch(
|
||||
'integrations.slack.slack_view.SaasConversationStore.get_resolver_instance',
|
||||
new_callable=AsyncMock,
|
||||
)
|
||||
@patch('integrations.slack.slack_view.start_conversation', new_callable=AsyncMock)
|
||||
async def test_v0_passes_none_when_no_claim(
|
||||
self,
|
||||
mock_start_convo,
|
||||
mock_get_resolver_instance,
|
||||
mock_provider_handler_cls,
|
||||
mock_resolve_org,
|
||||
mock_v1_enabled,
|
||||
slack_view,
|
||||
):
|
||||
"""V0 path should pass resolver_org_id=None when no claim exists."""
|
||||
# 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_start_convo.return_value = MagicMock(conversation_id='test-conv-id')
|
||||
|
||||
mock_jinja = MagicMock()
|
||||
|
||||
# Act
|
||||
with (
|
||||
patch.object(
|
||||
slack_view,
|
||||
'_get_instructions',
|
||||
new_callable=AsyncMock,
|
||||
return_value=('msg', 'instructions'),
|
||||
),
|
||||
patch.object(slack_view, 'save_slack_convo', new_callable=AsyncMock),
|
||||
):
|
||||
await slack_view.create_or_update_conversation(mock_jinja)
|
||||
|
||||
# Assert
|
||||
call_args = mock_get_resolver_instance.call_args
|
||||
assert call_args[0][2] is None # resolver_org_id is None
|
||||
|
||||
|
||||
class TestSlackV1ConversationRouting:
|
||||
"""Test V1 conversation routing logic in Slack integration."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch(
|
||||
'integrations.slack.slack_view.is_v1_enabled_for_slack_resolver',
|
||||
new_callable=AsyncMock,
|
||||
return_value=True,
|
||||
)
|
||||
@patch('integrations.slack.slack_view.resolve_org_for_repo', new_callable=AsyncMock)
|
||||
@patch('integrations.slack.slack_view.ProviderHandler')
|
||||
@patch('integrations.slack.slack_view.get_app_conversation_service')
|
||||
@patch('integrations.slack.slack_view.ResolverUserContext')
|
||||
async def test_v1_passes_resolver_org_id_to_context(
|
||||
self,
|
||||
mock_resolver_ctx_cls,
|
||||
mock_get_service,
|
||||
mock_provider_handler_cls,
|
||||
mock_resolve_org,
|
||||
mock_v1_enabled,
|
||||
slack_view,
|
||||
):
|
||||
"""V1 path should pass resolver_org_id to ResolverUserContext."""
|
||||
# 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_resolver_ctx_cls.return_value = MagicMock()
|
||||
|
||||
# Mock the async context manager for app_conversation_service
|
||||
mock_service = MagicMock()
|
||||
mock_service.start_app_conversation = MagicMock(return_value=aiter_empty())
|
||||
mock_ctx = MagicMock()
|
||||
mock_ctx.__aenter__ = AsyncMock(return_value=mock_service)
|
||||
mock_ctx.__aexit__ = AsyncMock(return_value=None)
|
||||
mock_get_service.return_value = mock_ctx
|
||||
|
||||
mock_jinja = MagicMock()
|
||||
|
||||
# Act
|
||||
with patch.object(
|
||||
slack_view,
|
||||
'_get_instructions',
|
||||
new_callable=AsyncMock,
|
||||
return_value=('msg', 'instructions'),
|
||||
):
|
||||
with patch.object(slack_view, 'save_slack_convo', new_callable=AsyncMock):
|
||||
await slack_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,
|
||||
)
|
||||
mock_resolver_ctx_cls.assert_called_once_with(
|
||||
saas_user_auth=slack_view.saas_user_auth,
|
||||
resolver_org_id=CLAIMING_ORG_ID,
|
||||
)
|
||||
|
||||
|
||||
class TestSlackNoRepoRouting:
|
||||
"""Test routing when no repository is selected."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch(
|
||||
'integrations.slack.slack_view.is_v1_enabled_for_slack_resolver',
|
||||
new_callable=AsyncMock,
|
||||
return_value=False,
|
||||
)
|
||||
@patch('integrations.slack.slack_view.resolve_org_for_repo', new_callable=AsyncMock)
|
||||
@patch(
|
||||
'integrations.slack.slack_view.SaasConversationStore.get_resolver_instance',
|
||||
new_callable=AsyncMock,
|
||||
)
|
||||
@patch('integrations.slack.slack_view.start_conversation', new_callable=AsyncMock)
|
||||
async def test_no_repo_skips_org_resolution(
|
||||
self,
|
||||
mock_start_convo,
|
||||
mock_get_resolver_instance,
|
||||
mock_resolve_org,
|
||||
mock_v1_enabled,
|
||||
slack_view_no_repo,
|
||||
):
|
||||
"""When selected_repo is None, org resolution should be skipped."""
|
||||
# Arrange
|
||||
mock_store = MagicMock()
|
||||
mock_store.save_metadata = AsyncMock()
|
||||
mock_get_resolver_instance.return_value = mock_store
|
||||
mock_start_convo.return_value = MagicMock(conversation_id='test-conv-id')
|
||||
mock_jinja = MagicMock()
|
||||
|
||||
# Act
|
||||
with (
|
||||
patch.object(
|
||||
slack_view_no_repo,
|
||||
'_get_instructions',
|
||||
new_callable=AsyncMock,
|
||||
return_value=('msg', 'instructions'),
|
||||
),
|
||||
patch.object(
|
||||
slack_view_no_repo, 'save_slack_convo', new_callable=AsyncMock
|
||||
),
|
||||
patch.object(slack_view_no_repo, '_verify_necessary_values_are_set'),
|
||||
):
|
||||
await slack_view_no_repo.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 # resolver_org_id is None
|
||||
saved_metadata = mock_store.save_metadata.call_args[0][0]
|
||||
assert saved_metadata.git_provider is None
|
||||
|
||||
|
||||
async def aiter_empty():
|
||||
"""Helper: empty async iterator."""
|
||||
return
|
||||
yield # noqa: unreachable - makes this an async generator
|
||||
@@ -1,141 +0,0 @@
|
||||
"""Tests for the GET /api/user/git-organizations endpoint.
|
||||
|
||||
This endpoint returns git organizations for the user's active provider
|
||||
in SaaS mode (single provider at a time).
|
||||
"""
|
||||
|
||||
from types import MappingProxyType
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import SecretStr
|
||||
|
||||
from openhands.integrations.provider import ProviderToken
|
||||
from openhands.integrations.service_types import ProviderType
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def github_provider_tokens():
|
||||
return MappingProxyType(
|
||||
{ProviderType.GITHUB: ProviderToken(token=SecretStr('gh-token'))}
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gitlab_provider_tokens():
|
||||
return MappingProxyType(
|
||||
{ProviderType.GITLAB: ProviderToken(token=SecretStr('gl-token'))}
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bitbucket_provider_tokens():
|
||||
return MappingProxyType(
|
||||
{ProviderType.BITBUCKET: ProviderToken(token=SecretStr('bb-token'))}
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def azure_devops_provider_tokens():
|
||||
return MappingProxyType(
|
||||
{ProviderType.AZURE_DEVOPS: ProviderToken(token=SecretStr('az-token'))}
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_check_idp():
|
||||
with patch('server.routes.user._check_idp', new_callable=AsyncMock) as mock_fn:
|
||||
yield mock_fn
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_provider_tokens_falls_back_to_idp(mock_check_idp):
|
||||
"""When no provider tokens exist, falls back to IDP check."""
|
||||
from server.routes.user import saas_get_user_git_organizations
|
||||
|
||||
mock_check_idp.return_value = {}
|
||||
|
||||
result = await saas_get_user_git_organizations(
|
||||
provider_tokens=None,
|
||||
access_token=SecretStr('token'),
|
||||
user_id='user-1',
|
||||
)
|
||||
|
||||
assert result == {}
|
||||
mock_check_idp.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unsupported_provider_returns_400(azure_devops_provider_tokens):
|
||||
"""Unsupported provider returns a 400 error."""
|
||||
from server.routes.user import saas_get_user_git_organizations
|
||||
|
||||
with patch('server.routes.user.ProviderHandler'):
|
||||
result = await saas_get_user_git_organizations(
|
||||
provider_tokens=azure_devops_provider_tokens,
|
||||
access_token=SecretStr('token'),
|
||||
user_id='user-1',
|
||||
)
|
||||
|
||||
assert isinstance(result, JSONResponse)
|
||||
assert result.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
'provider_tokens_fixture, mock_method, mock_return, expected_provider',
|
||||
[
|
||||
(
|
||||
'github_provider_tokens',
|
||||
'get_organizations_from_installations',
|
||||
['All-Hands-AI', 'OpenHands'],
|
||||
'github',
|
||||
),
|
||||
(
|
||||
'gitlab_provider_tokens',
|
||||
'get_user_groups',
|
||||
['my-team', 'open-source'],
|
||||
'gitlab',
|
||||
),
|
||||
(
|
||||
'bitbucket_provider_tokens',
|
||||
'get_installations',
|
||||
['my-workspace'],
|
||||
'bitbucket',
|
||||
),
|
||||
],
|
||||
ids=['github', 'gitlab', 'bitbucket'],
|
||||
)
|
||||
async def test_provider_routing_with_real_handler(
|
||||
provider_tokens_fixture,
|
||||
mock_method,
|
||||
mock_return,
|
||||
expected_provider,
|
||||
request,
|
||||
):
|
||||
"""Each provider routes to the correct service method and returns the expected JSON structure.
|
||||
|
||||
Uses a real ProviderHandler so the endpoint's if/elif routing and ProviderHandler's
|
||||
delegation are both exercised. Only the low-level git service call is mocked.
|
||||
"""
|
||||
from server.routes.user import saas_get_user_git_organizations
|
||||
|
||||
provider_tokens = request.getfixturevalue(provider_tokens_fixture)
|
||||
|
||||
with patch(
|
||||
'openhands.integrations.provider.ProviderHandler.get_service'
|
||||
) as mock_get_service:
|
||||
mock_service = mock_get_service.return_value
|
||||
setattr(mock_service, mock_method, AsyncMock(return_value=mock_return))
|
||||
|
||||
result = await saas_get_user_git_organizations(
|
||||
provider_tokens=provider_tokens,
|
||||
access_token=SecretStr('token'),
|
||||
user_id='user-1',
|
||||
)
|
||||
|
||||
assert result == {
|
||||
'provider': expected_provider,
|
||||
'organizations': mock_return,
|
||||
}
|
||||
192
frontend/__tests__/components/event-message.test.tsx
Normal file
192
frontend/__tests__/components/event-message.test.tsx
Normal file
@@ -0,0 +1,192 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { screen } from "@testing-library/react";
|
||||
import { renderWithProviders } from "test-utils";
|
||||
import { EventMessage } from "#/components/features/chat/event-message";
|
||||
|
||||
vi.mock("#/hooks/query/use-config", () => ({
|
||||
useConfig: () => ({
|
||||
data: { app_mode: "saas" },
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("#/hooks/query/use-feedback-exists", () => ({
|
||||
useFeedbackExists: (eventId: number | undefined) => ({
|
||||
data: { exists: false },
|
||||
isLoading: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("EventMessage", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should render LikertScale for finish action when it's the last message", () => {
|
||||
const finishEvent = {
|
||||
id: 123,
|
||||
source: "agent" as const,
|
||||
action: "finish" as const,
|
||||
args: {
|
||||
final_thought: "Task completed successfully",
|
||||
outputs: {},
|
||||
thought: "Task completed successfully",
|
||||
},
|
||||
message: "Task completed successfully",
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
renderWithProviders(
|
||||
<EventMessage
|
||||
event={finishEvent}
|
||||
hasObservationPair={false}
|
||||
isAwaitingUserConfirmation={false}
|
||||
isLastMessage={true}
|
||||
isInLast10Actions={true}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByLabelText("Rate 1 stars")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Rate 5 stars")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should render LikertScale for assistant message when it's the last message", () => {
|
||||
const assistantMessageEvent = {
|
||||
id: 456,
|
||||
source: "agent" as const,
|
||||
action: "message" as const,
|
||||
args: {
|
||||
thought: "I need more information to proceed.",
|
||||
image_urls: null,
|
||||
file_urls: [],
|
||||
wait_for_response: true,
|
||||
},
|
||||
message: "I need more information to proceed.",
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
renderWithProviders(
|
||||
<EventMessage
|
||||
event={assistantMessageEvent}
|
||||
hasObservationPair={false}
|
||||
isAwaitingUserConfirmation={false}
|
||||
isLastMessage={true}
|
||||
isInLast10Actions={true}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByLabelText("Rate 1 stars")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Rate 5 stars")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should render LikertScale for error observation when it's the last message", () => {
|
||||
const errorEvent = {
|
||||
id: 789,
|
||||
source: "user" as const,
|
||||
observation: "error" as const,
|
||||
content: "An error occurred",
|
||||
extras: {
|
||||
error_id: "test-error-123",
|
||||
},
|
||||
message: "An error occurred",
|
||||
timestamp: new Date().toISOString(),
|
||||
cause: 123,
|
||||
};
|
||||
|
||||
renderWithProviders(
|
||||
<EventMessage
|
||||
event={errorEvent}
|
||||
hasObservationPair={false}
|
||||
isAwaitingUserConfirmation={false}
|
||||
isLastMessage={true}
|
||||
isInLast10Actions={true}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByLabelText("Rate 1 stars")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Rate 5 stars")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should NOT render LikertScale when not the last message", () => {
|
||||
const finishEvent = {
|
||||
id: 101,
|
||||
source: "agent" as const,
|
||||
action: "finish" as const,
|
||||
args: {
|
||||
final_thought: "Task completed successfully",
|
||||
outputs: {},
|
||||
thought: "Task completed successfully",
|
||||
},
|
||||
message: "Task completed successfully",
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
renderWithProviders(
|
||||
<EventMessage
|
||||
event={finishEvent}
|
||||
hasObservationPair={false}
|
||||
isAwaitingUserConfirmation={false}
|
||||
isLastMessage={false}
|
||||
isInLast10Actions={false}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByLabelText("Rate 1 stars")).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText("Rate 5 stars")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should render LikertScale for error observation when in last 10 actions but not last message", () => {
|
||||
const errorEvent = {
|
||||
id: 999,
|
||||
source: "user" as const,
|
||||
observation: "error" as const,
|
||||
content: "An error occurred",
|
||||
extras: {
|
||||
error_id: "test-error-456",
|
||||
},
|
||||
message: "An error occurred",
|
||||
timestamp: new Date().toISOString(),
|
||||
cause: 123,
|
||||
};
|
||||
|
||||
renderWithProviders(
|
||||
<EventMessage
|
||||
event={errorEvent}
|
||||
hasObservationPair={false}
|
||||
isAwaitingUserConfirmation={false}
|
||||
isLastMessage={false}
|
||||
isInLast10Actions={true}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByLabelText("Rate 1 stars")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Rate 5 stars")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should NOT render LikertScale for error observation when not in last 10 actions", () => {
|
||||
const errorEvent = {
|
||||
id: 888,
|
||||
source: "user" as const,
|
||||
observation: "error" as const,
|
||||
content: "An error occurred",
|
||||
extras: {
|
||||
error_id: "test-error-789",
|
||||
},
|
||||
message: "An error occurred",
|
||||
timestamp: new Date().toISOString(),
|
||||
cause: 123,
|
||||
};
|
||||
|
||||
renderWithProviders(
|
||||
<EventMessage
|
||||
event={errorEvent}
|
||||
hasObservationPair={false}
|
||||
isAwaitingUserConfirmation={false}
|
||||
isLastMessage={false}
|
||||
isInLast10Actions={false}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByLabelText("Rate 1 stars")).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText("Rate 5 stars")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { LaunchMicroagentModal } from "#/components/features/chat/microagent/launch-microagent-modal";
|
||||
import { I18nKey } from "#/i18n/declaration";
|
||||
|
||||
vi.mock("react-router", async () => ({
|
||||
useParams: vi.fn().mockReturnValue({
|
||||
conversationId: "123",
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock the useHandleRuntimeActive hook
|
||||
vi.mock("#/hooks/use-handle-runtime-active", () => ({
|
||||
useHandleRuntimeActive: vi.fn().mockReturnValue({ runtimeActive: true }),
|
||||
}));
|
||||
|
||||
// Mock the useMicroagentPrompt hook
|
||||
vi.mock("#/hooks/query/use-microagent-prompt", () => ({
|
||||
useMicroagentPrompt: vi.fn().mockReturnValue({
|
||||
data: "Generated prompt",
|
||||
isLoading: false
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock the useGetMicroagents hook
|
||||
vi.mock("#/hooks/query/use-get-microagents", () => ({
|
||||
useGetMicroagents: vi.fn().mockReturnValue({
|
||||
data: ["file1", "file2"]
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock the useTranslation hook
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => {
|
||||
const translations: Record<string, string> = {
|
||||
[I18nKey.MICROAGENT$ADD_TO_MICROAGENT]: "Add to Microagent",
|
||||
[I18nKey.MICROAGENT$WHAT_TO_REMEMBER]: "What would you like your microagent to remember?",
|
||||
[I18nKey.MICROAGENT$WHERE_TO_PUT]: "Where should we put it?",
|
||||
[I18nKey.MICROAGENT$ADD_TRIGGERS]: "Add triggers for the microagent",
|
||||
[I18nKey.MICROAGENT$DESCRIBE_WHAT_TO_ADD]: "Describe what you want to add to the Microagent...",
|
||||
[I18nKey.MICROAGENT$SELECT_FILE_OR_CUSTOM]: "Select a microagent file or enter a custom value",
|
||||
[I18nKey.MICROAGENT$TYPE_TRIGGER_SPACE]: "Type a trigger and press Space to add it",
|
||||
[I18nKey.MICROAGENT$LOADING_PROMPT]: "Loading prompt...",
|
||||
[I18nKey.MICROAGENT$CANCEL]: "Cancel",
|
||||
[I18nKey.MICROAGENT$LAUNCH]: "Launch"
|
||||
};
|
||||
return translations[key] || key;
|
||||
},
|
||||
i18n: {
|
||||
changeLanguage: vi.fn(),
|
||||
},
|
||||
}),
|
||||
Trans: ({ i18nKey }: { i18nKey: string }) => i18nKey,
|
||||
}));
|
||||
|
||||
describe("LaunchMicroagentModal", () => {
|
||||
const onCloseMock = vi.fn();
|
||||
const onLaunchMock = vi.fn();
|
||||
const eventId = 12;
|
||||
const conversationId = "123";
|
||||
|
||||
const renderMicroagentModal = (
|
||||
{ isLoading }: { isLoading: boolean } = { isLoading: false },
|
||||
) =>
|
||||
render(
|
||||
<LaunchMicroagentModal
|
||||
onClose={onCloseMock}
|
||||
onLaunch={onLaunchMock}
|
||||
eventId={eventId}
|
||||
selectedRepo="some-repo"
|
||||
isLoading={isLoading}
|
||||
/>,
|
||||
{
|
||||
wrapper: ({ children }) => (
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
),
|
||||
},
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should render the launch microagent modal", () => {
|
||||
renderMicroagentModal();
|
||||
expect(screen.getByTestId("launch-microagent-modal")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should render the form fields", () => {
|
||||
renderMicroagentModal();
|
||||
|
||||
// inputs
|
||||
screen.getByTestId("query-input");
|
||||
screen.getByTestId("target-input");
|
||||
screen.getByTestId("trigger-input");
|
||||
|
||||
// action buttons
|
||||
screen.getByRole("button", { name: "Launch" });
|
||||
screen.getByRole("button", { name: "Cancel" });
|
||||
});
|
||||
|
||||
it("should call onClose when pressing the cancel button", async () => {
|
||||
renderMicroagentModal();
|
||||
|
||||
const cancelButton = screen.getByRole("button", { name: "Cancel" });
|
||||
await userEvent.click(cancelButton);
|
||||
expect(onCloseMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should display the prompt from the hook", async () => {
|
||||
renderMicroagentModal();
|
||||
|
||||
// Since we're mocking the hook, we just need to verify the UI shows the data
|
||||
const descriptionInput = screen.getByTestId("query-input");
|
||||
expect(descriptionInput).toHaveValue("Generated prompt");
|
||||
});
|
||||
|
||||
it("should display the list of microagent files from the hook", async () => {
|
||||
renderMicroagentModal();
|
||||
|
||||
// Since we're mocking the hook, we just need to verify the UI shows the data
|
||||
const targetInput = screen.getByTestId("target-input");
|
||||
expect(targetInput).toHaveValue("");
|
||||
|
||||
await userEvent.click(targetInput);
|
||||
|
||||
expect(screen.getByText("file1")).toBeInTheDocument();
|
||||
expect(screen.getByText("file2")).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByText("file1"));
|
||||
expect(targetInput).toHaveValue("file1");
|
||||
});
|
||||
|
||||
it("should call onLaunch with the form data", async () => {
|
||||
renderMicroagentModal();
|
||||
|
||||
const triggerInput = screen.getByTestId("trigger-input");
|
||||
await userEvent.type(triggerInput, "trigger1 ");
|
||||
await userEvent.type(triggerInput, "trigger2 ");
|
||||
|
||||
const targetInput = screen.getByTestId("target-input");
|
||||
await userEvent.click(targetInput);
|
||||
await userEvent.click(screen.getByText("file1"));
|
||||
|
||||
const launchButton = await screen.findByRole("button", { name: "Launch" });
|
||||
await userEvent.click(launchButton);
|
||||
|
||||
expect(onLaunchMock).toHaveBeenCalledWith("Generated prompt", "file1", [
|
||||
"trigger1",
|
||||
"trigger2",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should disable the launch button if isLoading is true", async () => {
|
||||
renderMicroagentModal({ isLoading: true });
|
||||
|
||||
const launchButton = screen.getByRole("button", { name: "Launch" });
|
||||
expect(launchButton).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -15,7 +15,7 @@ import { formatTimeDelta } from "#/utils/format-time-delta";
|
||||
import { ConversationCard } from "#/components/features/conversation-panel/conversation-card/conversation-card";
|
||||
import { clickOnEditButton } from "./utils";
|
||||
import { ConversationCardActions } from "#/components/features/conversation-panel/conversation-card/conversation-card-actions";
|
||||
import { V1SandboxStatus } from "#/api/sandbox-service/sandbox-service.types";
|
||||
import { ConversationStatus } from "#/types/conversation-status";
|
||||
|
||||
// We'll use the actual i18next implementation but override the translation function
|
||||
|
||||
@@ -434,63 +434,23 @@ describe("ConversationCard", () => {
|
||||
expect(screen.queryByTestId("ellipsis-button")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should render the llm model when provided", () => {
|
||||
renderWithProviders(
|
||||
<ConversationCard
|
||||
onDelete={onDelete}
|
||||
onChangeTitle={onChangeTitle}
|
||||
title="Conversation 1"
|
||||
selectedRepository={null}
|
||||
lastUpdatedAt="2021-10-01T12:00:00Z"
|
||||
llmModel="anthropic/claude-sonnet-4-20250514"
|
||||
/>,
|
||||
);
|
||||
|
||||
const model = screen.getByTestId("conversation-card-llm-model");
|
||||
expect(model).toBeInTheDocument();
|
||||
expect(model).toHaveTextContent("anthropic/claude-sonnet-4-20250514");
|
||||
expect(model).toHaveAttribute("title", "anthropic/claude-sonnet-4-20250514");
|
||||
expect(model.querySelector("svg")).toBeInTheDocument();
|
||||
|
||||
// Verify truncation structure: text is wrapped in a span with truncate class
|
||||
const textSpan = model.querySelector("span.truncate");
|
||||
expect(textSpan).toBeInTheDocument();
|
||||
expect(textSpan).toHaveTextContent("anthropic/claude-sonnet-4-20250514");
|
||||
});
|
||||
|
||||
it("should not render the llm model when not provided", () => {
|
||||
renderWithProviders(
|
||||
<ConversationCard
|
||||
onDelete={onDelete}
|
||||
onChangeTitle={onChangeTitle}
|
||||
title="Conversation 1"
|
||||
selectedRepository={null}
|
||||
lastUpdatedAt="2021-10-01T12:00:00Z"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId("conversation-card-llm-model"),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
const statusTable: [V1SandboxStatus, boolean][] = [
|
||||
const statusTable: [ConversationStatus, boolean][] = [
|
||||
["RUNNING", true],
|
||||
["STARTING", true],
|
||||
["STOPPED", false],
|
||||
["PAUSED", false],
|
||||
["MISSING", false],
|
||||
["ARCHIVED", false],
|
||||
["ERROR", false],
|
||||
];
|
||||
|
||||
it.each(statusTable)(
|
||||
"should toggle stop button visibility correctly for sandbox status",
|
||||
(sandboxStatus, shouldShow) => {
|
||||
"should toggle stop button visibility correctly for status",
|
||||
(status, shouldShow) => {
|
||||
renderWithProviders(
|
||||
<ConversationCardActions
|
||||
contextMenuOpen={true}
|
||||
onContextMenuToggle={vi.fn()}
|
||||
onStop={vi.fn()}
|
||||
sandboxStatus={sandboxStatus}
|
||||
conversationStatus={status}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
||||
@@ -5,10 +5,8 @@ import { createRoutesStub } from "react-router";
|
||||
import React from "react";
|
||||
import { renderWithProviders } from "test-utils";
|
||||
import { ConversationPanel } from "#/components/features/conversation-panel/conversation-panel";
|
||||
import V1ConversationService from "#/api/conversation-service/v1-conversation-service.api";
|
||||
import { V1AppConversation, V1ConversationExecutionStatus } from "#/api/conversation-service/v1-conversation-service.types";
|
||||
import { V1SandboxStatus } from "#/api/sandbox-service/sandbox-service.types";
|
||||
import type { Provider } from "#/types/settings";
|
||||
import ConversationService from "#/api/conversation-service/conversation-service.api";
|
||||
import { Conversation } from "#/api/open-hands.types";
|
||||
|
||||
// Mock the unified stop conversation hook
|
||||
const mockStopConversationMutate = vi.fn();
|
||||
@@ -18,29 +16,6 @@ vi.mock("#/hooks/mutation/use-unified-stop-conversation", () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
|
||||
// Helper to create complete V1AppConversation mock data
|
||||
const createMockConversation = (overrides: Partial<V1AppConversation> = {}): V1AppConversation => ({
|
||||
id: "test-id",
|
||||
title: "Test Conversation",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
updated_at: "2021-10-01T12:00:00Z",
|
||||
created_at: "2021-10-01T12:00:00Z",
|
||||
sandbox_status: "STOPPED" as V1SandboxStatus,
|
||||
execution_status: "FINISHED" as V1ConversationExecutionStatus,
|
||||
conversation_url: null,
|
||||
created_by_user_id: "user1",
|
||||
metrics: null,
|
||||
llm_model: null,
|
||||
sandbox_id: "sandbox1",
|
||||
trigger: null,
|
||||
pr_number: [],
|
||||
session_api_key: null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
// Mock toast handlers to prevent unhandled rejection errors
|
||||
vi.mock("#/utils/custom-toast-handlers", () => ({
|
||||
displaySuccessToast: vi.fn(),
|
||||
@@ -74,18 +49,54 @@ describe("ConversationPanel", () => {
|
||||
}));
|
||||
});
|
||||
|
||||
const mockConversations: V1AppConversation[] = [
|
||||
createMockConversation({ id: "1", title: "Conversation 1", updated_at: "2021-10-01T12:00:00Z", sandbox_id: "sandbox1" }),
|
||||
createMockConversation({ id: "2", title: "Conversation 2", updated_at: "2021-10-02T12:00:00Z", sandbox_id: "sandbox2" }),
|
||||
createMockConversation({ id: "3", title: "Conversation 3", updated_at: "2021-10-03T12:00:00Z", sandbox_id: "sandbox3" }),
|
||||
const mockConversations: Conversation[] = [
|
||||
{
|
||||
conversation_id: "1",
|
||||
title: "Conversation 1",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-01T12:00:00Z",
|
||||
created_at: "2021-10-01T12:00:00Z",
|
||||
status: "STOPPED" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
{
|
||||
conversation_id: "2",
|
||||
title: "Conversation 2",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-02T12:00:00Z",
|
||||
created_at: "2021-10-02T12:00:00Z",
|
||||
status: "STOPPED" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
{
|
||||
conversation_id: "3",
|
||||
title: "Conversation 3",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-03T12:00:00Z",
|
||||
created_at: "2021-10-03T12:00:00Z",
|
||||
status: "STOPPED" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockStopConversationMutate.mockClear();
|
||||
// Setup default mock for V1 searchConversations
|
||||
vi.spyOn(V1ConversationService, "searchConversations").mockResolvedValue({
|
||||
items: [...mockConversations],
|
||||
// Setup default mock for getUserConversations
|
||||
vi.spyOn(ConversationService, "getUserConversations").mockResolvedValue({
|
||||
results: [...mockConversations],
|
||||
next_page_id: null,
|
||||
});
|
||||
});
|
||||
@@ -100,12 +111,12 @@ describe("ConversationPanel", () => {
|
||||
});
|
||||
|
||||
it("should display an empty state when there are no conversations", async () => {
|
||||
const searchConversationsSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"searchConversations",
|
||||
const getUserConversationsSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"getUserConversations",
|
||||
);
|
||||
searchConversationsSpy.mockResolvedValue({
|
||||
items: [],
|
||||
getUserConversationsSpy.mockResolvedValue({
|
||||
results: [],
|
||||
next_page_id: null,
|
||||
});
|
||||
|
||||
@@ -116,11 +127,11 @@ describe("ConversationPanel", () => {
|
||||
});
|
||||
|
||||
it("should handle an error when fetching conversations", async () => {
|
||||
const searchConversationsSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"searchConversations",
|
||||
const getUserConversationsSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"getUserConversations",
|
||||
);
|
||||
searchConversationsSpy.mockRejectedValue(
|
||||
getUserConversationsSpy.mockRejectedValue(
|
||||
new Error("Failed to fetch conversations"),
|
||||
);
|
||||
|
||||
@@ -166,27 +177,63 @@ describe("ConversationPanel", () => {
|
||||
|
||||
it("should delete a conversation", async () => {
|
||||
const user = userEvent.setup();
|
||||
const mockData: V1AppConversation[] = [
|
||||
createMockConversation({ id: "1", title: "Conversation 1", updated_at: "2021-10-01T12:00:00Z", sandbox_id: "sandbox1" }),
|
||||
createMockConversation({ id: "2", title: "Conversation 2", updated_at: "2021-10-02T12:00:00Z", sandbox_id: "sandbox2" }),
|
||||
createMockConversation({ id: "3", title: "Conversation 3", updated_at: "2021-10-03T12:00:00Z", sandbox_id: "sandbox3" }),
|
||||
const mockData: Conversation[] = [
|
||||
{
|
||||
conversation_id: "1",
|
||||
title: "Conversation 1",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-01T12:00:00Z",
|
||||
created_at: "2021-10-01T12:00:00Z",
|
||||
status: "STOPPED" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
{
|
||||
conversation_id: "2",
|
||||
title: "Conversation 2",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-02T12:00:00Z",
|
||||
created_at: "2021-10-02T12:00:00Z",
|
||||
status: "STOPPED" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
{
|
||||
conversation_id: "3",
|
||||
title: "Conversation 3",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-03T12:00:00Z",
|
||||
created_at: "2021-10-03T12:00:00Z",
|
||||
status: "STOPPED" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
];
|
||||
|
||||
const searchConversationsSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"searchConversations",
|
||||
const getUserConversationsSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"getUserConversations",
|
||||
);
|
||||
searchConversationsSpy.mockImplementation(async () => ({
|
||||
items: mockData,
|
||||
getUserConversationsSpy.mockImplementation(async () => ({
|
||||
results: mockData,
|
||||
next_page_id: null,
|
||||
}));
|
||||
|
||||
const deleteConversationSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"deleteConversation",
|
||||
const deleteUserConversationSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"deleteUserConversation",
|
||||
);
|
||||
deleteConversationSpy.mockImplementation(async (id: string) => {
|
||||
const index = mockData.findIndex((conv) => conv.id === id);
|
||||
deleteUserConversationSpy.mockImplementation(async (id: string) => {
|
||||
const index = mockData.findIndex((conv) => conv.conversation_id === id);
|
||||
if (index !== -1) {
|
||||
mockData.splice(index, 1);
|
||||
}
|
||||
@@ -195,7 +242,6 @@ describe("ConversationPanel", () => {
|
||||
renderConversationPanel();
|
||||
|
||||
const cards = await screen.findAllByTestId("conversation-card");
|
||||
// Initially shows 3 conversations (no filtering)
|
||||
expect(cards).toHaveLength(3);
|
||||
|
||||
const ellipsisButton = within(cards[0]).getByTestId("ellipsis-button");
|
||||
@@ -209,10 +255,15 @@ describe("ConversationPanel", () => {
|
||||
const confirmButton = screen.getByRole("button", { name: /confirm/i });
|
||||
await user.click(confirmButton);
|
||||
|
||||
// Verify modal is closed after confirmation
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /confirm/i }),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// Wait for the cards to update
|
||||
await waitFor(() => {
|
||||
const updatedCards = screen.getAllByTestId("conversation-card");
|
||||
expect(updatedCards).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
it("should call onClose after clicking a card", async () => {
|
||||
@@ -228,12 +279,12 @@ describe("ConversationPanel", () => {
|
||||
|
||||
it("should refetch data on rerenders", async () => {
|
||||
const user = userEvent.setup();
|
||||
const searchConversationsSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"searchConversations",
|
||||
const getUserConversationsSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"getUserConversations",
|
||||
);
|
||||
searchConversationsSpy.mockResolvedValue({
|
||||
items: [...mockConversations],
|
||||
getUserConversationsSpy.mockResolvedValue({
|
||||
results: [...mockConversations],
|
||||
next_page_id: null,
|
||||
});
|
||||
|
||||
@@ -278,18 +329,54 @@ describe("ConversationPanel", () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
// Create mock data with a RUNNING conversation
|
||||
const mockRunningConversations: V1AppConversation[] = [
|
||||
createMockConversation({ id: "1", title: "Running Conversation", sandbox_status: "RUNNING", execution_status: "RUNNING", sandbox_id: "sandbox1" }),
|
||||
createMockConversation({ id: "2", title: "Starting Conversation", sandbox_status: "STARTING", execution_status: "RUNNING", sandbox_id: "sandbox2" }),
|
||||
createMockConversation({ id: "3", title: "Stopped Conversation", sandbox_status: "STOPPED", execution_status: "FINISHED", sandbox_id: "sandbox3" }),
|
||||
const mockRunningConversations: Conversation[] = [
|
||||
{
|
||||
conversation_id: "1",
|
||||
title: "Running Conversation",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-01T12:00:00Z",
|
||||
created_at: "2021-10-01T12:00:00Z",
|
||||
status: "RUNNING" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
{
|
||||
conversation_id: "2",
|
||||
title: "Starting Conversation",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-02T12:00:00Z",
|
||||
created_at: "2021-10-02T12:00:00Z",
|
||||
status: "STARTING" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
{
|
||||
conversation_id: "3",
|
||||
title: "Stopped Conversation",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-03T12:00:00Z",
|
||||
created_at: "2021-10-03T12:00:00Z",
|
||||
status: "STOPPED" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
];
|
||||
|
||||
const searchConversationsSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"searchConversations",
|
||||
const getUserConversationsSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"getUserConversations",
|
||||
);
|
||||
searchConversationsSpy.mockResolvedValue({
|
||||
items: mockRunningConversations,
|
||||
getUserConversationsSpy.mockResolvedValue({
|
||||
results: mockRunningConversations,
|
||||
next_page_id: null,
|
||||
});
|
||||
|
||||
@@ -325,26 +412,48 @@ describe("ConversationPanel", () => {
|
||||
it("should stop a conversation", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const mockData: V1AppConversation[] = [
|
||||
createMockConversation({ id: "1", title: "Conversation 1", sandbox_status: "RUNNING", execution_status: "RUNNING", sandbox_id: "sandbox1" }),
|
||||
createMockConversation({ id: "2", title: "Conversation 2", sandbox_status: "STOPPED", execution_status: "FINISHED", sandbox_id: "sandbox2" }),
|
||||
createMockConversation({ id: "3", title: "Conversation 3", sandbox_status: "STOPPED", execution_status: "FINISHED", sandbox_id: "sandbox3" }),
|
||||
const mockData: Conversation[] = [
|
||||
{
|
||||
conversation_id: "1",
|
||||
title: "Running Conversation",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-01T12:00:00Z",
|
||||
created_at: "2021-10-01T12:00:00Z",
|
||||
status: "RUNNING" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
{
|
||||
conversation_id: "2",
|
||||
title: "Starting Conversation",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-02T12:00:00Z",
|
||||
created_at: "2021-10-02T12:00:00Z",
|
||||
status: "STARTING" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
];
|
||||
|
||||
const searchConversationsSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"searchConversations",
|
||||
const getUserConversationsSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"getUserConversations",
|
||||
);
|
||||
searchConversationsSpy.mockImplementation(async () => ({
|
||||
items: mockData,
|
||||
getUserConversationsSpy.mockImplementation(async () => ({
|
||||
results: mockData,
|
||||
next_page_id: null,
|
||||
}));
|
||||
|
||||
renderConversationPanel();
|
||||
|
||||
const cards = await screen.findAllByTestId("conversation-card");
|
||||
// Component shows all 3 conversations (no filtering by status)
|
||||
expect(cards).toHaveLength(3);
|
||||
expect(cards).toHaveLength(2);
|
||||
|
||||
// Click ellipsis on the first card (RUNNING status)
|
||||
const ellipsisButton = within(cards[0]).getByTestId("ellipsis-button");
|
||||
@@ -366,7 +475,7 @@ describe("ConversationPanel", () => {
|
||||
// Verify the mutation was called
|
||||
expect(mockStopConversationMutate).toHaveBeenCalledWith({
|
||||
conversationId: "1",
|
||||
version: "V1",
|
||||
version: undefined,
|
||||
});
|
||||
expect(mockStopConversationMutate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
@@ -374,18 +483,54 @@ describe("ConversationPanel", () => {
|
||||
it("should only show stop button for STARTING or RUNNING conversations", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const mockMixedStatusConversations: V1AppConversation[] = [
|
||||
createMockConversation({ id: "1", title: "Running Conversation", sandbox_status: "RUNNING", execution_status: "RUNNING", sandbox_id: "sandbox1" }),
|
||||
createMockConversation({ id: "2", title: "Starting Conversation", sandbox_status: "STARTING", execution_status: "RUNNING", sandbox_id: "sandbox2" }),
|
||||
createMockConversation({ id: "3", title: "Stopped Conversation", sandbox_status: "STOPPED", execution_status: "FINISHED", sandbox_id: "sandbox3" }),
|
||||
const mockMixedStatusConversations: Conversation[] = [
|
||||
{
|
||||
conversation_id: "1",
|
||||
title: "Running Conversation",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-01T12:00:00Z",
|
||||
created_at: "2021-10-01T12:00:00Z",
|
||||
status: "RUNNING" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
{
|
||||
conversation_id: "2",
|
||||
title: "Starting Conversation",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-02T12:00:00Z",
|
||||
created_at: "2021-10-02T12:00:00Z",
|
||||
status: "STARTING" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
{
|
||||
conversation_id: "3",
|
||||
title: "Stopped Conversation",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-03T12:00:00Z",
|
||||
created_at: "2021-10-03T12:00:00Z",
|
||||
status: "STOPPED" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
];
|
||||
|
||||
const searchConversationsSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"searchConversations",
|
||||
const getUserConversationsSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"getUserConversations",
|
||||
);
|
||||
searchConversationsSpy.mockResolvedValue({
|
||||
items: mockMixedStatusConversations,
|
||||
getUserConversationsSpy.mockResolvedValue({
|
||||
results: mockMixedStatusConversations,
|
||||
next_page_id: null,
|
||||
});
|
||||
|
||||
@@ -489,12 +634,12 @@ describe("ConversationPanel", () => {
|
||||
it("should successfully update conversation title", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
// Mock the updateConversationTitle API call
|
||||
const updateConversationTitleSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"updateConversationTitle",
|
||||
// Mock the updateConversation API call
|
||||
const updateConversationSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"updateConversation",
|
||||
);
|
||||
updateConversationTitleSpy.mockResolvedValue(createMockConversation({ id: "1", title: "Updated Title" }));
|
||||
updateConversationSpy.mockResolvedValue(true);
|
||||
|
||||
renderConversationPanel();
|
||||
|
||||
@@ -516,17 +661,19 @@ describe("ConversationPanel", () => {
|
||||
await user.tab();
|
||||
|
||||
// Verify API call was made with correct parameters
|
||||
expect(updateConversationTitleSpy).toHaveBeenCalledWith("1", "Updated Title");
|
||||
expect(updateConversationSpy).toHaveBeenCalledWith("1", {
|
||||
title: "Updated Title",
|
||||
});
|
||||
});
|
||||
|
||||
it("should save title when Enter key is pressed", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const updateConversationTitleSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"updateConversationTitle",
|
||||
const updateConversationSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"updateConversation",
|
||||
);
|
||||
updateConversationTitleSpy.mockResolvedValue(createMockConversation({ id: "1", title: "Updated Title" }));
|
||||
updateConversationSpy.mockResolvedValue(true);
|
||||
|
||||
renderConversationPanel();
|
||||
|
||||
@@ -546,17 +693,19 @@ describe("ConversationPanel", () => {
|
||||
await user.keyboard("{Enter}");
|
||||
|
||||
// Verify API call was made
|
||||
expect(updateConversationTitleSpy).toHaveBeenCalledWith("1", "Title Updated via Enter");
|
||||
expect(updateConversationSpy).toHaveBeenCalledWith("1", {
|
||||
title: "Title Updated via Enter",
|
||||
});
|
||||
});
|
||||
|
||||
it("should trim whitespace from title", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const updateConversationTitleSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"updateConversationTitle",
|
||||
const updateConversationSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"updateConversation",
|
||||
);
|
||||
updateConversationTitleSpy.mockResolvedValue(createMockConversation({ id: "1", title: "Updated Title" }));
|
||||
updateConversationSpy.mockResolvedValue(true);
|
||||
|
||||
renderConversationPanel();
|
||||
|
||||
@@ -576,17 +725,19 @@ describe("ConversationPanel", () => {
|
||||
await user.tab();
|
||||
|
||||
// Verify API call was made with trimmed title
|
||||
expect(updateConversationTitleSpy).toHaveBeenCalledWith("1", "Trimmed Title");
|
||||
expect(updateConversationSpy).toHaveBeenCalledWith("1", {
|
||||
title: "Trimmed Title",
|
||||
});
|
||||
});
|
||||
|
||||
it("should revert to original title when empty", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const updateConversationTitleSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"updateConversationTitle",
|
||||
const updateConversationSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"updateConversation",
|
||||
);
|
||||
updateConversationTitleSpy.mockResolvedValue(createMockConversation({ id: "1", title: "Updated Title" }));
|
||||
updateConversationSpy.mockResolvedValue(true);
|
||||
|
||||
renderConversationPanel();
|
||||
|
||||
@@ -605,18 +756,17 @@ describe("ConversationPanel", () => {
|
||||
await user.tab();
|
||||
|
||||
// Verify API was not called
|
||||
expect(updateConversationTitleSpy).not.toHaveBeenCalled();
|
||||
expect(updateConversationSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle API error when updating title", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const updateConversationTitleSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"updateConversationTitle",
|
||||
const updateConversationSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"updateConversation",
|
||||
);
|
||||
updateConversationTitleSpy.mockRejectedValue(new Error("API Error"));
|
||||
// Provide return type for mock
|
||||
updateConversationSpy.mockRejectedValue(new Error("API Error"));
|
||||
|
||||
renderConversationPanel();
|
||||
|
||||
@@ -636,11 +786,13 @@ describe("ConversationPanel", () => {
|
||||
await user.tab();
|
||||
|
||||
// Verify API call was made
|
||||
expect(updateConversationTitleSpy).toHaveBeenCalledWith("1", "Failed Update");
|
||||
expect(updateConversationSpy).toHaveBeenCalledWith("1", {
|
||||
title: "Failed Update",
|
||||
});
|
||||
|
||||
// Wait for error handling
|
||||
await waitFor(() => {
|
||||
expect(updateConversationTitleSpy).toHaveBeenCalled();
|
||||
expect(updateConversationSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -676,11 +828,11 @@ describe("ConversationPanel", () => {
|
||||
it("should not call API when title is unchanged", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const updateConversationTitleSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"updateConversationTitle",
|
||||
const updateConversationSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"updateConversation",
|
||||
);
|
||||
updateConversationTitleSpy.mockResolvedValue(createMockConversation({ id: "1", title: "Updated Title" }));
|
||||
updateConversationSpy.mockResolvedValue(true);
|
||||
|
||||
renderConversationPanel();
|
||||
|
||||
@@ -697,7 +849,7 @@ describe("ConversationPanel", () => {
|
||||
await user.tab();
|
||||
|
||||
// Verify API was NOT called with the same title (since handleConversationTitleChange will always be called)
|
||||
expect(updateConversationTitleSpy).not.toHaveBeenCalledWith("1", {
|
||||
expect(updateConversationSpy).not.toHaveBeenCalledWith("1", {
|
||||
title: "Conversation 1",
|
||||
});
|
||||
});
|
||||
@@ -705,11 +857,11 @@ describe("ConversationPanel", () => {
|
||||
it("should handle special characters in title", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const updateConversationTitleSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"updateConversationTitle",
|
||||
const updateConversationSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"updateConversation",
|
||||
);
|
||||
updateConversationTitleSpy.mockResolvedValue(createMockConversation({ id: "1", title: "Updated Title" }));
|
||||
updateConversationSpy.mockResolvedValue(true);
|
||||
|
||||
renderConversationPanel();
|
||||
|
||||
@@ -729,7 +881,9 @@ describe("ConversationPanel", () => {
|
||||
await user.tab();
|
||||
|
||||
// Verify API call was made with special characters
|
||||
expect(updateConversationTitleSpy).toHaveBeenCalledWith("1", "Special @#$%^&*()_+ Characters");
|
||||
expect(updateConversationSpy).toHaveBeenCalledWith("1", {
|
||||
title: "Special @#$%^&*()_+ Characters",
|
||||
});
|
||||
});
|
||||
|
||||
it("should close delete modal when clicking backdrop", async () => {
|
||||
@@ -764,14 +918,24 @@ describe("ConversationPanel", () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
// Create mock data with a RUNNING conversation
|
||||
const mockRunningConversations: V1AppConversation[] = [
|
||||
createMockConversation({ id: "1", title: "Running Conversation", sandbox_status: "RUNNING", execution_status: "RUNNING", sandbox_id: "sandbox1" }),
|
||||
createMockConversation({ id: "2", title: "Starting Conversation", sandbox_status: "STARTING", execution_status: "RUNNING", sandbox_id: "sandbox2" }),
|
||||
createMockConversation({ id: "3", title: "Stopped Conversation", sandbox_status: "STOPPED", execution_status: "FINISHED", sandbox_id: "sandbox3" }),
|
||||
const mockRunningConversations: Conversation[] = [
|
||||
{
|
||||
conversation_id: "1",
|
||||
title: "Running Conversation",
|
||||
selected_repository: null,
|
||||
git_provider: null,
|
||||
selected_branch: null,
|
||||
last_updated_at: "2021-10-01T12:00:00Z",
|
||||
created_at: "2021-10-01T12:00:00Z",
|
||||
status: "RUNNING" as const,
|
||||
runtime_status: null,
|
||||
url: null,
|
||||
session_api_key: null,
|
||||
},
|
||||
];
|
||||
|
||||
vi.spyOn(V1ConversationService, "searchConversations").mockResolvedValue({
|
||||
items: mockRunningConversations,
|
||||
vi.spyOn(ConversationService, "getUserConversations").mockResolvedValue({
|
||||
results: mockRunningConversations,
|
||||
next_page_id: null,
|
||||
});
|
||||
|
||||
|
||||
@@ -296,46 +296,6 @@ describe("ConversationName", () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should render the llm model when available", () => {
|
||||
useActiveConversationMock.mockReturnValue({
|
||||
data: {
|
||||
conversation_id: "test-conversation-id",
|
||||
title: "Test Conversation",
|
||||
status: "RUNNING",
|
||||
llm_model: "openai/gpt-4o",
|
||||
} as Conversation,
|
||||
});
|
||||
|
||||
renderConversationNameWithRouter();
|
||||
|
||||
const model = screen.getByTestId("conversation-name-llm-model");
|
||||
expect(model).toBeInTheDocument();
|
||||
expect(model).toHaveTextContent("openai/gpt-4o");
|
||||
expect(model).toHaveAttribute("title", "openai/gpt-4o");
|
||||
expect(model.querySelector("svg")).toBeInTheDocument();
|
||||
|
||||
// Verify truncation structure: text is wrapped in a span with truncate class
|
||||
const textSpan = model.querySelector("span.truncate");
|
||||
expect(textSpan).toBeInTheDocument();
|
||||
expect(textSpan).toHaveTextContent("openai/gpt-4o");
|
||||
});
|
||||
|
||||
it("should not render the llm model when not available", () => {
|
||||
useActiveConversationMock.mockReturnValue({
|
||||
data: {
|
||||
conversation_id: "test-conversation-id",
|
||||
title: "Test Conversation",
|
||||
status: "RUNNING",
|
||||
},
|
||||
});
|
||||
|
||||
renderConversationNameWithRouter();
|
||||
|
||||
expect(
|
||||
screen.queryByTestId("conversation-name-llm-model"),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should focus input when entering edit mode", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderConversationNameWithRouter();
|
||||
|
||||
@@ -2,7 +2,6 @@ import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { ConversationTabsContextMenu } from "#/components/features/conversation/conversation-tabs/conversation-tabs-context-menu";
|
||||
import { useConversationStore } from "#/stores/conversation-store";
|
||||
|
||||
const CONVERSATION_ID = "conv-abc123";
|
||||
|
||||
@@ -22,11 +21,6 @@ describe("ConversationTabsContextMenu", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
mockHasTaskList = false;
|
||||
useConversationStore.setState({
|
||||
selectedTab: "editor",
|
||||
isRightPanelShown: true,
|
||||
hasRightPanelToggled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("should render nothing when isOpen is false", () => {
|
||||
@@ -75,33 +69,6 @@ describe("ConversationTabsContextMenu", () => {
|
||||
expect(storedState.unpinnedTabs).not.toContain("terminal");
|
||||
});
|
||||
|
||||
it("should close the right panel when unpinning the currently active tab", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<ConversationTabsContextMenu isOpen={true} onClose={vi.fn()} />);
|
||||
|
||||
await user.click(screen.getByText("COMMON$CHANGES"));
|
||||
|
||||
const storeState = useConversationStore.getState();
|
||||
expect(storeState.hasRightPanelToggled).toBe(false);
|
||||
|
||||
const storedState = JSON.parse(
|
||||
localStorage.getItem(`conversation-state-${CONVERSATION_ID}`)!,
|
||||
);
|
||||
expect(storedState.rightPanelShown).toBe(false);
|
||||
});
|
||||
|
||||
it("should not close the right panel when unpinning a non-active tab", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<ConversationTabsContextMenu isOpen={true} onClose={vi.fn()} />);
|
||||
|
||||
await user.click(screen.getByText("COMMON$TERMINAL"));
|
||||
|
||||
const storeState = useConversationStore.getState();
|
||||
expect(storeState.hasRightPanelToggled).toBe(true);
|
||||
});
|
||||
|
||||
describe("with tasklist", () => {
|
||||
beforeEach(() => {
|
||||
mockHasTaskList = true;
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
import { screen } from "@testing-library/react";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { renderWithProviders } from "test-utils";
|
||||
import { BrowserRouter } from "react-router";
|
||||
import { RecentConversation } from "#/components/features/home/recent-conversations/recent-conversation";
|
||||
import type { V1AppConversation } from "#/api/conversation-service/v1-conversation-service.types";
|
||||
|
||||
vi.mock("react-i18next", async () => {
|
||||
const actual = await vi.importActual("react-i18next");
|
||||
return {
|
||||
...actual,
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => {
|
||||
const translations: Record<string, string> = {
|
||||
CONVERSATION$AGO: "ago",
|
||||
COMMON$NO_REPOSITORY: "No repository",
|
||||
};
|
||||
return translations[key] || key;
|
||||
},
|
||||
i18n: {
|
||||
changeLanguage: () => new Promise(() => {}),
|
||||
},
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const baseConversation: V1AppConversation = {
|
||||
id: "test-id",
|
||||
title: "Test Conversation",
|
||||
sandbox_status: "RUNNING",
|
||||
execution_status: "RUNNING",
|
||||
updated_at: "2021-10-01T12:00:00Z",
|
||||
created_at: "2021-10-01T12:00:00Z",
|
||||
selected_repository: null,
|
||||
selected_branch: null,
|
||||
git_provider: null,
|
||||
conversation_url: null,
|
||||
created_by_user_id: "user1",
|
||||
metrics: null,
|
||||
llm_model: null,
|
||||
sandbox_id: "sandbox1",
|
||||
trigger: null,
|
||||
pr_number: [],
|
||||
session_api_key: null,
|
||||
};
|
||||
|
||||
const renderRecentConversation = (conversation: V1AppConversation) =>
|
||||
renderWithProviders(
|
||||
<BrowserRouter>
|
||||
<RecentConversation conversation={conversation} />
|
||||
</BrowserRouter>,
|
||||
);
|
||||
|
||||
describe("RecentConversation - llm_model", () => {
|
||||
it("should render the llm model when provided", () => {
|
||||
renderRecentConversation({
|
||||
...baseConversation,
|
||||
llm_model: "anthropic/claude-sonnet-4-20250514",
|
||||
});
|
||||
|
||||
const model = screen.getByTestId("recent-conversation-llm-model");
|
||||
expect(model).toBeInTheDocument();
|
||||
expect(model).toHaveTextContent("anthropic/claude-sonnet-4-20250514");
|
||||
expect(model).toHaveAttribute(
|
||||
"title",
|
||||
"anthropic/claude-sonnet-4-20250514",
|
||||
);
|
||||
expect(model.querySelector("svg")).toBeInTheDocument();
|
||||
|
||||
// Verify truncation structure: text is wrapped in a span with truncate class
|
||||
const textSpan = model.querySelector("span.truncate");
|
||||
expect(textSpan).toBeInTheDocument();
|
||||
expect(textSpan).toHaveTextContent("anthropic/claude-sonnet-4-20250514");
|
||||
});
|
||||
|
||||
it("should not render the llm model when not provided", () => {
|
||||
renderRecentConversation(baseConversation);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId("recent-conversation-llm-model"),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { describe, it, expect, vi } from "vitest";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createRoutesStub } from "react-router";
|
||||
import { RecentConversations } from "#/components/features/home/recent-conversations/recent-conversations";
|
||||
import V1ConversationService from "#/api/conversation-service/v1-conversation-service.api";
|
||||
import ConversationService from "#/api/conversation-service/conversation-service.api";
|
||||
|
||||
const renderRecentConversations = () => {
|
||||
const RouterStub = createRoutesStub([
|
||||
@@ -29,13 +29,13 @@ const renderRecentConversations = () => {
|
||||
};
|
||||
|
||||
describe("RecentConversations", () => {
|
||||
const searchConversationsSpy = vi.spyOn(
|
||||
V1ConversationService,
|
||||
"searchConversations",
|
||||
const getUserConversationsSpy = vi.spyOn(
|
||||
ConversationService,
|
||||
"getUserConversations",
|
||||
);
|
||||
|
||||
it("should not show empty state when there is an error", async () => {
|
||||
searchConversationsSpy.mockRejectedValue(
|
||||
getUserConversationsSpy.mockRejectedValue(
|
||||
new Error("Failed to fetch conversations"),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { MarkdownRenderer } from "#/components/features/markdown/markdown-renderer";
|
||||
|
||||
const GFM_TABLE = [
|
||||
"| Feature | OpenAI Codex | Claude Code |",
|
||||
"|---------|--------------|-------------|",
|
||||
"| CLI | ✅ | ✅ |",
|
||||
"| Mobile | ❌ | ✅ |",
|
||||
].join("\n");
|
||||
|
||||
describe("table (markdown)", () => {
|
||||
it("should render a GFM pipe table as a <table> element", () => {
|
||||
render(<MarkdownRenderer>{GFM_TABLE}</MarkdownRenderer>);
|
||||
|
||||
const table = screen.getByRole("table");
|
||||
expect(table).toBeInTheDocument();
|
||||
// border-collapse + border is what makes columns visually separate
|
||||
expect(table).toHaveClass("border-collapse");
|
||||
expect(table).toHaveClass("border");
|
||||
});
|
||||
|
||||
it("should wrap the table in a horizontally scrollable container", () => {
|
||||
const { container } = render(
|
||||
<MarkdownRenderer>{GFM_TABLE}</MarkdownRenderer>,
|
||||
);
|
||||
|
||||
// Wide tables must not break chat layout — wrapper enables overflow
|
||||
const wrapper = container.querySelector(".overflow-x-auto");
|
||||
expect(wrapper).not.toBeNull();
|
||||
expect(wrapper?.querySelector("table")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("should render header cells as styled <th> elements", () => {
|
||||
render(<MarkdownRenderer>{GFM_TABLE}</MarkdownRenderer>);
|
||||
|
||||
const headers = screen.getAllByRole("columnheader");
|
||||
expect(headers).toHaveLength(3);
|
||||
expect(headers[0]).toHaveTextContent("Feature");
|
||||
expect(headers[1]).toHaveTextContent("OpenAI Codex");
|
||||
expect(headers[2]).toHaveTextContent("Claude Code");
|
||||
// Padding + border is what was missing before the fix
|
||||
headers.forEach((h) => {
|
||||
expect(h).toHaveClass("border");
|
||||
expect(h).toHaveClass("px-3");
|
||||
expect(h).toHaveClass("py-2");
|
||||
});
|
||||
});
|
||||
|
||||
it("should render body cells as styled <td> elements", () => {
|
||||
render(<MarkdownRenderer>{GFM_TABLE}</MarkdownRenderer>);
|
||||
|
||||
const cells = screen.getAllByRole("cell");
|
||||
expect(cells).toHaveLength(6);
|
||||
expect(cells[0]).toHaveTextContent("CLI");
|
||||
expect(cells[3]).toHaveTextContent("Mobile");
|
||||
cells.forEach((c) => {
|
||||
expect(c).toHaveClass("border");
|
||||
expect(c).toHaveClass("px-3");
|
||||
expect(c).toHaveClass("py-2");
|
||||
});
|
||||
});
|
||||
|
||||
it("should not render table markdown as plain paragraph text", () => {
|
||||
// Regression guard: before the fix, missing component overrides made the
|
||||
// table render with no visible borders/padding so columns looked like
|
||||
// space-separated text. Ensure a real <table> exists now.
|
||||
const { container } = render(
|
||||
<MarkdownRenderer>{GFM_TABLE}</MarkdownRenderer>,
|
||||
);
|
||||
|
||||
expect(container.querySelectorAll("table")).toHaveLength(1);
|
||||
expect(container.querySelectorAll("th")).toHaveLength(3);
|
||||
expect(container.querySelectorAll("td")).toHaveLength(6);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,113 +0,0 @@
|
||||
import { screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { renderWithProviders } from "test-utils";
|
||||
import {
|
||||
ClaimButton,
|
||||
getButtonState,
|
||||
} from "#/components/features/org/claim-button";
|
||||
import type { GitOrg } from "#/types/org";
|
||||
|
||||
const createOrg = (overrides: Partial<GitOrg> = {}): GitOrg => ({
|
||||
id: "1",
|
||||
claimId: null,
|
||||
provider: "GitHub",
|
||||
name: "TestOrg",
|
||||
status: "unclaimed",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("getButtonState", () => {
|
||||
it("returns 'claiming' during claiming transition regardless of hover", () => {
|
||||
expect(getButtonState("claiming", false)).toBe("claiming");
|
||||
expect(getButtonState("claiming", true)).toBe("claiming");
|
||||
});
|
||||
|
||||
it("returns 'disconnecting' during disconnecting transition regardless of hover", () => {
|
||||
expect(getButtonState("disconnecting", false)).toBe("disconnecting");
|
||||
expect(getButtonState("disconnecting", true)).toBe("disconnecting");
|
||||
});
|
||||
|
||||
it("returns 'disconnect' when claimed and hovered", () => {
|
||||
expect(getButtonState("claimed", true)).toBe("disconnect");
|
||||
});
|
||||
|
||||
it("returns 'claimed' when claimed and not hovered", () => {
|
||||
expect(getButtonState("claimed", false)).toBe("claimed");
|
||||
});
|
||||
|
||||
it("returns 'unclaimed' when unclaimed", () => {
|
||||
expect(getButtonState("unclaimed", false)).toBe("unclaimed");
|
||||
expect(getButtonState("unclaimed", true)).toBe("unclaimed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ClaimButton", () => {
|
||||
it("calls onClaim when clicking an unclaimed org", async () => {
|
||||
// Arrange
|
||||
const onClaim = vi.fn();
|
||||
const org = createOrg({ status: "unclaimed" });
|
||||
renderWithProviders(
|
||||
<ClaimButton org={org} onClaim={onClaim} onDisconnect={vi.fn()} />,
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
|
||||
// Act
|
||||
await user.click(screen.getByTestId("claim-button-1"));
|
||||
|
||||
// Assert
|
||||
expect(onClaim).toHaveBeenCalledWith("1");
|
||||
});
|
||||
|
||||
it("calls onDisconnect when clicking a claimed org", async () => {
|
||||
// Arrange
|
||||
const onDisconnect = vi.fn();
|
||||
const org = createOrg({ status: "claimed" });
|
||||
renderWithProviders(
|
||||
<ClaimButton org={org} onClaim={vi.fn()} onDisconnect={onDisconnect} />,
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
|
||||
// Act
|
||||
await user.click(screen.getByTestId("claim-button-1"));
|
||||
|
||||
// Assert
|
||||
expect(onDisconnect).toHaveBeenCalledWith("1");
|
||||
});
|
||||
|
||||
it("does not call handlers when button is disabled during claiming", async () => {
|
||||
// Arrange
|
||||
const onClaim = vi.fn();
|
||||
const onDisconnect = vi.fn();
|
||||
const org = createOrg({ status: "claiming" });
|
||||
renderWithProviders(
|
||||
<ClaimButton org={org} onClaim={onClaim} onDisconnect={onDisconnect} />,
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
|
||||
// Act
|
||||
await user.click(screen.getByTestId("claim-button-1"));
|
||||
|
||||
// Assert
|
||||
expect(onClaim).not.toHaveBeenCalled();
|
||||
expect(onDisconnect).not.toHaveBeenCalled();
|
||||
expect(screen.getByTestId("claim-button-1")).toBeDisabled();
|
||||
});
|
||||
|
||||
it("shows 'Disconnect' label on hover when claimed", async () => {
|
||||
// Arrange
|
||||
const org = createOrg({ status: "claimed" });
|
||||
renderWithProviders(
|
||||
<ClaimButton org={org} onClaim={vi.fn()} onDisconnect={vi.fn()} />,
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
|
||||
// Act
|
||||
await user.hover(screen.getByTestId("claim-button-1"));
|
||||
|
||||
// Assert
|
||||
expect(screen.getByTestId("claim-button-1")).toHaveTextContent(
|
||||
"ORG$DISCONNECT",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,104 +0,0 @@
|
||||
import { screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderWithProviders } from "test-utils";
|
||||
import { GitConversationRouting } from "#/components/features/org/git-conversation-routing";
|
||||
|
||||
const mockMutate = vi.fn();
|
||||
const mockDisconnectMutate = vi.fn();
|
||||
|
||||
vi.mock("#/hooks/query/use-git-organizations", () => ({
|
||||
useUserGitOrganizations: () => ({
|
||||
data: {
|
||||
provider: "github",
|
||||
organizations: ["OpenHands", "AcmeCo"],
|
||||
},
|
||||
isLoading: false,
|
||||
}),
|
||||
useGitClaims: () => ({
|
||||
data: [
|
||||
{
|
||||
id: "claim-1",
|
||||
org_id: "org-1",
|
||||
provider: "github",
|
||||
git_organization: "OpenHands",
|
||||
claimed_by: "user-1",
|
||||
claimed_at: "2026-01-01T00:00:00",
|
||||
},
|
||||
],
|
||||
isLoading: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("#/hooks/mutation/use-claim-git-org", () => ({
|
||||
useClaimGitOrg: () => ({
|
||||
mutate: mockMutate,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("#/hooks/mutation/use-disconnect-git-org", () => ({
|
||||
useDisconnectGitOrg: () => ({
|
||||
mutate: mockDisconnectMutate,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("GitConversationRouting", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("should render organizations from API data", () => {
|
||||
renderWithProviders(<GitConversationRouting />);
|
||||
|
||||
expect(
|
||||
screen.getByTestId("org-row-github:openhands"),
|
||||
).toHaveTextContent("github/OpenHands");
|
||||
expect(
|
||||
screen.getByTestId("org-row-github:acmeco"),
|
||||
).toHaveTextContent("github/AcmeCo");
|
||||
});
|
||||
|
||||
it("should show claimed org with 'Claimed' label", () => {
|
||||
renderWithProviders(<GitConversationRouting />);
|
||||
|
||||
const claimedButton = screen.getByTestId("claim-button-github:openhands");
|
||||
expect(claimedButton).toHaveTextContent("ORG$CLAIMED");
|
||||
});
|
||||
|
||||
it("should show unclaimed orgs with 'Claim' label", () => {
|
||||
renderWithProviders(<GitConversationRouting />);
|
||||
|
||||
expect(
|
||||
screen.getByTestId("claim-button-github:acmeco"),
|
||||
).toHaveTextContent("ORG$CLAIM");
|
||||
});
|
||||
|
||||
it("should call claim mutation when clicking claim on unclaimed org", async () => {
|
||||
renderWithProviders(<GitConversationRouting />);
|
||||
const user = userEvent.setup();
|
||||
|
||||
await user.click(screen.getByTestId("claim-button-github:acmeco"));
|
||||
|
||||
expect(mockMutate).toHaveBeenCalledWith(
|
||||
{ provider: "github", gitOrganization: "AcmeCo" },
|
||||
expect.objectContaining({ onSettled: expect.any(Function) }),
|
||||
);
|
||||
});
|
||||
|
||||
it("should call disconnect mutation when clicking disconnect on claimed org", async () => {
|
||||
renderWithProviders(<GitConversationRouting />);
|
||||
const user = userEvent.setup();
|
||||
|
||||
await user.click(screen.getByTestId("claim-button-github:openhands"));
|
||||
|
||||
expect(mockDisconnectMutate).toHaveBeenCalledWith(
|
||||
{ claimId: "claim-1" },
|
||||
expect.objectContaining({ onSettled: expect.any(Function) }),
|
||||
);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
import { screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { renderWithProviders } from "test-utils";
|
||||
import { GitOrgRow } from "#/components/features/org/git-org-row";
|
||||
import type { GitOrg } from "#/types/org";
|
||||
|
||||
const createOrg = (overrides: Partial<GitOrg> = {}): GitOrg => ({
|
||||
id: "1",
|
||||
claimId: null,
|
||||
provider: "GitHub",
|
||||
name: "TestOrg",
|
||||
status: "unclaimed",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("GitOrgRow", () => {
|
||||
it("renders the provider and organization name", () => {
|
||||
// Arrange & Act
|
||||
renderWithProviders(
|
||||
<GitOrgRow
|
||||
org={createOrg({ provider: "GitLab", name: "MyOrg" })}
|
||||
isLast={false}
|
||||
onClaim={vi.fn()}
|
||||
onDisconnect={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Assert
|
||||
expect(screen.getByTestId("org-row-1")).toHaveTextContent("GitLab/MyOrg");
|
||||
});
|
||||
|
||||
it("renders a claim button for the organization", () => {
|
||||
// Arrange & Act
|
||||
renderWithProviders(
|
||||
<GitOrgRow
|
||||
org={createOrg()}
|
||||
isLast={false}
|
||||
onClaim={vi.fn()}
|
||||
onDisconnect={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Assert
|
||||
expect(screen.getByTestId("claim-button-1")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
85
frontend/__tests__/components/feedback-actions.test.tsx
Normal file
85
frontend/__tests__/components/feedback-actions.test.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import { screen, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderWithProviders } from "test-utils";
|
||||
import { TrajectoryActions } from "#/components/features/trajectory/trajectory-actions";
|
||||
|
||||
describe("TrajectoryActions", () => {
|
||||
const user = userEvent.setup();
|
||||
const onPositiveFeedback = vi.fn();
|
||||
const onNegativeFeedback = vi.fn();
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should render correctly", () => {
|
||||
renderWithProviders(
|
||||
<TrajectoryActions
|
||||
onPositiveFeedback={onPositiveFeedback}
|
||||
onNegativeFeedback={onNegativeFeedback}
|
||||
/>,
|
||||
);
|
||||
|
||||
const actions = screen.getByTestId("feedback-actions");
|
||||
within(actions).getByTestId("positive-feedback");
|
||||
within(actions).getByTestId("negative-feedback");
|
||||
});
|
||||
|
||||
it("should call onPositiveFeedback when positive feedback is clicked", async () => {
|
||||
renderWithProviders(
|
||||
<TrajectoryActions
|
||||
onPositiveFeedback={onPositiveFeedback}
|
||||
onNegativeFeedback={onNegativeFeedback}
|
||||
/>,
|
||||
);
|
||||
|
||||
const positiveFeedback = screen.getByTestId("positive-feedback");
|
||||
await user.click(positiveFeedback);
|
||||
|
||||
expect(onPositiveFeedback).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should call onNegativeFeedback when negative feedback is clicked", async () => {
|
||||
renderWithProviders(
|
||||
<TrajectoryActions
|
||||
onPositiveFeedback={onPositiveFeedback}
|
||||
onNegativeFeedback={onNegativeFeedback}
|
||||
/>,
|
||||
);
|
||||
|
||||
const negativeFeedback = screen.getByTestId("negative-feedback");
|
||||
await user.click(negativeFeedback);
|
||||
|
||||
expect(onNegativeFeedback).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe("SaaS mode", () => {
|
||||
it("should render all buttons when isSaasMode is false", () => {
|
||||
renderWithProviders(
|
||||
<TrajectoryActions
|
||||
onPositiveFeedback={onPositiveFeedback}
|
||||
onNegativeFeedback={onNegativeFeedback}
|
||||
isSaasMode={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
const actions = screen.getByTestId("feedback-actions");
|
||||
within(actions).getByTestId("positive-feedback");
|
||||
within(actions).getByTestId("negative-feedback");
|
||||
});
|
||||
|
||||
it("should render all buttons when isSaasMode is undefined (default behavior)", () => {
|
||||
renderWithProviders(
|
||||
<TrajectoryActions
|
||||
onPositiveFeedback={onPositiveFeedback}
|
||||
onNegativeFeedback={onNegativeFeedback}
|
||||
/>,
|
||||
);
|
||||
|
||||
const actions = screen.getByTestId("feedback-actions");
|
||||
within(actions).getByTestId("positive-feedback");
|
||||
within(actions).getByTestId("negative-feedback");
|
||||
});
|
||||
});
|
||||
});
|
||||
68
frontend/__tests__/components/feedback-form.test.tsx
Normal file
68
frontend/__tests__/components/feedback-form.test.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Mock useParams before importing components
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual("react-router");
|
||||
return {
|
||||
...(actual as object),
|
||||
useParams: () => ({ conversationId: "test-conversation-id" }),
|
||||
};
|
||||
});
|
||||
|
||||
import { screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { renderWithProviders } from "test-utils";
|
||||
import { FeedbackForm } from "#/components/features/feedback/feedback-form";
|
||||
import { I18nKey } from "#/i18n/declaration";
|
||||
|
||||
describe("FeedbackForm", () => {
|
||||
const user = userEvent.setup();
|
||||
const onCloseMock = vi.fn();
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should render correctly", () => {
|
||||
renderWithProviders(
|
||||
<FeedbackForm polarity="positive" onClose={onCloseMock} />,
|
||||
);
|
||||
|
||||
screen.getByLabelText(I18nKey.FEEDBACK$EMAIL_LABEL);
|
||||
screen.getByLabelText(I18nKey.FEEDBACK$PRIVATE_LABEL);
|
||||
screen.getByLabelText(I18nKey.FEEDBACK$PUBLIC_LABEL);
|
||||
|
||||
screen.getByRole("button", { name: I18nKey.FEEDBACK$SHARE_LABEL });
|
||||
screen.getByRole("button", { name: I18nKey.FEEDBACK$CANCEL_LABEL });
|
||||
});
|
||||
|
||||
it("should switch between private and public permissions", async () => {
|
||||
renderWithProviders(
|
||||
<FeedbackForm polarity="positive" onClose={onCloseMock} />,
|
||||
);
|
||||
const privateRadio = screen.getByLabelText(I18nKey.FEEDBACK$PRIVATE_LABEL);
|
||||
const publicRadio = screen.getByLabelText(I18nKey.FEEDBACK$PUBLIC_LABEL);
|
||||
|
||||
expect(privateRadio).toBeChecked(); // private is the default value
|
||||
expect(publicRadio).not.toBeChecked();
|
||||
|
||||
await user.click(publicRadio);
|
||||
expect(publicRadio).toBeChecked();
|
||||
expect(privateRadio).not.toBeChecked();
|
||||
|
||||
await user.click(privateRadio);
|
||||
expect(privateRadio).toBeChecked();
|
||||
expect(publicRadio).not.toBeChecked();
|
||||
});
|
||||
|
||||
it("should call onClose when the close button is clicked", async () => {
|
||||
renderWithProviders(
|
||||
<FeedbackForm polarity="positive" onClose={onCloseMock} />,
|
||||
);
|
||||
await user.click(
|
||||
screen.getByRole("button", { name: I18nKey.FEEDBACK$CANCEL_LABEL }),
|
||||
);
|
||||
|
||||
expect(onCloseMock).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
97
frontend/__tests__/components/likert-scale.test.tsx
Normal file
97
frontend/__tests__/components/likert-scale.test.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { renderWithProviders } from "test-utils";
|
||||
import { LikertScale } from "#/components/features/feedback/likert-scale";
|
||||
import { I18nKey } from "#/i18n/declaration";
|
||||
|
||||
// Mock the mutation hook
|
||||
vi.mock("#/hooks/mutation/use-submit-conversation-feedback", () => ({
|
||||
useSubmitConversationFeedback: () => ({
|
||||
mutate: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("LikertScale", () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should render with proper localized text for rating prompt", () => {
|
||||
renderWithProviders(<LikertScale eventId={1} />);
|
||||
|
||||
// Check that the rating prompt is displayed with proper translation key
|
||||
expect(screen.getByText(I18nKey.FEEDBACK$RATE_AGENT_PERFORMANCE)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should show localized feedback reasons when rating is 3 or below", async () => {
|
||||
renderWithProviders(<LikertScale eventId={1} />);
|
||||
|
||||
// Click on a rating of 3 (which should show reasons)
|
||||
const threeStarButton = screen.getAllByRole("button")[2]; // 3rd button (rating 3)
|
||||
await user.click(threeStarButton);
|
||||
|
||||
// Wait for reasons to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(I18nKey.FEEDBACK$SELECT_REASON)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Check that all feedback reasons are properly localized
|
||||
expect(screen.getByText(I18nKey.FEEDBACK$REASON_MISUNDERSTOOD_INSTRUCTION)).toBeInTheDocument();
|
||||
expect(screen.getByText(I18nKey.FEEDBACK$REASON_FORGOT_CONTEXT)).toBeInTheDocument();
|
||||
expect(screen.getByText(I18nKey.FEEDBACK$REASON_UNNECESSARY_CHANGES)).toBeInTheDocument();
|
||||
expect(screen.getByText(I18nKey.FEEDBACK$REASON_SHOULD_ASK_FIRST)).toBeInTheDocument();
|
||||
expect(screen.getByText(I18nKey.FEEDBACK$REASON_DIDNT_FINISH_JOB)).toBeInTheDocument();
|
||||
expect(screen.getByText(I18nKey.FEEDBACK$REASON_OTHER)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should show countdown message with proper localization", async () => {
|
||||
renderWithProviders(<LikertScale eventId={1} />);
|
||||
|
||||
// Click on a rating of 2 (which should show reasons and countdown)
|
||||
const twoStarButton = screen.getAllByRole("button")[1]; // 2nd button (rating 2)
|
||||
await user.click(twoStarButton);
|
||||
|
||||
// Wait for countdown to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(I18nKey.FEEDBACK$SELECT_REASON_COUNTDOWN)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("should show thank you message after submission", () => {
|
||||
renderWithProviders(
|
||||
<LikertScale eventId={1} initiallySubmitted={true} initialRating={4} />
|
||||
);
|
||||
|
||||
// Check that thank you message is displayed with proper translation key
|
||||
expect(screen.getByText(I18nKey.FEEDBACK$THANK_YOU_FOR_FEEDBACK)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should render all 5 star rating buttons", () => {
|
||||
renderWithProviders(<LikertScale eventId={1} />);
|
||||
|
||||
// Check that all 5 star buttons are rendered
|
||||
const starButtons = screen.getAllByRole("button");
|
||||
expect(starButtons).toHaveLength(5);
|
||||
|
||||
// Check that each button has proper aria-label
|
||||
for (let i = 1; i <= 5; i++) {
|
||||
expect(screen.getByLabelText(`Rate ${i} stars`)).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it("should not show reasons for ratings above 3", async () => {
|
||||
renderWithProviders(<LikertScale eventId={1} />);
|
||||
|
||||
// Click on a rating of 5 (which should NOT show reasons)
|
||||
const fiveStarButton = screen.getAllByRole("button")[4]; // 5th button (rating 5)
|
||||
await user.click(fiveStarButton);
|
||||
|
||||
// Wait a bit to ensure reasons don't appear
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText(I18nKey.FEEDBACK$SELECT_REASON)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { ModelSelector } from "#/components/shared/modals/settings/model-selector";
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => {
|
||||
@@ -31,20 +32,15 @@ describe("ModelSelector", () => {
|
||||
separator: "/",
|
||||
models: ["chat-bison", "chat-bison-32k"],
|
||||
},
|
||||
cohere: {
|
||||
separator: ".",
|
||||
models: ["command-r-v1:0"],
|
||||
},
|
||||
};
|
||||
|
||||
const verifiedModels = ["gpt-4o", "gpt-4o-mini"];
|
||||
const verifiedProviders = ["openai"];
|
||||
|
||||
it("should display the provider selector", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<ModelSelector
|
||||
models={models}
|
||||
verifiedModels={verifiedModels}
|
||||
verifiedProviders={verifiedProviders}
|
||||
/>,
|
||||
);
|
||||
render(<ModelSelector models={models} />);
|
||||
|
||||
const selector = screen.getByLabelText("LLM Provider");
|
||||
expect(selector).toBeInTheDocument();
|
||||
@@ -54,17 +50,12 @@ describe("ModelSelector", () => {
|
||||
expect(screen.getByText("OpenAI")).toBeInTheDocument();
|
||||
expect(screen.getByText("Azure")).toBeInTheDocument();
|
||||
expect(screen.getByText("VertexAI")).toBeInTheDocument();
|
||||
expect(screen.getByText("cohere")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should disable the model selector if the provider is not selected", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<ModelSelector
|
||||
models={models}
|
||||
verifiedModels={verifiedModels}
|
||||
verifiedProviders={verifiedProviders}
|
||||
/>,
|
||||
);
|
||||
render(<ModelSelector models={models} />);
|
||||
|
||||
const modelSelector = screen.getByLabelText("LLM Model");
|
||||
expect(modelSelector).toBeDisabled();
|
||||
@@ -80,13 +71,7 @@ describe("ModelSelector", () => {
|
||||
|
||||
it("should display the model selector", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<ModelSelector
|
||||
models={models}
|
||||
verifiedModels={verifiedModels}
|
||||
verifiedProviders={verifiedProviders}
|
||||
/>,
|
||||
);
|
||||
render(<ModelSelector models={models} />);
|
||||
|
||||
const providerSelector = screen.getByLabelText("LLM Provider");
|
||||
await user.click(providerSelector);
|
||||
@@ -99,43 +84,51 @@ describe("ModelSelector", () => {
|
||||
|
||||
expect(screen.getByText("ada")).toBeInTheDocument();
|
||||
expect(screen.getByText("gpt-35-turbo")).toBeInTheDocument();
|
||||
|
||||
await user.click(providerSelector);
|
||||
const vertexProvider = screen.getByText("VertexAI");
|
||||
await user.click(vertexProvider);
|
||||
|
||||
await user.click(modelSelector);
|
||||
|
||||
// Test fails when expecting these values to be present.
|
||||
// My hypothesis is that it has something to do with NextUI's
|
||||
// list virtualization
|
||||
|
||||
// expect(screen.getByText("chat-bison")).toBeInTheDocument();
|
||||
// expect(screen.getByText("chat-bison-32k")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should call onChange when the provider and model change", async () => {
|
||||
it("should call onModelChange when the model is changed", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<ModelSelector
|
||||
models={models}
|
||||
verifiedModels={verifiedModels}
|
||||
verifiedProviders={verifiedProviders}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
render(<ModelSelector models={models} />);
|
||||
|
||||
const providerSelector = screen.getByLabelText("LLM Provider");
|
||||
const modelSelector = screen.getByLabelText("LLM Model");
|
||||
|
||||
await user.click(providerSelector);
|
||||
await user.click(screen.getByText("Azure"));
|
||||
|
||||
const modelSelector = screen.getByLabelText("LLM Model");
|
||||
await user.click(modelSelector);
|
||||
await user.click(screen.getByText("ada"));
|
||||
|
||||
expect(onChange).toHaveBeenNthCalledWith(1, "azure", null);
|
||||
expect(onChange).toHaveBeenNthCalledWith(2, "azure", "ada");
|
||||
await user.click(modelSelector);
|
||||
await user.click(screen.getByText("gpt-35-turbo"));
|
||||
|
||||
await user.click(providerSelector);
|
||||
await user.click(screen.getByText("cohere"));
|
||||
|
||||
await user.click(modelSelector);
|
||||
|
||||
// Test fails when expecting this values to be present.
|
||||
// My hypothesis is that it has something to do with NextUI's
|
||||
// list virtualization
|
||||
|
||||
// await user.click(screen.getByText("command-r-v1:0"));
|
||||
});
|
||||
|
||||
|
||||
it("should have a default value if passed", async () => {
|
||||
render(
|
||||
<ModelSelector
|
||||
models={models}
|
||||
verifiedModels={verifiedModels}
|
||||
verifiedProviders={verifiedProviders}
|
||||
currentModel="azure/ada"
|
||||
/>,
|
||||
);
|
||||
render(<ModelSelector models={models} currentModel="azure/ada" />);
|
||||
|
||||
expect(screen.getByLabelText("LLM Provider")).toHaveValue("Azure");
|
||||
expect(screen.getByLabelText("LLM Model")).toHaveValue("ada");
|
||||
|
||||
@@ -17,8 +17,6 @@ describe("SettingsForm", () => {
|
||||
<SettingsForm
|
||||
settings={DEFAULT_SETTINGS}
|
||||
models={[DEFAULT_SETTINGS.llm_model]}
|
||||
verifiedModels={[]}
|
||||
verifiedProviders={["openhands"]}
|
||||
onClose={onCloseMock}
|
||||
/>
|
||||
),
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
createMockMessageEvent,
|
||||
createMockUserMessageEvent,
|
||||
createMockConversationErrorEvent,
|
||||
createMockServerErrorEvent,
|
||||
createMockAgentErrorEvent,
|
||||
createMockBrowserObservationEvent,
|
||||
createMockBrowserNavigateActionEvent,
|
||||
@@ -335,17 +334,18 @@ describe("Conversation WebSocket Handler", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("should update error message store on ServerErrorEvent", async () => {
|
||||
// ServerErrorEvent represents server-side errors (e.g., MCP configuration errors)
|
||||
// that should be shown as a banner to the user.
|
||||
const mockServerErrorEvent = createMockServerErrorEvent();
|
||||
it("should show friendly i18n message for budget/credit errors", async () => {
|
||||
// Create a mock AgentErrorEvent with budget-related error message
|
||||
const mockBudgetErrorEvent = createMockAgentErrorEvent({
|
||||
error:
|
||||
"litellm.BadRequestError: Litellm_proxyException - ExceededBudget: User=xxx over budget.",
|
||||
});
|
||||
|
||||
// Set up MSW to send the error event when connection is established
|
||||
// Set up MSW to send the budget error event when connection is established
|
||||
mswServer.use(
|
||||
wsLink.addEventListener("connection", ({ client, server }) => {
|
||||
server.connect();
|
||||
// Send the mock error event after connection
|
||||
client.send(JSON.stringify(mockServerErrorEvent));
|
||||
client.send(JSON.stringify(mockBudgetErrorEvent));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -356,98 +356,14 @@ describe("Conversation WebSocket Handler", () => {
|
||||
expect(screen.getByTestId("error-message")).toHaveTextContent("none");
|
||||
|
||||
// Wait for connection and error event processing
|
||||
// Should show the i18n key instead of raw error message
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("error-message")).toHaveTextContent(
|
||||
"MCP server connection failed: Invalid configuration",
|
||||
"STATUS$ERROR_LLM_OUT_OF_CREDITS",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle different ServerErrorEvent error codes", async () => {
|
||||
// Test different error codes for ServerErrorEvent
|
||||
const mockServerErrorEvent = createMockServerErrorEvent({
|
||||
code: "RuntimeError",
|
||||
detail: "Agent server runtime error: Out of memory",
|
||||
});
|
||||
|
||||
mswServer.use(
|
||||
wsLink.addEventListener("connection", ({ client, server }) => {
|
||||
server.connect();
|
||||
client.send(JSON.stringify(mockServerErrorEvent));
|
||||
}),
|
||||
);
|
||||
|
||||
renderWithWebSocketContext(<ErrorMessageStoreComponent />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("error-message")).toHaveTextContent(
|
||||
"Agent server runtime error: Out of memory",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should clear error message when a successful event is received after a ServerErrorEvent", async () => {
|
||||
// This test verifies that error banners disappear when follow-up messages
|
||||
// are sent and received after a ServerErrorEvent.
|
||||
// Note: This test was originally commented out because the implementation
|
||||
// didn't properly clear ServerErrorEvent errors on subsequent events.
|
||||
// After the fix using isDisplayableErrorEvent, this now works correctly.
|
||||
const conversationId = "test-server-error-clear";
|
||||
|
||||
// Set up MSW to mock event count API and send events
|
||||
mswServer.use(
|
||||
http.get(
|
||||
`http://localhost:3000/api/conversations/${conversationId}/events/count`,
|
||||
() => HttpResponse.json(2),
|
||||
),
|
||||
wsLink.addEventListener("connection", ({ client, server }) => {
|
||||
server.connect();
|
||||
|
||||
// Send ServerErrorEvent first (sets the error banner)
|
||||
const mockServerErrorEvent = createMockServerErrorEvent();
|
||||
client.send(JSON.stringify(mockServerErrorEvent));
|
||||
|
||||
// Send a successful (non-error) event immediately after
|
||||
// This simulates the user sending a follow-up message and receiving a response
|
||||
const mockSuccessEvent = createMockMessageEvent({
|
||||
id: "success-event-after-server-error",
|
||||
});
|
||||
client.send(JSON.stringify(mockSuccessEvent));
|
||||
}),
|
||||
);
|
||||
|
||||
// Verify error message store is initially empty
|
||||
expect(useErrorMessageStore.getState().errorMessage).toBeNull();
|
||||
|
||||
// Render with WebSocket context (minimal component just to trigger connection)
|
||||
renderWithWebSocketContext(
|
||||
<ConnectionStatusComponent />,
|
||||
conversationId,
|
||||
`http://localhost:3000/api/conversations/${conversationId}`,
|
||||
);
|
||||
|
||||
// Wait for connection
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(screen.getByTestId("connection-state")).toHaveTextContent(
|
||||
"OPEN",
|
||||
);
|
||||
},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
|
||||
// Wait for both events to be received and error to be cleared
|
||||
// The error was set by the first event (ServerErrorEvent),
|
||||
// then cleared by the second successful event (MessageEvent).
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(useEventStore.getState().events.length).toBe(2);
|
||||
expect(useErrorMessageStore.getState().errorMessage).toBeNull();
|
||||
},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
});
|
||||
|
||||
it("should show friendly i18n message for budget ConversationErrorEvent", async () => {
|
||||
const mockBudgetConversationError = createMockConversationErrorEvent({
|
||||
detail:
|
||||
@@ -472,97 +388,6 @@ describe("Conversation WebSocket Handler", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("should not clear budget error when non-agent events are received", async () => {
|
||||
// Regression test: budget/credit error banner used to disappear ~500ms after
|
||||
// appearing because every subsequent non-error event called removeErrorMessage().
|
||||
const conversationId = "test-conversation-budget-persist";
|
||||
|
||||
const mockBudgetError = createMockConversationErrorEvent({
|
||||
id: "budget-error-1",
|
||||
detail:
|
||||
"Budget has been exceeded! Current cost: 18.51, Max budget: 18.24",
|
||||
});
|
||||
|
||||
// A user MessageEvent (source: "user") should NOT clear the budget error
|
||||
const mockUserEvent = createMockUserMessageEvent({
|
||||
id: "user-msg-after-error",
|
||||
});
|
||||
|
||||
mswServer.use(
|
||||
http.get(
|
||||
`http://localhost:3000/api/conversations/${conversationId}/events/count`,
|
||||
() => HttpResponse.json(2),
|
||||
),
|
||||
wsLink.addEventListener("connection", ({ client, server }) => {
|
||||
server.connect();
|
||||
// Send budget error, then a non-agent event right after
|
||||
client.send(JSON.stringify(mockBudgetError));
|
||||
client.send(JSON.stringify(mockUserEvent));
|
||||
}),
|
||||
);
|
||||
|
||||
renderWithWebSocketContext(
|
||||
<ErrorMessageStoreComponent />,
|
||||
conversationId,
|
||||
`http://localhost:3000/api/conversations/${conversationId}`,
|
||||
);
|
||||
|
||||
// Wait for both events to be processed
|
||||
await waitFor(() => {
|
||||
expect(useEventStore.getState().events.length).toBe(2);
|
||||
});
|
||||
|
||||
// Budget error should still be visible — not cleared by the user event
|
||||
expect(useErrorMessageStore.getState().errorMessage).toBe(
|
||||
"STATUS$ERROR_LLM_OUT_OF_CREDITS",
|
||||
);
|
||||
});
|
||||
|
||||
it("should clear budget error when an agent event is received", async () => {
|
||||
// When the agent sends a new event, it means the LLM is working
|
||||
// (credits are available), so the budget error should be cleared.
|
||||
const conversationId = "test-conversation-budget-clear";
|
||||
|
||||
const mockBudgetError = createMockConversationErrorEvent({
|
||||
id: "budget-error-2",
|
||||
detail:
|
||||
"Budget has been exceeded! Current cost: 18.51, Max budget: 18.24",
|
||||
});
|
||||
|
||||
// An agent MessageEvent (source: "agent") SHOULD clear the budget error
|
||||
const mockAgentEvent = createMockMessageEvent({
|
||||
id: "agent-msg-after-credits",
|
||||
});
|
||||
|
||||
mswServer.use(
|
||||
http.get(
|
||||
`http://localhost:3000/api/conversations/${conversationId}/events/count`,
|
||||
() => HttpResponse.json(2),
|
||||
),
|
||||
wsLink.addEventListener("connection", ({ client, server }) => {
|
||||
server.connect();
|
||||
client.send(JSON.stringify(mockBudgetError));
|
||||
client.send(JSON.stringify(mockAgentEvent));
|
||||
}),
|
||||
);
|
||||
|
||||
renderWithWebSocketContext(
|
||||
<ErrorMessageStoreComponent />,
|
||||
conversationId,
|
||||
`http://localhost:3000/api/conversations/${conversationId}`,
|
||||
);
|
||||
|
||||
// Wait for both events to be processed
|
||||
await waitFor(() => {
|
||||
expect(useEventStore.getState().events.length).toBe(2);
|
||||
});
|
||||
|
||||
// After both events processed, the budget error should have been cleared
|
||||
// by the agent event (source: "agent"). Check it's not the budget error.
|
||||
const currentError = useErrorMessageStore.getState().errorMessage;
|
||||
expect(currentError).not.toBe("STATUS$ERROR_LLM_OUT_OF_CREDITS");
|
||||
});
|
||||
|
||||
it("should set error message store on WebSocket connection errors", async () => {
|
||||
// Simulate a connect-then-fail sequence (the MSW server auto-connects by default).
|
||||
// This should surface an error message because the app has previously connected.
|
||||
@@ -1111,9 +936,7 @@ describe("Conversation WebSocket Handler", () => {
|
||||
http.get(
|
||||
`http://localhost:3000/api/v1/conversation/${conversationId}/events/search`,
|
||||
async () => {
|
||||
await new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, 10);
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return HttpResponse.json({
|
||||
items: mockHistoryEvents,
|
||||
});
|
||||
@@ -1234,9 +1057,7 @@ describe("Conversation WebSocket Handler", () => {
|
||||
http.get(
|
||||
`http://localhost:3000/api/v1/conversation/${conversationId}/events/search`,
|
||||
async () => {
|
||||
await new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, 10);
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return HttpResponse.json({
|
||||
items: mockHistoryEvents,
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user