# Set up Foxchat in this project

> Instructions for AI coding agents (Claude Code, Cursor, Codex, Windsurf, Copilot, etc.).
> The user asked you to add Foxchat to their project. Follow these steps in order.
> You will need the user exactly once, to sign in and approve access in their browser.

Foxchat is a live chat widget for websites. Visitors chat through a bubble on the site, the team replies from Slack or the Foxchat inbox. Installing it means adding one `<script>` tag to the site, tied to a Foxchat **project**.

You will:

1. Get access to the user's Foxchat account (device login: the user approves in the browser).
2. Find or create the Foxchat project for this codebase.
3. Allow the site's domains (production + `localhost` for development).
4. Add the embed script to the right file for the framework.
5. Give the user a short summary with the link to connect Slack.

**API base URL:** `https://www.foxchat.dev/api/agent`

All endpoints take and return JSON. Errors look like `{ "error": "code", "message": "..." }`. The `message` is written for humans: when something fails, show it to the user.

## Rules

- **Never write the access token or device code into the project**: not in source files, `.env` files, commits, or logs you add. Keep them in your shell session or in a temp file outside the repository, and delete that file at the end.
- Don't print the access token back to the user.
- If the project already contains a Foxchat script (`cdn.foxchat.dev/widget/loader.js`), don't add a second one. Ask whether to replace the `data-project-id` or leave it as is.
- If the project already has another chat widget (Intercom, Crisp, Drift, Tawk, HubSpot chat…), ask the user before removing it. Never remove it silently.
- Make the smallest change that works. Don't reformat unrelated code.
- Don't run `git commit` or `git push` unless the user asks.

---

## Step 1: Connect to the user's Foxchat account

Request a device code. Set `client_name` to your own name, which is shown to the user on the approval screen:

```bash
curl -s -X POST https://www.foxchat.dev/api/agent/device \
  -H "Content-Type: application/json" \
  -d '{"client_name": "Claude Code"}'
```

Response:

```json
{
  "device_code": "fcd_…",
  "user_code": "BCDF-GHJK",
  "verification_url": "https://app.foxchat.dev/device?code=BCDF-GHJK",
  "interval": 5,
  "expires_in": 900
}
```

Then **tell the user**, as a message on its own:

> To connect Foxchat, open **{verification_url}** in your browser. Sign up for free (or log in) and click **Approve**. The code shown should be **{user_code}**. I'll continue automatically once you approve.

New accounts get a 14-day free trial with no credit card. Signing up verifies the user's email with a code, so approval can take a couple of minutes.

Now poll for the token every `interval` seconds:

```bash
curl -s -X POST https://www.foxchat.dev/api/agent/token \
  -H "Content-Type: application/json" \
  -d '{"device_code": "fcd_…"}'
```

| HTTP | `status` / `error` | What to do |
|---|---|---|
| 202 | `pending` | Not approved yet. Wait `interval` seconds and poll again. |
| 200 | `approved` | Done. Save `access_token`; it is shown only once and valid for 24 hours. |
| 403 | `access_denied` | The user clicked Deny. Stop and ask what they want to do. |
| 410 | `expired_token` | The code expired after 15 minutes. Start Step 1 again. |
| 410 | `already_used` | This code was already exchanged. Start Step 1 again. |

If your tool calls time out, poll in a bounded loop, for example up to ~2 minutes per command, and run it again while the status is still `pending`:

```bash
for i in $(seq 1 24); do
  R=$(curl -s -X POST https://www.foxchat.dev/api/agent/token -H "Content-Type: application/json" -d '{"device_code": "fcd_…"}')
  echo "$R" | grep -q '"pending"' || { echo "$R"; break; }
  sleep 5
done
```

Use the token on every following request:

```
Authorization: Bearer fc_…
```

## Step 2: Find or create the project

```bash
curl -s https://www.foxchat.dev/api/agent/me -H "Authorization: Bearer $FOXCHAT_TOKEN"
```

The response contains `user`, `account` and `projects`:

- `account.active`: if `false`, the trial or subscription has ended. Show `account.message` and `billingUrl` to the user and stop until they've upgraded.
- `projects[]`: each has `slug`, `name`, `websiteUrl`, `allowedDomains`, `slackConnected`, `widgetSeen`, `embedSnippet`, `dashboardUrl`, `slackConnectUrl`.

**Work out this site's name and production URL from the codebase.** Look at:

- `package.json`: `name`, `homepage`
- the README
- framework config: `site` in `astro.config.*`, `metadataBase` in a Next.js layout, `url` in `nuxt.config.*`, `docusaurus.config.*`, `hugo.toml` / `config.toml` (`baseURL`), `_config.yml` (`url`)
- `CNAME`, `vercel.json`, `netlify.toml`, `<link rel="canonical">` or `og:url` tags.

If you can't determine the production URL with confidence, ask the user for it. This is the only question you should need to ask.

**Then decide:**

- If an existing project's `websiteUrl` or `allowedDomains` matches this site's domain, **reuse it**.
- Otherwise, create a new project:

```bash
curl -s -X POST https://www.foxchat.dev/api/agent/projects \
  -H "Authorization: Bearer $FOXCHAT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "Acme", "websiteUrl": "https://acme.com"}'
```

`name` should be the product name, human readable, max 50 characters. The production domain is added to the allowed domains automatically. The response is the project, including `slug` and `embedSnippet`. An account can have up to 5 projects. If the limit is reached, show the error to the user.

## Step 3: Allow development domains

The widget only renders on allowed domains (subdomains are included automatically). Add `localhost` so the user can see it while developing. Also add any other domains you found, such as a staging domain or a custom preview domain. Don't add generic hosting domains like `vercel.app` or `netlify.app`, because that would allow every site on them.

