-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathcommand-registry.ts
More file actions
245 lines (229 loc) · 7.16 KB
/
command-registry.ts
File metadata and controls
245 lines (229 loc) · 7.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { handleImageCommand } from './image'
import { handleInitializationFlowLocally } from './init'
import { handleReferralCode } from './referral'
import { normalizeReferralCode } from './router-utils'
import { handleUsageCommand } from './usage'
import { useChatStore } from '../state/chat-store'
import { useLoginStore } from '../state/login-store'
import { getSystemMessage, getUserMessage } from '../utils/message-history'
import { capturePendingImages } from '../utils/add-pending-image'
import type { MultilineInputHandle } from '../components/multiline-input'
import type { InputValue, PendingImage } from '../state/chat-store'
import type { ChatMessage } from '../types/chat'
import type { SendMessageFn } from '../types/contracts/send-message'
import type { User } from '../utils/auth'
import type { AgentMode } from '../utils/constants'
import type { UseMutationResult } from '@tanstack/react-query'
export type RouterParams = {
abortControllerRef: React.MutableRefObject<AbortController | null>
agentMode: AgentMode
inputRef: React.MutableRefObject<MultilineInputHandle | null>
inputValue: string
isChainInProgressRef: React.MutableRefObject<boolean>
isStreaming: boolean
logoutMutation: UseMutationResult<boolean, Error, void, unknown>
streamMessageIdRef: React.MutableRefObject<string | null>
addToQueue: (message: string, images?: PendingImage[]) => void
clearMessages: () => void
saveToHistory: (message: string) => void
scrollToLatest: () => void
sendMessage: SendMessageFn
setCanProcessQueue: (value: React.SetStateAction<boolean>) => void
setInputFocused: (focused: boolean) => void
setInputValue: (
value: InputValue | ((prev: InputValue) => InputValue),
) => void
setIsAuthenticated: (value: React.SetStateAction<boolean | null>) => void
setMessages: (
value: ChatMessage[] | ((prev: ChatMessage[]) => ChatMessage[]),
) => void
setUser: (value: React.SetStateAction<User | null>) => void
stopStreaming: () => void
}
export type CommandResult = { openFeedbackMode?: boolean } | void
export type CommandHandler = (
params: RouterParams,
args: string,
) => Promise<CommandResult> | CommandResult
export type CommandDefinition = {
name: string
aliases: string[]
handler: CommandHandler
}
const clearInput = (params: RouterParams) => {
params.setInputValue({ text: '', cursorPosition: 0, lastEditDueToNav: false })
}
export const COMMAND_REGISTRY: CommandDefinition[] = [
{
name: 'feedback',
aliases: ['bug', 'report'],
handler: (params) => {
params.saveToHistory(params.inputValue.trim())
clearInput(params)
return { openFeedbackMode: true }
},
},
{
name: 'bash',
aliases: ['!'],
handler: (params) => {
useChatStore.getState().setInputMode('bash')
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
},
{
name: 'referral',
aliases: ['redeem'],
handler: async (params, args) => {
const trimmedArgs = args.trim()
// If user provided a code directly, redeem it immediately
if (trimmedArgs) {
const code = normalizeReferralCode(trimmedArgs)
try {
const { postUserMessage } = await handleReferralCode(code)
params.setMessages((prev) => [
...prev,
getUserMessage(params.inputValue.trim()),
...postUserMessage([]),
])
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : 'Unknown error'
params.setMessages((prev) => [
...prev,
getUserMessage(params.inputValue.trim()),
getSystemMessage(`Error redeeming referral code: ${errorMessage}`),
])
}
params.saveToHistory(params.inputValue.trim())
clearInput(params)
return
}
// Otherwise enter referral mode
useChatStore.getState().setInputMode('referral')
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
},
{
name: 'login',
aliases: ['signin'],
handler: (params) => {
params.setMessages((prev) => [
...prev,
getSystemMessage(
"You're already in the app. Use /logout to switch accounts.",
),
])
clearInput(params)
},
},
{
name: 'logout',
aliases: ['signout'],
handler: (params) => {
params.abortControllerRef.current?.abort()
params.stopStreaming()
params.setCanProcessQueue(false)
const { resetLoginState } = useLoginStore.getState()
params.logoutMutation.mutate(undefined, {
onSettled: () => {
resetLoginState()
params.setMessages((prev) => [
...prev,
getSystemMessage('Logged out.'),
])
clearInput(params)
setTimeout(() => {
params.setUser(null)
params.setIsAuthenticated(false)
}, 300)
},
})
},
},
{
name: 'exit',
aliases: ['quit', 'q'],
handler: () => {
process.kill(process.pid, 'SIGINT')
},
},
{
name: 'new',
aliases: ['n', 'clear', 'c'],
handler: (params) => {
params.setMessages(() => [])
params.clearMessages()
params.saveToHistory(params.inputValue.trim())
clearInput(params)
params.stopStreaming()
params.setCanProcessQueue(false)
},
},
{
name: 'init',
aliases: [],
handler: async (params, args) => {
const { postUserMessage } = handleInitializationFlowLocally()
const trimmed = params.inputValue.trim()
params.saveToHistory(trimmed)
clearInput(params)
// Check streaming/queue state
if (
params.isStreaming ||
params.streamMessageIdRef.current ||
params.isChainInProgressRef.current
) {
const pendingImages = capturePendingImages()
params.addToQueue(trimmed, pendingImages)
params.setInputFocused(true)
params.inputRef.current?.focus()
return
}
params.sendMessage({
content: trimmed,
agentMode: params.agentMode,
postUserMessage,
})
setTimeout(() => {
params.scrollToLatest()
}, 0)
},
},
{
name: 'usage',
aliases: ['credits'],
handler: async (params) => {
const { postUserMessage } = await handleUsageCommand()
params.setMessages((prev) => postUserMessage(prev))
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
},
{
name: 'image',
aliases: ['img', 'attach'],
handler: async (params, args) => {
const trimmedArgs = args.trim()
// If user provided a path directly, process it immediately
if (trimmedArgs) {
await handleImageCommand(trimmedArgs)
params.saveToHistory(params.inputValue.trim())
clearInput(params)
return
}
// Otherwise enter image mode
useChatStore.getState().setInputMode('image')
params.saveToHistory(params.inputValue.trim())
clearInput(params)
},
},
]
export function findCommand(cmd: string): CommandDefinition | undefined {
const lowerCmd = cmd.toLowerCase()
return COMMAND_REGISTRY.find(
(def) => def.name === lowerCmd || def.aliases.includes(lowerCmd),
)
}