[[for script]]
[[bitbacket ssh setup]]
[[setup redirect url]]




### **Introduction**

This guide provides a detailed walkthrough for deploying the APAC Ops Bot. The process involves cloning the application's repository, using an AI assistant (Claude) to generate a deployment script, preparing the server environment, and implementing production-ready authentication. This documentation is designed to be followed step-by-step, ensuring a successful deployment even for new users.

### **Part 1: Prepare the Local Environment**

The first phase involves setting up the project on your local machine and preparing the context for generating deployment scripts.

#### 1.1. Clone the Application Repository

Obtain a local copy of the application's source code from its Git repository.

1. **Navigate to the Repository:** Open your web browser and go to the `APAC ops Bot` repository page.
    
2. **Copy the Repository URL:** Click the green **`< > Code`** button. In the dropdown that appears, copy the HTTPS URL provided.
    
    ```
    https://bitbucket.org/your-workspace/apac-ops-bot.git
    ```
    
3. **Clone the Repository Locally:** Open a terminal window on your local machine. Use the `git clone` command followed by the URL you just copied.
    
    ```bash
    git clone https://bitbucket.org/your-workspace/apac-ops-bot.git
    ```
    
    _Note: If you have previously cloned the repository, you will see a message indicating that the destination path already exists._
    
4. **Navigate into the Project Directory:** Change your current directory to the newly created project folder.
    
    ```bash
    cd apac-ops-bot/
    ```
    
5. **Update the Repository:** Ensure your local copy is up-to-date with the latest changes from the remote repository by running `git pull`.
    
    ```bash
    git pull
    ```
    
    The output should indicate that your local repository is "Already up to date."
    

#### 1.2. Initialize the Claude AI Environment

To generate the deployment script, we will use the Claude Command-Line Interface (CLI). We need to provide the AI with the context of our project structure and key files.

1. **Start the Claude CLI:** In your terminal, within the project's root directory, start the Claude interactive session.
    
    ```bash
    claude
    ```
    
2. **Provide Project Context to Claude:** Execute the following `claude explore` commands one by one. These commands read the specified files and directories, allowing the AI to understand the project's architecture, dependencies, and configuration.
    
    - **Explore the entire project directory structure:**
        
        ```bash
        claude explore . --name "root" --type "tree" --verbose
        ```
        
    - **Explore key configuration and source code files:** `bash claude explore .env.sample --name ".env.sample" --type "file" claude explore backend/app/main.py --name "backend/app/main.py" --type "file" claude explore backend/app/config.py --name "backend/app/config.py" --type "file" claude explore backend/app/database.py --name "backend/app/database.py" --type "file" claude explore frontend/package.json --name "frontend/package.json" --type "file" claude explore frontend/src/App.tsx --name "frontend/src/App.tsx" --type "file" claude explore backend/Dockerfile --name "backend/Dockerfile" --type "file" claude explore frontend/Dockerfile --name "frontend/Dockerfile" --type "file" claude explore docker-compose.yml --name "docker-compose.yml" --type "file" claude explore backend/app/authentication/main.py --name "backend/app/authentication/main.py" --type "file" claude explore backend/app/dependencies.py --name "backend/app/dependencies.py" --type "file"` After running these commands, Claude will have a comprehensive understanding of the project's layout and will create a `CLAUDE.md` file summarizing the explored context.
        

### **Part 2: Implement Azure AD Authentication**

After the initial deployment, the application may use a basic email/password form for testing. The next step is to switch to the production authentication method, which uses Azure Active Directory (AD).

#### 2.1. Modify Frontend Code for Azure AD Login

The frontend application code needs to be modified to display the "Sign in with Microsoft" button instead of the email/password form.

1. **Navigate to the Login Component:** Open the source code for the login page component in your code editor. In the video, this appears to be `frontend/src/components/Login/Login.jsx`.
    
2. **Update Conditional Rendering:** Locate the section responsible for rendering the login forms. The code uses conditional rendering to switch between the standard login and the Azure AD login. You need to modify the condition to show the Azure AD component by default.
    
    An equivalent change to what is shown in the video would be to invert the `when` condition:
    
    ```diff
    // src/components/Login/Login.jsx
    
    // ...
        <Show
    -       when={!isAzureAuthLoginPage}
    +       when={isAzureAuthLoginPage}
            fallback={<AzureLoginComponent />}
        >
            <form onSubmit={handleLogin}>
                {/* Email/Password form content */}
            </form>
        </Show>
    //...
    ```
    
    This change makes the `AzureLoginComponent` the default and the email/password form the fallback, effectively enabling the Azure AD login.
    
3. **Commit and Push Changes:** Save the file and commit the changes to your Git repository.
    
    ```bash
    # Add the changed file to the staging area
    git add frontend/src/components/Login/Login.jsx
    
    # Commit the changes with a descriptive message
    git commit -m "feat: add Azure AD login support"
    
    # Push the changes to the remote repository
    git push
    ```
    

#### 2.2. Configure Frontend Environment Variables

The frontend needs specific environment variables to connect to Azure AD.

1. **Open the Backend Environment File:** View the contents of the backend's environment file to find the required variables.
    
    ```bash
    cat backend/.env
    ```
    
2. **Identify and Copy Azure AD Variables:** Locate the variables related to Azure AD. They will look similar to this:
    
    ```env
    # Azure AD Configuration (Example Values)
    REACT_APP_AD_TENANT=your-tenant-id
    REACT_APP_AD_CLIENT_ID=your-client-id
    REACT_APP_AD_REDIRECT_URI=https://your-app-url/.auth/login/aad/callback
    ```
    