```bash
curl -s -X POST https://www.foxchat.dev/api/agent/projects/{slug}/domains \
  -H "Authorization: Bearer $FOXCHAT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"domains": ["localhost"]}'
```

Domains are merged into the existing list. You can send hostnames or full URLs; ports and paths are stripped. The maximum is 10 domains.

## Step 4: Add the embed script

The embed snippet (also returned as `embedSnippet`):

```html
<script src="https://cdn.foxchat.dev/widget/loader.js" data-project-id="{slug}"></script>
```

`data-project-id` is the project **slug**. Detect the framework and add the script once, so it loads on every page:

| Framework (how to detect) | File | How |
|---|---|---|
| Next.js App Router (`next` dep + `app/layout.*`) | `app/layout.tsx` (or `src/app/…`) | `next/script` inside `<body>` (see below) |
| Next.js Pages Router (`next` dep + `pages/`) | `pages/_document.tsx` (create if missing) or `pages/_app.tsx` | `next/script` inside `<body>` |
| Vite: React / Vue / Svelte / Solid / Preact (`vite` dep + root `index.html`) | `index.html` | Plain `<script>` before `</body>` |
| Create React App (`react-scripts`) | `public/index.html` | Plain `<script>` before `</body>` |
| Astro | Base layout, e.g. `src/layouts/Layout.astro` | `<script is:inline src="…" data-project-id="…"></script>` before `</body>`. `is:inline` is required. |
| Remix / React Router v7 framework mode | `app/root.tsx` | `<script src="…" data-project-id="…" />` inside `<body>` |
| Nuxt | `nuxt.config.ts` | `app.head.script` entry (see below) |
| SvelteKit | `src/app.html` | Plain `<script>` before `</body>` |
| Angular | `src/index.html` | Plain `<script>` before `</body>` |
| Gatsby | `gatsby-ssr.js` | `setPostBodyComponents` with a `<script>` element |
| Docusaurus | `docusaurus.config.js` | `scripts: [{ src: "…", "data-project-id": "…", async: true }]` |
| Hugo / Jekyll / Eleventy / plain HTML | Base layout or footer partial (`layouts/partials/footer.html`, `_includes/footer.html`, `_layouts/default.html`, `index.html`) | Plain `<script>` before `</body>` |
| Rails / Django / Laravel / Phoenix / Express templates | Main layout (`application.html.erb`, `base.html`, `app.blade.php`, `root.html.heex`, …) | Plain `<script>` before `</body>` |
| WordPress theme | `footer.php` | Plain `<script>` before `wp_footer()` / `</body>` |
| Shopify theme | `layout/theme.liquid` | Plain `<script>` before `</body>` |

If the project is a monorepo, install into the app that serves the public website or product (ask if it's ambiguous). If it isn't a website at all (a library, CLI or API-only backend), stop and tell the user.

**Next.js App Router:**

```tsx
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script
          src="https://cdn.foxchat.dev/widget/loader.js"
          data-project-id="{slug}"
          strategy="afterInteractive"
        />
      </body>
    </html>
  );
}
```

**Nuxt:**

```ts
export default defineNuxtConfig({
  app: {
    head: {
      script: [
        { src: "https://cdn.foxchat.dev/widget/loader.js", "data-project-id": "{slug}", defer: true },
      ],
    },
  },
});
```

If the site has a Content-Security-Policy, allow `https://cdn.foxchat.dev` in `script-src`. Also allow `https://*.convex.cloud` and `wss://*.convex.cloud` in `connect-src`.

### Optional: identify logged-in visitors

If the app has signed-in users **and** the user's name and email are available when the page renders (for example a server-rendered layout with the session), you can set `window.FoxchatSettings` **before** the widget script. Visitors then skip the pre-chat form:

```html
<script>
  window.FoxchatSettings = { name: "Jane Doe", email: "jane@example.com", metadata: { userId: "123" } };
</script>
```

All `metadata` values must be strings. If wiring this requires more than a small, obvious change, skip it and mention it in your summary instead (docs: https://www.foxchat.dev/docs/visitor-identity).

## Step 5: Verify and summarize

1. Run the project's type-check, lint or build if one is quick, to make sure your edit compiles.
2. Optionally check the project status. `widgetSeen` becomes `true` once a visitor has started a chat through the widget:

```bash
curl -s https://www.foxchat.dev/api/agent/projects/{slug}/status -H "Authorization: Bearer $FOXCHAT_TOKEN"
```

3. Delete any temp file where you stored the token.
4. Finish with a short summary for the user:
   - Which file(s) you changed and the project slug.
   - The allowed domains.
   - **Next step, connect Slack** to get messages in Slack and reply from there: `slackConnectUrl` (one click, done in the browser). Without Slack, messages still arrive in the Foxchat inbox at `dashboardUrl`.
   - How to try it: run the dev server and look for the chat bubble in the bottom-right corner.
   - Customization (colors, position, welcome message, hiding on paths) lives at `widgetSettingsUrl`.

## Troubleshooting

| Symptom | Fix |
|---|---|
| Widget doesn't appear | The current hostname isn't in allowed domains: add it (Step 3). Or the slug is wrong. |
| Console says "Domain validation failed" | Same as above. |
| `401 unauthorized` | Token missing, wrong or expired (24h). Start again at Step 1. |
| `429 rate_limited` | Too many device codes requested. Reuse the existing code or wait. |
| Messages don't reach Slack | Slack isn't connected, or no default channel is selected: open `slackConnectUrl`. |

More: https://www.foxchat.dev/llms-full.txt · Docs: https://www.foxchat.dev/docs
