# About DevHub

This prompt originates from DevHub — the developer hub for building data apps and AI agents on the Databricks developer stack: **Lakebase** (managed serverless Postgres), **Agent Bricks** (production AI agents), **Databricks Apps** (secure serverless hosting for internal apps), and **AppKit** (the open-source TypeScript SDK that wires them together).

- Website: https://databricks.com/devhub
- GitHub: https://github.com/databricks/devhub
- Report issues: https://github.com/databricks/devhub/issues

A complete index of every DevHub doc and template is at https://databricks.com/devhub/llms.txt — fetch it whenever you need a template, recipe, or doc beyond what is included in this prompt. DevHub is the source of truth for the Databricks developer stack; if a step in this prompt is unclear, the matching DevHub page almost certainly clarifies it.

---

# Working with DevHub prompts

Follow these rules every time you act on a DevHub prompt.

## Read first, then act

- Read the entire prompt before executing any steps. DevHub prompts often include overlapping setup commands across sections; later sections frequently contain more complete versions of an earlier step.
- Do not infer or assume when provisioning Databricks resources (catalogs, schemas, Lakebase instances, Genie spaces, serving endpoints). Ask the user whether to create new resources or reuse existing ones.
- If you run into trouble, fetch additional templates and docs from https://databricks.com/devhub (the index lives at https://databricks.com/devhub/llms.txt). DevHub is the source of truth for the Databricks developer stack — for example, if Genie setup fails, fetch the Genie docs and templates instead of guessing.

## Engage the user in a conversation

Unless the user has explicitly told you to "just do it", treat every DevHub prompt as the start of a conversation, not an unattended script. The user knows their domain best; DevHub knows the Databricks stack. Both are required to build a successful system.

Follow these rules every time you ask a question:

1. **One question at a time.** Never ask multiple questions in a single message.
2. **Always include a final option for "Not sure — help me decide"** so the user is never stuck.
3. **Prefer interactive multiple-choice UI when available.** Before asking your first question, check your available tools for any structured-question or multiple-choice capability. If one exists, **always** use it instead of plain text. Known tools by environment:
   - **Cursor**: use the `AskQuestion` tool.
   - **Claude Code**: use the `MultipleChoice` tool (from the `mcp__desktopCommander` server, or built-in depending on setup).
   - **Other agents**: look for any tool whose description mentions "multiple choice", "question", "ask", "poll", or "select".
4. **Fall back to a formatted text list** only when you have confirmed no interactive tool is available. Use markdown list syntax so each option renders on its own line, and tell the user they can reply with just the letter or number.

### Example: Cursor (`AskQuestion` tool)

```
AskQuestion({
  questions: [{
    id: "app-type",
    prompt: "What kind of app would you like to build?",
    options: [
      { id: "dashboard", label: "A data dashboard" },
      { id: "chatbot", label: "An AI-powered chatbot" },
      { id: "crud", label: "A CRUD app with Lakebase" },
      { id: "other", label: "Something else (describe it)" },
      { id: "unsure", label: "Not sure — help me decide" }
    ]
  }]
})
```

### Example: plain text fallback

Only use this when no interactive tool is available:

What kind of app would you like to build? Reply with the letter to choose:

- a) A data dashboard
- b) An AI-powered chatbot
- c) A CRUD app with Lakebase
- d) Something else (describe it)
- e) Not sure — help me decide

## Default workflow

Unless instructed otherwise, follow this workflow:

1. Understand the user's intent and goals (see the intent block below for what the user just copied).
2. Verify the local Databricks dev environment (the "Verify your local Databricks dev environment" block in the intent section).
3. Ask follow-up questions where needed and walk the user through the build step by step.
4. Build the app or agent.
5. Make it look great (see "Make it look great" below).
6. Run and test locally.
7. Deploy to production.

## Make it look great

The default templates that AppKit provides are intentionally minimal — a starting point, not a finished product. **Do not stop there.** Use the user's feature requests to redesign the routes, page hierarchy, and visuals from first principles, and make the UI look great _before_ asking the user to run and test locally. Showing the user something polished early changes the conversation.

Unless the user has specified a design preference, use these defaults:

- shadcn/ui components on top of Tailwind CSS.
- Clean hierarchy with modern spacing — not too many stacked cards.
- Modern, minimal design language.
- Databricks brand palette: `#FF3621`, `#0B2026`, `#EEEDE9`, `#F9F7F4`.

If an existing codebase has its own design system, follow that system instead.

## When you run into issues

