# Setting up Pulse: instructions for coding agents

You are a coding agent, and your user wants the Pulse voice feedback widget in their website or React Native app. Follow these steps in order. Do the code changes yourself. Where a step says the user must do something, ask them and wait.

Pulse adds a "Feedback" button. Customers tap it, record a voice note (or type), and the business reads the transcript in Pulse. The full guide is at https://www.pulseapp.click/docs/widget.md.

## 1. Work out the stack

Read `package.json` and the project layout. Use the website steps for Next.js, React (Vite), Astro, Vue or Nuxt, or plain HTML. Use the React Native steps for Expo or bare React Native. For WordPress, Webflow or Framer there is no code to change: tell the user to paste the HTML snippet into the site's custom code box, before `</body>`.

## 2. Get the widget key

The user must do this: ask them to open https://www.pulseapp.click/settings, turn on the website widget, and send you the `data-key` value from the install code. It starts with `pk_`. Never make one up. The key is public, like a publishable API key, so it can go straight into source code. Below, replace `pk_your_key` with it.

For a website, ask them in the same message to list each site that will show the widget, on the same Settings page: one origin per line, such as `https://example.com`, plus `http://localhost:3000` (with the real port) to try it locally. The panel won't open on a site that isn't listed, and you can't do this for them. Apps don't need listing.

## 3a. Website

Add the snippet for the stack, once, so it loads on every page. Add it to the existing root layout or entry file; don't replace the file. With the Next.js Pages Router, put the `<Script>` in `pages/_app.tsx`.

### HTML

```
<!-- Paste before </body> -->
<script src="https://www.pulseapp.click/widget.js" data-key="pk_your_key" async></script>
```

### Next.js

```
// app/layout.tsx: next/script works in a Server Component.
import Script from 'next/script'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script
          src="https://www.pulseapp.click/widget.js"
          data-key="pk_your_key"
          strategy="afterInteractive"
        />
      </body>
    </html>
  )
}
```

### React (Vite)

```
<!-- index.html, before </body> -->
<script src="https://www.pulseapp.click/widget.js" data-key="pk_your_key" async></script>
```

### Astro

```
---
// src/layouts/Layout.astro
---
<body>
  <slot />
  <script
    is:inline
    src="https://www.pulseapp.click/widget.js"
    data-key="pk_your_key"
    async
  ></script>
</body>
```

### Vue / Nuxt

```
<!-- Vue: index.html, before </body> -->
<script src="https://www.pulseapp.click/widget.js" data-key="pk_your_key" async></script>

// Nuxt: nuxt.config.ts
export default defineNuxtConfig({
  app: {
    head: {
      script: [
        {
          src: 'https://www.pulseapp.click/widget.js',
          async: true,
          'data-key': "pk_your_key",
          tagPosition: 'bodyClose',
        },
      ],
    },
  },
})
```

If the project sends a Content-Security-Policy, add `https://www.pulseapp.click` to its `script-src` and `frame-src`. If it sends a Permissions-Policy, allow `microphone=("https://www.pulseapp.click")`, or recording fails. Keep what is already there.

If the app has signed-in users, ask the user whether notes should say who sent them. If yes, call `identify` in the browser once the user is known:

```js
window.PulseQueue = window.PulseQueue || []
PulseQueue.push(['identify', { id: user.id, email: user.email }])
```

In Next.js, do it from a Client Component rendered in the layout:

```tsx
// app/pulse-user.tsx
'use client'

import { useEffect } from 'react'

declare global {
  interface Window {
    PulseQueue?: { push(call: [string, unknown?]): unknown }
  }
}

export function PulseUser({ id, email }: { id: string; email?: string }) {
  useEffect(() => {
    window.PulseQueue ??= []
    window.PulseQueue.push(['identify', { id, email }])
  }, [id, email])
  return null
}
```

## 3b. React Native

Install the WebView: `npx expo install react-native-webview` with Expo, or `npm install react-native-webview` and then `npx pod-install` without Expo. Use the project's package manager.

Create this component, in the folder the project keeps components in:

