You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A multi-turn chat app built with the AI SDK's `useChat` hook and Trigger.dev's `chat.task`. Conversations run as durable Trigger.dev tasks with realtime streaming, automatic message accumulation, and persistence across page refreshes.
|`runId`| The Trigger.dev run handling this conversation |
27
+
|`publicAccessToken`| Scoped token for reading the run's stream and sending input stream messages |
28
+
|`lastEventId`| Stream position — used to resume without replaying old events |
29
+
30
+
A Chat can outlive many ChatSessions. When the run ends (turn timeout, max turns reached, crash), the ChatSession is gone but the Chat and its messages remain. The next message from the user starts a fresh run and creates a new ChatSession for the same Chat.
31
+
32
+
**Think of it as: Chat = the conversation, ChatSession = the live connection to the run handling it.**
33
+
34
+
## Lifecycle Hooks
35
+
36
+
Persistence is handled server-side in the Trigger.dev task via three hooks:
37
+
38
+
-**`onChatStart`** — Creates the Chat and ChatSession records when a new conversation starts (turn 0).
39
+
-**`onTurnStart`** — Saves messages and updates the session _before_ streaming begins, so a mid-stream page refresh still shows the user's message.
40
+
-**`onTurnComplete`** — Saves the assistant's response and the `lastEventId` for stream resumption.
41
+
42
+
## Setup
43
+
44
+
```bash
45
+
# From the repo root
46
+
pnpm run docker # Start PostgreSQL, Redis, Electric
47
+
pnpm run db:migrate # Run webapp migrations
48
+
pnpm run db:seed # Seed the database
49
+
50
+
# Set up the reference app's database
51
+
cd references/ai-chat
52
+
cp .env.example .env # Edit DATABASE_URL if needed
53
+
npx prisma migrate deploy
54
+
55
+
# Build and run
56
+
pnpm run build --filter trigger.dev --filter @trigger.dev/sdk
57
+
pnpm run dev --filter webapp # In one terminal
58
+
cd references/ai-chat && pnpm exec trigger dev # In another
59
+
cd references/ai-chat && pnpm run dev # In another
0 commit comments