# For coding AIs

> **In short.** This page is written for AI coding agents (Claude Code, Cursor, Copilot, Codex and
> the like) adding Junco to a project. Follow it top to bottom. You need two values from the
> human: the product's **public key** (`jk_...`) and Junco's **server address**
> (`https://desk.juncodesk.app`). For a website or web game, add one script and one `Junco.init` call. For
> anything else, link the hosted page or call the HTTP API. Then send a test ticket.

If you're a person, copy this into your coding AI inside your project, with your product's key in
place of `jk_YOUR_PUBLIC_KEY`. Junco's desk gives you a longer one with your details already filled
in: a product's page, **Install**, **Ask your AI**.

```prompt
Add the Junco support form to this project. Follow https://desk.juncodesk.app/docs/for-ai-agents.md (plain Markdown) step by step.

Public key: jk_YOUR_PUBLIC_KEY
Junco server: https://desk.juncodesk.app

Ask me for anything else that guide says you need. When it's done, send a test ticket and tell me what you changed and anything I need to do myself.
```

## 1. Get what you need from the human

You can't make these yourself; they come from the product's page on Junco's desk. Ask for any you
don't have, in one message:

| Value | Looks like | Needed for | Secret? |
|---|---|---|---|
| Public key | `jk_` + about 20 characters | Everything | **No.** Safe in client code. |
| Junco server | `https://desk.juncodesk.app` | Everything | No |
| The site's web addresses | `https://example.com` | Web: each must be listed on the product in Junco, exactly (scheme, host and port if any; no path), or the form is refused. `https://` only, except `http://localhost:<port>` and `http://127.0.0.1:<port>` for development. Up to 20. | No |
| Do users sign in? | yes / no | Choosing how users are recognised | |
| Signing key | a `.pem` file, Ed25519 private key | Only if users sign in and the human wants tickets to follow accounts | **Yes.** Server only. |
| Release key | `jr_...` | Only for telling users from a deploy script that fixes are live | **Yes.** CI secrets only. |

If the human has no Junco account: Junco is invite only for now; they ask for an invite on
Junco's website. You can still write the code with a placeholder key and tell them.

## 2. Pick the way in

Look at the project and choose one:

| The project is | Do this |
|---|---|
| A website, web app or web game (any framework: plain HTML, React, Next.js, Vue, Nuxt, Svelte, SvelteKit, Angular, Phaser, PixiJS, three.js, Babylon.js, Godot or Unity **web export**) | **The widget.** Section 3. |
| An Electron or Tauri app | If its window loads an `https://` site, the widget (section 3). If it loads local files (`file://`, `app://`, `tauri://`), Junco can't allow that origin: use the hosted page, or the API from the main process (section 4). |
| A phone app (Swift, Kotlin, Flutter, React Native), a desktop or console game, a native Unity/Godot/Unreal build | **The hosted page** (no code: open a URL) or **the API** (your own form). Section 4. |
| A Discord server, store page or docs site | **The hosted page**: a link. Section 4. |
| A backend only | Usually nothing; if it should report problems itself, use the API with a signed token. |

## 3. Websites and web games: the widget

### 3.1 Load and start it once

Add this where the app starts, on every page that should have support. Call `Junco.init` exactly
once per page load; later calls are ignored.

```html
<script src="https://desk.juncodesk.app/widget/junco.js"></script>
<script>
  Junco.init({
    game: "jk_YOUR_PUBLIC_KEY",
    server: "https://desk.juncodesk.app",
    context: () => ({ version: APP_VERSION, page: location.pathname }),
  });
</script>
```

In a bundled app (React, Vue, Svelte and so on), load the script at runtime instead of importing
it. There's no npm package. A helper that works everywhere, including with server-side rendering:

```js
// junco.js: load Junco's widget once, in the browser only.
let loading;
export function startJunco(options) {
  if (typeof window === "undefined") return Promise.resolve(null); // server-side render: skip
  loading ??= new Promise((resolve, reject) => {
    const s = document.createElement("script");
    s.src = `${options.server}/widget/junco.js`;
    s.async = true;
    s.onload = () => resolve(window.Junco.init(options));
    s.onerror = () => reject(new Error("Couldn't load Junco"));
    document.head.append(s);
  });
  return loading;
}
```

Call `startJunco({...})` from the app's root once mounted: `useEffect(() => { startJunco(...) }, [])`
in React or Next.js (in a `"use client"` component), `onMounted` in Vue, `onMount` in Svelte.
Recipes per framework: [Installing the form](/docs/install).

**Options are read once**, at init. To send what's current when the user opens the form, pass
**functions** that read the current state (`context: () => store.getState()...`), not values.

### 3.2 Put it where users look for help

- If the app has a help, menu, settings or account area, add a **Support** (or **Help**) item
  there that calls `Junco.open()`, and pass `button: false` to hide Junco's own round button.
- `Junco.open({ type: "bug" })` opens straight to a bug report (`"idea"`, `"help"` too).
- If there's no sensible place, leave `button` out: Junco shows a small round button in the
  bottom right corner.

### 3.3 Send useful context, never personal details

`context` returns a plain object (under 16 KB as JSON) the team sees with the ticket and the AI
reads. Good things to send: app version or build, current screen or route, platform and browser,
screen size, language, relevant settings, the user's current level or place, feature flags,
recent errors. **Never** send passwords, tokens, cookies, emails, phone numbers, addresses or
payment details.

```js
context: () => ({
  version: "1.4.2",
  screen: router.currentRoute,
  device: navigator.userAgent,
  viewport: `${innerWidth}x${innerHeight}`,
  language: navigator.language,
  level: game.level?.id,
}),
```