```tsx
// components/pulse-feedback.tsx
import { useRef, useState } from 'react'
import type { ComponentRef } from 'react'
import {
  Linking,
  Modal,
  Platform,
  Pressable,
  StatusBar,
  processColor,
  Text,
  View,
  useColorScheme,
} from 'react-native'
import { WebView } from 'react-native-webview'

const PULSE = 'https://www.pulseapp.click'

type SheetProps = {
  siteKey: string
  open: boolean
  onClose: () => void
  /** Title above the recorder, up to 120 characters. */
  heading?: string
  user?: { id: string; email?: string }
  context?: { appVersion?: string } & Record<string, string | undefined>
  onSent?: () => void
}

/** The recorder in a sheet. Open it from any button of your own. */
export function PulseFeedbackSheet({ siteKey, open, onClose, heading, user, context = {}, onSent }: SheetProps) {
  const webView = useRef<ComponentRef<typeof WebView>>(null)
  const { appVersion, ...custom } = context
  // The × and the iOS dismiss can both report one close; tell the app once.
  const close = () => {
    if (open) onClose()
  }

  const sendContext = () => {
    const message = {
      type: 'pulse:context',
      context: { userId: user?.id, userEmail: user?.email, appVersion, custom },
    }
    webView.current?.injectJavaScript(`window.postMessage(${JSON.stringify(message)}, '*'); true;`)
  }

  return (
    <Modal
      visible={open}
      animationType="slide"
      presentationStyle="pageSheet"
      onRequestClose={close}
      onDismiss={close}
      statusBarTranslucent
    >
      <View style={{ flex: 1, paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0 }}>
        <WebView
          ref={webView}
          source={{
            uri: `${PULSE}/embed/${siteKey}${heading ? `?heading=${encodeURIComponent(heading)}` : ''}`,
            // Shows the close button inside the page, and lets it use the heading.
            headers: { 'x-pulse-app': '1' },
          }}
          mediaCapturePermissionGrantType="grantIfSameHostElsePrompt"
          allowsInlineMediaPlayback
          onShouldStartLoadWithRequest={(request) => {
            // Links out of the recorder, such as the privacy policy, open in the browser.
            if (request.isTopFrame === false || request.url.startsWith(`${PULSE}/embed/`)) return true
            Linking.openURL(request.url).catch(() => {})
            return false
          }}
          onMessage={(event) => {
            let type: unknown
            try {
              type = JSON.parse(event.nativeEvent.data).type
            } catch {
              return // Not a message from Pulse.
            }
            if (type === 'pulse:ready') sendContext()
            if (type === 'pulse:sent') onSent?.()
            if (type === 'pulse:close') close()
          }}
        />
      </View>
    </Modal>
  )
}

type Props = Omit<SheetProps, 'open' | 'onClose'> & {
  /** Button text, up to 40 characters. Read out by screen readers for the circle. */
  label?: string
  shape?: 'pill' | 'square' | 'circle' | 'bubble'
  /** 'auto' is black or white against the phone's light or dark mode. Or any colour. */
  color?: string
  position?: 'right' | 'left'
}

/** Black or white, whichever reads better on the given colour. */
const textOn = (color: string) => {
  const argb = Number(processColor(color)) >>> 0
  const [r, g, b] = [16, 8, 0].map((shift) => (argb >> shift) & 255)
  return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.6 ? '#111111' : '#ffffff'
}

/** A floating button, styled like the website widget, that opens the sheet. */
export function PulseFeedback({
  label = 'Feedback',
  shape = 'pill',
  color = 'auto',
  position = 'right',
  ...sheet
}: Props) {
  const [open, setOpen] = useState(false)
  const dark = useColorScheme() === 'dark'

  const fill = color === 'auto' ? (dark ? '#ffffff' : '#111111') : color
  const text = color === 'auto' ? (dark ? '#111111' : '#ffffff') : textOn(color)
  const edge = color === 'auto' ? fill : '#111111'
  const tail = position === 'right' ? 'borderBottomRightRadius' : 'borderBottomLeftRadius'
  const shapeStyle = {
    pill: { paddingVertical: 14, paddingHorizontal: 20, borderRadius: 999 },
    square: { paddingVertical: 14, paddingHorizontal: 18, borderRadius: 6 },
    circle: { width: 56, height: 56, borderRadius: 999 },
    bubble: { paddingVertical: 14, paddingHorizontal: 20, borderRadius: 20, [tail]: 4 },
  }[shape]

  return (
    <>
      <Pressable
        accessibilityRole="button"
        accessibilityLabel={shape === 'circle' ? label.trim().slice(0, 40) || 'Feedback' : undefined}
        onPress={() => setOpen(true)}
        style={({ pressed }) => [
          {
            position: 'absolute',
            bottom: 20,
            [position]: 20,
            minHeight: 44,
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: fill,
            borderWidth: 2,
            borderColor: edge,
            shadowColor: edge === '#ffffff' ? '#ffffff' : '#111111',
            shadowOffset: { width: 3, height: 3 },
            shadowOpacity: edge === '#ffffff' ? 0.35 : 1,
            shadowRadius: 0,
            elevation: 4,
            transform: [{ scale: pressed ? 0.96 : 1 }],
          },
          shapeStyle,
        ]}
      >
        {shape === 'circle' ? (
          // A microphone: capsule, cup and stand.
          <View style={{ alignItems: 'center' }}>
            <View style={{ width: 8, height: 13, borderRadius: 4, borderWidth: 2, borderColor: text }} />
            <View
              style={{
                width: 14,
                height: 7,
                marginTop: -4,
                borderWidth: 2,
                borderTopWidth: 0,
                borderColor: text,
                borderBottomLeftRadius: 7,
                borderBottomRightRadius: 7,
              }}
            />
            <View style={{ width: 2, height: 4, backgroundColor: text }} />
          </View>
        ) : (
          <Text style={{ color: text, fontSize: 15, fontWeight: '700' }}>{label.trim().slice(0, 40) || 'Feedback'}</Text>
        )}
      </Pressable>
      <PulseFeedbackSheet {...sheet} open={open} onClose={() => setOpen(false)} />
    </>
  )
}
```