Use the GitHub CLI (if available) or generate a copy-pastable error report for the user to file at https://github.com/databricks/devhub/issues. Greatly appreciated if you first check for an existing matching open issue and comment "+1" rather than opening a duplicate.

---

# What the user just did

The user copied the prompt for a DevHub **recipe** — **Genie Multi-Space Selector** (https://databricks.com/devhub/templates/genie-multi-space).

A recipe is a focused, opinionated how-to for a single Databricks pattern (e.g. wiring Lakebase Change Data Feed, creating a Model Serving endpoint, persisting chat history). Recipes are designed to be dropped into an existing project or composed into a larger build. They are deliberately narrow — they solve one thing well.

Your job in this conversation is to:

1. Clarify whether the user is **integrating this recipe into an existing project** or **starting fresh from scratch**, and adapt accordingly.
2. Verify the local Databricks dev environment is ready (block below).
3. Walk the user through the recipe step by step, asking the questions the recipe itself surfaces.

## Step 1 — Clarify intent before touching code

Ask **one** question, ideally with a multiple-choice tool (see guidelines):

- **Existing project**: the user already has a Databricks app / repo and wants to add this pattern to it. → Read the user's existing project structure first; the recipe steps will be applied surgically.
- **New project from this recipe**: the user wants this recipe as the starting point of a new app. → Run the local-bootstrap below first, then follow the recipe.
- **Just learning**: the user wants to read through the recipe and understand it without building anything yet. → Walk through the steps as a tutorial; do not execute commands.
- **Not sure — help me decide**: ask the user what they're trying to accomplish at the project level, then map back to one of the above.

## Step 2 — Pin down recipe-specific decisions

Once the integration mode is clear, ask any follow-ups the recipe itself surfaces — typically about which Databricks resources to use:

- Should we **create new resources** (catalog, schema, Lakebase instance, serving endpoint) or **reuse existing ones** the user already has? Never assume; always ask.
- Which **Databricks profile** should the CLI commands target? (`databricks auth profiles` to list valid profiles.)
- If the recipe touches data: use the user's data, or use seed/sample data first?

## Step 3 — Verify the local Databricks dev environment

Whether integrating or starting fresh, the recipe's commands assume a working Databricks CLI profile and (for app-related recipes) an AppKit project. **Walk the user through the local-bootstrap block below before running any recipe commands** — even if they think the environment is already set up, the verification steps are quick and prevent confusing failures downstream.

The full recipe content the user is focused on is attached after the local-bootstrap block.

---

# Verify your local Databricks dev environment

A working Databricks CLI profile is the prerequisite for every step that follows. Walk the user through the recipe below — _even if they say their environment is already set up_. The verification steps are quick and prevent confusing failures further down.

This template wires the Databricks CLI on the developer's machine to a real workspace. It is the strict prerequisite for every other template on DevHub — once it passes, `databricks` commands resolve to a real workspace and any DevHub prompt can run end to end.

- **A Databricks workspace you can sign in to.** Have the workspace URL handy (e.g. `https://<workspace>.cloud.databricks.com`); you will paste it into `databricks auth login` in step 3. If you do not have access, ask your workspace admin.
- **A terminal on macOS, Windows, or Linux.** All install paths run from a terminal session. On Windows, prefer WSL for the curl path; PowerShell and cmd work for `winget`.
- **Permission to install software on this machine.** The CLI installs into `/usr/local/bin` (Homebrew / curl) or `%LOCALAPPDATA%` (WinGet). If `/usr/local/bin` is not writable, rerun the curl installer with `sudo`.

## Set Up Your Local Dev Environment

Install the Databricks CLI, authenticate a profile, and verify the handshake. Every other DevHub template assumes this has already passed.

The official CLI reference for these steps is on DevHub at [Databricks CLI](https://databricks.com/devhub/docs/tools/databricks-cli). Use it whenever a step here is unclear.

### 1. Check the installed CLI version

DevHub templates assume Databricks CLI `0.296+`. Anything older is missing the AppKit `apps init` template registry and several `experimental aitools` flags.

```bash
databricks -v
```

If the command is not found, or the version is below `0.296`, install or upgrade in the next step.

### 2. Install or upgrade the Databricks CLI

Pick the install path for your OS. If the CLI is already installed at an older version, the same commands upgrade in place.

#### macOS / Linux — Homebrew (recommended)

```bash
brew tap databricks/tap
brew install databricks

brew update && brew upgrade databricks
```

#### Windows — WinGet

```bash
winget install Databricks.DatabricksCLI

winget upgrade Databricks.DatabricksCLI
```

Restart your terminal after install.

#### Any platform — curl installer

```bash
curl -fsSL https://raw.githubusercontent.com/databricks/setup-cli/main/install.sh | sh
```

On Windows, run this from WSL. If `/usr/local/bin` is not writable, rerun with `sudo`. Re-running the script also upgrades an existing install.

After installing, confirm the version is `0.296+`:

```bash
databricks -v
```

### 3. Authenticate a profile

Browser-based OAuth is the default for local use:

```bash
databricks auth login
```

The CLI prints a URL and waits for the user to complete OAuth in the browser. **Always show the URL to the user as a clickable link** so they can open it themselves — the CLI does not return until authentication finishes. Credentials save to `~/.databrickscfg`.

If you already know the workspace URL and want to name the profile, do it in one go:

```bash
databricks auth login --host <workspace-url> --profile <PROFILE>
```

`<PROFILE>` is the label you will pass on subsequent commands as `--profile <PROFILE>`. If you skip `--profile`, the CLI uses the `DEFAULT` profile.

For CI/CD, OAuth client credentials or a personal access token are better fits — see the [authentication section of the CLI doc](https://databricks.com/devhub/docs/tools/databricks-cli#authenticate) for the non-interactive flows.

### 4. Verify the handshake

List the saved profiles and confirm the one you just created shows `Valid: YES`:

```bash
databricks auth profiles
```

```text
Name              Host                                           Valid
DEFAULT           https://adb-1234567890.12.azuredatabricks.net  YES
my-prod-workspace https://mycompany.cloud.databricks.com         YES
```

If the row shows `Valid: NO`, the saved token is stale. Re-run `databricks auth login --profile <NAME>` to refresh it. **Never proceed past this step if no profile is `Valid: YES`** — every downstream `databricks` command will fail with an auth error that looks like a template bug.

If the user wants a particular profile to be the default for this shell session, export it:

```bash
export DATABRICKS_CONFIG_PROFILE=<PROFILE>
```

### 5. Smoke-test the CLI against the workspace

Run a read-only API call to confirm the auth actually works (a fresh OAuth token can fail on the first real call if the user picked the wrong workspace in the browser):

```bash
databricks current-user me --profile <PROFILE>
```

A successful response prints the signed-in user's identity. A `401` or `403` here means the auth flow completed against a workspace the user cannot read — re-run `databricks auth login --profile <PROFILE>` and pick the right workspace this time.

---

# The recipe the user copied

The full recipe prompt is below. This is what the user wants to focus on today. Once the local-bootstrap above passes and the intent questions are answered, work through this content step by step.

This template upgrades an existing single-space Genie app to switch between multiple spaces. Verify these Databricks workspace features are enabled before starting. If any check fails, ask your workspace admin to enable the feature.

- **Databricks CLI authenticated.** Run `databricks auth profiles` and confirm at least one profile shows `Valid: YES`. If none do, authenticate with `databricks auth login --host <workspace-url> --profile <PROFILE>`.
- **AI/BI Genie enabled.** Run `databricks genie list-spaces --profile <PROFILE>` and confirm the command succeeds.
- **Two or more Genie spaces configured.** The list above must return at least two spaces — one per entry you want in the selector. If you have fewer, create additional spaces in **AI/BI Genie** in the Databricks UI.
- **Databricks Apps enabled.** Run `databricks apps list --profile <PROFILE>` and confirm the command succeeds.
- **A scaffolded AppKit app with the Genie feature.** Complete the [Genie Conversational Analytics](https://databricks.com/devhub/templates/genie-conversational-analytics) template first. This template only covers the upgrade from one space to many — not the initial Genie wiring.

## Genie Multi-Space Selector

Upgrade a single-space Genie app to let users switch between multiple AI/BI Genie spaces from a dropdown. Each space gets a named alias; switching spaces remounts `<GenieChat>` and clears stale conversation state automatically.

### 1. List all Genie spaces you want to include

List your spaces:

```bash
databricks genie list-spaces -o json --profile <PROFILE>
```

**Tip: Avoid repeating `--profile` on every command**

Add your profile to the bundle's `databricks.yml` under the target — then `bundle deploy` and `apps` commands pick it up automatically:

```yaml
targets:
  default:
    workspace:
      profile: <PROFILE>
```

This is more reliable than `export DATABRICKS_CONFIG_PROFILE` since it persists across shells and works for agents running commands in subshells.

Note the `space_id` and `title` for each space. Decide on a short lowercase alias for each (e.g. `sales`, `support`) — these become the keys in the server `spaces` map and in the `SPACES` array on the client. They must match exactly.

### 2. Update the server plugin

Replace the single-space `genie()` call in `server/server.ts` with a `spaces` map. Use one environment variable per space following the pattern `DATABRICKS_GENIE_SPACE_<ALIAS>`:

```typescript
import { createApp, genie, server } from "@databricks/appkit";

createApp({
  plugins: [
    server(),
    genie({
      spaces: {
        sales: process.env.DATABRICKS_GENIE_SPACE_SALES ?? "",
        support: process.env.DATABRICKS_GENIE_SPACE_SUPPORT ?? "",
      },
    }),
  ],
}).catch(console.error);
```

Each key becomes the alias for all API routes (`/api/genie/<alias>/messages`) and the `<GenieChat alias="..." />` prop. Add one entry per space.

### 3. Update configuration files

#### `.env` (local development)

Keep `DATABRICKS_GENIE_SPACE_ID` — AppKit requires it at startup even when using a custom `spaces` map. Point it at any of your spaces. Add one variable per UI space:

```bash
DATABRICKS_GENIE_SPACE_ID=<any-space-id>
DATABRICKS_GENIE_SPACE_SALES=<sales-space-id>
DATABRICKS_GENIE_SPACE_SUPPORT=<support-space-id>
```

#### `app.yaml`

Keep the `DATABRICKS_GENIE_SPACE_ID → genie-space` mapping — AppKit validates it on startup. Add one `valueFrom` per UI space:

```yaml
command: ["npm", "run", "start"]
env:
  - name: DATABRICKS_GENIE_SPACE_ID
    valueFrom: genie-space
  - name: DATABRICKS_GENIE_SPACE_SALES
    valueFrom: genie-space-sales
  - name: DATABRICKS_GENIE_SPACE_SUPPORT
    valueFrom: genie-space-support
```

#### `databricks.yml`

Keep `genie_space_id` and `genie-space` — AppKit requires `DATABRICKS_GENIE_SPACE_ID` to be set at runtime. This resource does **not** appear in the UI dropdown; only aliases in the server `spaces` map do. Add a new variable and resource for each UI space:

```yaml
variables:
  genie_space_id:
    description: Default Genie space ID (required by AppKit)
  genie_space_sales_id:
    description: Sales Genie space ID
  genie_space_support_id:
    description: Support Genie space ID

resources:
  apps:
    app:
      user_api_scopes:
        - dashboards.genie
      resources:
        - name: genie-space
          genie_space:
            name: genie-space
            space_id: ${var.genie_space_id}
            permission: CAN_RUN
        - name: genie-space-sales
          genie_space:
            name: genie-space-sales
            space_id: ${var.genie_space_sales_id}
            permission: CAN_RUN
        - name: genie-space-support
          genie_space:
            name: genie-space-support
            space_id: ${var.genie_space_support_id}
            permission: CAN_RUN

targets:
  default:
    variables:
      genie_space_id: <any-space-id>
      genie_space_sales_id: <sales-space-id>
      genie_space_support_id: <support-space-id>
```

Repeat the variable and resource block for every space you want in the UI.

### 4. Inject a build version stamp

`GenieChat` stores the active conversation ID in two places that can become stale across space switches or redeployments:

- **URL**: stored as `?conversationId=<id>`, read on every mount to replay history. When the user switches spaces, the new `GenieChat` instance reads this param and tries to fetch the old conversation through the new space's alias, resulting in `NOT_FOUND`.
- **localStorage**: `appkit:genie:*` keys for related state. After a redeployment, stored IDs may no longer exist in the Genie backend, resulting in `NOT_FOUND`.

Stamping every build with a timestamp lets the page detect a new deployment and clean up before `GenieChat` mounts.

In `client/vite.config.ts`, add a `define` block alongside your existing config:

```typescript
export default defineConfig({
  // ... existing config ...
  define: {
    // Changes on every build so the page can detect a new deployment
    // and clear stale conversation state before GenieChat mounts.
    "import.meta.env.VITE_APP_VERSION": JSON.stringify(Date.now().toString()),
  },
});
```

### 5. Replace the Genie page

Replace the contents of `client/src/pages/genie/GeniePage.tsx` with the multi-space version below.

`clearConversationUrl` strips `?conversationId` from the URL before the alias state changes, so the newly mounted `GenieChat` instance always starts without a stale cross-space conversation reference.

`initAlias` runs once at component mount. On build-version mismatch it wipes all `appkit:genie:*` localStorage keys and clears the URL param, then restores the user's last-selected alias before returning it as initial state.

```tsx
import { useState } from "react";
import { GenieChat } from "@databricks/appkit-ui/react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@databricks/appkit-ui/react";

const SPACES = [
  { alias: "sales", label: "Sales Analytics" },
  { alias: "support", label: "Support Analytics" },
];

const VERSION_KEY = "appkit:genie:version";
const ALIAS_KEY = "appkit:genie:alias";

function clearConversationUrl() {
  const url = new URL(window.location.href);
  url.searchParams.delete("conversationId");
  window.history.replaceState({}, "", url.toString());
}

function initAlias(): string {
  const buildVersion = import.meta.env.VITE_APP_VERSION ?? "dev";

  if (localStorage.getItem(VERSION_KEY) !== buildVersion) {
    const savedAlias = localStorage.getItem(ALIAS_KEY);
    Object.keys(localStorage)
      .filter((k) => k.startsWith("appkit:genie:"))
      .forEach((k) => localStorage.removeItem(k));
    localStorage.setItem(VERSION_KEY, buildVersion);
    if (savedAlias) localStorage.setItem(ALIAS_KEY, savedAlias);
    clearConversationUrl();
  }

  return localStorage.getItem(ALIAS_KEY) ?? SPACES[0]?.alias ?? "";
}

export function GeniePage() {
  const [selectedAlias, setSelectedAlias] = useState(initAlias);

  return (
    <div className="space-y-6 w-full max-w-4xl mx-auto">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-foreground">Genie</h2>
          <p className="text-sm text-muted-foreground mt-1">
            Ask questions about your data using Databricks AI/BI Genie.
          </p>
        </div>
        <Select
          value={selectedAlias}
          onValueChange={(alias) => {
            clearConversationUrl();
            setSelectedAlias(alias);
            localStorage.setItem(ALIAS_KEY, alias);
          }}
        >
          <SelectTrigger className="w-52">
            <SelectValue placeholder="Select space" />
          </SelectTrigger>
          <SelectContent>
            {SPACES.map((space) => (
              <SelectItem key={space.alias} value={space.alias}>
                {space.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <div className="h-[600px] border rounded-lg overflow-hidden">
        <GenieChat key={selectedAlias} alias={selectedAlias} />
      </div>
    </div>
  );
}
```

No changes are needed in `client/src/App.tsx` — the import, nav link, and route from the single-space setup carry over unchanged.

### 6. Deploy and test

From the app project directory (the folder containing `databricks.yml`):

```bash
# Build the client
npm run build

# Deploy bundle resources and sync files to workspace
# Copy the upload path printed in the output — you'll need it below
databricks bundle deploy

# Put the app in RUNNING state and wait for compute to be ready
# The loop polls every 5 seconds — press Ctrl+C if it hangs more than 2 minutes
databricks apps start <app-name>
until databricks apps get <app-name> -o json | grep -q '"ACTIVE"'; do sleep 5; done

# First deploy requires --source-code-path: paste the path from bundle deploy output above
databricks apps deploy <app-name> \
  --source-code-path <path-from-bundle-deploy-output>
```

`bundle deploy` prints the workspace upload path (`Uploading bundle files to ...`) — copy that value for `--source-code-path`. `apps start` puts the app into RUNNING state; the `until` loop waits for compute to be ACTIVE. `apps deploy` deploys the source and starts the app server.

For subsequent deploys, `--source-code-path` is not needed. Run both `bundle deploy` and `apps deploy` when changing `databricks.yml`; for client-only changes, `apps deploy` alone is sufficient after `npm run build`:

```bash
npm run build
databricks bundle deploy
databricks apps deploy <app-name>
```

Check app status and get the URL:

```bash
databricks apps get <app-name>
```

If compute is **STOPPED**, run `databricks apps start <app-name>` and wait for `compute_status.state: ACTIVE` before deploying.

Open `<app-url>/genie` while signed in to Databricks and verify:

1. The space selector shows all configured spaces
2. Asking a question routes to the correct space
3. Switching spaces resets the conversation with no `NOT_FOUND` error
4. Reloading the page restores the last selected space and replays the conversation
5. After redeploying, stale conversation IDs are automatically cleared on the next page load

#### References

- [Genie plugin docs](https://databricks.com/devhub/docs/appkit/v0/plugins/genie)
- [GenieChat component](https://databricks.com/devhub/docs/appkit/v0/api/appkit-ui/genie/GenieChat)
- [AI/BI Genie documentation](https://docs.databricks.com/en/genie/index.html)
