-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathindex.tsx
More file actions
343 lines (303 loc) · 10.7 KB
/
index.tsx
File metadata and controls
343 lines (303 loc) · 10.7 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
#!/usr/bin/env bun
import fs from 'fs'
import { createRequire } from 'module'
import os from 'os'
import path from 'path'
import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events'
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, trackEvent } from './utils/analytics'
import { getAuthTokenDetails } from './utils/auth'
import { resetCodebuffClient } from './utils/codebuff-client'
import { getCliEnv } from './utils/env'
import { initializeAgentRegistry } from './utils/local-agent-registry'
import { clearLogFile, logger } from './utils/logger'
import { shouldShowProjectPicker } from './utils/project-picker'
import { saveRecentProject } from './utils/recent-projects'
import { installProcessCleanupHandlers } from './utils/renderer-cleanup'
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>',
'Run a specific agent id (skips loading local .agents overrides)',
)
.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('--free', 'Start in FREE mode')
.option('--lite', 'Start in FREE mode (deprecated, use --free)')
.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.free || options.lite) initialMode = 'FREE'
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()
const isPublishCommand = process.argv.includes('publish')
const hasAgentOverride = Boolean(agent && agent.trim().length > 0)
await initializeApp({ cwd })
// Show project picker only when user starts at the home directory or an ancestor
const projectRoot = getProjectRoot()
const homeDir = os.homedir()
const startCwd = process.cwd()
const showProjectPicker = shouldShowProjectPicker(startCwd, homeDir)
// Initialize agent registry (loads user agents via SDK).
// When --agent is provided, skip local .agents to avoid overrides.
if (isPublishCommand || !hasAgentOverride) {
await initializeAgentRegistry()
}
// Handle publish command before rendering the app
if (isPublishCommand) {
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) {
logger.info(green('✅ Successfully published:'))
for (const agent of result.agents) {
logger.info(
cyan(
` - ${agent.displayName} (${result.publisherId}/${agent.id}@${agent.version})`,
),
)
}
process.exit(0)
} else {
logger.error(red('❌ Publish failed'))
if (result.error) logger.error(red(`Error: ${result.error}`))
if (result.details) logger.error(red(result.details))
if (result.hint) logger.warn(yellow(`Hint: ${result.hint}`))
process.exit(1)
}
}
// Initialize analytics
try {
initAnalytics()
// Track app launch event
trackEvent(AnalyticsEvent.APP_LAUNCHED, {
version: loadPackageVersion(),
platform: process.platform,
arch: process.arch,
hasInitialPrompt: Boolean(initialPrompt),
hasAgentOverride: hasAgentOverride,
continueChat,
initialMode: initialMode ?? 'DEFAULT',
})
} 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.promises,
})
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) => {
const previousPath = process.cwd()
// Change process working directory
process.chdir(newProjectPath)
// Track directory change (avoid logging full paths for privacy)
const isGitRepo = fs.existsSync(path.join(newProjectPath, '.git'))
const pathDepth = newProjectPath.split(path.sep).filter(Boolean).length
trackEvent(AnalyticsEvent.CHANGE_DIRECTORY, {
isGitRepo,
pathDepth,
isHomeDir: newProjectPath === os.homedir(),
})
// Update the project root in the module state
setProjectRoot(newProjectPath)
// Reset client to ensure tools use the updated project root
resetCodebuffClient()
// 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,
})
installProcessCleanupHandlers(renderer)
createRoot(renderer).render(
<QueryClientProvider client={queryClient}>
<AppWithAsyncAuth />
</QueryClientProvider>,
)
}
void main()