### 3.4 Screenshots, saves and logs (games especially)

All optional, all callbacks, called when needed; each may return a promise.

```js
screenshot: () => new Promise((resolve) => {
  // A canvas game. WebGL needs preserveDrawingBuffer: true, or call this right after a render.
  const c = document.querySelector("canvas");
  const scale = Math.min(1, 1280 / c.width);
  const out = document.createElement("canvas");
  out.width = Math.round(c.width * scale);
  out.height = Math.round(c.height * scale);
  out.getContext("2d").drawImage(c, 0, 0, out.width, out.height);
  out.toBlob(resolve, "image/jpeg", 0.8);
}),
save: () => JSON.stringify(game.saveData()),   // up to 1 MB
log: () => recentLogLines.join("\n"),          // up to 512 KB, text
```

The screenshot is taken when the panel opens, before it covers the screen; the user chooses
whether to attach it. Keep it a JPEG at most 1280 px wide (it must be under 2 MB).

### 3.5 Signed-in users (optional)

Without anything extra, Junco recognises a user by a random id kept in their browser. If the app
has accounts and the human wants tickets to follow the account across devices:

1. On the **server**, add an endpoint (e.g. `GET /api/junco-token`) that returns a token for the
   signed-in user, signed with the `.pem` key from an environment variable (`JUNCO_SIGNING_KEY`).
   Code for Node, Python, Go, PHP and others: [Signed user tokens](/docs/user-tokens).
2. In the browser: `playerToken: () => fetch("/api/junco-token").then((r) => (r.ok ? r.text() : null))`.

Never put the private key in client code or the repo.

### 3.6 Content Security Policy

If the project sets a CSP (a meta tag, a header in server config, `next.config.js`, `helmet`,
Netlify/Vercel headers), add `https://desk.juncodesk.app` to `script-src` and `connect-src`. Nothing else is
needed: the widget uses no inline scripts, no iframes and no third parties.

### 3.7 Unread badge (optional)

If the app shows notification badges: `onUnread: (n) => setSupportBadge(n)`. Junco calls it with
the number of tickets that have replies the user hasn't read.

## 4. Everything else: hosted page or API

**Hosted page (no code).** The human turns on "Junco's support page" on the product's page in
Junco; then open `https://desk.juncodesk.app/s/jk_YOUR_PUBLIC_KEY` from a Help or Support menu item, in the system
browser or an in-app browser (`SFSafariViewController`, Custom Tabs, `Application.OpenURL`,
`OS.shell_open`, `url_launcher`, `Linking.openURL`). It remembers the user in that browser. It
can't receive game state or signed-in identity; for those, use the API.

**API (your own form).** Four calls: raise a ticket, list tickets, read one, reply. Make a random
id once per install and keep it. Complete examples for Unity, Godot, Swift, Kotlin, Flutter and
React Native: [Apps, engines and desktop](/docs/platforms). Reference: [API](/docs/api) and
`https://desk.juncodesk.app/openapi.json`.

## 5. Check it works

1. Run the app, open the form, send a **bug** report saying "Junco test".
2. You should see the thread with your message and, if the AI is on for the product, its reply
   within a few seconds (typing dots while it writes).
3. The product's page in Junco now says **Connected**. Ask the human to check.

From a terminal, the same test without a browser (a random id, no `Origin` header):

```sh
curl -s -X POST https://desk.juncodesk.app/v1/games/jk_YOUR_PUBLIC_KEY/tickets \
  -H "Content-Type: application/json" \
  -H "X-Junco-Player: $(head -c 24 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=')" \
  -d '{"type":"bug","text":"Junco test from the command line"}'
```

If something fails, look the message up in [Troubleshooting](/docs/troubleshooting). The common
ones: `This page isn't allowed to use this game's support` (the page's origin isn't listed on the
product in Junco), a CSP error in the console, `This game needs a player token`.

## 6. Rules

- **Don't** put the signing key (`.pem`) or a release key (`jr_...`) in client code, the repo or
  logs. The public key (`jk_...`) is fine anywhere.
- **Don't** put the form in an iframe, restyle it or reach into it: it lives in a closed shadow
  root and is built to be left alone.
- **Don't** send personal details in `context`.
- **Don't** copy `junco.js` into the repo unless the project's CSP or offline needs demand it;
  loading it from `https://desk.juncodesk.app` keeps it up to date.
- **Do** call `Junco.init` once, with functions for anything that changes.
- **Do** tell the human at the end: what you changed, which web addresses must be listed on the
  product in Junco, any secret they must add to the server's environment, and to turn on the
  hosted page if you linked to it.

## 7. TypeScript

There's no types package; add this declaration if the project uses TypeScript:

```ts
// junco.d.ts
type JuncoMaybe<T> = T | null | undefined | Promise<T | null | undefined>;
interface JuncoOptions {
  game: string;
  server?: string;
  context?: () => JuncoMaybe<Record<string, unknown>>;
  screenshot?: () => JuncoMaybe<Blob>;
  save?: () => JuncoMaybe<Blob | string>;
  log?: () => JuncoMaybe<string>;
  playerToken?: () => JuncoMaybe<string>;
  handle?: () => JuncoMaybe<string>;
  button?: boolean;
  onUnread?: (count: number) => void;
}
interface JuncoApi {
  version: string;
  init(options: JuncoOptions): JuncoApi;
  open(options?: { type?: "bug" | "idea" | "help" }): Promise<void> | undefined;
  close(): void;
}
declare global {
  interface Window { Junco: JuncoApi }
  const Junco: JuncoApi;
}
export {};
```

Full details of every option: [Widget reference](/docs/widget).