It floats in the bottom corner, like the website button. Ask the user which screens should show it if it isn't obvious, then render it once in each, as the last child of a view that fills the screen:

```tsx
<PulseFeedback siteKey="pk_your_key" />
```

If the user wants an existing button, menu item or screen to open the recorder instead, render `PulseFeedbackSheet` with `open` and `onClose` and open it from there, rather than the floating `PulseFeedback`. If the user wants the floating button to match their website button, copy its `data-label`, `data-shape`, `data-color`, `data-position` and `data-heading` into the `label`, `shape`, `color`, `position` and `heading` props. If the app has signed-in users, pass `user={{ id, email }}`, and `context={{ appVersion }}` if the version is easy to read.

Recording needs microphone permission. With Expo, merge this into `app.json` (or the equivalent keys in `app.config.*`), keeping what is there:

```json
{
  "expo": {
    "ios": {
      "infoPlist": {
        "NSMicrophoneUsageDescription": "Record voice feedback"
      }
    },
    "android": {
      "permissions": ["android.permission.RECORD_AUDIO", "android.permission.MODIFY_AUDIO_SETTINGS"]
    }
  }
}
```

Without Expo, add `NSMicrophoneUsageDescription` to `ios/<App>/Info.plist`, and `RECORD_AUDIO` and `MODIFY_AUDIO_SETTINGS` to `android/app/src/main/AndroidManifest.xml`. Skip any already present.

A new native build is needed for the permission to take effect; an over-the-air update can't add it. Expo Go already has it, so the user can try the widget there first. Tell the user that making a new key or turning the widget off in Settings breaks the widget in app versions already released.

## 4. Check it

Website: start the dev server and open a page. A "Feedback" button should sit in the bottom-right corner and open a recorder. If the panel is blank, the site isn't listed in Settings yet.

React Native: build or start the app, tap the button and check the recorder opens.

Ask the user to send one test note and look for it at https://www.pulseapp.click/dashboard. Each note spends one pulse.

## 5. Report back

Tell the user which files you changed, and list the steps only they can do: for a website, listing their sites in Settings; for an app, a new native build for the microphone permission.