3. **Update the Frontend Environment File:** Open the frontend's environment file in an editor (like `vim`).
    
    ```bash
    vim frontend/.env
    ```
    
4. **Add the Azure AD Variables:** Paste the copied variables into the `frontend/.env` file and save it. The file should now contain these variables along with any others.
    
    ```env
    # frontend/.env
    
    # API Configuration
    REACT_APP_API_URL=http://sb-random.silver.solutions/api/v1/task/ops/
    # ... other variables
    
    # Azure AD Configuration
    REACT_APP_AD_TENANT=...
    REACT_APP_AD_CLIENT_ID=...
    REACT_APP_AD_REDIRECT_URI=...
    ```
    

#### 2.3. Rebuild and Deploy the Application

With the code and configuration updated, you need to rebuild the frontend and redeploy the application.

1. **Navigate to the Project Root:** Make sure you are in the main project directory (`apac-ops-bot`).
    
2. **Build the Frontend:** Run the build script to compile the React application.
    
    ```bash
    npm run build
    ```
    
3. **Deploy to Google App Engine:** Deploy the application. `gcloud` will deploy all services defined in the `app.yaml` files, including the updated frontend and any backend changes.
    
    ```bash
    gcloud app deploy
    ```
    

### **Part 3: Final Troubleshooting and Verification**

After deployment, it's crucial to test the application to ensure all changes work as expected and to fix any remaining bugs.

#### 3.1. Fixing a CORS (Cross-Origin Resource Sharing) Error

1. **Test the New Login:** Open your web browser and navigate to the application's URL. Perform a hard refresh (Cmd+Shift+R on Mac, Ctrl+F5 on Windows) to ensure you are loading the latest version. The page should now display the "Sign in with Microsoft" button.
    
2. **Identify the Error:** Click the "Sign in with Microsoft" button and complete the authentication process. You may notice that after authentication, you are redirected back to the login page instead of the main application. Open the browser's Developer Tools (F12) and go to the **Console** tab. You will likely see a CORS or mixed content error.
    
    ```
    Blocked loading active content at "http://sb-random.silver.solutions/api/v1/task/ops/..."
    ```
    
    This error occurs because the frontend, served over **HTTPS**, is trying to make a request to a backend API served over **HTTP**. Browsers block these "mixed content" requests for security reasons.
    
3. **Correct the API URL:** The fix is to ensure the frontend calls the API using the same protocol (HTTPS).
    
    - Open the frontend environment file again: `bash vim frontend/.env`
        
    - Locate the `REACT_APP_API_URL` variable and change the protocol from `http` to `https`.
        
        ```diff
        - REACT_APP_API_URL=http://sb-random.silver.solutions/api/v1/task/ops/
        + REACT_APP_API_URL=https://sb-random.silver.solutions/api/v1/task/ops/
        ```
        
    - Save the file.
        
4. **Rebuild and Redeploy:** Repeat the build and deploy process one more time to apply the environment variable change.
    
    ```bash
    npm run build
    gcloud app deploy
    ```
    
5. **Verify Successful Login:** Once the deployment is complete, perform another hard refresh on the application page. Click "Sign in with Microsoft" and authenticate. This time, you should be successfully logged in and see the "Welcome to Scopic Ops Bot" chat interface.
    

#### 3.2. Fixing a Backend Chat Error

Even after logging in, the application might have runtime bugs.

1. **Test the Chat Functionality:** Try sending a message through the chatbot interface (e.g., "where's COSMICC?").
    
2. **Identify the Error:** The application may fail to get a response. Check the browser's Developer Console again. You may see a `500 Internal Server Error` for the API request that sends the message.
    
3. **Analyze Backend Logs:** To understand the server error, check the backend service logs in Google App Engine.
    
    ```bash
    gcloud app logs tail -s backend
    ```
    
    Look for recent error messages. In the video, a traceback shows an `InvalidRequestError`, indicating that the code `can't find a previous_response_id`. This suggests the application is trying to continue a conversation that doesn't exist, especially on the first message of a new chat.
    
4. **Implement the Backend Fix:** The solution is to make the backend code resilient to cases where there is no previous response.
    
    - Open the relevant backend file, which appears to be `backend/app/services/response_service.py`.
    - Locate the code that accesses `previous_response_id`.
    - Wrap this logic in a `try...except` block to gracefully handle the error when the ID is not found.
    
    ```python
    # backend/app/services/response_service.py
    
    # ... inside a method like generate_response ...
    try:
        # Code that might fail
        previous_response_id = request.payload.get("previous_response_id")
        # ... logic that uses previous_response_id
    except AttributeError: # Or the appropriate exception type for a missing ID
        # Handle the error, e.g., by creating a new conversation
        # or proceeding without the previous response context.
        logger.warning("Previous response ID not found, starting new conversation.")
        response = self.apps.client.responses.create(request.payload)
    ```
    
5. **Commit and Redeploy the Final Fix:**
    
    - Commit the changes to your backend code. `bash git add backend/app/services/response_service.py git commit -m "fix: handle missing previous response in chat" git push`
    - Run the deployment command for the final time. `bash gcloud app deploy`

#### 3.3. Final Verification

1. **Perform a Full Test:** After the final deployment finishes, go back to the application in your browser.
2. **Start a New Chat:** Click the "New Chat" button to ensure you start with a clean state.
3. **Send a Message:** Type your query (e.g., "where's COSMICC?") and send it.
4. **Confirm Success:** The chatbot should now process the request and return a valid response, confirming that both the authentication and backend logic are working correctly.

The application is now fully deployed and functional.