-
Notifications
You must be signed in to change notification settings - Fork 37
refactor(bot): persist Thread/Message state for callback rehydration #3127
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
RSO
wants to merge
5
commits into
main
Choose a base branch
from
RSO/dust-ferryboat
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
6059d10
refactor(bot): persist Thread/Message state for callback rehydration
RSO 7e3f857
Use single line
RSO 234264f
Tighten up types
RSO 59ee450
Don't pass state, just fetch it
RSO 28b4e11
fix(bot): fail bot_request when callback message state is missing
RSO File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| import 'server-only'; | ||
| import * as z from 'zod'; | ||
| import { ThreadImpl, Message, type StateAdapter, type Thread } from 'chat'; | ||
| import type { Root } from 'mdast'; | ||
| import { bot } from '@/lib/bot'; | ||
|
|
||
| const BOT_REQUEST_MESSAGE_STATE_KEY_PREFIX = 'bot-request-message-state:'; | ||
| const BOT_REQUEST_MESSAGE_STATE_TTL_MS = 24 * 60 * 60 * 1000; | ||
|
|
||
| type SerializedThread = ReturnType<Thread['toJSON']>; | ||
| type SerializedMessage = ReturnType<Message['toJSON']>; | ||
|
|
||
| type BotRequestMessageState = { | ||
| thread: SerializedThread; | ||
| message: SerializedMessage; | ||
| }; | ||
|
|
||
| const serializedThreadShape = z.looseObject({ | ||
| _type: z.literal('chat:Thread'), | ||
| adapterName: z.string(), | ||
| channelId: z.string(), | ||
| channelVisibility: z.enum(['private', 'workspace', 'external', 'unknown']).optional(), | ||
| currentMessage: z.lazy(() => serializedMessageShape).optional(), | ||
| id: z.string(), | ||
| isDM: z.boolean(), | ||
| }) satisfies z.ZodType<SerializedThread>; | ||
|
|
||
| const serializedMessageAttachmentShape = z.object({ | ||
| type: z.enum(['image', 'file', 'video', 'audio']), | ||
| url: z.string().optional(), | ||
| name: z.string().optional(), | ||
| mimeType: z.string().optional(), | ||
| size: z.number().optional(), | ||
| width: z.number().optional(), | ||
| height: z.number().optional(), | ||
| fetchMetadata: z.record(z.string(), z.string()).optional(), | ||
| }); | ||
|
|
||
| const serializedMessageLinkShape = z.object({ | ||
| url: z.string(), | ||
| title: z.string().optional(), | ||
| description: z.string().optional(), | ||
| imageUrl: z.string().optional(), | ||
| siteName: z.string().optional(), | ||
| }); | ||
|
|
||
| const formattedContentShape = z.custom<Root>( | ||
| value => | ||
| z.object({ type: z.literal('root'), children: z.array(z.unknown()) }).safeParse(value).success | ||
| ); | ||
|
|
||
| export const serializedThreadSchema = z.custom<SerializedThread>( | ||
| value => serializedThreadShape.safeParse(value).success | ||
| ); | ||
|
|
||
| const serializedMessageShape = z.looseObject({ | ||
| _type: z.literal('chat:Message'), | ||
| attachments: z.array(serializedMessageAttachmentShape), | ||
| author: z.object({ | ||
| userId: z.string(), | ||
| userName: z.string(), | ||
| fullName: z.string(), | ||
| isBot: z.union([z.boolean(), z.literal('unknown')]), | ||
| isMe: z.boolean(), | ||
| }), | ||
| formatted: formattedContentShape, | ||
| id: z.string(), | ||
| isMention: z.boolean().optional(), | ||
| links: z.array(serializedMessageLinkShape).optional(), | ||
| metadata: z.object({ | ||
| dateSent: z.iso.datetime(), | ||
| edited: z.boolean(), | ||
| editedAt: z.iso.datetime().optional(), | ||
| }), | ||
| raw: z.unknown(), | ||
| text: z.string(), | ||
| threadId: z.string(), | ||
| }) satisfies z.ZodType<SerializedMessage>; | ||
|
|
||
| export const serializedMessageSchema = z.custom<SerializedMessage>( | ||
| value => serializedMessageShape.safeParse(value).success | ||
| ); | ||
|
|
||
| const botRequestMessageStateSchema = z.object({ | ||
| thread: serializedThreadSchema, | ||
| message: serializedMessageSchema, | ||
| }); | ||
|
|
||
| function botRequestMessageStateKey(botRequestId: string): string { | ||
| return `${BOT_REQUEST_MESSAGE_STATE_KEY_PREFIX}${botRequestId}`; | ||
| } | ||
|
|
||
| export async function storeBotRequestMessageState({ | ||
| state, | ||
| botRequestId, | ||
| thread, | ||
| message, | ||
| }: { | ||
| state: StateAdapter; | ||
| botRequestId: string; | ||
| thread: Thread; | ||
| message: Message; | ||
| }): Promise<void> { | ||
| await state.set<BotRequestMessageState>( | ||
| botRequestMessageStateKey(botRequestId), | ||
| { | ||
| thread: thread.toJSON(), | ||
| message: message.toJSON(), | ||
| }, | ||
| BOT_REQUEST_MESSAGE_STATE_TTL_MS | ||
| ); | ||
| } | ||
|
|
||
| export async function getBotRequestMessageState( | ||
| state: StateAdapter, | ||
| botRequestId: string | ||
| ): Promise<BotRequestMessageState | null> { | ||
| const value = await state.get<unknown>(botRequestMessageStateKey(botRequestId)); | ||
| if (!value) { | ||
| return null; | ||
| } | ||
|
|
||
| return botRequestMessageStateSchema.parse(value); | ||
| } | ||
|
|
||
| export async function getRehydratedBotRequestMessageState(botRequestId: string) { | ||
| const stored = await getBotRequestMessageState(bot.getState(), botRequestId); | ||
|
|
||
| if (!stored) { | ||
| throw new Error('Could not find message state for botRequest ' + botRequestId); | ||
| } | ||
|
|
||
| return { | ||
| thread: ThreadImpl.fromJSON(stored.thread), | ||
| message: Message.fromJSON(stored.message), | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.