> **Photon Beta documentation**
> Browse all pages: https://photon.codes/docs/beta/llms.txt
> Search Beta docs via MCP: https://photon.codes/docs/beta/mcp (OAuth REST API MCP: https://mcp.photon.codes/mcp)

# Convex

> Receive and answer Photon messages in a Convex app with the @photon-ai/convex component.

> [!WARNING]
>
> **Beta is a preview.** The Beta (2.0) platform does not have all the features
> of [Stable](https://photon.codes/docs/spectrum-ts/introduction) yet. For example, iMessage on Beta
> supports text, attachments, voice messages, replies, read receipts, and typing
> indicators, but tapbacks, polls, and message effects are
> [only on Stable](https://photon.codes/docs/spectrum-ts/providers/imessage/messaging-features) for now.
> Use Stable for production agents, and confirm that Beta supports the features
> you need before you buy a plan.

[`@photon-ai/convex`](https://www.npmjs.com/package/@photon-ai/convex) is a
[Convex component](https://docs.convex.dev/components) that connects a Convex
app to the channels connected to a Photon Beta project: iMessage, SMS,
WhatsApp, WhatsApp Business, email, and Telegram. It receives Photon's
`message.received` webhook events, stores each message before it acknowledges
the delivery, and calls one of your functions for each turn of the
conversation. Replies, read receipts, and typing indicators go into an outbox
in your deployment; the component calls the Photon API for them and retries
requests that fail temporarily.

This guide covers the published **0.2.0** component, which requires Convex
1.31.0 or a later 1.x release. The
[source and issue tracker](https://github.com/photon-hq/convex) are maintained
by Photon.

> [!NOTE]
>
> `@photon-ai/convex` works only with Photon Beta. The Stable component,
> `@spectrum-ts/convex`, is a different package with a different API: it uses
> Spectrum credentials and webhooks and exports `Spectrum`, not
> `PhotonComponent`.

## Installation

Install the component in your Convex app:

```bash
npm install @photon-ai/convex
```

Then register it in `convex/convex.config.ts`:

```ts convex/convex.config.ts
import photon from "@photon-ai/convex/convex.config";
import { defineApp } from "convex/server";

const app = defineApp();
app.use(photon);

export default app;
```

The component is named `photon`, so your functions reach it as
`components.photon`.

## Configuration

1. [Set up a Beta project and API key](/docs/beta/get-started/project.md). The
   component calls the Photon API only to send, so the key needs
   `project:write`.
2. Connect the channels you want to use in the
   [Beta dashboard](https://app.beta.photon.codes). Start with the
   [iMessage](/docs/beta/get-started/imessage.md) or [email](/docs/beta/get-started/email.md) guide.
3. [Add a webhook destination](/docs/beta/message-delivery/webhook.md#add-a-destination)
   with these settings:
   * **URL**: `https://<deployment>.convex.site/photon/webhook`, where
     `<deployment>.convex.site` is your deployment's HTTP actions URL.
   * **API version**: `2026-07-01`. Component 0.2.0 reads only this version, and
     you cannot change a destination's API version after you create it.
   * **Events**: `message.received`.
4. Set these environment variables on the Convex deployment, in the Convex
   dashboard or with the Convex CLI:

```bash
npx convex env set PHOTON_PROJECT_ID pho_prj_REPLACE_WITH_YOUR_PROJECT_ID
npx convex env set PHOTON_API_KEY pho_sk_REPLACE_WITH_YOUR_PROJECT_API_KEY
npx convex env set PHOTON_WEBHOOK_SECRET whsec_REPLACE_WITH_YOUR_SIGNING_SECRET
```

| Environment variable | Option | Purpose |
| - | - | - |
| `PHOTON_PROJECT_ID` | `projectId` | Required to send. Your Beta project ID. |
| `PHOTON_API_KEY` | `apiKey` | Required to send. The project's API key. |
| `PHOTON_WEBHOOK_SECRET` | `webhookSecret` | Required to receive. The destination's `whsec_...` signing secret. |
| `PHOTON_BASE_URL` | `baseUrl` | Defaults to `https://api.photon.codes`. |

Options passed to `new PhotonComponent()` override the environment variables.

> [!WARNING]
>
> The component's send jobs cannot read your app's environment variables, so
> the component stores the project ID, API key, and base URL in its own
> `config` table. Anyone who can view this deployment's data in the Convex
> dashboard can read the API key.

## Add the component

Create one `PhotonComponent` for the app, and name the function to call for
each turn:

```ts convex/photon.ts
import { PhotonComponent } from "@photon-ai/convex";
import { components, internal } from "./_generated/api";

// The explicit type annotation avoids a circular type inference error,
// because convex/agent.ts imports `photon` from this file.
export const photon: PhotonComponent = new PhotonComponent(components.photon, {
  onTurn: internal.agent.respond,
});
```

Mount the webhook route:

```ts convex/http.ts
import { httpRouter } from "convex/server";
import { photon } from "./photon";

const http = httpRouter();

// POST https://<deployment>.convex.site/photon/webhook
photon.registerRoutes(http);

export default http;
```

When someone messages your project, the component stores the message and
calls your `onTurn` function, here `respond`, with it. The messages that one
call of `respond` handles are a turn; by default, each message is its own turn.
`respond` builds a reply and calls `sendMessage`, which adds the reply to the
component's outbox, and the component sends it to Photon from there.

This echo bot marks the message read, replies with its text, and completes the
turn:

```ts convex/agent.ts
import { v } from "convex/values";
import { internalAction } from "./_generated/server";
import { photon } from "./photon";

export const respond = internalAction({
  args: {
    spaceId: v.string(),
    turnId: v.string(),
    messages: v.array(v.any()),
    carried: v.array(v.any()),
  },
  returns: v.null(),
  handler: async (ctx, args) => {
    await photon.markMessageRead(ctx, args);

    const texts = args.messages.map((message) =>
      message.content?.type === "text"
        ? message.content.text
        : `[${message.content?.type}]`
    );
    const reply = `You said: ${texts.join("\n")}`; // Call your model here.

    await photon.sendMessage(ctx, {
      spaceId: args.spaceId,
      turnId: args.turnId,
      content: { type: "text", format: "plain", text: reply },
    });
    await photon.completeTurn(ctx, args);
    return null;
  },
});
```

> [!WARNING]
>
> The component does not filter by sender: a message from anyone, including
> another bot, starts a turn. Test an echo bot from your own phone or account,
> so that two bots do not keep replying to each other.

## Receiving messages

The webhook route verifies each delivery's Standard Webhooks signature, then
stores the message before it returns `200`, so an acknowledged message is
already saved. A message that Photon delivers again is recognized by its
message ID and stored once.

[Event Deliveries](https://app.beta.photon.codes/project/activity/events) in
the dashboard shows the HTTP response code each delivery got. A delivery that
fails signature verification gets `401`. If the signing secret is missing or
cannot be decoded, every delivery gets `500`. Events other than
`message.received` are acknowledged without being stored.

Pass `webhookPath` to `new PhotonComponent()` to mount the route on another path.

Read receipts (`message.read`) are stored but do not start a turn. Every other
content type, including attachments and reactions, starts one.

Your Agent User is the Photon user (`pho_usr_...`) for the phone number, email
address, or bot that your project sends from. A received message names it in
`receivedBy`. A Space (`pho_spc_...`) is a conversation in Photon. The
component sends into a Space as the Agent User named in the messages it
received there. Until the Space has received a message with `receivedBy`,
`sendMessage` and `setSpaceTyping` fail for it: the outbox row becomes `failed`
without a request to Photon.

## Turns

The component calls the `onTurn` function with:

| Argument | Contents |
| - | - |
| `spaceId` | The Photon Space (`pho_spc_...`) the messages arrived in. |
| `turnId` | The turn. Pass it to `sendMessage`, `markMessageRead`, `setSpaceTyping`, `isCancelled`, and `completeTurn`. |
| `messages` | The turn's messages, in the order the component stored them. |
| `carried` | Collapse mode only: messages from earlier turns that a newer message superseded, described in [Consecutive messages](#consecutive-messages). The component stored them before `messages`. |

Both arrays hold each event's `data.object` unchanged: a Photon `Message`.

Call `completeTurn` when the handler finishes. It marks the turn's messages
`handled` and does not wait for the turn's replies to be sent. In collapse
mode, it also affects which messages the next turn gets in `carried`; see
[Consecutive messages](#consecutive-messages).

### Consecutive messages

People often split one request into several messages, for example:

> Look up my order
>
> The order number is 123

By default (`mode: "immediate"`), the component calls `respond` once for each
message, so the first call answers "Look up my order" without the order
number. A new message never supersedes an earlier turn, and `carried` is
always empty. Replies keep their order within a turn but not across turns, so
the two replies can arrive out of order.

To answer such messages together, set `mode` to `"collapse"`. `debounceMs` is
optional:

```ts convex/photon.ts
import { PhotonComponent } from "@photon-ai/convex";
import { components, internal } from "./_generated/api";

export const photon: PhotonComponent = new PhotonComponent(components.photon, {
  onTurn: internal.agent.respond,
  mode: "collapse",
  debounceMs: 2000,
});
```

`debounceMs` delays the start of every turn, in either mode, so it also delays
every reply. It defaults to `0`. In collapse mode, each new message restarts
the delay: with `debounceMs: 2000`, if "The order number is 123" arrives within
two seconds of "Look up my order", one turn gets both in `messages`.

In collapse mode, each new message supersedes the Space's latest turn, even
when `respond` has already returned for it. Read receipts do not, because they
do not start a turn. The diagram shows "The order number is 123" arriving while
`respond` is still working on "Look up my order", for example waiting for a
model:

```mermaid
sequenceDiagram
    participant Photon as Photon
    participant Component as Component
    participant Turn1 as respond, turn 1
    participant Turn2 as respond, turn 2
    Photon->>Component: Look up my order
    Component->>Turn1: messages: Look up my order
    Turn1->>Turn1: Wait for the model
    Photon->>Component: The order number is 123
    Component->>Component: Supersede turn 1 and cancel its queued sends
    Component->>Turn2: messages: The order number is 123, carried: Look up my order
    Turn1->>Component: isCancelled
    Component-->>Turn1: true
    Turn1->>Turn1: Return without replying
    Turn2->>Component: sendMessage with one answer to both, then completeTurn
    Component->>Photon: Send the answer
```

Superseding cancels everything the first turn queued with its `turnId`,
including reactions, read receipts, and typing indicators, but a request
already in progress still goes out. Convex cannot stop the first call of
`respond`, so it keeps running, but from then on its `sendMessage`,
`markMessageRead`, and `setSpaceTyping` calls with its `turnId` queue nothing.
If that call had not called `completeTurn` yet, Convex also cancels every
function it schedules from then on, so a send without `turnId` from it returns
`queued: true` but stays `pending` and is never sent.

When a newer message supersedes a turn, the next turn gets the superseded
turn's messages in `carried`, including any that turn had itself received in
`carried`. The only exception is a turn that had answered and called
`completeTurn`: its messages are not carried. A turn has answered when at least
one of its replies has outbox status `sent` or `sending`, and none is still
`pending`. Reactions and deletions (`message.delete`) do not count as replies.

So the messages are carried if, for example, the turn had not answered yet,
`respond` replied without calling `completeTurn`, or it called `completeTurn`
without replying. This holds however much later the next message arrives.

A handler for collapse mode answers `carried` and `messages` together, and
checks `isCancelled` after slow work, such as a model call:

```ts convex/agent.ts
import { v } from "convex/values";
import { internalAction } from "./_generated/server";
import { photon } from "./photon";

export const respond = internalAction({
  args: {
    spaceId: v.string(),
    turnId: v.string(),
    messages: v.array(v.any()),
    carried: v.array(v.any()),
  },
  returns: v.null(),
  handler: async (ctx, args) => {
    await photon.markMessageRead(ctx, args);

    // Older messages from a superseded turn come first.
    const messages = [...args.carried, ...args.messages];
    const reply = await generateReply(messages);

    // A newer message superseded this turn while the model was running.
    if (await photon.isCancelled(ctx, args)) {
      return null;
    }

    await photon.sendMessage(ctx, {
      spaceId: args.spaceId,
      turnId: args.turnId,
      content: { type: "text", format: "plain", text: reply },
    });
    await photon.completeTurn(ctx, args);
    return null;
  },
});
```

`generateReply` stands for your own function that calls a model and returns
the reply text. When `isCancelled` returns `true`, the next turn answers these
messages. The superseded call's sends would not be queued anyway, but anything
else it does after that point, such as saving the reply with `ctx.runMutation`,
still runs; functions it schedules do not.

## Sending

`sendMessage`, `markMessageRead`, and `setSpaceTyping` add a row to the
component's outbox and return immediately.

| Method | Sends |
| - | - |
| `sendMessage` | A message into the Space. `content` is the `content` of a [Send a Message](/docs/beta/api-reference/messages/send-a-message.md) request, for example `{ type: "text", format: "plain", text }`. `parentMessageId` makes it a reply to that message, `email` sets email options such as the subject, and `telegram` sets Telegram options. |
| `markMessageRead` | A read receipt for the newest message in the turn. |
| `setSpaceTyping` | A typing indicator in the Space. |

The component then calls the Photon API for the row, and tracks the row only
until Photon accepts or rejects the request:

| Point | What it means | How to check |
| - | - | - |
| The method returns | The row is queued, with status `pending`. If `turnId` belongs to a superseded turn, nothing is queued: `queued` is `false` and `reason` is `"turn-cancelled"`. | The returned `{ queued, idempotencyKey, reason }`. |
| Photon accepts or rejects the request | While the request is in progress, the row is `sending`. When Photon accepts it, the row becomes `sent`. If the request fails for good, as described in [Retries](#retries), or Photon returns a message that is already `failed`, the row becomes `failed`. | The `status` of the `listOutbox` row with the same `idempotencyKey`. |
| The message is delivered | The component does not track delivery, so `sent` does not mean delivered. | Get the message by the row's `messageId` with [Get a Message](/docs/beta/api-reference/messages/get-a-message.md). Its `status` is `dispatched`, `accepted`, `delivered`, or `failed`; only `delivered` means the message was delivered. Get a Message needs an API key with `project:read`, which the component itself does not need. |

`sendMessage`, `markMessageRead`, and `setSpaceTyping` throw if the project ID
or API key is missing. A `sent` row's `messageId` is the ID of the message
Photon created; it is missing if Photon accepted the request but the component
could not parse the response. A `failed` row has no `messageId`; its
`lastError` holds the reason.

Omit `turnId` from `sendMessage` or `setSpaceTyping` to send outside a turn, for
example a scheduled follow-up. Such a send goes out as soon as it is queued,
and a newer message does not cancel it. The exception is a send that a call of
`respond` makes after a newer message superseded it, if the call had not called
`completeTurn` by then: it stays `pending` and is never sent; see
[Consecutive messages](#consecutive-messages). The Space must already have
received a message with `receivedBy`, as described in
[Receiving messages](#receiving-messages). `markMessageRead` always needs a
`turnId`.

A turn's replies go out one at a time, in the order they were queued. Each
reply waits until Photon has accepted the one before it, or that reply has
failed for good, and then waits `pacingMs` more. Set `pacingMs` as an option of
`new PhotonComponent()`; it defaults to `0`, and a `sendMessage` call can
override it. Read receipts, typing indicators, reactions, and deletions are not
held back.

### Retries

A row is retried when Photon returns `408`, `429`, or a `5xx` status, or when
the request fails or times out. It gets up to five attempts in total; the
retries start 4, 16, 64, and 256 seconds after successive failures. Between
attempts the row is `pending` again, so in collapse mode a newer message that
supersedes the turn also cancels its replies that are waiting to retry. Other
`4xx` errors, and messages that Photon reports as `failed`, are not retried.
Every attempt of a `sendMessage` or `markMessageRead` row sends the row's ID as
its `idempotency-key`, so when Photon already accepted an earlier attempt, it
returns that message instead of sending a new one.

Read receipts and typing indicators are not available on every platform. On a
platform without them, Photon returns `422` `OPERATION_UNAVAILABLE`, and the
row fails without delaying the turn's replies.

## Reading component data

| Method | Returns |
| - | - |
| `getSpace` | The Space's `spaceId`, `platform`, the Agent User it sends as (`senderId`), its `kind`, and `lastInboundAt`, or `null`. `lastInboundAt` is when the component stored the Space's newest message, read receipts included. |
| `listMessages` | The Space's stored messages, in the order they were stored, with `messageId`, `message`, `queuedAt`, and `status`. A message is `queued` until a turn takes it, then `drained` until that turn calls `completeTurn` or a newer message supersedes it, then `handled`. Read receipts are stored as `handled`. `handled` does not mean a message was answered. |
| `listOutbox` | The Space's outbox rows, in the order they were queued, with `idempotencyKey`, `kind`, `status` (`pending`, `sending`, `sent`, `failed`, or `cancelled`), `attempts`, `queuedAt`, `sentAt`, `messageId`, and `lastError`. |

`listMessages` and `listOutbox` return the 50 most recent rows unless you pass
`limit`.
