-
Notifications
You must be signed in to change notification settings - Fork 629
Expand file tree
/
Copy pathapp.tsx
More file actions
426 lines (391 loc) · 12.8 KB
/
app.tsx
File metadata and controls
426 lines (391 loc) · 12.8 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import { isRetryableStatusCode, getErrorStatusCode } from '@codebuff/sdk'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useShallow } from 'zustand/react/shallow'
import { Chat } from './chat'
import { ChatHistoryScreen } from './components/chat-history-screen'
import { FreebuffSupersededScreen } from './components/freebuff-superseded-screen'
import { LoginModal } from './components/login-modal'
import { ProjectPickerScreen } from './components/project-picker-screen'
import { TerminalLink } from './components/terminal-link'
import { WaitingRoomScreen } from './components/waiting-room-screen'
import { useAuthQuery } from './hooks/use-auth-query'
import { useAuthState } from './hooks/use-auth-state'
import { useFreebuffSession } from './hooks/use-freebuff-session'
import { useLogo } from './hooks/use-logo'
import { useSheenAnimation } from './hooks/use-sheen-animation'
import { useTerminalDimensions } from './hooks/use-terminal-dimensions'
import { useTerminalFocus } from './hooks/use-terminal-focus'
import { useTheme } from './hooks/use-theme'
import { getProjectRoot } from './project-files'
import { useChatHistoryStore } from './state/chat-history-store'
import { useChatStore } from './state/chat-store'
import type { TopBannerType } from './types/store'
import { IS_FREEBUFF } from './utils/constants'
import { findGitRoot } from './utils/git'
import { openFileAtPath } from './utils/open-file'
import { formatCwd } from './utils/path-helpers'
import { getLogoBlockColor, getLogoAccentColor } from './utils/theme-system'
import type { MultilineInputHandle } from './components/multiline-input'
import type { AgentMode } from './utils/constants'
import type { AuthStatus } from './utils/status-indicator-state'
import type { FileTreeNode } from '@codebuff/common/util/file'
interface AppProps {
initialPrompt: string | null
agentId?: string
requireAuth: boolean | null
hasInvalidCredentials: boolean
fileTree: FileTreeNode[]
continueChat: boolean
continueChatId?: string
initialMode?: AgentMode
showProjectPicker: boolean
onProjectChange: (projectPath: string) => void
}
export const App = ({
initialPrompt,
agentId,
requireAuth,
hasInvalidCredentials,
fileTree,
continueChat,
continueChatId,
initialMode,
showProjectPicker,
onProjectChange,
}: AppProps) => {
const { contentMaxWidth, terminalWidth } = useTerminalDimensions()
const theme = useTheme()
// Sheen animation state for the logo
const [sheenPosition, setSheenPosition] = useState(0)
const blockColor = getLogoBlockColor(theme.name)
const accentColor = getLogoAccentColor(theme.name)
const { applySheenToChar } = useSheenAnimation({
logoColor: theme.foreground,
accentColor,
blockColor,
terminalWidth,
sheenPosition,
setSheenPosition,
})
const { component: logoComponent } = useLogo({
availableWidth: contentMaxWidth,
accentColor,
blockColor,
applySheenToChar,
})
const inputRef = useRef<MultilineInputHandle | null>(null)
const {
setInputFocused,
setIsFocusSupported,
resetChatStore,
activeTopBanner,
setActiveTopBanner,
closeTopBanner,
} = useChatStore(
useShallow((store) => ({
setInputFocused: store.setInputFocused,
setIsFocusSupported: store.setIsFocusSupported,
resetChatStore: store.reset,
activeTopBanner: store.activeTopBanner,
setActiveTopBanner: store.setActiveTopBanner,
closeTopBanner: store.closeTopBanner,
})),
)
// Wrap in useCallback to prevent re-subscribing on every render
const handleSupportDetected = useCallback(() => {
setIsFocusSupported(true)
}, [setIsFocusSupported])
// Enable terminal focus detection to stop cursor blinking when window loses focus
// Cursor starts visible but not blinking; blinking enabled once terminal support confirmed
useTerminalFocus({
onFocusChange: setInputFocused,
onSupportDetected: handleSupportDetected,
})
// Get auth query for network status tracking
const authQuery = useAuthQuery()
const {
isAuthenticated,
setIsAuthenticated,
setUser,
handleLoginSuccess,
logoutMutation,
} = useAuthState({
requireAuth,
inputRef,
setInputFocused,
resetChatStore,
})
const projectRoot = getProjectRoot()
const gitRoot = useMemo(
() => findGitRoot({ cwd: projectRoot }),
[projectRoot],
)
const showGitRootBanner = Boolean(gitRoot && gitRoot !== projectRoot)
const [gitRootBannerDismissed, setGitRootBannerDismissed] = useState(false)
const prevTopBannerRef = useRef<TopBannerType | null>(null)
useEffect(() => {
setGitRootBannerDismissed(false)
}, [projectRoot])
useEffect(() => {
const prevBanner = prevTopBannerRef.current
if (
prevBanner === 'gitRoot' &&
activeTopBanner === null &&
showGitRootBanner
) {
setGitRootBannerDismissed(true)
}
prevTopBannerRef.current = activeTopBanner
}, [activeTopBanner, showGitRootBanner])
useEffect(() => {
if (!showGitRootBanner) {
if (activeTopBanner === 'gitRoot') {
closeTopBanner()
}
return
}
if (!gitRootBannerDismissed && activeTopBanner === null) {
setActiveTopBanner('gitRoot')
}
}, [
activeTopBanner,
closeTopBanner,
gitRootBannerDismissed,
setActiveTopBanner,
showGitRootBanner,
])
const handleSwitchToGitRoot = useCallback(() => {
if (gitRoot) {
onProjectChange(gitRoot)
}
}, [gitRoot, onProjectChange])
// Chat history state from store
const { showChatHistory, closeChatHistory } = useChatHistoryStore()
// State to track which chat to resume (set when user selects from history)
const [resumeChatId, setResumeChatId] = useState<string | null>(null)
const handleResumeChat = useCallback(
(chatId: string) => {
closeChatHistory()
// Reset chat store to clear previous messages before loading the selected chat
resetChatStore()
setResumeChatId(chatId)
},
[closeChatHistory, resetChatStore]
)
const handleNewChat = useCallback(() => {
closeChatHistory()
resetChatStore()
setResumeChatId(null)
}, [closeChatHistory, resetChatStore])
// Determine effective continueChat values
const effectiveContinueChat = continueChat || resumeChatId !== null
const effectiveContinueChatId = resumeChatId ?? continueChatId
const headerContent = useMemo(() => {
const displayPath = formatCwd(projectRoot)
return (
<box
style={{
flexDirection: 'column',
gap: 0,
paddingLeft: 1,
paddingRight: 1,
}}
>
<box
style={{
flexDirection: 'column',
marginBottom: 1,
marginTop: 2,
}}
>
{logoComponent}
</box>
<text
style={{ wrapMode: 'word', marginBottom: 1, fg: theme.foreground }}
>
{IS_FREEBUFF ? 'Freebuff' : 'Codebuff'} will run commands on your behalf to help you build.
</text>
<text
style={{ wrapMode: 'word', marginBottom: 1, fg: theme.foreground }}
>
Directory{' '}
<TerminalLink
text={displayPath}
color={theme.muted}
inline={true}
underlineOnHover={true}
onActivate={() => openFileAtPath(projectRoot)}
/>
</text>
</box>
)
}, [logoComponent, projectRoot, theme])
// Derive auth reachability + retrying state from authQuery error
const authError = authQuery.error
const authErrorStatusCode = authError ? getErrorStatusCode(authError) : undefined
let authStatus: AuthStatus = 'ok'
if (authQuery.isError && authErrorStatusCode !== undefined) {
if (isRetryableStatusCode(authErrorStatusCode)) {
// Retryable errors (408 timeout, 429 rate limit, 5xx server errors)
authStatus = 'retrying'
} else if (authErrorStatusCode >= 500) {
// Non-retryable server errors (unlikely but possible future codes)
authStatus = 'unreachable'
}
// 4xx client errors (401, 403, etc.) keep 'ok' - network is fine, just auth failed
}
// Render login modal when not authenticated AND auth service is reachable
// Don't show login modal during network outages OR while retrying
if (
requireAuth !== null &&
isAuthenticated === false &&
authStatus === 'ok'
) {
return (
<LoginModal
onLoginSuccess={handleLoginSuccess}
hasInvalidCredentials={hasInvalidCredentials}
/>
)
}
// Render project picker when at home directory or outside a project
if (showProjectPicker) {
return (
<ProjectPickerScreen
onSelectProject={onProjectChange}
initialPath={projectRoot}
/>
)
}
// Use key to force remount when resuming a different chat from history
const chatKey = resumeChatId ?? 'current'
return (
<AuthedSurface
chatKey={chatKey}
headerContent={headerContent}
initialPrompt={initialPrompt}
agentId={agentId}
fileTree={fileTree}
inputRef={inputRef}
setIsAuthenticated={setIsAuthenticated}
setUser={setUser}
logoutMutation={logoutMutation}
continueChat={effectiveContinueChat}
continueChatId={effectiveContinueChatId}
authStatus={authStatus}
initialMode={initialMode}
gitRoot={gitRoot}
onSwitchToGitRoot={handleSwitchToGitRoot}
showChatHistory={showChatHistory}
onSelectChat={handleResumeChat}
onCancelChatHistory={closeChatHistory}
onNewChat={handleNewChat}
/>
)
}
interface AuthedSurfaceProps {
chatKey: string
headerContent: React.ReactNode
initialPrompt: string | null
agentId?: string
fileTree: FileTreeNode[]
inputRef: React.MutableRefObject<MultilineInputHandle | null>
setIsAuthenticated: React.Dispatch<React.SetStateAction<boolean | null>>
setUser: React.Dispatch<React.SetStateAction<import('./utils/auth').User | null>>
logoutMutation: ReturnType<typeof useAuthState>['logoutMutation']
continueChat: boolean
continueChatId: string | undefined
authStatus: AuthStatus
initialMode: AgentMode | undefined
gitRoot: string | null | undefined
onSwitchToGitRoot: () => void
showChatHistory: boolean
onSelectChat: (chatId: string) => void
onCancelChatHistory: () => void
onNewChat: () => void
}
/**
* Rendered only after auth is confirmed. Owns the freebuff waiting-room gate
* so `useFreebuffSession` runs exactly once per authed session (not before
* we have a token).
*/
const AuthedSurface = ({
chatKey,
headerContent,
initialPrompt,
agentId,
fileTree,
inputRef,
setIsAuthenticated,
setUser,
logoutMutation,
continueChat,
continueChatId,
authStatus,
initialMode,
gitRoot,
onSwitchToGitRoot,
showChatHistory,
onSelectChat,
onCancelChatHistory,
onNewChat,
}: AuthedSurfaceProps) => {
const { session, error: sessionError } = useFreebuffSession()
// Terminal state: a 409 from the gate means another CLI rotated our
// instance id. Show a dedicated screen and stop polling — don't fall back
// into the waiting room, which would look like normal queued progress.
if (IS_FREEBUFF && session?.status === 'superseded') {
return <FreebuffSupersededScreen />
}
// Route every non-admitted state through the pre-chat screen:
// null → initial GET in flight (brief)
// 'none' → no seat yet; show model-picker landing
// 'queued' → waiting our turn
// 'country_blocked' → terminal region-gate message
//
// 'ended' deliberately falls through to <Chat>: the agent may still be
// finishing work under the server-side grace period, and the chat surface
// itself swaps the input box for the session-ended banner.
if (
IS_FREEBUFF &&
(session === null ||
session.status === 'queued' ||
session.status === 'none' ||
session.status === 'country_blocked')
) {
return <WaitingRoomScreen session={session} error={sessionError} />
}
// Chat history renders inside AuthedSurface so the freebuff session stays
// mounted while the user browses history. Unmounting this surface would
// DELETE the session row and drop the user back into the waiting room on
// return.
if (showChatHistory) {
return (
<ChatHistoryScreen
onSelectChat={onSelectChat}
onCancel={onCancelChatHistory}
onNewChat={onNewChat}
/>
)
}
return (
<Chat
key={chatKey}
headerContent={headerContent}
initialPrompt={initialPrompt}
agentId={agentId}
fileTree={fileTree}
inputRef={inputRef}
setIsAuthenticated={setIsAuthenticated}
setUser={setUser}
logoutMutation={logoutMutation}
continueChat={continueChat}
continueChatId={continueChatId}
authStatus={authStatus}
initialMode={initialMode}
gitRoot={gitRoot}
onSwitchToGitRoot={onSwitchToGitRoot}
freebuffSession={session}
/>
)
}