-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathindex.tsx
More file actions
327 lines (286 loc) · 9.89 KB
/
index.tsx
File metadata and controls
327 lines (286 loc) · 9.89 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
#!/usr/bin/env bun
import { promises as fs } from 'fs'
import { createRequire } from 'module'
import os from 'os'
import { getProjectFileTree } from '@codebuff/common/project-file-tree'
import { createCliRenderer } from '@opentui/core'
import { createRoot } from '@opentui/react'
import {
QueryClient,
QueryClientProvider,
focusManager,
} from '@tanstack/react-query'
import { Command } from 'commander'
import { cyan, green, red, yellow } from 'picocolors'
import React from 'react'
import { App } from './app'
import { handlePublish } from './commands/publish'
import { initializeApp } from './init/init-app'
import { getProjectRoot, setProjectRoot } from './project-files'
import { initAnalytics } from './utils/analytics'
import { getAuthTokenDetails } from './utils/auth'
import { getCliEnv } from './utils/env'
import { findGitRoot } from './utils/git'
import { initializeAgentRegistry } from './utils/local-agent-registry'
import { clearLogFile, logger } from './utils/logger'
import { saveRecentProject } from './utils/recent-projects'
import { detectTerminalTheme } from './utils/terminal-color-detection'
import { setOscDetectedTheme } from './utils/theme-system'
import type { AgentMode } from './utils/constants'
import type { FileTreeNode } from '@codebuff/common/util/file'
const require = createRequire(import.meta.url)
function loadPackageVersion(): string {
const env = getCliEnv()
if (env.CODEBUFF_CLI_VERSION) {
return env.CODEBUFF_CLI_VERSION
}
try {
const pkg = require('../package.json') as { version?: string }
if (pkg.version) {
return pkg.version
}
} catch {
// Continue to dev fallback
}
return 'dev'
}
// Configure TanStack Query's focusManager for terminal environments
// This is required because there's no browser visibility API in terminal apps
// Without this, refetchInterval won't work because TanStack Query thinks the app is "unfocused"
focusManager.setEventListener(() => {
// No-op: no event listeners in CLI environment (no window focus/visibility events)
return () => {}
})
focusManager.setFocused(true)
function createQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: {
staleTime: 5 * 60 * 1000, // 5 minutes - auth tokens don't change frequently
gcTime: 10 * 60 * 1000, // 10 minutes - keep cached data a bit longer
retry: false, // Don't retry failed auth queries automatically
refetchOnWindowFocus: false, // CLI doesn't have window focus
refetchOnReconnect: true, // Refetch when network reconnects
refetchOnMount: false, // Don't refetch on every mount
},
mutations: {
retry: 1, // Retry mutations once on failure
},
},
})
}
type ParsedArgs = {
initialPrompt: string | null
agent?: string
clearLogs: boolean
continue: boolean
continueId?: string | null
cwd?: string
initialMode?: AgentMode
}
function parseArgs(): ParsedArgs {
const program = new Command()
program
.name('codebuff')
.description('Codebuff CLI - AI-powered coding assistant')
.version(loadPackageVersion(), '-v, --version', 'Print the CLI version')
.option(
'--agent <agent-id>',
'Specify which agent to use (e.g., "base", "ask", "file-picker")',
)
.option('--clear-logs', 'Remove any existing CLI log files before starting')
.option(
'--continue [conversation-id]',
'Continue from a previous conversation (optionally specify a conversation id)',
)
.option(
'--cwd <directory>',
'Set the working directory (default: current directory)',
)
.option('--lite', 'Start in LITE mode')
.option('--max', 'Start in MAX mode')
.option('--plan', 'Start in PLAN mode')
.helpOption('-h, --help', 'Show this help message')
.argument('[prompt...]', 'Initial prompt to send to the agent')
.allowExcessArguments(true)
.parse(process.argv)
const options = program.opts()
const args = program.args
const continueFlag = options.continue
// Determine initial mode from flags (last flag wins if multiple specified)
let initialMode: AgentMode | undefined
if (options.lite) initialMode = 'LITE'
if (options.max) initialMode = 'MAX'
if (options.plan) initialMode = 'PLAN'
return {
initialPrompt: args.length > 0 ? args.join(' ') : null,
agent: options.agent,
clearLogs: options.clearLogs || false,
continue: Boolean(continueFlag),
continueId:
typeof continueFlag === 'string' && continueFlag.trim().length > 0
? continueFlag.trim()
: null,
cwd: options.cwd,
initialMode,
}
}
async function main(): Promise<void> {
// Run OSC theme detection BEFORE anything else.
// This MUST happen before OpenTUI starts because OSC responses come through stdin,
// and OpenTUI also listens to stdin. Running detection here ensures stdin is clean.
if (process.stdin.isTTY && process.platform !== 'win32') {
try {
const oscTheme = await detectTerminalTheme()
if (oscTheme) {
setOscDetectedTheme(oscTheme)
}
} catch {
// Silently ignore OSC detection failures
}
}
const {
initialPrompt,
agent,
clearLogs,
continue: continueChat,
continueId,
cwd,
initialMode,
} = parseArgs()
await initializeApp({ cwd })
// Detect if user is at home directory or outside a project (should show project picker)
const projectRoot = getProjectRoot()
const homeDir = os.homedir()
const gitRoot = findGitRoot({ cwd: projectRoot })
const showProjectPicker =
projectRoot === '/' || projectRoot === homeDir || gitRoot === null
// Initialize agent registry (loads user agents via SDK)
await initializeAgentRegistry()
// Handle publish command before rendering the app
if (process.argv.includes('publish')) {
const publishIndex = process.argv.indexOf('publish')
const agentIds = process.argv.slice(publishIndex + 1)
const result = await handlePublish(agentIds)
if (result.success && result.publisherId && result.agents) {
console.log(green('✅ Successfully published:'))
for (const agent of result.agents) {
console.log(
cyan(
` - ${agent.displayName} (${result.publisherId}/${agent.id}@${agent.version})`,
),
)
}
process.exit(0)
} else {
console.log(red('❌ Publish failed'))
if (result.error) console.log(red(`Error: ${result.error}`))
if (result.details) console.log(red(result.details))
if (result.hint) console.log(yellow(`Hint: ${result.hint}`))
process.exit(1)
}
}
// Initialize analytics
try {
initAnalytics()
} catch (error) {
// Analytics initialization is optional - don't fail the app if it errors
logger.debug(error, 'Failed to initialize analytics')
}
if (clearLogs) {
clearLogFile()
}
const queryClient = createQueryClient()
const AppWithAsyncAuth = () => {
const [requireAuth, setRequireAuth] = React.useState<boolean | null>(null)
const [hasInvalidCredentials, setHasInvalidCredentials] =
React.useState(false)
const [fileTree, setFileTree] = React.useState<FileTreeNode[]>([])
const [currentProjectRoot, setCurrentProjectRoot] =
React.useState(projectRoot)
const [showProjectPickerScreen, setShowProjectPickerScreen] =
React.useState(showProjectPicker)
React.useEffect(() => {
const apiKey = getAuthTokenDetails().token ?? ''
if (!apiKey) {
setRequireAuth(true)
setHasInvalidCredentials(false)
return
}
setHasInvalidCredentials(true)
setRequireAuth(false)
}, [])
const loadFileTree = React.useCallback(async (root: string) => {
try {
if (root) {
const tree = await getProjectFileTree({
projectRoot: root,
fs: fs,
})
logger.info({ tree }, 'Loaded file tree')
setFileTree(tree)
}
} catch (error) {
// Silently fail - fileTree is optional for @ menu
}
}, [])
React.useEffect(() => {
loadFileTree(currentProjectRoot)
}, [currentProjectRoot, loadFileTree])
// Callback for when user selects a new project from the picker
const handleProjectChange = React.useCallback(
async (newProjectPath: string) => {
// Change process working directory
process.chdir(newProjectPath)
// Update the project root in the module state
setProjectRoot(newProjectPath)
// Save to recent projects list
saveRecentProject(newProjectPath)
// Update local state
setCurrentProjectRoot(newProjectPath)
// Reset file tree state to trigger reload
setFileTree([])
// Hide the picker and show the chat
setShowProjectPickerScreen(false)
},
[],
)
return (
<App
initialPrompt={initialPrompt}
agentId={agent}
requireAuth={requireAuth}
hasInvalidCredentials={hasInvalidCredentials}
fileTree={fileTree}
continueChat={continueChat}
continueChatId={continueId ?? undefined}
initialMode={initialMode}
showProjectPicker={showProjectPickerScreen}
onProjectChange={handleProjectChange}
/>
)
}
const renderer = await createCliRenderer({
backgroundColor: 'transparent',
exitOnCtrlC: false,
})
const root = createRoot(renderer)
// React component tree to render
const app = (
<QueryClientProvider client={queryClient}>
<AppWithAsyncAuth />
</QueryClientProvider>
)
// Add resize event listener for terminal resize support on Windows PowerShell
// On Windows, the SIGWINCH signal may not fire reliably, so we listen to
// process.stdout 'resize' event to ensure the UI updates when the window is resized
if (process.stdout.isTTY) {
process.stdout.on('resize', () => {
// Re-render the React tree to update with new terminal dimensions
root.render(app)
})
}
// Initial render
root.render(app)
}
void main()