Compare commits

...

11 Commits

29 changed files with 3857 additions and 1096 deletions

View File

@@ -4,7 +4,7 @@
</div>
A desktop and mobile UI for [Claude Code](https://docs.anthropic.com/en/docs/claude-code), and [Cursor CLI](https://docs.cursor.com/en/cli/overview). You can use it locally or remotely to view your active projects and sessions in Claude Code or Cursor and make changes to them from everywhere (mobile or desktop). This gives you a proper interface that works everywhere. Supports models including **Claude Sonnet 4**, **Opus 4.1**, and **GPT-5**
A desktop and mobile UI for [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [Cursor CLI](https://docs.cursor.com/en/cli/overview) and [Codex](https://developers.openai.com/codex). You can use it locally or remotely to view your active projects and sessions in Claude Code, Cursor, or Codex and make changes to them from everywhere (mobile or desktop). This gives you a proper interface that works everywhere.
## Screenshots
@@ -30,7 +30,7 @@ A desktop and mobile UI for [Claude Code](https://docs.anthropic.com/en/docs/cla
<h3>CLI Selection</h3>
<img src="public/screenshots/cli-selection.png" alt="CLI Selection" width="400">
<br>
<em>Select between Claude Code and Cursor CLI</em>
<em>Select between Claude Code, Cursor CLI and Codex</em>
</td>
</tr>
</table>
@@ -41,14 +41,14 @@ A desktop and mobile UI for [Claude Code](https://docs.anthropic.com/en/docs/cla
## Features
- **Responsive Design** - Works seamlessly across desktop, tablet, and mobile so you can also use Claude Code from mobile
- **Interactive Chat Interface** - Built-in chat interface for seamless communication with Claude Code or Cursor
- **Integrated Shell Terminal** - Direct access to Claude Code or Cursor CLI through built-in shell functionality
- **Responsive Design** - Works seamlessly across desktop, tablet, and mobile so you can also use Claude Code, Cursor, or Codex from mobile
- **Interactive Chat Interface** - Built-in chat interface for seamless communication with Claude Code, Cursor, or Codex
- **Integrated Shell Terminal** - Direct access to Claude Code, Cursor CLI, or Codex through built-in shell functionality
- **File Explorer** - Interactive file tree with syntax highlighting and live editing
- **Git Explorer** - View, stage and commit your changes. You can also switch branches
- **Session Management** - Resume conversations, manage multiple sessions, and track history
- **TaskMaster AI Integration** *(Optional)* - Advanced project management with AI-powered task planning, PRD parsing, and workflow automation
- **Model Compatibility** - Works with Claude Sonnet 4, Opus 4.1, and GPT-5
- **Model Compatibility** - Works with Claude Sonnet 4.5, Opus 4.5, and GPT-5.2
## Quick Start
@@ -57,7 +57,8 @@ A desktop and mobile UI for [Claude Code](https://docs.anthropic.com/en/docs/cla
- [Node.js](https://nodejs.org/) v20 or higher
- [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code) installed and configured, and/or
- [Cursor CLI](https://docs.cursor.com/en/cli/overview) installed and configured
- [Cursor CLI](https://docs.cursor.com/en/cli/overview) installed and configured, and/or
- [Codex](https://developers.openai.com/codex) installed and configured
### One-click Operation (Recommended)
@@ -218,15 +219,15 @@ After installing it you should be able to enable it from the Settings
### Core Features
#### Project Management
The UI automatically discovers Claude Code projects from `~/.claude/projects/` and provides:
- **Visual Project Browser** - All available projects with metadata and session counts
It automatically discovers Claude Code, Cursor or Codex sessions when available and groups them together into projects
session counts
- **Project Actions** - Rename, delete, and organize projects
- **Smart Navigation** - Quick access to recent projects and sessions
- **MCP support** - Add your own MCP servers through the UI
#### Chat Interface
- **Use responsive chat or Claude Code/Cursor CLI** - You can either use the adapted chat interface or use the shell button to connect to your selected CLI.
- **Real-time Communication** - Stream responses from Claude with WebSocket connection
- **Use responsive chat or Claude Code/Cursor CLI/Codex CLI** - You can either use the adapted chat interface or use the shell button to connect to your selected CLI.
- **Real-time Communication** - Stream responses from your selected CLI (Claude Code/Cursor/Codex) with WebSocket connection
- **Session Management** - Resume previous conversations or start fresh sessions
- **Message History** - Complete conversation history with timestamps and metadata
- **Multi-format Support** - Text, code blocks, and file references
@@ -264,16 +265,16 @@ The UI automatically discovers Claude Code projects from `~/.claude/projects/` a
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Frontend │ │ Backend │ │ Claude CLI
│ Frontend │ │ Backend │ │ Agent
│ (React/Vite) │◄──►│ (Express/WS) │◄──►│ Integration │
│ │ │ │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
```
### Backend (Node.js + Express)
- **Express Server** - RESTful API with static file serving
- **WebSocket Server** - Communication for chats and project refresh
- **CLI Integration (Claude Code / Cursor)** - Process spawning and management
- **Session Management** - JSONL parsing and conversation persistence
- **Agent Integration (Claude Code / Cursor CLI / Codex)** - Process spawning and management
- **File System API** - Exposing file browser for projects
### Frontend (React + Vite)
@@ -320,7 +321,7 @@ We welcome contributions! Please follow these guidelines:
#### "No Claude projects found"
**Problem**: The UI shows no projects or empty project list
**Solutions**:
- Ensure [Claude CLI](https://docs.anthropic.com/en/docs/claude-code) is properly installed
- Ensure [Claude Code](https://docs.anthropic.com/en/docs/claude-code) is properly installed
- Run `claude` command in at least one project directory to initialize
- Verify `~/.claude/projects/` directory exists and has proper permissions
@@ -343,6 +344,8 @@ This project is open source and free to use, modify, and distribute under the GP
### Built With
- **[Claude Code](https://docs.anthropic.com/en/docs/claude-code)** - Anthropic's official CLI
- **[Cursor CLI](https://docs.cursor.com/en/cli/overview)** - Cursor's official CLI
- **[Codex](https://developers.openai.com/codex)** - OpenAI Codex
- **[React](https://react.dev/)** - User interface library
- **[Vite](https://vitejs.dev/)** - Fast build tool and dev server
- **[Tailwind CSS](https://tailwindcss.com/)** - Utility-first CSS framework
@@ -361,5 +364,5 @@ This project is open source and free to use, modify, and distribute under the GP
---
<div align="center">
<strong>Made with care for the Claude Code community.</strong>
<strong>Made with care for the Claude Code, Cursor and Codex community.</strong>
</div>

View File

@@ -11,7 +11,7 @@
<link rel="manifest" href="/manifest.json" />
<!-- iOS Safari PWA Meta Tags -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="Claude UI" />

27
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "@siteboon/claude-code-ui",
"version": "1.12.0",
"version": "1.13.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@siteboon/claude-code-ui",
"version": "1.12.0",
"version": "1.13.0",
"license": "MIT",
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.1.29",
@@ -18,7 +18,9 @@
"@codemirror/lang-python": "^6.2.1",
"@codemirror/merge": "^6.11.1",
"@codemirror/theme-one-dark": "^6.1.2",
"@iarna/toml": "^2.2.5",
"@octokit/rest": "^22.0.0",
"@openai/codex-sdk": "^0.75.0",
"@replit/codemirror-minimap": "^0.5.2",
"@tailwindcss/typography": "^0.5.16",
"@uiw/react-codemirror": "^4.23.13",
@@ -1062,6 +1064,12 @@
"license": "MIT",
"optional": true
},
"node_modules/@iarna/toml": {
"version": "2.2.5",
"resolved": "https://registry.npmjs.org/@iarna/toml/-/toml-2.2.5.tgz",
"integrity": "sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==",
"license": "ISC"
},
"node_modules/@img/sharp-darwin-arm64": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz",
@@ -2417,6 +2425,15 @@
"@octokit/openapi-types": "^26.0.0"
}
},
"node_modules/@openai/codex-sdk": {
"version": "0.75.0",
"resolved": "https://registry.npmjs.org/@openai/codex-sdk/-/codex-sdk-0.75.0.tgz",
"integrity": "sha512-4X5kHPXLu16SmGUdsvSa9xRuVmRC8oQw62iH8dRyIDbyy2MNkh068NNoHWDoJErRLUc4X4Ed2ceiNs6Tbkswnw==",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
}
},
"node_modules/@phun-ky/typeof": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@phun-ky/typeof/-/typeof-2.0.3.tgz",
@@ -3748,9 +3765,9 @@
}
},
"node_modules/caniuse-lite": {
"version": "1.0.30001727",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001727.tgz",
"integrity": "sha512-pB68nIHmbN6L/4C6MH1DokyR3bYqFwjaSs/sWDHGj4CTcFtQUQMuJftVwWkXq7mNWOybD3KhUv3oWHoGxgP14Q==",
"version": "1.0.30001761",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001761.tgz",
"integrity": "sha512-JF9ptu1vP2coz98+5051jZ4PwQgd2ni8A+gYSN7EA7dPKIMf0pDlSUxhdmVOaV3/fYK5uWBkgSXJaRLr4+3A6g==",
"dev": true,
"funding": [
{

View File

@@ -1,6 +1,6 @@
{
"name": "@siteboon/claude-code-ui",
"version": "1.12.0",
"version": "1.13.0",
"description": "A web-based UI for Claude Code CLI",
"type": "module",
"main": "server/index.js",
@@ -49,7 +49,9 @@
"@codemirror/lang-python": "^6.2.1",
"@codemirror/merge": "^6.11.1",
"@codemirror/theme-one-dark": "^6.1.2",
"@iarna/toml": "^2.2.5",
"@octokit/rest": "^22.0.0",
"@openai/codex-sdk": "^0.75.0",
"@replit/codemirror-minimap": "^0.5.2",
"@tailwindcss/typography": "^0.5.16",
"@uiw/react-codemirror": "^4.23.13",

View File

@@ -0,0 +1,3 @@
<svg viewBox="100 100 520 520" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M304.246 295.411V249.828C304.246 245.989 305.687 243.109 309.044 241.191L400.692 188.412C413.167 181.215 428.042 177.858 443.394 177.858C500.971 177.858 537.44 222.482 537.44 269.982C537.44 273.34 537.44 277.179 536.959 281.018L441.954 225.358C436.197 222 430.437 222 424.68 225.358L304.246 295.411ZM518.245 472.945V364.024C518.245 357.304 515.364 352.507 509.608 349.149L389.174 279.096L428.519 256.543C431.877 254.626 434.757 254.626 438.115 256.543L529.762 309.323C556.154 324.679 573.905 357.304 573.905 388.971C573.905 425.436 552.315 459.024 518.245 472.941V472.945ZM275.937 376.982L236.592 353.952C233.235 352.034 231.794 349.154 231.794 345.315V239.756C231.794 188.416 271.139 149.548 324.4 149.548C344.555 149.548 363.264 156.268 379.102 168.262L284.578 222.964C278.822 226.321 275.942 231.119 275.942 237.838V376.986L275.937 376.982ZM360.626 425.922L304.246 394.255V327.083L360.626 295.416L417.002 327.083V394.255L360.626 425.922ZM396.852 571.789C376.698 571.789 357.989 565.07 342.151 553.075L436.674 498.374C442.431 495.017 445.311 490.219 445.311 483.499V344.352L485.138 367.382C488.495 369.299 489.936 372.179 489.936 376.018V481.577C489.936 532.917 450.109 571.785 396.852 571.785V571.789ZM283.134 464.79L191.486 412.01C165.094 396.654 147.343 364.029 147.343 332.362C147.343 295.416 169.415 262.309 203.48 248.393V357.791C203.48 364.51 206.361 369.308 212.117 372.665L332.074 442.237L292.729 464.79C289.372 466.707 286.491 466.707 283.134 464.79ZM277.859 543.48C223.639 543.48 183.813 502.695 183.813 452.314C183.813 448.475 184.294 444.636 184.771 440.797L279.295 495.498C285.051 498.856 290.812 498.856 296.568 495.498L417.002 425.927V471.509C417.002 475.349 415.562 478.229 412.204 480.146L320.557 532.926C308.081 540.122 293.206 543.48 277.854 543.48H277.859ZM396.852 600.576C454.911 600.576 503.37 559.313 514.41 504.612C568.149 490.696 602.696 440.315 602.696 388.976C602.696 355.387 588.303 322.762 562.392 299.25C564.791 289.173 566.231 279.096 566.231 269.024C566.231 200.411 510.571 149.067 446.274 149.067C433.322 149.067 420.846 150.984 408.37 155.305C386.775 134.192 357.026 120.758 324.4 120.758C266.342 120.758 217.883 162.02 206.843 216.721C153.104 230.637 118.557 281.018 118.557 332.357C118.557 365.946 132.95 398.571 158.861 422.083C156.462 432.16 155.022 442.237 155.022 452.309C155.022 520.922 210.682 572.266 274.978 572.266C287.931 572.266 300.407 570.349 312.883 566.028C334.473 587.141 364.222 600.576 396.852 600.576Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

3
public/icons/codex.svg Normal file
View File

@@ -0,0 +1,3 @@
<svg viewBox="100 100 520 520" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M304.246 294.611V249.028C304.246 245.189 305.687 242.309 309.044 240.392L400.692 187.612C413.167 180.415 428.042 177.058 443.394 177.058C500.971 177.058 537.44 221.682 537.44 269.182C537.44 272.54 537.44 276.379 536.959 280.218L441.954 224.558C436.197 221.201 430.437 221.201 424.68 224.558L304.246 294.611ZM518.245 472.145V363.224C518.245 356.505 515.364 351.707 509.608 348.349L389.174 278.296L428.519 255.743C431.877 253.826 434.757 253.826 438.115 255.743L529.762 308.523C556.154 323.879 573.905 356.505 573.905 388.171C573.905 424.636 552.315 458.225 518.245 472.141V472.145ZM275.937 376.182L236.592 353.152C233.235 351.235 231.794 348.354 231.794 344.515V238.956C231.794 187.617 271.139 148.749 324.4 148.749C344.555 148.749 363.264 155.468 379.102 167.463L284.578 222.164C278.822 225.521 275.942 230.319 275.942 237.039V376.186L275.937 376.182ZM360.626 425.122L304.246 393.455V326.283L360.626 294.616L417.002 326.283V393.455L360.626 425.122ZM396.852 570.989C376.698 570.989 357.989 564.27 342.151 552.276L436.674 497.574C442.431 494.217 445.311 489.419 445.311 482.699V343.552L485.138 366.582C488.495 368.499 489.936 371.379 489.936 375.219V480.778C489.936 532.117 450.109 570.985 396.852 570.985V570.989ZM283.134 463.99L191.486 411.211C165.094 395.854 147.343 363.229 147.343 331.562C147.343 294.616 169.415 261.509 203.48 247.593V356.991C203.48 363.71 206.361 368.508 212.117 371.866L332.074 441.437L292.729 463.99C289.372 465.907 286.491 465.907 283.134 463.99ZM277.859 542.68C223.639 542.68 183.813 501.895 183.813 451.514C183.813 447.675 184.294 443.836 184.771 439.997L279.295 494.698C285.051 498.056 290.812 498.056 296.568 494.698L417.002 425.127V470.71C417.002 474.549 415.562 477.429 412.204 479.346L320.557 532.126C308.081 539.323 293.206 542.68 277.854 542.68H277.859ZM396.852 599.776C454.911 599.776 503.37 558.513 514.41 503.812C568.149 489.896 602.696 439.515 602.696 388.176C602.696 354.587 588.303 321.962 562.392 298.45C564.791 288.373 566.231 278.296 566.231 268.224C566.231 199.611 510.571 148.267 446.274 148.267C433.322 148.267 420.846 150.184 408.37 154.505C386.775 133.392 357.026 119.958 324.4 119.958C266.342 119.958 217.883 161.22 206.843 215.921C153.104 229.837 118.557 280.218 118.557 331.557C118.557 365.146 132.95 397.771 158.861 421.283C156.462 431.36 155.022 441.437 155.022 451.51C155.022 520.123 210.682 571.466 274.978 571.466C287.931 571.466 300.407 569.549 312.883 565.228C334.473 586.341 364.222 599.776 396.852 599.776Z" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09">
<!-- Generator: Adobe Illustrator 29.6.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 9) -->
<defs>
<style>
.st0 {
fill: #edecec;
}
</style>
</defs>
<path class="st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"/>
</svg>

After

Width:  |  Height:  |  Size: 793 B

View File

@@ -57,7 +57,7 @@ function mapCliOptionsToSDK(options = {}) {
// Add plan mode default tools
if (permissionMode === 'plan') {
const planModeTools = ['Read', 'Task', 'exit_plan_mode', 'TodoRead', 'TodoWrite'];
const planModeTools = ['Read', 'Task', 'exit_plan_mode', 'TodoRead', 'TodoWrite', 'WebFetch', 'WebSearch'];
for (const tool of planModeTools) {
if (!allowedTools.includes(tool)) {
allowedTools.push(tool);
@@ -76,8 +76,9 @@ function mapCliOptionsToSDK(options = {}) {
}
// Map model (default to sonnet)
// Map model (default to sonnet)
// Valid models: sonnet, opus, haiku, opusplan, sonnet[1m]
sdkOptions.model = options.model || 'sonnet';
console.log(`Using model: ${sdkOptions.model}`);
// Map system prompt configuration
sdkOptions.systemPrompt = {
@@ -183,7 +184,7 @@ function extractTokenBudget(resultMessage) {
// This is the user's budget limit, not the model's context window
const contextWindow = parseInt(process.env.CONTEXT_WINDOW) || 160000;
console.log(`📊 Token calculation: input=${inputTokens}, output=${outputTokens}, cache=${cacheReadTokens + cacheCreationTokens}, total=${totalUsed}/${contextWindow}`);
console.log(`Token calculation: input=${inputTokens}, output=${outputTokens}, cache=${cacheReadTokens + cacheCreationTokens}, total=${totalUsed}/${contextWindow}`);
return {
used: totalUsed,
@@ -239,7 +240,7 @@ async function handleImages(command, images, cwd) {
modifiedCommand = command + imageNote;
}
console.log(`📸 Processed ${tempImagePaths.length} images to temp directory: ${tempDir}`);
console.log(`Processed ${tempImagePaths.length} images to temp directory: ${tempDir}`);
return { modifiedCommand, tempImagePaths, tempDir };
} catch (error) {
console.error('Error processing images for SDK:', error);
@@ -272,7 +273,7 @@ async function cleanupTempFiles(tempImagePaths, tempDir) {
);
}
console.log(`🧹 Cleaned up ${tempImagePaths.length} temp image files`);
console.log(`Cleaned up ${tempImagePaths.length} temp image files`);
} catch (error) {
console.error('Error during temp file cleanup:', error);
}
@@ -292,7 +293,7 @@ async function loadMcpConfig(cwd) {
await fs.access(claudeConfigPath);
} catch (error) {
// File doesn't exist, return null
console.log('📡 No ~/.claude.json found, proceeding without MCP servers');
console.log('No ~/.claude.json found, proceeding without MCP servers');
return null;
}
@@ -302,7 +303,7 @@ async function loadMcpConfig(cwd) {
const configContent = await fs.readFile(claudeConfigPath, 'utf8');
claudeConfig = JSON.parse(configContent);
} catch (error) {
console.error('Failed to parse ~/.claude.json:', error.message);
console.error('Failed to parse ~/.claude.json:', error.message);
return null;
}
@@ -312,7 +313,7 @@ async function loadMcpConfig(cwd) {
// Add global MCP servers
if (claudeConfig.mcpServers && typeof claudeConfig.mcpServers === 'object') {
mcpServers = { ...claudeConfig.mcpServers };
console.log(`📡 Loaded ${Object.keys(mcpServers).length} global MCP servers`);
console.log(`Loaded ${Object.keys(mcpServers).length} global MCP servers`);
}
// Add/override with project-specific MCP servers
@@ -320,20 +321,20 @@ async function loadMcpConfig(cwd) {
const projectConfig = claudeConfig.claudeProjects[cwd];
if (projectConfig && projectConfig.mcpServers && typeof projectConfig.mcpServers === 'object') {
mcpServers = { ...mcpServers, ...projectConfig.mcpServers };
console.log(`📡 Loaded ${Object.keys(projectConfig.mcpServers).length} project-specific MCP servers`);
console.log(`Loaded ${Object.keys(projectConfig.mcpServers).length} project-specific MCP servers`);
}
}
// Return null if no servers found
if (Object.keys(mcpServers).length === 0) {
console.log('📡 No MCP servers configured');
console.log('No MCP servers configured');
return null;
}
console.log(`Total MCP servers loaded: ${Object.keys(mcpServers).length}`);
console.log(`Total MCP servers loaded: ${Object.keys(mcpServers).length}`);
return mcpServers;
} catch (error) {
console.error('Error loading MCP config:', error.message);
console.error('Error loading MCP config:', error.message);
return null;
}
}
@@ -380,7 +381,7 @@ async function queryClaudeSDK(command, options = {}, ws) {
}
// Process streaming messages
console.log('🔄 Starting async generator loop for session:', capturedSessionId || 'NEW');
console.log('Starting async generator loop for session:', capturedSessionId || 'NEW');
for await (const message of queryInstance) {
// Capture session ID from first message
if (message.session_id && !capturedSessionId) {
@@ -401,10 +402,10 @@ async function queryClaudeSDK(command, options = {}, ws) {
sessionId: capturedSessionId
}));
} else {
console.log('⚠️ Not sending session-created. sessionId:', sessionId, 'sessionCreatedSent:', sessionCreatedSent);
console.log('Not sending session-created. sessionId:', sessionId, 'sessionCreatedSent:', sessionCreatedSent);
}
} else {
console.log('⚠️ No session_id in message or already captured. message.session_id:', message.session_id, 'capturedSessionId:', capturedSessionId);
console.log('No session_id in message or already captured. message.session_id:', message.session_id, 'capturedSessionId:', capturedSessionId);
}
// Transform and send message to WebSocket
@@ -418,7 +419,7 @@ async function queryClaudeSDK(command, options = {}, ws) {
if (message.type === 'result') {
const tokenBudget = extractTokenBudget(message);
if (tokenBudget) {
console.log('📊 Token budget from modelUsage:', tokenBudget);
console.log('Token budget from modelUsage:', tokenBudget);
ws.send(JSON.stringify({
type: 'token-budget',
data: tokenBudget
@@ -436,14 +437,14 @@ async function queryClaudeSDK(command, options = {}, ws) {
await cleanupTempFiles(tempImagePaths, tempDir);
// Send completion event
console.log('Streaming complete, sending claude-complete event');
console.log('Streaming complete, sending claude-complete event');
ws.send(JSON.stringify({
type: 'claude-complete',
sessionId: capturedSessionId,
exitCode: 0,
isNewSession: !sessionId && !!command
}));
console.log('📤 claude-complete event sent');
console.log('claude-complete event sent');
} catch (error) {
console.error('SDK query error:', error);
@@ -480,7 +481,7 @@ async function abortClaudeSDKSession(sessionId) {
}
try {
console.log(`🛑 Aborting SDK session: ${sessionId}`);
console.log(`Aborting SDK session: ${sessionId}`);
// Call interrupt() on the query instance
await session.instance.interrupt();

View File

@@ -60,6 +60,7 @@ import mime from 'mime-types';
import { getProjects, getSessions, getSessionMessages, renameProject, deleteSession, deleteProject, addProjectManually, extractProjectDirectory, clearProjectDirectoryCache } from './projects.js';
import { queryClaudeSDK, abortClaudeSDKSession, isClaudeSDKSessionActive, getActiveClaudeSDKSessions } from './claude-sdk.js';
import { spawnCursor, abortCursorSession, isCursorSessionActive, getActiveCursorSessions } from './cursor-cli.js';
import { queryCodex, abortCodexSession, isCodexSessionActive, getActiveCodexSessions } from './openai-codex.js';
import gitRoutes from './routes/git.js';
import authRoutes from './routes/auth.js';
import mcpRoutes from './routes/mcp.js';
@@ -72,6 +73,7 @@ import agentRoutes from './routes/agent.js';
import projectsRoutes from './routes/projects.js';
import cliAuthRoutes from './routes/cli-auth.js';
import userRoutes from './routes/user.js';
import codexRoutes from './routes/codex.js';
import { initializeDatabase } from './database/db.js';
import { validateApiKey, authenticateToken, authenticateWebSocket } from './middleware/auth.js';
@@ -211,7 +213,17 @@ const wss = new WebSocketServer({
app.locals.wss = wss;
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.json({
limit: '50mb',
type: (req) => {
// Skip multipart/form-data requests (for file uploads like images)
const contentType = req.headers['content-type'] || '';
if (contentType.includes('multipart/form-data')) {
return false;
}
return contentType.includes('json');
}
}));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
// Public health check endpoint (no authentication required)
@@ -258,6 +270,9 @@ app.use('/api/cli', authenticateToken, cliAuthRoutes);
// User API Routes (protected)
app.use('/api/user', authenticateToken, userRoutes);
// Codex API Routes (protected)
app.use('/api/codex', authenticateToken, codexRoutes);
// Agent API Routes (uses API key authentication)
app.use('/api/agent', agentRoutes);
@@ -726,6 +741,12 @@ function handleChatConnection(ws) {
console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
console.log('🤖 Model:', data.options?.model || 'default');
await spawnCursor(data.command, data.options, ws);
} else if (data.type === 'codex-command') {
console.log('[DEBUG] Codex message:', data.command || '[Continue/Resume]');
console.log('📁 Project:', data.options?.projectPath || data.options?.cwd || 'Unknown');
console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
console.log('🤖 Model:', data.options?.model || 'default');
await queryCodex(data.command, data.options, ws);
} else if (data.type === 'cursor-resume') {
// Backward compatibility: treat as cursor-command with resume and no prompt
console.log('[DEBUG] Cursor resume session (compat):', data.sessionId);
@@ -741,6 +762,8 @@ function handleChatConnection(ws) {
if (provider === 'cursor') {
success = abortCursorSession(data.sessionId);
} else if (provider === 'codex') {
success = abortCodexSession(data.sessionId);
} else {
// Use Claude Agents SDK
success = await abortClaudeSDKSession(data.sessionId);
@@ -769,6 +792,8 @@ function handleChatConnection(ws) {
if (provider === 'cursor') {
isActive = isCursorSessionActive(sessionId);
} else if (provider === 'codex') {
isActive = isCodexSessionActive(sessionId);
} else {
// Use Claude Agents SDK
isActive = isClaudeSDKSessionActive(sessionId);
@@ -784,7 +809,8 @@ function handleChatConnection(ws) {
// Get all currently active sessions
const activeSessions = {
claude: getActiveClaudeSDKSessions(),
cursor: getActiveCursorSessions()
cursor: getActiveCursorSessions(),
codex: getActiveCodexSessions()
};
ws.send(JSON.stringify({
type: 'active-sessions',
@@ -827,9 +853,31 @@ function handleShellConnection(ws) {
const initialCommand = data.initialCommand;
const isPlainShell = data.isPlainShell || (!!initialCommand && !hasSession) || provider === 'plain-shell';
ptySessionKey = `${projectPath}_${sessionId || 'default'}`;
// Login commands (Claude/Cursor auth) should never reuse cached sessions
const isLoginCommand = initialCommand && (
initialCommand.includes('setup-token') ||
initialCommand.includes('cursor-agent login') ||
initialCommand.includes('auth login')
);
const existingSession = ptySessionsMap.get(ptySessionKey);
// Include command hash in session key so different commands get separate sessions
const commandSuffix = isPlainShell && initialCommand
? `_cmd_${Buffer.from(initialCommand).toString('base64').slice(0, 16)}`
: '';
ptySessionKey = `${projectPath}_${sessionId || 'default'}${commandSuffix}`;
// Kill any existing login session before starting fresh
if (isLoginCommand) {
const oldSession = ptySessionsMap.get(ptySessionKey);
if (oldSession) {
console.log('🧹 Cleaning up existing login session:', ptySessionKey);
if (oldSession.timeoutId) clearTimeout(oldSession.timeoutId);
if (oldSession.pty && oldSession.pty.kill) oldSession.pty.kill();
ptySessionsMap.delete(ptySessionKey);
}
}
const existingSession = isLoginCommand ? null : ptySessionsMap.get(ptySessionKey);
if (existingSession) {
console.log('♻️ Reconnecting to existing PTY session:', ptySessionKey);
shellProcess = existingSession.pty;
@@ -1332,8 +1380,98 @@ app.post('/api/projects/:projectName/upload-images', authenticateToken, async (r
app.get('/api/projects/:projectName/sessions/:sessionId/token-usage', authenticateToken, async (req, res) => {
try {
const { projectName, sessionId } = req.params;
const { provider = 'claude' } = req.query;
const homeDir = os.homedir();
// Allow only safe characters in sessionId
const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '');
if (!safeSessionId) {
return res.status(400).json({ error: 'Invalid sessionId' });
}
// Handle Cursor sessions - they use SQLite and don't have token usage info
if (provider === 'cursor') {
return res.json({
used: 0,
total: 0,
breakdown: { input: 0, cacheCreation: 0, cacheRead: 0 },
unsupported: true,
message: 'Token usage tracking not available for Cursor sessions'
});
}
// Handle Codex sessions
if (provider === 'codex') {
const codexSessionsDir = path.join(homeDir, '.codex', 'sessions');
// Find the session file by searching for the session ID
const findSessionFile = async (dir) => {
try {
const entries = await fsPromises.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
const found = await findSessionFile(fullPath);
if (found) return found;
} else if (entry.name.includes(safeSessionId) && entry.name.endsWith('.jsonl')) {
return fullPath;
}
}
} catch (error) {
// Skip directories we can't read
}
return null;
};
const sessionFilePath = await findSessionFile(codexSessionsDir);
if (!sessionFilePath) {
return res.status(404).json({ error: 'Codex session file not found', sessionId: safeSessionId });
}
// Read and parse the Codex JSONL file
let fileContent;
try {
fileContent = await fsPromises.readFile(sessionFilePath, 'utf8');
} catch (error) {
if (error.code === 'ENOENT') {
return res.status(404).json({ error: 'Session file not found', path: sessionFilePath });
}
throw error;
}
const lines = fileContent.trim().split('\n');
let totalTokens = 0;
let contextWindow = 200000; // Default for Codex/OpenAI
// Find the latest token_count event with info (scan from end)
for (let i = lines.length - 1; i >= 0; i--) {
try {
const entry = JSON.parse(lines[i]);
// Codex stores token info in event_msg with type: "token_count"
if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
const tokenInfo = entry.payload.info;
if (tokenInfo.total_token_usage) {
totalTokens = tokenInfo.total_token_usage.total_tokens || 0;
}
if (tokenInfo.model_context_window) {
contextWindow = tokenInfo.model_context_window;
}
break; // Stop after finding the latest token count
}
} catch (parseError) {
// Skip lines that can't be parsed
continue;
}
}
return res.json({
used: totalTokens,
total: contextWindow
});
}
// Handle Claude sessions (default)
// Extract actual project path
let projectPath;
try {
@@ -1349,11 +1487,6 @@ app.get('/api/projects/:projectName/sessions/:sessionId/token-usage', authentica
const encodedPath = projectPath.replace(/[\\/:\s~_]/g, '-');
const projectDir = path.join(homeDir, '.claude', 'projects', encodedPath);
// Allow only safe characters in sessionId
const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '');
if (!safeSessionId) {
return res.status(400).json({ error: 'Invalid sessionId' });
}
const jsonlPath = path.join(projectDir, `${safeSessionId}.jsonl`);
// Constrain to projectDir

387
server/openai-codex.js Normal file
View File

@@ -0,0 +1,387 @@
/**
* OpenAI Codex SDK Integration
* =============================
*
* This module provides integration with the OpenAI Codex SDK for non-interactive
* chat sessions. It mirrors the pattern used in claude-sdk.js for consistency.
*
* ## Usage
*
* - queryCodex(command, options, ws) - Execute a prompt with streaming via WebSocket
* - abortCodexSession(sessionId) - Cancel an active session
* - isCodexSessionActive(sessionId) - Check if a session is running
* - getActiveCodexSessions() - List all active sessions
*/
import { Codex } from '@openai/codex-sdk';
// Track active sessions
const activeCodexSessions = new Map();
/**
* Transform Codex SDK event to WebSocket message format
* @param {object} event - SDK event
* @returns {object} - Transformed event for WebSocket
*/
function transformCodexEvent(event) {
// Map SDK event types to a consistent format
switch (event.type) {
case 'item.started':
case 'item.updated':
case 'item.completed':
const item = event.item;
if (!item) {
return { type: event.type, item: null };
}
// Transform based on item type
switch (item.type) {
case 'agent_message':
return {
type: 'item',
itemType: 'agent_message',
message: {
role: 'assistant',
content: item.text
}
};
case 'reasoning':
return {
type: 'item',
itemType: 'reasoning',
message: {
role: 'assistant',
content: item.text,
isReasoning: true
}
};
case 'command_execution':
return {
type: 'item',
itemType: 'command_execution',
command: item.command,
output: item.aggregated_output,
exitCode: item.exit_code,
status: item.status
};
case 'file_change':
return {
type: 'item',
itemType: 'file_change',
changes: item.changes,
status: item.status
};
case 'mcp_tool_call':
return {
type: 'item',
itemType: 'mcp_tool_call',
server: item.server,
tool: item.tool,
arguments: item.arguments,
result: item.result,
error: item.error,
status: item.status
};
case 'web_search':
return {
type: 'item',
itemType: 'web_search',
query: item.query
};
case 'todo_list':
return {
type: 'item',
itemType: 'todo_list',
items: item.items
};
case 'error':
return {
type: 'item',
itemType: 'error',
message: {
role: 'error',
content: item.message
}
};
default:
return {
type: 'item',
itemType: item.type,
item: item
};
}
case 'turn.started':
return {
type: 'turn_started'
};
case 'turn.completed':
return {
type: 'turn_complete',
usage: event.usage
};
case 'turn.failed':
return {
type: 'turn_failed',
error: event.error
};
case 'thread.started':
return {
type: 'thread_started',
threadId: event.id
};
case 'error':
return {
type: 'error',
message: event.message
};
default:
return {
type: event.type,
data: event
};
}
}
/**
* Map permission mode to Codex SDK options
* @param {string} permissionMode - 'default', 'acceptEdits', or 'bypassPermissions'
* @returns {object} - { sandboxMode, approvalPolicy }
*/
function mapPermissionModeToCodexOptions(permissionMode) {
switch (permissionMode) {
case 'acceptEdits':
return {
sandboxMode: 'workspace-write',
approvalPolicy: 'never'
};
case 'bypassPermissions':
return {
sandboxMode: 'danger-full-access',
approvalPolicy: 'never'
};
case 'default':
default:
return {
sandboxMode: 'workspace-write',
approvalPolicy: 'untrusted'
};
}
}
/**
* Execute a Codex query with streaming
* @param {string} command - The prompt to send
* @param {object} options - Options including cwd, sessionId, model, permissionMode
* @param {WebSocket|object} ws - WebSocket connection or response writer
*/
export async function queryCodex(command, options = {}, ws) {
const {
sessionId,
cwd,
projectPath,
model,
permissionMode = 'default'
} = options;
const workingDirectory = cwd || projectPath || process.cwd();
const { sandboxMode, approvalPolicy } = mapPermissionModeToCodexOptions(permissionMode);
let codex;
let thread;
let currentSessionId = sessionId;
try {
// Initialize Codex SDK
codex = new Codex();
// Thread options with sandbox and approval settings
const threadOptions = {
workingDirectory,
skipGitRepoCheck: true,
sandboxMode,
approvalPolicy
};
// Start or resume thread
if (sessionId) {
thread = codex.resumeThread(sessionId, threadOptions);
} else {
thread = codex.startThread(threadOptions);
}
// Get the thread ID
currentSessionId = thread.id || sessionId || `codex-${Date.now()}`;
// Track the session
activeCodexSessions.set(currentSessionId, {
thread,
codex,
status: 'running',
startedAt: new Date().toISOString()
});
// Send session created event
sendMessage(ws, {
type: 'session-created',
sessionId: currentSessionId,
provider: 'codex'
});
// Execute with streaming
const streamedTurn = await thread.runStreamed(command);
for await (const event of streamedTurn.events) {
// Check if session was aborted
const session = activeCodexSessions.get(currentSessionId);
if (!session || session.status === 'aborted') {
break;
}
if (event.type === 'item.started' || event.type === 'item.updated') {
continue;
}
const transformed = transformCodexEvent(event);
sendMessage(ws, {
type: 'codex-response',
data: transformed,
sessionId: currentSessionId
});
// Extract and send token usage if available (normalized to match Claude format)
if (event.type === 'turn.completed' && event.usage) {
const totalTokens = (event.usage.input_tokens || 0) + (event.usage.output_tokens || 0);
sendMessage(ws, {
type: 'token-budget',
data: {
used: totalTokens,
total: 200000 // Default context window for Codex models
}
});
}
}
// Send completion event
sendMessage(ws, {
type: 'codex-complete',
sessionId: currentSessionId
});
} catch (error) {
console.error('[Codex] Error:', error);
sendMessage(ws, {
type: 'codex-error',
error: error.message,
sessionId: currentSessionId
});
} finally {
// Update session status
if (currentSessionId) {
const session = activeCodexSessions.get(currentSessionId);
if (session) {
session.status = 'completed';
}
}
}
}
/**
* Abort an active Codex session
* @param {string} sessionId - Session ID to abort
* @returns {boolean} - Whether abort was successful
*/
export function abortCodexSession(sessionId) {
const session = activeCodexSessions.get(sessionId);
if (!session) {
return false;
}
session.status = 'aborted';
// The SDK doesn't have a direct abort method, but marking status
// will cause the streaming loop to exit
return true;
}
/**
* Check if a session is active
* @param {string} sessionId - Session ID to check
* @returns {boolean} - Whether session is active
*/
export function isCodexSessionActive(sessionId) {
const session = activeCodexSessions.get(sessionId);
return session?.status === 'running';
}
/**
* Get all active sessions
* @returns {Array} - Array of active session info
*/
export function getActiveCodexSessions() {
const sessions = [];
for (const [id, session] of activeCodexSessions.entries()) {
if (session.status === 'running') {
sessions.push({
id,
status: session.status,
startedAt: session.startedAt
});
}
}
return sessions;
}
/**
* Helper to send message via WebSocket or writer
* @param {WebSocket|object} ws - WebSocket or response writer
* @param {object} data - Data to send
*/
function sendMessage(ws, data) {
try {
if (typeof ws.send === 'function') {
// WebSocket
ws.send(JSON.stringify(data));
} else if (typeof ws.write === 'function') {
// SSE writer (for agent API)
ws.write(`data: ${JSON.stringify(data)}\n\n`);
}
} catch (error) {
console.error('[Codex] Error sending message:', error);
}
}
// Clean up old completed sessions periodically
setInterval(() => {
const now = Date.now();
const maxAge = 30 * 60 * 1000; // 30 minutes
for (const [id, session] of activeCodexSessions.entries()) {
if (session.status !== 'running') {
const startedAt = new Date(session.startedAt).getTime();
if (now - startedAt > maxAge) {
activeCodexSessions.delete(id);
}
}
}
}, 5 * 60 * 1000); // Every 5 minutes

View File

@@ -266,8 +266,16 @@ async function extractProjectDirectory(projectName) {
if (projectDirectoryCache.has(projectName)) {
return projectDirectoryCache.get(projectName);
}
// Check project config for originalPath (manually added projects via UI or platform)
// This handles projects with dashes in their directory names correctly
const config = await loadProjectConfig();
if (config[projectName]?.originalPath) {
const originalPath = config[projectName].originalPath;
projectDirectoryCache.set(projectName, originalPath);
return originalPath;
}
const projectDir = path.join(process.env.HOME, '.claude', 'projects', projectName);
const cwdCounts = new Map();
let latestTimestamp = 0;
@@ -425,7 +433,15 @@ async function getProjects() {
console.warn(`Could not load Cursor sessions for project ${entry.name}:`, e.message);
project.cursorSessions = [];
}
// Also fetch Codex sessions for this project
try {
project.codexSessions = await getCodexSessions(actualProjectDir);
} catch (e) {
console.warn(`Could not load Codex sessions for project ${entry.name}:`, e.message);
project.codexSessions = [];
}
// Add TaskMaster detection
try {
const taskMasterResult = await detectTaskMasterFolder(actualProjectDir);
@@ -478,16 +494,24 @@ async function getProjects() {
isCustomName: !!projectConfig.displayName,
isManuallyAdded: true,
sessions: [],
cursorSessions: []
cursorSessions: [],
codexSessions: []
};
// Try to fetch Cursor sessions for manual projects too
try {
project.cursorSessions = await getCursorSessions(actualProjectDir);
} catch (e) {
console.warn(`Could not load Cursor sessions for manual project ${projectName}:`, e.message);
}
// Try to fetch Codex sessions for manual projects too
try {
project.codexSessions = await getCodexSessions(actualProjectDir);
} catch (e) {
console.warn(`Could not load Codex sessions for manual project ${projectName}:`, e.message);
}
// Add TaskMaster detection for manual projects
try {
const taskMasterResult = await detectTaskMasterFolder(actualProjectDir);
@@ -1141,6 +1165,420 @@ async function getCursorSessions(projectPath) {
}
// Fetch Codex sessions for a given project path
async function getCodexSessions(projectPath) {
try {
const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
const sessions = [];
// Check if the directory exists
try {
await fs.access(codexSessionsDir);
} catch (error) {
// No Codex sessions directory
return [];
}
// Recursively find all .jsonl files in the sessions directory
const findJsonlFiles = async (dir) => {
const files = [];
try {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...await findJsonlFiles(fullPath));
} else if (entry.name.endsWith('.jsonl')) {
files.push(fullPath);
}
}
} catch (error) {
// Skip directories we can't read
}
return files;
};
const jsonlFiles = await findJsonlFiles(codexSessionsDir);
// Process each file to find sessions matching the project path
for (const filePath of jsonlFiles) {
try {
const sessionData = await parseCodexSessionFile(filePath);
// Check if this session matches the project path
if (sessionData && sessionData.cwd === projectPath) {
sessions.push({
id: sessionData.id,
summary: sessionData.summary || 'Codex Session',
messageCount: sessionData.messageCount || 0,
lastActivity: sessionData.timestamp ? new Date(sessionData.timestamp) : new Date(),
cwd: sessionData.cwd,
model: sessionData.model,
filePath: filePath,
provider: 'codex'
});
}
} catch (error) {
console.warn(`Could not parse Codex session file ${filePath}:`, error.message);
}
}
// Sort sessions by last activity (newest first)
sessions.sort((a, b) => new Date(b.lastActivity) - new Date(a.lastActivity));
// Return only the first 5 sessions for performance
return sessions.slice(0, 5);
} catch (error) {
console.error('Error fetching Codex sessions:', error);
return [];
}
}
// Parse a Codex session JSONL file to extract metadata
async function parseCodexSessionFile(filePath) {
try {
const fileStream = fsSync.createReadStream(filePath);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
let sessionMeta = null;
let lastTimestamp = null;
let lastUserMessage = null;
let messageCount = 0;
for await (const line of rl) {
if (line.trim()) {
try {
const entry = JSON.parse(line);
// Track timestamp
if (entry.timestamp) {
lastTimestamp = entry.timestamp;
}
// Extract session metadata
if (entry.type === 'session_meta' && entry.payload) {
sessionMeta = {
id: entry.payload.id,
cwd: entry.payload.cwd,
model: entry.payload.model || entry.payload.model_provider,
timestamp: entry.timestamp,
git: entry.payload.git
};
}
// Count messages and extract user messages for summary
if (entry.type === 'event_msg' && entry.payload?.type === 'user_message') {
messageCount++;
if (entry.payload.text) {
lastUserMessage = entry.payload.text;
}
}
if (entry.type === 'response_item' && entry.payload?.type === 'message') {
messageCount++;
}
} catch (parseError) {
// Skip malformed lines
}
}
}
if (sessionMeta) {
return {
...sessionMeta,
timestamp: lastTimestamp || sessionMeta.timestamp,
summary: lastUserMessage ?
(lastUserMessage.length > 50 ? lastUserMessage.substring(0, 50) + '...' : lastUserMessage) :
'Codex Session',
messageCount
};
}
return null;
} catch (error) {
console.error('Error parsing Codex session file:', error);
return null;
}
}
// Get messages for a specific Codex session
async function getCodexSessionMessages(sessionId, limit = null, offset = 0) {
try {
const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
// Find the session file by searching for the session ID
const findSessionFile = async (dir) => {
try {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
const found = await findSessionFile(fullPath);
if (found) return found;
} else if (entry.name.includes(sessionId) && entry.name.endsWith('.jsonl')) {
return fullPath;
}
}
} catch (error) {
// Skip directories we can't read
}
return null;
};
const sessionFilePath = await findSessionFile(codexSessionsDir);
if (!sessionFilePath) {
console.warn(`Codex session file not found for session ${sessionId}`);
return { messages: [], total: 0, hasMore: false };
}
const messages = [];
let tokenUsage = null;
const fileStream = fsSync.createReadStream(sessionFilePath);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Helper to extract text from Codex content array
const extractText = (content) => {
if (!Array.isArray(content)) return content;
return content
.map(item => {
if (item.type === 'input_text' || item.type === 'output_text') {
return item.text;
}
if (item.type === 'text') {
return item.text;
}
return '';
})
.filter(Boolean)
.join('\n');
};
for await (const line of rl) {
if (line.trim()) {
try {
const entry = JSON.parse(line);
// Extract token usage from token_count events (keep latest)
if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
const info = entry.payload.info;
if (info.total_token_usage) {
tokenUsage = {
used: info.total_token_usage.total_tokens || 0,
total: info.model_context_window || 200000
};
}
}
// Extract messages from response_item
if (entry.type === 'response_item' && entry.payload?.type === 'message') {
const content = entry.payload.content;
const role = entry.payload.role || 'assistant';
const textContent = extractText(content);
// Skip system context messages (environment_context)
if (textContent?.includes('<environment_context>')) {
continue;
}
// Only add if there's actual content
if (textContent?.trim()) {
messages.push({
type: role === 'user' ? 'user' : 'assistant',
timestamp: entry.timestamp,
message: {
role: role,
content: textContent
}
});
}
}
if (entry.type === 'response_item' && entry.payload?.type === 'reasoning') {
const summaryText = entry.payload.summary
?.map(s => s.text)
.filter(Boolean)
.join('\n');
if (summaryText?.trim()) {
messages.push({
type: 'thinking',
timestamp: entry.timestamp,
message: {
role: 'assistant',
content: summaryText
}
});
}
}
if (entry.type === 'response_item' && entry.payload?.type === 'function_call') {
let toolName = entry.payload.name;
let toolInput = entry.payload.arguments;
// Map Codex tool names to Claude equivalents
if (toolName === 'shell_command') {
toolName = 'Bash';
try {
const args = JSON.parse(entry.payload.arguments);
toolInput = JSON.stringify({ command: args.command });
} catch (e) {
// Keep original if parsing fails
}
}
messages.push({
type: 'tool_use',
timestamp: entry.timestamp,
toolName: toolName,
toolInput: toolInput,
toolCallId: entry.payload.call_id
});
}
if (entry.type === 'response_item' && entry.payload?.type === 'function_call_output') {
messages.push({
type: 'tool_result',
timestamp: entry.timestamp,
toolCallId: entry.payload.call_id,
output: entry.payload.output
});
}
if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call') {
const toolName = entry.payload.name || 'custom_tool';
const input = entry.payload.input || '';
if (toolName === 'apply_patch') {
// Parse Codex patch format and convert to Claude Edit format
const fileMatch = input.match(/\*\*\* Update File: (.+)/);
const filePath = fileMatch ? fileMatch[1].trim() : 'unknown';
// Extract old and new content from patch
const lines = input.split('\n');
const oldLines = [];
const newLines = [];
for (const line of lines) {
if (line.startsWith('-') && !line.startsWith('---')) {
oldLines.push(line.substring(1));
} else if (line.startsWith('+') && !line.startsWith('+++')) {
newLines.push(line.substring(1));
}
}
messages.push({
type: 'tool_use',
timestamp: entry.timestamp,
toolName: 'Edit',
toolInput: JSON.stringify({
file_path: filePath,
old_string: oldLines.join('\n'),
new_string: newLines.join('\n')
}),
toolCallId: entry.payload.call_id
});
} else {
messages.push({
type: 'tool_use',
timestamp: entry.timestamp,
toolName: toolName,
toolInput: input,
toolCallId: entry.payload.call_id
});
}
}
if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call_output') {
messages.push({
type: 'tool_result',
timestamp: entry.timestamp,
toolCallId: entry.payload.call_id,
output: entry.payload.output || ''
});
}
} catch (parseError) {
// Skip malformed lines
}
}
}
// Sort by timestamp
messages.sort((a, b) => new Date(a.timestamp || 0) - new Date(b.timestamp || 0));
const total = messages.length;
// Apply pagination if limit is specified
if (limit !== null) {
const startIndex = Math.max(0, total - offset - limit);
const endIndex = total - offset;
const paginatedMessages = messages.slice(startIndex, endIndex);
const hasMore = startIndex > 0;
return {
messages: paginatedMessages,
total,
hasMore,
offset,
limit,
tokenUsage
};
}
return { messages, tokenUsage };
} catch (error) {
console.error(`Error reading Codex session messages for ${sessionId}:`, error);
return { messages: [], total: 0, hasMore: false };
}
}
async function deleteCodexSession(sessionId) {
try {
const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
const findJsonlFiles = async (dir) => {
const files = [];
try {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...await findJsonlFiles(fullPath));
} else if (entry.name.endsWith('.jsonl')) {
files.push(fullPath);
}
}
} catch (error) {}
return files;
};
const jsonlFiles = await findJsonlFiles(codexSessionsDir);
for (const filePath of jsonlFiles) {
const sessionData = await parseCodexSessionFile(filePath);
if (sessionData && sessionData.id === sessionId) {
await fs.unlink(filePath);
return true;
}
}
throw new Error(`Codex session file not found for session ${sessionId}`);
} catch (error) {
console.error(`Error deleting Codex session ${sessionId}:`, error);
throw error;
}
}
export {
getProjects,
getSessions,
@@ -1154,5 +1592,8 @@ export {
loadProjectConfig,
saveProjectConfig,
extractProjectDirectory,
clearProjectDirectoryCache
clearProjectDirectoryCache,
getCodexSessions,
getCodexSessionMessages,
deleteCodexSession
};

View File

@@ -4,16 +4,44 @@ import path from 'path';
import os from 'os';
import { promises as fs } from 'fs';
import crypto from 'crypto';
import { apiKeysDb, githubTokensDb } from '../database/db.js';
import { userDb, apiKeysDb, githubTokensDb } from '../database/db.js';
import { addProjectManually } from '../projects.js';
import { queryClaudeSDK } from '../claude-sdk.js';
import { spawnCursor } from '../cursor-cli.js';
import { queryCodex } from '../openai-codex.js';
import { Octokit } from '@octokit/rest';
const router = express.Router();
// Middleware to validate API key for external requests
/**
* Middleware to authenticate agent API requests.
*
* Supports two authentication modes:
* 1. Platform mode (VITE_IS_PLATFORM=true): For managed/hosted deployments where
* authentication is handled by an external proxy. Requests are trusted and
* the default user context is used.
*
* 2. API key mode (default): For self-hosted deployments where users authenticate
* via API keys created in the UI. Keys are validated against the local database.
*/
const validateExternalApiKey = (req, res, next) => {
// Platform mode: Authentication is handled externally (e.g., by a proxy layer).
// Trust the request and use the default user context.
if (process.env.VITE_IS_PLATFORM === 'true') {
try {
const user = userDb.getFirstUser();
if (!user) {
return res.status(500).json({ error: 'Platform mode: No user found in database' });
}
req.user = user;
return next();
} catch (error) {
console.error('Platform mode error:', error);
return res.status(500).json({ error: 'Platform mode: Failed to fetch user' });
}
}
// Self-hosted mode: Validate API key from header or query parameter
const apiKey = req.headers['x-api-key'] || req.query.apiKey;
if (!apiKey) {
@@ -819,8 +847,8 @@ router.post('/', validateExternalApiKey, async (req, res) => {
return res.status(400).json({ error: 'message is required' });
}
if (!['claude', 'cursor'].includes(provider)) {
return res.status(400).json({ error: 'provider must be "claude" or "cursor"' });
if (!['claude', 'cursor', 'codex'].includes(provider)) {
return res.status(400).json({ error: 'provider must be "claude", "cursor", or "codex"' });
}
// Validate GitHub branch/PR creation requirements
@@ -924,6 +952,16 @@ router.post('/', validateExternalApiKey, async (req, res) => {
model: model || undefined,
skipPermissions: true // Bypass permissions for Cursor
}, writer);
} else if (provider === 'codex') {
console.log('🤖 Starting Codex SDK session');
await queryCodex(message.trim(), {
projectPath: finalProjectPath,
cwd: finalProjectPath,
sessionId: null,
model: model || 'gpt-5.2',
permissionMode: 'bypassPermissions'
}, writer);
}
// Handle GitHub branch and PR creation after successful agent completion

View File

@@ -54,6 +54,26 @@ router.get('/cursor/status', async (req, res) => {
}
});
router.get('/codex/status', async (req, res) => {
try {
const result = await checkCodexCredentials();
res.json({
authenticated: result.authenticated,
email: result.email,
error: result.error
});
} catch (error) {
console.error('Error checking Codex auth status:', error);
res.status(500).json({
authenticated: false,
email: null,
error: error.message
});
}
});
async function checkClaudeCredentials() {
try {
const credPath = path.join(os.homedir(), '.claude', '.credentials.json');
@@ -177,4 +197,67 @@ function checkCursorStatus() {
});
}
async function checkCodexCredentials() {
try {
const authPath = path.join(os.homedir(), '.codex', 'auth.json');
const content = await fs.readFile(authPath, 'utf8');
const auth = JSON.parse(content);
// Tokens are nested under 'tokens' key
const tokens = auth.tokens || {};
// Check for valid tokens (id_token or access_token)
if (tokens.id_token || tokens.access_token) {
// Try to extract email from id_token JWT payload
let email = 'Authenticated';
if (tokens.id_token) {
try {
// JWT is base64url encoded: header.payload.signature
const parts = tokens.id_token.split('.');
if (parts.length >= 2) {
// Decode the payload (second part)
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
email = payload.email || payload.user || 'Authenticated';
}
} catch {
// If JWT decoding fails, use fallback
email = 'Authenticated';
}
}
return {
authenticated: true,
email
};
}
// Also check for OPENAI_API_KEY as fallback auth method
if (auth.OPENAI_API_KEY) {
return {
authenticated: true,
email: 'API Key Auth'
};
}
return {
authenticated: false,
email: null,
error: 'No valid tokens found'
};
} catch (error) {
if (error.code === 'ENOENT') {
return {
authenticated: false,
email: null,
error: 'Codex not configured'
};
}
return {
authenticated: false,
email: null,
error: error.message
};
}
}
export default router;

310
server/routes/codex.js Normal file
View File

@@ -0,0 +1,310 @@
import express from 'express';
import { spawn } from 'child_process';
import { promises as fs } from 'fs';
import path from 'path';
import os from 'os';
import TOML from '@iarna/toml';
import { getCodexSessions, getCodexSessionMessages, deleteCodexSession } from '../projects.js';
const router = express.Router();
router.get('/config', async (req, res) => {
try {
const configPath = path.join(os.homedir(), '.codex', 'config.toml');
const content = await fs.readFile(configPath, 'utf8');
const config = TOML.parse(content);
res.json({
success: true,
config: {
model: config.model || null,
mcpServers: config.mcp_servers || {},
approvalMode: config.approval_mode || 'suggest'
}
});
} catch (error) {
if (error.code === 'ENOENT') {
res.json({
success: true,
config: {
model: null,
mcpServers: {},
approvalMode: 'suggest'
}
});
} else {
console.error('Error reading Codex config:', error);
res.status(500).json({ success: false, error: error.message });
}
}
});
router.get('/sessions', async (req, res) => {
try {
const { projectPath } = req.query;
if (!projectPath) {
return res.status(400).json({ success: false, error: 'projectPath query parameter required' });
}
const sessions = await getCodexSessions(projectPath);
res.json({ success: true, sessions });
} catch (error) {
console.error('Error fetching Codex sessions:', error);
res.status(500).json({ success: false, error: error.message });
}
});
router.get('/sessions/:sessionId/messages', async (req, res) => {
try {
const { sessionId } = req.params;
const { limit, offset } = req.query;
const result = await getCodexSessionMessages(
sessionId,
limit ? parseInt(limit, 10) : null,
offset ? parseInt(offset, 10) : 0
);
res.json({ success: true, ...result });
} catch (error) {
console.error('Error fetching Codex session messages:', error);
res.status(500).json({ success: false, error: error.message });
}
});
router.delete('/sessions/:sessionId', async (req, res) => {
try {
const { sessionId } = req.params;
await deleteCodexSession(sessionId);
res.json({ success: true });
} catch (error) {
console.error(`Error deleting Codex session ${req.params.sessionId}:`, error);
res.status(500).json({ success: false, error: error.message });
}
});
// MCP Server Management Routes
router.get('/mcp/cli/list', async (req, res) => {
try {
const proc = spawn('codex', ['mcp', 'list'], { stdio: ['pipe', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
proc.stdout.on('data', (data) => { stdout += data.toString(); });
proc.stderr.on('data', (data) => { stderr += data.toString(); });
proc.on('close', (code) => {
if (code === 0) {
res.json({ success: true, output: stdout, servers: parseCodexListOutput(stdout) });
} else {
res.status(500).json({ error: 'Codex CLI command failed', details: stderr });
}
});
proc.on('error', (error) => {
res.status(500).json({ error: 'Failed to run Codex CLI', details: error.message });
});
} catch (error) {
res.status(500).json({ error: 'Failed to list MCP servers', details: error.message });
}
});
router.post('/mcp/cli/add', async (req, res) => {
try {
const { name, command, args = [], env = {} } = req.body;
if (!name || !command) {
return res.status(400).json({ error: 'name and command are required' });
}
// Build: codex mcp add <name> [-e KEY=VAL]... -- <command> [args...]
let cliArgs = ['mcp', 'add', name];
Object.entries(env).forEach(([key, value]) => {
cliArgs.push('-e', `${key}=${value}`);
});
cliArgs.push('--', command);
if (args && args.length > 0) {
cliArgs.push(...args);
}
const proc = spawn('codex', cliArgs, { stdio: ['pipe', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
proc.stdout.on('data', (data) => { stdout += data.toString(); });
proc.stderr.on('data', (data) => { stderr += data.toString(); });
proc.on('close', (code) => {
if (code === 0) {
res.json({ success: true, output: stdout, message: `MCP server "${name}" added successfully` });
} else {
res.status(400).json({ error: 'Codex CLI command failed', details: stderr });
}
});
proc.on('error', (error) => {
res.status(500).json({ error: 'Failed to run Codex CLI', details: error.message });
});
} catch (error) {
res.status(500).json({ error: 'Failed to add MCP server', details: error.message });
}
});
router.delete('/mcp/cli/remove/:name', async (req, res) => {
try {
const { name } = req.params;
const proc = spawn('codex', ['mcp', 'remove', name], { stdio: ['pipe', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
proc.stdout.on('data', (data) => { stdout += data.toString(); });
proc.stderr.on('data', (data) => { stderr += data.toString(); });
proc.on('close', (code) => {
if (code === 0) {
res.json({ success: true, output: stdout, message: `MCP server "${name}" removed successfully` });
} else {
res.status(400).json({ error: 'Codex CLI command failed', details: stderr });
}
});
proc.on('error', (error) => {
res.status(500).json({ error: 'Failed to run Codex CLI', details: error.message });
});
} catch (error) {
res.status(500).json({ error: 'Failed to remove MCP server', details: error.message });
}
});
router.get('/mcp/cli/get/:name', async (req, res) => {
try {
const { name } = req.params;
const proc = spawn('codex', ['mcp', 'get', name], { stdio: ['pipe', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
proc.stdout.on('data', (data) => { stdout += data.toString(); });
proc.stderr.on('data', (data) => { stderr += data.toString(); });
proc.on('close', (code) => {
if (code === 0) {
res.json({ success: true, output: stdout, server: parseCodexGetOutput(stdout) });
} else {
res.status(404).json({ error: 'Codex CLI command failed', details: stderr });
}
});
proc.on('error', (error) => {
res.status(500).json({ error: 'Failed to run Codex CLI', details: error.message });
});
} catch (error) {
res.status(500).json({ error: 'Failed to get MCP server details', details: error.message });
}
});
router.get('/mcp/config/read', async (req, res) => {
try {
const configPath = path.join(os.homedir(), '.codex', 'config.toml');
let configData = null;
try {
const fileContent = await fs.readFile(configPath, 'utf8');
configData = TOML.parse(fileContent);
} catch (error) {
// Config file doesn't exist
}
if (!configData) {
return res.json({ success: false, message: 'No Codex configuration file found', servers: [] });
}
const servers = [];
if (configData.mcp_servers && typeof configData.mcp_servers === 'object') {
for (const [name, config] of Object.entries(configData.mcp_servers)) {
servers.push({
id: name,
name: name,
type: 'stdio',
scope: 'user',
config: {
command: config.command || '',
args: config.args || [],
env: config.env || {}
},
raw: config
});
}
}
res.json({ success: true, configPath, servers });
} catch (error) {
res.status(500).json({ error: 'Failed to read Codex configuration', details: error.message });
}
});
function parseCodexListOutput(output) {
const servers = [];
const lines = output.split('\n').filter(line => line.trim());
for (const line of lines) {
if (line.includes(':')) {
const colonIndex = line.indexOf(':');
const name = line.substring(0, colonIndex).trim();
if (!name) continue;
const rest = line.substring(colonIndex + 1).trim();
let description = rest;
let status = 'unknown';
if (rest.includes('✓') || rest.includes('✗')) {
const statusMatch = rest.match(/(.*?)\s*-\s*([✓✗].*)$/);
if (statusMatch) {
description = statusMatch[1].trim();
status = statusMatch[2].includes('✓') ? 'connected' : 'failed';
}
}
servers.push({ name, type: 'stdio', status, description });
}
}
return servers;
}
function parseCodexGetOutput(output) {
try {
const jsonMatch = output.match(/\{[\s\S]*\}/);
if (jsonMatch) {
return JSON.parse(jsonMatch[0]);
}
const server = { raw_output: output };
const lines = output.split('\n');
for (const line of lines) {
if (line.includes('Name:')) server.name = line.split(':')[1]?.trim();
else if (line.includes('Type:')) server.type = line.split(':')[1]?.trim();
else if (line.includes('Command:')) server.command = line.split(':')[1]?.trim();
}
return server;
} catch (error) {
return { raw_output: output, parse_error: error.message };
}
}
export default router;

View File

@@ -55,7 +55,7 @@ function AppContent() {
const [isLoadingProjects, setIsLoadingProjects] = useState(true);
const [isInputFocused, setIsInputFocused] = useState(false);
const [showSettings, setShowSettings] = useState(false);
const [settingsInitialTab, setSettingsInitialTab] = useState('tools');
const [settingsInitialTab, setSettingsInitialTab] = useState('agents');
const [showQuickSettings, setShowQuickSettings] = useState(false);
const [autoExpandTools, setAutoExpandTools] = useLocalStorage('autoExpandTools', false);
const [showRawParameters, setShowRawParameters] = useLocalStorage('showRawParameters', false);
@@ -89,7 +89,8 @@ function AppContent() {
window.navigator.standalone ||
document.referrer.includes('android-app://');
setIsPWA(isStandalone);
document.addEventListener('touchstart', {});
// Add class to html and body for CSS targeting
if (isStandalone) {
document.documentElement.classList.add('pwa-mode');
@@ -229,14 +230,16 @@ function AppContent() {
setSelectedProject(updatedSelectedProject);
}
// Update selected session only if it was deleted - avoid unnecessary reloads
if (selectedSession) {
const updatedSelectedSession = updatedSelectedProject.sessions?.find(s => s.id === selectedSession.id);
const allSessions = [
...(updatedSelectedProject.sessions || []),
...(updatedSelectedProject.codexSessions || []),
...(updatedSelectedProject.cursorSessions || [])
];
const updatedSelectedSession = allSessions.find(s => s.id === selectedSession.id);
if (!updatedSelectedSession) {
// Session was deleted
setSelectedSession(null);
}
// Don't update if session still exists with same ID - prevents reload
}
}
}
@@ -966,4 +969,4 @@ function App() {
);
}
export default App;
export default App;

View File

@@ -25,6 +25,7 @@ import { useDropzone } from 'react-dropzone';
import TodoList from './TodoList';
import ClaudeLogo from './ClaudeLogo.jsx';
import CursorLogo from './CursorLogo.jsx';
import CodexLogo from './CodexLogo.jsx';
import NextTaskBanner from './NextTaskBanner.jsx';
import { useTasksSettings } from '../contexts/TasksSettingsContext';
@@ -442,13 +443,15 @@ const MessageComponent = memo(({ message, index, prevMessage, createDiff, onFile
<div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-sm flex-shrink-0 p-1">
{(localStorage.getItem('selected-provider') || 'claude') === 'cursor' ? (
<CursorLogo className="w-full h-full" />
) : (localStorage.getItem('selected-provider') || 'claude') === 'codex' ? (
<CodexLogo className="w-full h-full" />
) : (
<ClaudeLogo className="w-full h-full" />
)}
</div>
)}
<div className="text-sm font-medium text-gray-900 dark:text-white">
{message.type === 'error' ? 'Error' : message.type === 'tool' ? 'Tool' : ((localStorage.getItem('selected-provider') || 'claude') === 'cursor' ? 'Cursor' : 'Claude')}
{message.type === 'error' ? 'Error' : message.type === 'tool' ? 'Tool' : ((localStorage.getItem('selected-provider') || 'claude') === 'cursor' ? 'Cursor' : (localStorage.getItem('selected-provider') || 'claude') === 'codex' ? 'Codex' : 'Claude')}
</div>
</div>
)}
@@ -1522,6 +1525,23 @@ const MessageComponent = memo(({ message, index, prevMessage, createDiff, onFile
<span className="font-medium">Read todo list</span>
</div>
</div>
) : message.isThinking ? (
/* Thinking messages - collapsible by default */
<div className="text-sm text-gray-700 dark:text-gray-300">
<details className="group">
<summary className="cursor-pointer text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 font-medium flex items-center gap-2">
<svg className="w-3 h-3 transition-transform group-open:rotate-90" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
<span>💭 Thinking...</span>
</summary>
<div className="mt-2 pl-4 border-l-2 border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 text-sm">
<Markdown className="prose prose-sm max-w-none dark:prose-invert prose-gray">
{message.content}
</Markdown>
</div>
</details>
</div>
) : (
<div className="text-sm text-gray-700 dark:text-gray-300">
{/* Thinking accordion for reasoning */}
@@ -1537,7 +1557,7 @@ const MessageComponent = memo(({ message, index, prevMessage, createDiff, onFile
</div>
</details>
)}
{(() => {
const content = formatUsageLimitText(String(message.content || ''));
@@ -1641,7 +1661,7 @@ const ImageAttachment = ({ file, onRemove, uploadProgress, error }) => {
//
// This ensures uninterrupted chat experience by pausing sidebar refreshes during conversations.
function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, messages, onFileOpen, onInputFocusChange, onSessionActive, onSessionInactive, onSessionProcessing, onSessionNotProcessing, processingSessions, onReplaceTemporarySession, onNavigateToSession, onShowSettings, autoExpandTools, showRawParameters, showThinking, autoScrollToBottom, sendByCtrlEnter, externalMessageUpdate, onTaskClick, onShowAllTasks }) {
const { tasksEnabled } = useTasksSettings();
const { tasksEnabled, isTaskMasterInstalled } = useTasksSettings();
const [input, setInput] = useState(() => {
if (typeof window !== 'undefined' && selectedProject) {
return safeLocalStorage.getItem(`draft_input_${selectedProject.name}`) || '';
@@ -1705,6 +1725,12 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
const [cursorModel, setCursorModel] = useState(() => {
return localStorage.getItem('cursor-model') || 'gpt-5';
});
const [claudeModel, setClaudeModel] = useState(() => {
return localStorage.getItem('claude-model') || 'sonnet';
});
const [codexModel, setCodexModel] = useState(() => {
return localStorage.getItem('codex-model') || 'gpt-5.2';
});
// Load permission mode for the current session
useEffect(() => {
if (selectedSession?.id) {
@@ -2036,7 +2062,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
projectName: selectedProject.name,
sessionId: currentSessionId,
provider,
model: provider === 'cursor' ? cursorModel : 'claude-sonnet-4.5',
model: provider === 'cursor' ? cursorModel : claudeModel,
tokenUsage: tokenBudget
};
@@ -2109,24 +2135,29 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
}, []);
// Load session messages from API with pagination
const loadSessionMessages = useCallback(async (projectName, sessionId, loadMore = false) => {
const loadSessionMessages = useCallback(async (projectName, sessionId, loadMore = false, provider = 'claude') => {
if (!projectName || !sessionId) return [];
const isInitialLoad = !loadMore;
if (isInitialLoad) {
setIsLoadingSessionMessages(true);
} else {
setIsLoadingMoreMessages(true);
}
try {
const currentOffset = loadMore ? messagesOffset : 0;
const response = await api.sessionMessages(projectName, sessionId, MESSAGES_PER_PAGE, currentOffset);
const response = await api.sessionMessages(projectName, sessionId, MESSAGES_PER_PAGE, currentOffset, provider);
if (!response.ok) {
throw new Error('Failed to load session messages');
}
const data = await response.json();
// Extract token usage if present (Codex includes it in messages response)
if (isInitialLoad && data.tokenUsage) {
setTokenBudget(data.tokenUsage);
}
// Handle paginated response
if (data.hasMore !== undefined) {
setHasMoreMessages(data.hasMore);
@@ -2569,6 +2600,45 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
}
}
// Handle thinking messages (Codex reasoning)
else if (msg.type === 'thinking' && msg.message?.content) {
converted.push({
type: 'assistant',
content: unescapeWithMathProtection(msg.message.content),
timestamp: msg.timestamp || new Date().toISOString(),
isThinking: true
});
}
// Handle tool_use messages (Codex function calls)
else if (msg.type === 'tool_use' && msg.toolName) {
converted.push({
type: 'assistant',
content: '',
timestamp: msg.timestamp || new Date().toISOString(),
isToolUse: true,
toolName: msg.toolName,
toolInput: msg.toolInput || '',
toolCallId: msg.toolCallId
});
}
// Handle tool_result messages (Codex function outputs)
else if (msg.type === 'tool_result') {
// Find the matching tool_use by callId, or the last tool_use without a result
for (let i = converted.length - 1; i >= 0; i--) {
if (converted[i].isToolUse && !converted[i].toolResult) {
if (!msg.toolCallId || converted[i].toolCallId === msg.toolCallId) {
converted[i].toolResult = {
content: msg.output || '',
isError: false
};
break;
}
}
}
}
// Handle assistant messages
else if (msg.message?.role === 'assistant' && msg.message?.content) {
if (Array.isArray(msg.message.content)) {
@@ -2663,7 +2733,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
const previousScrollTop = container.scrollTop;
// Load more messages
const moreMessages = await loadSessionMessages(selectedProject.name, selectedSession.id, true);
const moreMessages = await loadSessionMessages(selectedProject.name, selectedSession.id, true, selectedSession.__provider || 'claude');
if (moreMessages.length > 0) {
// Prepend new messages to the existing ones
@@ -2754,7 +2824,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
// Only load messages from API if this is a user-initiated session change
// For system-initiated changes, preserve existing messages and rely on WebSocket
if (!isSystemSessionChange) {
const messages = await loadSessionMessages(selectedProject.name, selectedSession.id, false);
const messages = await loadSessionMessages(selectedProject.name, selectedSession.id, false, selectedSession.__provider || 'claude');
setSessionMessages(messages);
// convertedMessages will be automatically updated via useMemo
// Scroll will be handled by the main scroll useEffect after messages are rendered
@@ -2803,8 +2873,8 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
setSessionMessages([]);
setChatMessages(converted);
} else {
// Reload Claude messages from API/JSONL
const messages = await loadSessionMessages(selectedProject.name, selectedSession.id, false);
// Reload Claude/Codex messages from API/JSONL
const messages = await loadSessionMessages(selectedProject.name, selectedSession.id, false, selectedSession.__provider || 'claude');
setSessionMessages(messages);
// convertedMessages will be automatically updated via useMemo
@@ -2890,7 +2960,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
// Filter messages by session ID to prevent cross-session interference
// Skip filtering for global messages that apply to all sessions
const globalMessageTypes = ['projects_updated', 'taskmaster-project-updated', 'session-created', 'claude-complete'];
const globalMessageTypes = ['projects_updated', 'taskmaster-project-updated', 'session-created', 'claude-complete', 'codex-complete'];
const isGlobalMessage = globalMessageTypes.includes(latestMessage.type);
// For new sessions (currentSessionId is null), allow messages through
@@ -2917,8 +2987,10 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
break;
case 'token-budget':
// Token budget now fetched via API after message completion instead of WebSocket
// This case is kept for compatibility but does nothing
// Use token budget from WebSocket for active sessions
if (latestMessage.data) {
setTokenBudget(latestMessage.data);
}
break;
case 'claude-response':
@@ -3311,23 +3383,6 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
setIsLoading(false);
setCanAbortSession(false);
setClaudeStatus(null);
// Fetch updated token usage after message completes
if (selectedProject && selectedSession?.id) {
const fetchUpdatedTokenUsage = async () => {
try {
const url = `/api/projects/${selectedProject.name}/sessions/${selectedSession.id}/token-usage`;
const response = await authenticatedFetch(url);
if (response.ok) {
const data = await response.json();
setTokenBudget(data);
}
} catch (error) {
console.error('Failed to fetch updated token usage:', error);
}
};
fetchUpdatedTokenUsage();
}
}
// Always mark the completed session as inactive and not processing
@@ -3355,7 +3410,154 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
safeLocalStorage.removeItem(`chat_messages_${selectedProject.name}`);
}
break;
case 'codex-response':
// Handle Codex SDK responses
const codexData = latestMessage.data;
if (codexData) {
// Handle item events
if (codexData.type === 'item') {
switch (codexData.itemType) {
case 'agent_message':
if (codexData.message?.content?.trim()) {
const content = decodeHtmlEntities(codexData.message.content);
setChatMessages(prev => [...prev, {
type: 'assistant',
content: content,
timestamp: new Date()
}]);
}
break;
case 'reasoning':
if (codexData.message?.content?.trim()) {
const content = decodeHtmlEntities(codexData.message.content);
setChatMessages(prev => [...prev, {
type: 'assistant',
content: content,
timestamp: new Date(),
isThinking: true
}]);
}
break;
case 'command_execution':
if (codexData.command) {
setChatMessages(prev => [...prev, {
type: 'assistant',
content: '',
timestamp: new Date(),
isToolUse: true,
toolName: 'Bash',
toolInput: codexData.command,
toolResult: codexData.output || null,
exitCode: codexData.exitCode
}]);
}
break;
case 'file_change':
if (codexData.changes?.length > 0) {
const changesList = codexData.changes.map(c => `${c.kind}: ${c.path}`).join('\n');
setChatMessages(prev => [...prev, {
type: 'assistant',
content: '',
timestamp: new Date(),
isToolUse: true,
toolName: 'FileChanges',
toolInput: changesList,
toolResult: `Status: ${codexData.status}`
}]);
}
break;
case 'mcp_tool_call':
setChatMessages(prev => [...prev, {
type: 'assistant',
content: '',
timestamp: new Date(),
isToolUse: true,
toolName: `${codexData.server}:${codexData.tool}`,
toolInput: JSON.stringify(codexData.arguments, null, 2),
toolResult: codexData.result ? JSON.stringify(codexData.result, null, 2) : (codexData.error?.message || null)
}]);
break;
case 'error':
if (codexData.message?.content) {
setChatMessages(prev => [...prev, {
type: 'error',
content: codexData.message.content,
timestamp: new Date()
}]);
}
break;
default:
console.log('[Codex] Unhandled item type:', codexData.itemType, codexData);
}
}
// Handle turn complete
if (codexData.type === 'turn_complete') {
// Turn completed, message stream done
setIsLoading(false);
}
// Handle turn failed
if (codexData.type === 'turn_failed') {
setIsLoading(false);
setChatMessages(prev => [...prev, {
type: 'error',
content: codexData.error?.message || 'Turn failed',
timestamp: new Date()
}]);
}
}
break;
case 'codex-complete':
// Handle Codex session completion
const codexCompletedSessionId = latestMessage.sessionId || currentSessionId || sessionStorage.getItem('pendingSessionId');
if (codexCompletedSessionId === currentSessionId || !currentSessionId) {
setIsLoading(false);
setCanAbortSession(false);
setClaudeStatus(null);
}
if (codexCompletedSessionId) {
if (onSessionInactive) {
onSessionInactive(codexCompletedSessionId);
}
if (onSessionNotProcessing) {
onSessionNotProcessing(codexCompletedSessionId);
}
}
const codexPendingSessionId = sessionStorage.getItem('pendingSessionId');
if (codexPendingSessionId && !currentSessionId) {
setCurrentSessionId(codexPendingSessionId);
sessionStorage.removeItem('pendingSessionId');
console.log('Codex session complete, ID set to:', codexPendingSessionId);
}
if (selectedProject) {
safeLocalStorage.removeItem(`chat_messages_${selectedProject.name}`);
}
break;
case 'codex-error':
// Handle Codex errors
setIsLoading(false);
setCanAbortSession(false);
setChatMessages(prev => [...prev, {
type: 'error',
content: latestMessage.error || 'An error occurred with Codex',
timestamp: new Date()
}]);
break;
case 'session-aborted': {
// Get session ID from message or fall back to current session
const abortedSessionId = latestMessage.sessionId || currentSessionId;
@@ -3606,21 +3808,26 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
}
}, [input]);
// Load token usage when session changes (but don't poll to avoid conflicts with WebSocket)
// Load token usage when session changes for Claude sessions only
// (Codex token usage is included in messages response, Cursor doesn't support it)
useEffect(() => {
if (!selectedProject || !selectedSession?.id || selectedSession.id.startsWith('new-session-')) {
// Reset for new/empty sessions
setTokenBudget(null);
return;
}
// Fetch token usage once when session loads
const sessionProvider = selectedSession.__provider || 'claude';
// Skip for Codex (included in messages) and Cursor (not supported)
if (sessionProvider !== 'claude') {
return;
}
// Fetch token usage for Claude sessions
const fetchInitialTokenUsage = async () => {
try {
const url = `/api/projects/${selectedProject.name}/sessions/${selectedSession.id}/token-usage`;
const response = await authenticatedFetch(url);
if (response.ok) {
const data = await response.json();
setTokenBudget(data);
@@ -3633,7 +3840,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
};
fetchInitialTokenUsage();
}, [selectedSession?.id, selectedProject?.path]);
}, [selectedSession?.id, selectedSession?.__provider, selectedProject?.path]);
const handleTranscript = useCallback((text) => {
if (text.trim()) {
@@ -3805,7 +4012,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
// Get tools settings from localStorage based on provider
const getToolsSettings = () => {
try {
const settingsKey = provider === 'cursor' ? 'cursor-tools-settings' : 'claude-settings';
const settingsKey = provider === 'cursor' ? 'cursor-tools-settings' : provider === 'codex' ? 'codex-settings' : 'claude-settings';
const savedSettings = safeLocalStorage.getItem(settingsKey);
if (savedSettings) {
return JSON.parse(savedSettings);
@@ -3840,6 +4047,21 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
toolsSettings: toolsSettings
}
});
} else if (provider === 'codex') {
// Send Codex command
sendMessage({
type: 'codex-command',
command: input,
sessionId: effectiveSessionId,
options: {
cwd: selectedProject.fullPath || selectedProject.path,
projectPath: selectedProject.fullPath || selectedProject.path,
sessionId: effectiveSessionId,
resume: !!effectiveSessionId,
model: codexModel,
permissionMode: permissionMode === 'plan' ? 'default' : permissionMode
}
});
} else {
// Send Claude command (existing code)
sendMessage({
@@ -3852,6 +4074,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
resume: !!currentSessionId,
toolsSettings: toolsSettings,
permissionMode: permissionMode,
model: claudeModel,
images: uploadedImages // Pass images to backend
}
});
@@ -3872,7 +4095,7 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
if (selectedProject) {
safeLocalStorage.removeItem(`draft_input_${selectedProject.name}`);
}
}, [input, isLoading, selectedProject, attachedImages, currentSessionId, selectedSession, provider, permissionMode, onSessionActive, cursorModel, sendMessage, setInput, setAttachedImages, setUploadingImages, setImageErrors, setIsTextareaExpanded, textareaRef, setChatMessages, setIsLoading, setCanAbortSession, setClaudeStatus, setIsUserScrolledUp, scrollToBottom]);
}, [input, isLoading, selectedProject, attachedImages, currentSessionId, selectedSession, provider, permissionMode, onSessionActive, cursorModel, claudeModel, codexModel, sendMessage, setInput, setAttachedImages, setUploadingImages, setImageErrors, setIsTextareaExpanded, textareaRef, setChatMessages, setIsLoading, setCanAbortSession, setClaudeStatus, setIsUserScrolledUp, scrollToBottom]);
// Store handleSubmit in ref so handleCustomCommand can access it
useEffect(() => {
@@ -3982,7 +4205,10 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
// Handle Tab key for mode switching (only when dropdowns are not showing)
if (e.key === 'Tab' && !showFileDropdown && !showCommandMenu) {
e.preventDefault();
const modes = ['default', 'acceptEdits', 'bypassPermissions', 'plan'];
// Codex doesn't support plan mode
const modes = provider === 'codex'
? ['default', 'acceptEdits', 'bypassPermissions']
: ['default', 'acceptEdits', 'bypassPermissions', 'plan'];
const currentIndex = modes.indexOf(permissionMode);
const nextIndex = (currentIndex + 1) % modes.length;
const newMode = modes[nextIndex];
@@ -4151,7 +4377,10 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
};
const handleModeSwitch = () => {
const modes = ['default', 'acceptEdits', 'bypassPermissions', 'plan'];
// Codex doesn't support plan mode
const modes = provider === 'codex'
? ['default', 'acceptEdits', 'bypassPermissions']
: ['default', 'acceptEdits', 'bypassPermissions', 'plan'];
const currentIndex = modes.indexOf(permissionMode);
const nextIndex = (currentIndex + 1) % modes.length;
const newMode = modes[nextIndex];
@@ -4269,42 +4498,123 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
</div>
)}
</button>
</div>
{/* Model Selection for Cursor - Always reserve space to prevent jumping */}
<div className={`mb-6 transition-opacity duration-200 ${provider === 'cursor' ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{provider === 'cursor' ? 'Select Model' : '\u00A0'}
</label>
<select
value={cursorModel}
onChange={(e) => {
const newModel = e.target.value;
setCursorModel(newModel);
localStorage.setItem('cursor-model', newModel);
{/* Codex Button */}
<button
onClick={() => {
setProvider('codex');
localStorage.setItem('selected-provider', 'codex');
// Focus input after selection
setTimeout(() => textareaRef.current?.focus(), 100);
}}
className="pl-4 pr-10 py-2 text-sm bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 min-w-[140px]"
disabled={provider !== 'cursor'}
className={`group relative w-64 h-32 bg-white dark:bg-gray-800 rounded-xl border-2 transition-all duration-200 hover:scale-105 hover:shadow-xl ${
provider === 'codex'
? 'border-gray-800 dark:border-gray-300 shadow-lg ring-2 ring-gray-800/20 dark:ring-gray-300/20'
: 'border-gray-200 dark:border-gray-700 hover:border-gray-500 dark:hover:border-gray-400'
}`}
>
<option value="gpt-5">GPT-5</option>
<option value="sonnet-4">Sonnet-4</option>
<option value="opus-4.1">Opus 4.1</option>
</select>
<div className="flex flex-col items-center justify-center h-full gap-3">
<CodexLogo className="w-10 h-10" />
<div>
<p className="font-semibold text-gray-900 dark:text-white">Codex</p>
<p className="text-xs text-gray-500 dark:text-gray-400">by OpenAI</p>
</div>
</div>
{provider === 'codex' && (
<div className="absolute top-2 right-2">
<div className="w-5 h-5 bg-gray-800 dark:bg-gray-300 rounded-full flex items-center justify-center">
<svg className="w-3 h-3 text-white dark:text-gray-800" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
</svg>
</div>
</div>
)}
</button>
</div>
{/* Model Selection - Always reserve space to prevent jumping */}
<div className={`mb-6 transition-opacity duration-200 ${provider ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Select Model
</label>
{provider === 'claude' ? (
<select
value={claudeModel}
onChange={(e) => {
const newModel = e.target.value;
setClaudeModel(newModel);
localStorage.setItem('claude-model', newModel);
}}
className="pl-4 pr-10 py-2 text-sm bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 min-w-[140px]"
>
<option value="sonnet">Sonnet</option>
<option value="opus">Opus</option>
<option value="haiku">Haiku</option>
<option value="opusplan">Opus Plan</option>
<option value="sonnet[1m]">Sonnet [1M]</option>
</select>
) : provider === 'codex' ? (
<select
value={codexModel}
onChange={(e) => {
const newModel = e.target.value;
setCodexModel(newModel);
localStorage.setItem('codex-model', newModel);
}}
className="pl-4 pr-10 py-2 text-sm bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-gray-500 focus:border-gray-500 min-w-[140px]"
>
<option value="gpt-5.2">GPT-5.2</option>
<option value="gpt-5.1-codex-max">GPT-5.1 Codex Max</option>
<option value="o3">O3</option>
<option value="o4-mini">O4-mini</option>
</select>
) : (
<select
value={cursorModel}
onChange={(e) => {
const newModel = e.target.value;
setCursorModel(newModel);
localStorage.setItem('cursor-model', newModel);
}}
className="pl-4 pr-10 py-2 text-sm bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 min-w-[140px]"
disabled={provider !== 'cursor'}
>
<option value="gpt-5.2-high">GPT-5.2 High</option>
<option value="gemini-3-pro">Gemini 3 Pro</option>
<option value="opus-4.5-thinking">Claude 4.5 Opus (Thinking)</option>
<option value="gpt-5.2">GPT-5.2</option>
<option value="gpt-5.1">GPT-5.1</option>
<option value="gpt-5.1-high">GPT-5.1 High</option>
<option value="composer-1">Composer 1</option>
<option value="auto">Auto</option>
<option value="sonnet-4.5">Claude 4.5 Sonnet</option>
<option value="sonnet-4.5-thinking">Claude 4.5 Sonnet (Thinking)</option>
<option value="opus-4.5">Claude 4.5 Opus</option>
<option value="gpt-5.1-codex">GPT-5.1 Codex</option>
<option value="gpt-5.1-codex-high">GPT-5.1 Codex High</option>
<option value="gpt-5.1-codex-max">GPT-5.1 Codex Max</option>
<option value="gpt-5.1-codex-max-high">GPT-5.1 Codex Max High</option>
<option value="opus-4.1">Claude 4.1 Opus</option>
<option value="grok">Grok</option>
</select>
)}
</div>
<p className="text-sm text-gray-500 dark:text-gray-400">
{provider === 'claude'
? 'Ready to use Claude AI. Start typing your message below.'
{provider === 'claude'
? `Ready to use Claude with ${claudeModel}. Start typing your message below.`
: provider === 'cursor'
? `Ready to use Cursor with ${cursorModel}. Start typing your message below.`
: provider === 'codex'
? `Ready to use Codex with ${codexModel}. Start typing your message below.`
: 'Select a provider above to begin'
}
</p>
{/* Show NextTaskBanner when provider is selected and ready */}
{provider && tasksEnabled && (
{/* Show NextTaskBanner when provider is selected and ready, only if TaskMaster is installed */}
{provider && tasksEnabled && isTaskMasterInstalled && (
<div className="mt-4 px-4 sm:px-0">
<NextTaskBanner
<NextTaskBanner
onStartTask={() => setInput('Start the next task')}
onShowAllTasks={onShowAllTasks}
/>
@@ -4319,10 +4629,10 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
Ask questions about your code, request changes, or get help with development tasks
</p>
{/* Show NextTaskBanner for existing sessions too */}
{tasksEnabled && (
{/* Show NextTaskBanner for existing sessions too, only if TaskMaster is installed */}
{tasksEnabled && isTaskMasterInstalled && (
<div className="mt-4 px-4 sm:px-0">
<NextTaskBanner
<NextTaskBanner
onStartTask={() => setInput('Start the next task')}
onShowAllTasks={onShowAllTasks}
/>
@@ -4397,11 +4707,13 @@ function ChatInterface({ selectedProject, selectedSession, ws, sendMessage, mess
<div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-sm flex-shrink-0 p-1 bg-transparent">
{(localStorage.getItem('selected-provider') || 'claude') === 'cursor' ? (
<CursorLogo className="w-full h-full" />
) : (localStorage.getItem('selected-provider') || 'claude') === 'codex' ? (
<CodexLogo className="w-full h-full" />
) : (
<ClaudeLogo className="w-full h-full" />
)}
</div>
<div className="text-sm font-medium text-gray-900 dark:text-white">{(localStorage.getItem('selected-provider') || 'claude') === 'cursor' ? 'Cursor' : 'Claude'}</div>
<div className="text-sm font-medium text-gray-900 dark:text-white">{(localStorage.getItem('selected-provider') || 'claude') === 'cursor' ? 'Cursor' : (localStorage.getItem('selected-provider') || 'claude') === 'codex' ? 'Codex' : 'Claude'}</div>
{/* Abort button removed - functionality not yet implemented at backend */}
</div>
<div className="w-full text-sm text-gray-500 dark:text-gray-400 pl-3 sm:pl-0">

View File

@@ -0,0 +1,16 @@
import React from 'react';
import { useTheme } from '../contexts/ThemeContext';
const CodexLogo = ({ className = 'w-5 h-5' }) => {
const { isDarkMode } = useTheme();
return (
<img
src={isDarkMode ? "/icons/codex-white.svg" : "/icons/codex.svg"}
alt="Codex"
className={className}
/>
);
};
export default CodexLogo;

View File

@@ -1,8 +1,15 @@
import React from 'react';
import { useTheme } from '../contexts/ThemeContext';
const CursorLogo = ({ className = 'w-5 h-5' }) => {
const { isDarkMode } = useTheme();
return (
<img src="/icons/cursor.svg" alt="Cursor" className={className} />
<img
src={isDarkMode ? "/icons/cursor-white.svg" : "/icons/cursor.svg"}
alt="Cursor"
className={className}
/>
);
};

View File

@@ -2,12 +2,12 @@ import { X } from 'lucide-react';
import StandaloneShell from './StandaloneShell';
/**
* Reusable login modal component for Claude and Cursor CLI authentication
* Reusable login modal component for Claude, Cursor, and Codex CLI authentication
*
* @param {Object} props
* @param {boolean} props.isOpen - Whether the modal is visible
* @param {Function} props.onClose - Callback when modal is closed
* @param {'claude'|'cursor'} props.provider - Which CLI provider to authenticate with
* @param {'claude'|'cursor'|'codex'} props.provider - Which CLI provider to authenticate with
* @param {Object} props.project - Project object containing name and path information
* @param {Function} props.onComplete - Callback when login process completes (receives exitCode)
* @param {string} props.customCommand - Optional custom command to override defaults
@@ -30,6 +30,8 @@ function LoginModal({
return 'claude setup-token --dangerously-skip-permissions';
case 'cursor':
return 'cursor-agent login';
case 'codex':
return 'codex login';
default:
return 'claude setup-token --dangerously-skip-permissions';
}
@@ -41,6 +43,8 @@ function LoginModal({
return 'Claude CLI Login';
case 'cursor':
return 'Cursor CLI Login';
case 'codex':
return 'Codex CLI Login';
default:
return 'CLI Login';
}

View File

@@ -1,7 +1,8 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useRef } from 'react';
import { ChevronRight, ChevronLeft, Check, GitBranch, User, Mail, LogIn, ExternalLink, Loader2 } from 'lucide-react';
import ClaudeLogo from './ClaudeLogo';
import CursorLogo from './CursorLogo';
import CodexLogo from './CodexLogo';
import LoginModal from './LoginModal';
import { authenticatedFetch } from '../utils/api';
import { useAuth } from '../contexts/AuthContext';
@@ -13,10 +14,8 @@ const Onboarding = ({ onComplete }) => {
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState('');
// CLI authentication states
const [showLoginModal, setShowLoginModal] = useState(false);
const [loginProvider, setLoginProvider] = useState('');
const [selectedProject, setSelectedProject] = useState({ name: 'default', fullPath: '' });
const [activeLoginProvider, setActiveLoginProvider] = useState(null);
const [selectedProject] = useState({ name: 'default', fullPath: '' });
const [claudeAuthStatus, setClaudeAuthStatus] = useState({
authenticated: false,
@@ -32,19 +31,21 @@ const Onboarding = ({ onComplete }) => {
error: null
});
const [codexAuthStatus, setCodexAuthStatus] = useState({
authenticated: false,
email: null,
loading: true,
error: null
});
const { user } = useAuth();
// Load existing git config on mount
const prevActiveLoginProviderRef = useRef(undefined);
useEffect(() => {
loadGitConfig();
}, []);
// Check authentication status on mount and when modal closes
useEffect(() => {
checkClaudeAuthStatus();
checkCursorAuthStatus();
}, []);
const loadGitConfig = async () => {
try {
const response = await authenticatedFetch('/api/user/git-config');
@@ -55,24 +56,22 @@ const Onboarding = ({ onComplete }) => {
}
} catch (error) {
console.error('Error loading git config:', error);
// Silently fail - user can still enter config manually
}
};
// Auto-check authentication status periodically when on CLI steps
useEffect(() => {
if (currentStep === 1 || currentStep === 2) {
const interval = setInterval(() => {
if (currentStep === 1) {
checkClaudeAuthStatus();
} else if (currentStep === 2) {
checkCursorAuthStatus();
}
}, 3000); // Check every 3 seconds
const prevProvider = prevActiveLoginProviderRef.current;
prevActiveLoginProviderRef.current = activeLoginProvider;
return () => clearInterval(interval);
const isInitialMount = prevProvider === undefined;
const isModalClosing = prevProvider !== null && activeLoginProvider === null;
if (isInitialMount || isModalClosing) {
checkClaudeAuthStatus();
checkCursorAuthStatus();
checkCodexAuthStatus();
}
}, [currentStep]);
}, [activeLoginProvider]);
const checkClaudeAuthStatus = async () => {
try {
@@ -134,22 +133,48 @@ const Onboarding = ({ onComplete }) => {
}
};
const handleClaudeLogin = () => {
setLoginProvider('claude');
setShowLoginModal(true);
const checkCodexAuthStatus = async () => {
try {
const response = await authenticatedFetch('/api/cli/codex/status');
if (response.ok) {
const data = await response.json();
setCodexAuthStatus({
authenticated: data.authenticated,
email: data.email,
loading: false,
error: data.error || null
});
} else {
setCodexAuthStatus({
authenticated: false,
email: null,
loading: false,
error: 'Failed to check authentication status'
});
}
} catch (error) {
console.error('Error checking Codex auth status:', error);
setCodexAuthStatus({
authenticated: false,
email: null,
loading: false,
error: error.message
});
}
};
const handleCursorLogin = () => {
setLoginProvider('cursor');
setShowLoginModal(true);
};
const handleClaudeLogin = () => setActiveLoginProvider('claude');
const handleCursorLogin = () => setActiveLoginProvider('cursor');
const handleCodexLogin = () => setActiveLoginProvider('codex');
const handleLoginComplete = (exitCode) => {
if (exitCode === 0) {
if (loginProvider === 'claude') {
if (activeLoginProvider === 'claude') {
checkClaudeAuthStatus();
} else if (loginProvider === 'cursor') {
} else if (activeLoginProvider === 'cursor') {
checkCursorAuthStatus();
} else if (activeLoginProvider === 'codex') {
checkCodexAuthStatus();
}
}
};
@@ -194,7 +219,6 @@ const Onboarding = ({ onComplete }) => {
return;
}
// Other steps: just move forward
setCurrentStep(currentStep + 1);
};
@@ -208,7 +232,6 @@ const Onboarding = ({ onComplete }) => {
setError('');
try {
// Mark onboarding as complete
const response = await authenticatedFetch('/api/user/complete-onboarding', {
method: 'POST'
});
@@ -218,7 +241,6 @@ const Onboarding = ({ onComplete }) => {
throw new Error(data.error || 'Failed to complete onboarding');
}
// Call the onComplete callback
if (onComplete) {
onComplete();
}
@@ -237,15 +259,9 @@ const Onboarding = ({ onComplete }) => {
required: true
},
{
title: 'Claude Code CLI',
description: 'Connect your Claude Code account',
icon: () => <ClaudeLogo size={24} />,
required: false
},
{
title: 'Cursor CLI',
description: 'Connect your Cursor account',
icon: () => <CursorLogo size={24} />,
title: 'Connect Agents',
description: 'Connect your AI coding assistants',
icon: LogIn,
required: false
}
];
@@ -312,135 +328,117 @@ const Onboarding = ({ onComplete }) => {
case 1:
return (
<div className="space-y-6">
<div className="text-center mb-8">
<div className="w-16 h-16 bg-blue-100 dark:bg-blue-900/30 rounded-full flex items-center justify-center mx-auto mb-4">
<ClaudeLogo size={32} />
</div>
<h2 className="text-2xl font-bold text-foreground mb-2">Claude Code CLI</h2>
<div className="text-center mb-6">
<h2 className="text-2xl font-bold text-foreground mb-2">Connect Your AI Agents</h2>
<p className="text-muted-foreground">
Connect your Claude account to enable AI-powered coding features
Login to one or more AI coding assistants. All are optional.
</p>
</div>
{/* Auth Status Card */}
<div className="border border-border rounded-lg p-6 bg-card">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-3">
<div className={`w-3 h-3 rounded-full ${
claudeAuthStatus.loading ? 'bg-gray-400 animate-pulse' :
claudeAuthStatus.authenticated ? 'bg-green-500' : 'bg-gray-300'
}`} />
<span className="font-medium text-foreground">
{claudeAuthStatus.loading ? 'Checking...' :
claudeAuthStatus.authenticated ? 'Connected' : 'Not Connected'}
</span>
{/* Agent Cards Grid */}
<div className="space-y-3">
{/* Claude */}
<div className={`border rounded-lg p-4 transition-colors ${
claudeAuthStatus.authenticated
? 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800'
: 'border-border bg-card'
}`}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-blue-100 dark:bg-blue-900/30 rounded-full flex items-center justify-center">
<ClaudeLogo size={20} />
</div>
<div>
<div className="font-medium text-foreground flex items-center gap-2">
Claude Code
{claudeAuthStatus.authenticated && <Check className="w-4 h-4 text-green-500" />}
</div>
<div className="text-xs text-muted-foreground">
{claudeAuthStatus.loading ? 'Checking...' :
claudeAuthStatus.authenticated ? claudeAuthStatus.email || 'Connected' : 'Not connected'}
</div>
</div>
</div>
{!claudeAuthStatus.authenticated && !claudeAuthStatus.loading && (
<button
onClick={handleClaudeLogin}
className="bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium py-2 px-4 rounded-lg transition-colors"
>
Login
</button>
)}
</div>
{claudeAuthStatus.authenticated && (
<Check className="w-5 h-5 text-green-500" />
)}
</div>
{claudeAuthStatus.authenticated && claudeAuthStatus.email && (
<p className="text-sm text-muted-foreground mb-4">
Signed in as: <span className="text-foreground font-medium">{claudeAuthStatus.email}</span>
</p>
)}
{!claudeAuthStatus.authenticated && (
<>
<p className="text-sm text-muted-foreground mb-4">
Click the button below to authenticate with Claude Code CLI. A terminal will open with authentication instructions.
</p>
<button
onClick={handleClaudeLogin}
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg transition-colors duration-200 flex items-center justify-center gap-2"
>
<LogIn className="w-5 h-5" />
Login to Claude Code
</button>
<p className="text-xs text-muted-foreground mt-3 text-center">
Or manually run: <code className="bg-muted px-2 py-1 rounded">claude auth login</code>
</p>
</>
)}
{claudeAuthStatus.error && !claudeAuthStatus.authenticated && (
<div className="mt-4 p-3 bg-yellow-100 dark:bg-yellow-900/20 border border-yellow-300 dark:border-yellow-800 rounded-lg">
<p className="text-sm text-yellow-700 dark:text-yellow-400">{claudeAuthStatus.error}</p>
{/* Cursor */}
<div className={`border rounded-lg p-4 transition-colors ${
cursorAuthStatus.authenticated
? 'bg-purple-50 dark:bg-purple-900/20 border-purple-200 dark:border-purple-800'
: 'border-border bg-card'
}`}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-purple-100 dark:bg-purple-900/30 rounded-full flex items-center justify-center">
<CursorLogo size={20} />
</div>
<div>
<div className="font-medium text-foreground flex items-center gap-2">
Cursor
{cursorAuthStatus.authenticated && <Check className="w-4 h-4 text-green-500" />}
</div>
<div className="text-xs text-muted-foreground">
{cursorAuthStatus.loading ? 'Checking...' :
cursorAuthStatus.authenticated ? cursorAuthStatus.email || 'Connected' : 'Not connected'}
</div>
</div>
</div>
{!cursorAuthStatus.authenticated && !cursorAuthStatus.loading && (
<button
onClick={handleCursorLogin}
className="bg-purple-600 hover:bg-purple-700 text-white text-sm font-medium py-2 px-4 rounded-lg transition-colors"
>
Login
</button>
)}
</div>
)}
</div>
<div className="text-center text-sm text-muted-foreground">
<p>This step is optional. You can skip and configure it later in Settings.</p>
</div>
</div>
);
case 2:
return (
<div className="space-y-6">
<div className="text-center mb-8">
<div className="w-16 h-16 bg-purple-100 dark:bg-purple-900/30 rounded-full flex items-center justify-center mx-auto mb-4">
<CursorLogo size={32} />
</div>
<h2 className="text-2xl font-bold text-foreground mb-2">Cursor CLI</h2>
<p className="text-muted-foreground">
Connect your Cursor account to enable AI-powered features
</p>
</div>
{/* Auth Status Card */}
<div className="border border-border rounded-lg p-6 bg-card">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-3">
<div className={`w-3 h-3 rounded-full ${
cursorAuthStatus.loading ? 'bg-gray-400 animate-pulse' :
cursorAuthStatus.authenticated ? 'bg-green-500' : 'bg-gray-300'
}`} />
<span className="font-medium text-foreground">
{cursorAuthStatus.loading ? 'Checking...' :
cursorAuthStatus.authenticated ? 'Connected' : 'Not Connected'}
</span>
</div>
{cursorAuthStatus.authenticated && (
<Check className="w-5 h-5 text-green-500" />
)}
</div>
{cursorAuthStatus.authenticated && cursorAuthStatus.email && (
<p className="text-sm text-muted-foreground mb-4">
Signed in as: <span className="text-foreground font-medium">{cursorAuthStatus.email}</span>
</p>
)}
{!cursorAuthStatus.authenticated && (
<>
<p className="text-sm text-muted-foreground mb-4">
Click the button below to authenticate with Cursor CLI. A terminal will open with authentication instructions.
</p>
<button
onClick={handleCursorLogin}
className="w-full bg-purple-600 hover:bg-purple-700 text-white font-medium py-3 px-4 rounded-lg transition-colors duration-200 flex items-center justify-center gap-2"
>
<LogIn className="w-5 h-5" />
Login to Cursor
</button>
<p className="text-xs text-muted-foreground mt-3 text-center">
Or manually run: <code className="bg-muted px-2 py-1 rounded">cursor auth login</code>
</p>
</>
)}
{cursorAuthStatus.error && !cursorAuthStatus.authenticated && (
<div className="mt-4 p-3 bg-yellow-100 dark:bg-yellow-900/20 border border-yellow-300 dark:border-yellow-800 rounded-lg">
<p className="text-sm text-yellow-700 dark:text-yellow-400">{cursorAuthStatus.error}</p>
{/* Codex */}
<div className={`border rounded-lg p-4 transition-colors ${
codexAuthStatus.authenticated
? 'bg-gray-100 dark:bg-gray-800/50 border-gray-300 dark:border-gray-600'
: 'border-border bg-card'
}`}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center">
<CodexLogo className="w-5 h-5" />
</div>
<div>
<div className="font-medium text-foreground flex items-center gap-2">
OpenAI Codex
{codexAuthStatus.authenticated && <Check className="w-4 h-4 text-green-500" />}
</div>
<div className="text-xs text-muted-foreground">
{codexAuthStatus.loading ? 'Checking...' :
codexAuthStatus.authenticated ? codexAuthStatus.email || 'Connected' : 'Not connected'}
</div>
</div>
</div>
{!codexAuthStatus.authenticated && !codexAuthStatus.loading && (
<button
onClick={handleCodexLogin}
className="bg-gray-800 hover:bg-gray-900 dark:bg-gray-700 dark:hover:bg-gray-600 text-white text-sm font-medium py-2 px-4 rounded-lg transition-colors"
>
Login
</button>
)}
</div>
)}
</div>
</div>
<div className="text-center text-sm text-muted-foreground">
<p>This step is optional. You can skip and configure it later in Settings.</p>
<div className="text-center text-sm text-muted-foreground pt-2">
<p>You can configure these later in Settings.</p>
</div>
</div>
);
@@ -455,8 +453,7 @@ const Onboarding = ({ onComplete }) => {
case 0:
return gitName.trim() && gitEmail.trim() && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(gitEmail);
case 1:
case 2:
return true; // CLI steps are optional
return true;
default:
return false;
}
@@ -572,14 +569,13 @@ const Onboarding = ({ onComplete }) => {
</div>
</div>
{/* Login Modal */}
{showLoginModal && (
{activeLoginProvider && (
<LoginModal
isOpen={showLoginModal}
onClose={() => setShowLoginModal(false)}
provider={loginProvider}
isOpen={!!activeLoginProvider}
onClose={() => setActiveLoginProvider(null)}
provider={activeLoginProvider}
project={selectedProject}
onLoginComplete={handleLoginComplete}
onComplete={handleLoginComplete}
/>
)}
</>

File diff suppressed because it is too large Load Diff

View File

@@ -220,7 +220,6 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
return;
}
console.log('[Shell] Terminal initializing, mounting component');
terminal.current = new Terminal({
cursorBlink: true,
@@ -346,7 +345,6 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
}
return () => {
console.log('[Shell] Terminal cleanup, unmounting component');
resizeObserver.disconnect();
if (ws.current && (ws.current.readyState === WebSocket.OPEN || ws.current.readyState === WebSocket.CONNECTING)) {

View File

@@ -9,6 +9,7 @@ import { FolderOpen, Folder, Plus, MessageSquare, Clock, ChevronDown, ChevronRig
import { cn } from '../lib/utils';
import ClaudeLogo from './ClaudeLogo';
import CursorLogo from './CursorLogo.jsx';
import CodexLogo from './CodexLogo.jsx';
import TaskIndicator from './TaskIndicator';
import ProjectCreationWizard from './ProjectCreationWizard';
import { api } from '../utils/api';
@@ -220,12 +221,17 @@ function Sidebar({
// Helper function to get all sessions for a project (initial + additional)
const getAllSessions = (project) => {
// Combine Claude and Cursor sessions; Sidebar will display icon per row
// Combine Claude, Cursor, and Codex sessions; Sidebar will display icon per row
const claudeSessions = [...(project.sessions || []), ...(additionalSessions[project.name] || [])].map(s => ({ ...s, __provider: 'claude' }));
const cursorSessions = (project.cursorSessions || []).map(s => ({ ...s, __provider: 'cursor' }));
const codexSessions = (project.codexSessions || []).map(s => ({ ...s, __provider: 'codex' }));
// Sort by most recent activity/date
const normalizeDate = (s) => new Date(s.__provider === 'cursor' ? s.createdAt : s.lastActivity);
return [...claudeSessions, ...cursorSessions].sort((a, b) => normalizeDate(b) - normalizeDate(a));
const normalizeDate = (s) => {
if (s.__provider === 'cursor') return new Date(s.createdAt);
if (s.__provider === 'codex') return new Date(s.createdAt || s.lastActivity);
return new Date(s.lastActivity);
};
return [...claudeSessions, ...cursorSessions, ...codexSessions].sort((a, b) => normalizeDate(b) - normalizeDate(a));
};
// Helper function to get the last activity date for a project
@@ -297,14 +303,22 @@ function Sidebar({
setEditingName('');
};
const deleteSession = async (projectName, sessionId) => {
const deleteSession = async (projectName, sessionId, provider = 'claude') => {
if (!confirm('Are you sure you want to delete this session? This action cannot be undone.')) {
return;
}
try {
console.log('[Sidebar] Deleting session:', { projectName, sessionId });
const response = await api.deleteSession(projectName, sessionId);
console.log('[Sidebar] Deleting session:', { projectName, sessionId, provider });
// Call the appropriate API based on provider
let response;
if (provider === 'codex') {
response = await api.deleteCodexSession(sessionId);
} else {
response = await api.deleteSession(projectName, sessionId);
}
console.log('[Sidebar] Delete response:', { ok: response.ok, status: response.status });
if (response.ok) {
@@ -1012,17 +1026,33 @@ function Sidebar({
</div>
) : (
getAllSessions(project).map((session) => {
// Handle both Claude and Cursor session formats
// Handle Claude, Cursor, and Codex session formats
const isCursorSession = session.__provider === 'cursor';
const isCodexSession = session.__provider === 'codex';
// Calculate if session is active (within last 10 minutes)
const sessionDate = new Date(isCursorSession ? session.createdAt : session.lastActivity);
const getSessionDate = () => {
if (isCursorSession) return new Date(session.createdAt);
if (isCodexSession) return new Date(session.createdAt || session.lastActivity);
return new Date(session.lastActivity);
};
const sessionDate = getSessionDate();
const diffInMinutes = Math.floor((currentTime - sessionDate) / (1000 * 60));
const isActive = diffInMinutes < 10;
// Get session display values
const sessionName = isCursorSession ? (session.name || 'Untitled Session') : (session.summary || 'New Session');
const sessionTime = isCursorSession ? session.createdAt : session.lastActivity;
const getSessionName = () => {
if (isCursorSession) return session.name || 'Untitled Session';
if (isCodexSession) return session.summary || session.name || 'Codex Session';
return session.summary || 'New Session';
};
const sessionName = getSessionName();
const getSessionTime = () => {
if (isCursorSession) return session.createdAt;
if (isCodexSession) return session.createdAt || session.lastActivity;
return session.lastActivity;
};
const sessionTime = getSessionTime();
const messageCount = session.messageCount || 0;
return (
@@ -1057,6 +1087,8 @@ function Sidebar({
)}>
{isCursorSession ? (
<CursorLogo className="w-3 h-3" />
) : isCodexSession ? (
<CodexLogo className="w-3 h-3" />
) : (
<ClaudeLogo className="w-3 h-3" />
)}
@@ -1079,21 +1111,22 @@ function Sidebar({
<span className="ml-1 opacity-70">
{isCursorSession ? (
<CursorLogo className="w-3 h-3" />
) : isCodexSession ? (
<CodexLogo className="w-3 h-3" />
) : (
<ClaudeLogo className="w-3 h-3" />
)}
</span>
</div>
</div>
{/* Mobile delete button - only for Claude sessions */}
{!isCursorSession && (
<button
className="w-5 h-5 rounded-md bg-red-50 dark:bg-red-900/20 flex items-center justify-center active:scale-95 transition-transform opacity-70 ml-1"
onClick={(e) => {
e.stopPropagation();
deleteSession(project.name, session.id);
deleteSession(project.name, session.id, session.__provider);
}}
onTouchEnd={handleTouchClick(() => deleteSession(project.name, session.id))}
onTouchEnd={handleTouchClick(() => deleteSession(project.name, session.id, session.__provider))}
>
<Trash2 className="w-2.5 h-2.5 text-red-600 dark:text-red-400" />
</button>
@@ -1116,6 +1149,8 @@ function Sidebar({
<div className="flex items-start gap-2 min-w-0 w-full">
{isCursorSession ? (
<CursorLogo className="w-3 h-3 mt-0.5 flex-shrink-0" />
) : isCodexSession ? (
<CodexLogo className="w-3 h-3 mt-0.5 flex-shrink-0" />
) : (
<ClaudeLogo className="w-3 h-3 mt-0.5 flex-shrink-0" />
)}
@@ -1133,10 +1168,11 @@ function Sidebar({
{messageCount}
</Badge>
)}
{/* Provider tiny icon */}
<span className="ml-1 opacity-70">
{isCursorSession ? (
<CursorLogo className="w-3 h-3" />
) : isCodexSession ? (
<CodexLogo className="w-3 h-3" />
) : (
<ClaudeLogo className="w-3 h-3" />
)}
@@ -1145,10 +1181,9 @@ function Sidebar({
</div>
</div>
</Button>
{/* Desktop hover buttons - only for Claude sessions */}
{!isCursorSession && (
<div className="absolute right-2 top-1/2 transform -translate-y-1/2 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-all duration-200">
{editingSession === session.id ? (
{editingSession === session.id && !isCodexSession ? (
<>
<input
type="text"
@@ -1191,40 +1226,24 @@ function Sidebar({
</>
) : (
<>
{/* Generate summary button */}
{/* <button
className="w-6 h-6 bg-blue-50 hover:bg-blue-100 dark:bg-blue-900/20 dark:hover:bg-blue-900/40 rounded flex items-center justify-center"
onClick={(e) => {
e.stopPropagation();
generateSessionSummary(project.name, session.id);
}}
title="Generate AI summary for this session"
disabled={generatingSummary[`${project.name}-${session.id}`]}
>
{generatingSummary[`${project.name}-${session.id}`] ? (
<div className="w-3 h-3 animate-spin rounded-full border border-blue-600 dark:border-blue-400 border-t-transparent" />
) : (
<Sparkles className="w-3 h-3 text-blue-600 dark:text-blue-400" />
)}
</button> */}
{/* Edit button */}
<button
className="w-6 h-6 bg-gray-50 hover:bg-gray-100 dark:bg-gray-900/20 dark:hover:bg-gray-900/40 rounded flex items-center justify-center"
onClick={(e) => {
e.stopPropagation();
setEditingSession(session.id);
setEditingSessionName(session.summary || 'New Session');
}}
title="Manually edit session name"
>
<Edit2 className="w-3 h-3 text-gray-600 dark:text-gray-400" />
</button>
{/* Delete button */}
{!isCodexSession && (
<button
className="w-6 h-6 bg-gray-50 hover:bg-gray-100 dark:bg-gray-900/20 dark:hover:bg-gray-900/40 rounded flex items-center justify-center"
onClick={(e) => {
e.stopPropagation();
setEditingSession(session.id);
setEditingSessionName(session.summary || 'New Session');
}}
title="Manually edit session name"
>
<Edit2 className="w-3 h-3 text-gray-600 dark:text-gray-400" />
</button>
)}
<button
className="w-6 h-6 bg-red-50 hover:bg-red-100 dark:bg-red-900/20 dark:hover:bg-red-900/40 rounded flex items-center justify-center"
onClick={(e) => {
e.stopPropagation();
deleteSession(project.name, session.id);
deleteSession(project.name, session.id, session.__provider);
}}
title="Delete this session permanently"
>

View File

@@ -0,0 +1,124 @@
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { LogIn } from 'lucide-react';
import ClaudeLogo from '../ClaudeLogo';
import CursorLogo from '../CursorLogo';
import CodexLogo from '../CodexLogo';
const agentConfig = {
claude: {
name: 'Claude',
description: 'Anthropic Claude AI assistant',
Logo: ClaudeLogo,
bgClass: 'bg-blue-50 dark:bg-blue-900/20',
borderClass: 'border-blue-200 dark:border-blue-800',
textClass: 'text-blue-900 dark:text-blue-100',
subtextClass: 'text-blue-700 dark:text-blue-300',
buttonClass: 'bg-blue-600 hover:bg-blue-700',
},
cursor: {
name: 'Cursor',
description: 'Cursor AI-powered code editor',
Logo: CursorLogo,
bgClass: 'bg-purple-50 dark:bg-purple-900/20',
borderClass: 'border-purple-200 dark:border-purple-800',
textClass: 'text-purple-900 dark:text-purple-100',
subtextClass: 'text-purple-700 dark:text-purple-300',
buttonClass: 'bg-purple-600 hover:bg-purple-700',
},
codex: {
name: 'Codex',
description: 'OpenAI Codex AI assistant',
Logo: CodexLogo,
bgClass: 'bg-gray-100 dark:bg-gray-800/50',
borderClass: 'border-gray-300 dark:border-gray-600',
textClass: 'text-gray-900 dark:text-gray-100',
subtextClass: 'text-gray-700 dark:text-gray-300',
buttonClass: 'bg-gray-800 hover:bg-gray-900 dark:bg-gray-700 dark:hover:bg-gray-600',
},
};
export default function AccountContent({ agent, authStatus, onLogin }) {
const config = agentConfig[agent];
const { Logo } = config;
return (
<div className="space-y-6">
<div className="flex items-center gap-3 mb-4">
<Logo className="w-6 h-6" />
<div>
<h3 className="text-lg font-medium text-foreground">{config.name} Account</h3>
<p className="text-sm text-muted-foreground">{config.description}</p>
</div>
</div>
<div className={`${config.bgClass} border ${config.borderClass} rounded-lg p-4`}>
<div className="space-y-4">
{/* Connection Status */}
<div className="flex items-center gap-3">
<div className="flex-1">
<div className={`font-medium ${config.textClass}`}>
Connection Status
</div>
<div className={`text-sm ${config.subtextClass}`}>
{authStatus?.loading ? (
'Checking authentication status...'
) : authStatus?.authenticated ? (
`Logged in as ${authStatus.email || 'authenticated user'}`
) : (
'Not connected'
)}
</div>
</div>
<div>
{authStatus?.loading ? (
<Badge variant="secondary" className="bg-gray-100 dark:bg-gray-800">
Checking...
</Badge>
) : authStatus?.authenticated ? (
<Badge variant="success" className="bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300">
Connected
</Badge>
) : (
<Badge variant="secondary" className="bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300">
Disconnected
</Badge>
)}
</div>
</div>
<div className="border-t border-gray-200 dark:border-gray-700 pt-4">
<div className="flex items-center justify-between">
<div>
<div className={`font-medium ${config.textClass}`}>
{authStatus?.authenticated ? 'Re-authenticate' : 'Login'}
</div>
<div className={`text-sm ${config.subtextClass}`}>
{authStatus?.authenticated
? 'Sign in with a different account or refresh credentials'
: `Sign in to your ${config.name} account to enable AI features`}
</div>
</div>
<Button
onClick={onLogin}
className={`${config.buttonClass} text-white`}
size="sm"
>
<LogIn className="w-4 h-4 mr-2" />
{authStatus?.authenticated ? 'Re-login' : 'Login'}
</Button>
</div>
</div>
{authStatus?.error && (
<div className="border-t border-gray-200 dark:border-gray-700 pt-4">
<div className="text-sm text-red-600 dark:text-red-400">
Error: {authStatus.error}
</div>
</div>
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,104 @@
import ClaudeLogo from '../ClaudeLogo';
import CursorLogo from '../CursorLogo';
import CodexLogo from '../CodexLogo';
const agentConfig = {
claude: {
name: 'Claude',
color: 'blue',
Logo: ClaudeLogo,
},
cursor: {
name: 'Cursor',
color: 'purple',
Logo: CursorLogo,
},
codex: {
name: 'Codex',
color: 'gray',
Logo: CodexLogo,
},
};
const colorClasses = {
blue: {
border: 'border-l-blue-500 md:border-l-blue-500',
borderBottom: 'border-b-blue-500',
bg: 'bg-blue-50 dark:bg-blue-900/20',
dot: 'bg-blue-500',
},
purple: {
border: 'border-l-purple-500 md:border-l-purple-500',
borderBottom: 'border-b-purple-500',
bg: 'bg-purple-50 dark:bg-purple-900/20',
dot: 'bg-purple-500',
},
gray: {
border: 'border-l-gray-700 dark:border-l-gray-300',
borderBottom: 'border-b-gray-700 dark:border-b-gray-300',
bg: 'bg-gray-100 dark:bg-gray-800/50',
dot: 'bg-gray-700 dark:bg-gray-300',
},
};
export default function AgentListItem({ agentId, authStatus, isSelected, onClick, isMobile = false }) {
const config = agentConfig[agentId];
const colors = colorClasses[config.color];
const { Logo } = config;
// Mobile: horizontal layout with bottom border
if (isMobile) {
return (
<button
onClick={onClick}
className={`flex-1 text-center py-3 px-2 border-b-2 transition-colors ${
isSelected
? `${colors.borderBottom} ${colors.bg}`
: 'border-transparent hover:bg-gray-50 dark:hover:bg-gray-800'
}`}
>
<div className="flex flex-col items-center gap-1">
<Logo className="w-5 h-5" />
<span className="text-xs font-medium text-foreground">{config.name}</span>
{authStatus?.authenticated && (
<span className={`w-1.5 h-1.5 rounded-full ${colors.dot}`} />
)}
</div>
</button>
);
}
// Desktop: vertical layout with left border
return (
<button
onClick={onClick}
className={`w-full text-left p-3 border-l-4 transition-colors ${
isSelected
? `${colors.border} ${colors.bg}`
: 'border-transparent hover:bg-gray-50 dark:hover:bg-gray-800'
}`}
>
<div className="flex items-center gap-2 mb-1">
<Logo className="w-4 h-4" />
<span className="font-medium text-foreground">{config.name}</span>
</div>
<div className="text-xs text-muted-foreground pl-6">
{authStatus?.loading ? (
<span className="text-gray-400">Checking...</span>
) : authStatus?.authenticated ? (
<div className="flex items-center gap-1">
<span className={`w-1.5 h-1.5 rounded-full ${colors.dot}`} />
<span className="truncate max-w-[120px]" title={authStatus.email}>
{authStatus.email || 'Connected'}
</span>
</div>
) : (
<div className="flex items-center gap-1">
<span className="w-1.5 h-1.5 rounded-full bg-gray-400" />
<span>Not connected</span>
</div>
)}
</div>
</button>
);
}

View File

@@ -0,0 +1,314 @@
import { useState } from 'react';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Server, Plus, Edit3, Trash2, Terminal, Globe, Zap, X } from 'lucide-react';
const getTransportIcon = (type) => {
switch (type) {
case 'stdio': return <Terminal className="w-4 h-4" />;
case 'sse': return <Zap className="w-4 h-4" />;
case 'http': return <Globe className="w-4 h-4" />;
default: return <Server className="w-4 h-4" />;
}
};
// Claude MCP Servers
function ClaudeMcpServers({
servers,
onAdd,
onEdit,
onDelete,
onTest,
onDiscoverTools,
testResults,
serverTools,
toolsLoading,
}) {
return (
<div className="space-y-4">
<div className="flex items-center gap-3">
<Server className="w-5 h-5 text-purple-500" />
<h3 className="text-lg font-medium text-foreground">
MCP Servers
</h3>
</div>
<p className="text-sm text-muted-foreground">
Model Context Protocol servers provide additional tools and data sources to Claude
</p>
<div className="flex justify-between items-center">
<Button
onClick={onAdd}
className="bg-purple-600 hover:bg-purple-700 text-white"
size="sm"
>
<Plus className="w-4 h-4 mr-2" />
Add MCP Server
</Button>
</div>
<div className="space-y-2">
{servers.map(server => (
<div key={server.id} className="bg-gray-50 dark:bg-gray-900/50 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
{getTransportIcon(server.type)}
<span className="font-medium text-foreground">{server.name}</span>
<Badge variant="outline" className="text-xs">
{server.type}
</Badge>
<Badge variant="outline" className="text-xs">
{server.scope === 'local' ? 'local' : server.scope === 'user' ? 'user' : server.scope}
</Badge>
</div>
<div className="text-sm text-muted-foreground space-y-1">
{server.type === 'stdio' && server.config?.command && (
<div>Command: <code className="bg-gray-100 dark:bg-gray-800 px-1 rounded text-xs">{server.config.command}</code></div>
)}
{(server.type === 'sse' || server.type === 'http') && server.config?.url && (
<div>URL: <code className="bg-gray-100 dark:bg-gray-800 px-1 rounded text-xs">{server.config.url}</code></div>
)}
{server.config?.args && server.config.args.length > 0 && (
<div>Args: <code className="bg-gray-100 dark:bg-gray-800 px-1 rounded text-xs">{server.config.args.join(' ')}</code></div>
)}
</div>
{/* Test Results */}
{testResults?.[server.id] && (
<div className={`mt-2 p-2 rounded text-xs ${
testResults[server.id].success
? 'bg-green-50 dark:bg-green-900/20 text-green-800 dark:text-green-200'
: 'bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200'
}`}>
<div className="font-medium">{testResults[server.id].message}</div>
</div>
)}
{/* Tools Discovery Results */}
{serverTools?.[server.id] && serverTools[server.id].tools?.length > 0 && (
<div className="mt-2 p-2 rounded text-xs bg-blue-50 dark:bg-blue-900/20 text-blue-800 dark:text-blue-200">
<div className="font-medium">Tools ({serverTools[server.id].tools.length}):</div>
<div className="flex flex-wrap gap-1 mt-1">
{serverTools[server.id].tools.slice(0, 5).map((tool, i) => (
<code key={i} className="bg-blue-100 dark:bg-blue-800 px-1 rounded">{tool.name}</code>
))}
{serverTools[server.id].tools.length > 5 && (
<span className="text-xs opacity-75">+{serverTools[server.id].tools.length - 5} more</span>
)}
</div>
</div>
)}
</div>
<div className="flex items-center gap-2 ml-4">
<Button
onClick={() => onEdit(server)}
variant="ghost"
size="sm"
className="text-gray-600 hover:text-gray-700"
title="Edit server"
>
<Edit3 className="w-4 h-4" />
</Button>
<Button
onClick={() => onDelete(server.id, server.scope)}
variant="ghost"
size="sm"
className="text-red-600 hover:text-red-700"
title="Delete server"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
</div>
))}
{servers.length === 0 && (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
No MCP servers configured
</div>
)}
</div>
</div>
);
}
// Cursor MCP Servers
function CursorMcpServers({ servers, onAdd, onEdit, onDelete }) {
return (
<div className="space-y-4">
<div className="flex items-center gap-3">
<Server className="w-5 h-5 text-purple-500" />
<h3 className="text-lg font-medium text-foreground">
MCP Servers
</h3>
</div>
<p className="text-sm text-muted-foreground">
Model Context Protocol servers provide additional tools and data sources to Cursor
</p>
<div className="flex justify-between items-center">
<Button
onClick={onAdd}
className="bg-purple-600 hover:bg-purple-700 text-white"
size="sm"
>
<Plus className="w-4 h-4 mr-2" />
Add MCP Server
</Button>
</div>
<div className="space-y-2">
{servers.map(server => (
<div key={server.name || server.id} className="bg-gray-50 dark:bg-gray-900/50 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<Terminal className="w-4 h-4" />
<span className="font-medium text-foreground">{server.name}</span>
<Badge variant="outline" className="text-xs">stdio</Badge>
</div>
<div className="text-sm text-muted-foreground">
{server.config?.command && (
<div>Command: <code className="bg-gray-100 dark:bg-gray-800 px-1 rounded text-xs">{server.config.command}</code></div>
)}
</div>
</div>
<div className="flex items-center gap-2 ml-4">
<Button
onClick={() => onEdit(server)}
variant="ghost"
size="sm"
className="text-gray-600 hover:text-gray-700"
>
<Edit3 className="w-4 h-4" />
</Button>
<Button
onClick={() => onDelete(server.name)}
variant="ghost"
size="sm"
className="text-red-600 hover:text-red-700"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
</div>
))}
{servers.length === 0 && (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
No MCP servers configured
</div>
)}
</div>
</div>
);
}
// Codex MCP Servers
function CodexMcpServers({ servers, onAdd, onEdit, onDelete }) {
return (
<div className="space-y-4">
<div className="flex items-center gap-3">
<Server className="w-5 h-5 text-gray-700 dark:text-gray-300" />
<h3 className="text-lg font-medium text-foreground">
MCP Servers
</h3>
</div>
<p className="text-sm text-muted-foreground">
Model Context Protocol servers provide additional tools and data sources to Codex
</p>
<div className="flex justify-between items-center">
<Button
onClick={onAdd}
className="bg-gray-800 hover:bg-gray-900 dark:bg-gray-700 dark:hover:bg-gray-600 text-white"
size="sm"
>
<Plus className="w-4 h-4 mr-2" />
Add MCP Server
</Button>
</div>
<div className="space-y-2">
{servers.map(server => (
<div key={server.name} className="bg-gray-50 dark:bg-gray-900/50 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<Terminal className="w-4 h-4" />
<span className="font-medium text-foreground">{server.name}</span>
<Badge variant="outline" className="text-xs">stdio</Badge>
</div>
<div className="text-sm text-muted-foreground space-y-1">
{server.config?.command && (
<div>Command: <code className="bg-gray-100 dark:bg-gray-800 px-1 rounded text-xs">{server.config.command}</code></div>
)}
{server.config?.args && server.config.args.length > 0 && (
<div>Args: <code className="bg-gray-100 dark:bg-gray-800 px-1 rounded text-xs">{server.config.args.join(' ')}</code></div>
)}
{server.config?.env && Object.keys(server.config.env).length > 0 && (
<div>Environment: <code className="bg-gray-100 dark:bg-gray-800 px-1 rounded text-xs">{Object.entries(server.config.env).map(([k, v]) => `${k}=${v}`).join(', ')}</code></div>
)}
</div>
</div>
<div className="flex items-center gap-2 ml-4">
<Button
onClick={() => onEdit(server)}
variant="ghost"
size="sm"
className="text-gray-600 hover:text-gray-700"
title="Edit server"
>
<Edit3 className="w-4 h-4" />
</Button>
<Button
onClick={() => onDelete(server.name)}
variant="ghost"
size="sm"
className="text-red-600 hover:text-red-700"
title="Delete server"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
</div>
))}
{servers.length === 0 && (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
No MCP servers configured
</div>
)}
</div>
{/* Help Section */}
<div className="bg-gray-100 dark:bg-gray-800/50 border border-gray-300 dark:border-gray-600 rounded-lg p-4">
<h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">About Codex MCP</h4>
<p className="text-sm text-gray-700 dark:text-gray-300">
Codex supports stdio-based MCP servers. You can add servers that extend Codex's capabilities
with additional tools and resources.
</p>
</div>
</div>
);
}
// Main component
export default function McpServersContent({ agent, ...props }) {
if (agent === 'claude') {
return <ClaudeMcpServers {...props} />;
}
if (agent === 'cursor') {
return <CursorMcpServers {...props} />;
}
if (agent === 'codex') {
return <CodexMcpServers {...props} />;
}
return null;
}

View File

@@ -0,0 +1,611 @@
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Shield, AlertTriangle, Plus, X } from 'lucide-react';
// Common tool patterns for Claude
const commonClaudeTools = [
'Bash(git log:*)',
'Bash(git diff:*)',
'Bash(git status:*)',
'Write',
'Read',
'Edit',
'Glob',
'Grep',
'MultiEdit',
'Task',
'TodoWrite',
'TodoRead',
'WebFetch',
'WebSearch'
];
// Common shell commands for Cursor
const commonCursorCommands = [
'Shell(ls)',
'Shell(mkdir)',
'Shell(cd)',
'Shell(cat)',
'Shell(echo)',
'Shell(git status)',
'Shell(git diff)',
'Shell(git log)',
'Shell(npm install)',
'Shell(npm run)',
'Shell(python)',
'Shell(node)'
];
// Claude Permissions
function ClaudePermissions({
skipPermissions,
setSkipPermissions,
allowedTools,
setAllowedTools,
disallowedTools,
setDisallowedTools,
newAllowedTool,
setNewAllowedTool,
newDisallowedTool,
setNewDisallowedTool,
}) {
const addAllowedTool = (tool) => {
if (tool && !allowedTools.includes(tool)) {
setAllowedTools([...allowedTools, tool]);
setNewAllowedTool('');
}
};
const removeAllowedTool = (tool) => {
setAllowedTools(allowedTools.filter(t => t !== tool));
};
const addDisallowedTool = (tool) => {
if (tool && !disallowedTools.includes(tool)) {
setDisallowedTools([...disallowedTools, tool]);
setNewDisallowedTool('');
}
};
const removeDisallowedTool = (tool) => {
setDisallowedTools(disallowedTools.filter(t => t !== tool));
};
return (
<div className="space-y-6">
{/* Skip Permissions */}
<div className="space-y-4">
<div className="flex items-center gap-3">
<AlertTriangle className="w-5 h-5 text-orange-500" />
<h3 className="text-lg font-medium text-foreground">
Permission Settings
</h3>
</div>
<div className="bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-lg p-4">
<label className="flex items-center gap-3">
<input
type="checkbox"
checked={skipPermissions}
onChange={(e) => setSkipPermissions(e.target.checked)}
className="w-4 h-4 text-blue-600 bg-gray-100 dark:bg-gray-700 border-gray-300 dark:border-gray-600 rounded focus:ring-blue-500 focus:ring-2"
/>
<div>
<div className="font-medium text-orange-900 dark:text-orange-100">
Skip permission prompts (use with caution)
</div>
<div className="text-sm text-orange-700 dark:text-orange-300">
Equivalent to --dangerously-skip-permissions flag
</div>
</div>
</label>
</div>
</div>
{/* Allowed Tools */}
<div className="space-y-4">
<div className="flex items-center gap-3">
<Shield className="w-5 h-5 text-green-500" />
<h3 className="text-lg font-medium text-foreground">
Allowed Tools
</h3>
</div>
<p className="text-sm text-muted-foreground">
Tools that are automatically allowed without prompting for permission
</p>
<div className="flex flex-col sm:flex-row gap-2">
<Input
value={newAllowedTool}
onChange={(e) => setNewAllowedTool(e.target.value)}
placeholder='e.g., "Bash(git log:*)" or "Write"'
onKeyPress={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
addAllowedTool(newAllowedTool);
}
}}
className="flex-1 h-10"
/>
<Button
onClick={() => addAllowedTool(newAllowedTool)}
disabled={!newAllowedTool}
size="sm"
className="h-10 px-4"
>
<Plus className="w-4 h-4 mr-2 sm:mr-0" />
<span className="sm:hidden">Add</span>
</Button>
</div>
{/* Quick add buttons */}
<div className="space-y-2">
<p className="text-sm font-medium text-gray-700 dark:text-gray-300">
Quick add common tools:
</p>
<div className="flex flex-wrap gap-2">
{commonClaudeTools.map(tool => (
<Button
key={tool}
variant="outline"
size="sm"
onClick={() => addAllowedTool(tool)}
disabled={allowedTools.includes(tool)}
className="text-xs h-8"
>
{tool}
</Button>
))}
</div>
</div>
<div className="space-y-2">
{allowedTools.map(tool => (
<div key={tool} className="flex items-center justify-between bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
<span className="font-mono text-sm text-green-800 dark:text-green-200">
{tool}
</span>
<Button
variant="ghost"
size="sm"
onClick={() => removeAllowedTool(tool)}
className="text-green-600 hover:text-green-700"
>
<X className="w-4 h-4" />
</Button>
</div>
))}
{allowedTools.length === 0 && (
<div className="text-center py-6 text-gray-500 dark:text-gray-400">
No allowed tools configured
</div>
)}
</div>
</div>
{/* Disallowed Tools */}
<div className="space-y-4">
<div className="flex items-center gap-3">
<AlertTriangle className="w-5 h-5 text-red-500" />
<h3 className="text-lg font-medium text-foreground">
Blocked Tools
</h3>
</div>
<p className="text-sm text-muted-foreground">
Tools that are automatically blocked without prompting for permission
</p>
<div className="flex flex-col sm:flex-row gap-2">
<Input
value={newDisallowedTool}
onChange={(e) => setNewDisallowedTool(e.target.value)}
placeholder='e.g., "Bash(rm:*)"'
onKeyPress={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
addDisallowedTool(newDisallowedTool);
}
}}
className="flex-1 h-10"
/>
<Button
onClick={() => addDisallowedTool(newDisallowedTool)}
disabled={!newDisallowedTool}
size="sm"
className="h-10 px-4"
>
<Plus className="w-4 h-4 mr-2 sm:mr-0" />
<span className="sm:hidden">Add</span>
</Button>
</div>
<div className="space-y-2">
{disallowedTools.map(tool => (
<div key={tool} className="flex items-center justify-between bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3">
<span className="font-mono text-sm text-red-800 dark:text-red-200">
{tool}
</span>
<Button
variant="ghost"
size="sm"
onClick={() => removeDisallowedTool(tool)}
className="text-red-600 hover:text-red-700"
>
<X className="w-4 h-4" />
</Button>
</div>
))}
{disallowedTools.length === 0 && (
<div className="text-center py-6 text-gray-500 dark:text-gray-400">
No blocked tools configured
</div>
)}
</div>
</div>
{/* Help Section */}
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
<h4 className="font-medium text-blue-900 dark:text-blue-100 mb-2">
Tool Pattern Examples:
</h4>
<ul className="text-sm text-blue-800 dark:text-blue-200 space-y-1">
<li><code className="bg-blue-100 dark:bg-blue-800 px-1 rounded">"Bash(git log:*)"</code> - Allow all git log commands</li>
<li><code className="bg-blue-100 dark:bg-blue-800 px-1 rounded">"Bash(git diff:*)"</code> - Allow all git diff commands</li>
<li><code className="bg-blue-100 dark:bg-blue-800 px-1 rounded">"Write"</code> - Allow all Write tool usage</li>
<li><code className="bg-blue-100 dark:bg-blue-800 px-1 rounded">"Bash(rm:*)"</code> - Block all rm commands (dangerous)</li>
</ul>
</div>
</div>
);
}
// Cursor Permissions
function CursorPermissions({
skipPermissions,
setSkipPermissions,
allowedCommands,
setAllowedCommands,
disallowedCommands,
setDisallowedCommands,
newAllowedCommand,
setNewAllowedCommand,
newDisallowedCommand,
setNewDisallowedCommand,
}) {
const addAllowedCommand = (cmd) => {
if (cmd && !allowedCommands.includes(cmd)) {
setAllowedCommands([...allowedCommands, cmd]);
setNewAllowedCommand('');
}
};
const removeAllowedCommand = (cmd) => {
setAllowedCommands(allowedCommands.filter(c => c !== cmd));
};
const addDisallowedCommand = (cmd) => {
if (cmd && !disallowedCommands.includes(cmd)) {
setDisallowedCommands([...disallowedCommands, cmd]);
setNewDisallowedCommand('');
}
};
const removeDisallowedCommand = (cmd) => {
setDisallowedCommands(disallowedCommands.filter(c => c !== cmd));
};
return (
<div className="space-y-6">
{/* Skip Permissions */}
<div className="space-y-4">
<div className="flex items-center gap-3">
<AlertTriangle className="w-5 h-5 text-orange-500" />
<h3 className="text-lg font-medium text-foreground">
Permission Settings
</h3>
</div>
<div className="bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-lg p-4">
<label className="flex items-center gap-3">
<input
type="checkbox"
checked={skipPermissions}
onChange={(e) => setSkipPermissions(e.target.checked)}
className="w-4 h-4 text-purple-600 bg-gray-100 dark:bg-gray-700 border-gray-300 dark:border-gray-600 rounded focus:ring-purple-500 focus:ring-2"
/>
<div>
<div className="font-medium text-orange-900 dark:text-orange-100">
Skip permission prompts (use with caution)
</div>
<div className="text-sm text-orange-700 dark:text-orange-300">
Equivalent to -f flag in Cursor CLI
</div>
</div>
</label>
</div>
</div>
{/* Allowed Commands */}
<div className="space-y-4">
<div className="flex items-center gap-3">
<Shield className="w-5 h-5 text-green-500" />
<h3 className="text-lg font-medium text-foreground">
Allowed Shell Commands
</h3>
</div>
<p className="text-sm text-muted-foreground">
Shell commands that are automatically allowed without prompting
</p>
<div className="flex flex-col sm:flex-row gap-2">
<Input
value={newAllowedCommand}
onChange={(e) => setNewAllowedCommand(e.target.value)}
placeholder='e.g., "Shell(ls)" or "Shell(git status)"'
onKeyPress={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
addAllowedCommand(newAllowedCommand);
}
}}
className="flex-1 h-10"
/>
<Button
onClick={() => addAllowedCommand(newAllowedCommand)}
disabled={!newAllowedCommand}
size="sm"
className="h-10 px-4"
>
<Plus className="w-4 h-4 mr-2 sm:mr-0" />
<span className="sm:hidden">Add</span>
</Button>
</div>
{/* Quick add buttons */}
<div className="space-y-2">
<p className="text-sm font-medium text-gray-700 dark:text-gray-300">
Quick add common commands:
</p>
<div className="flex flex-wrap gap-2">
{commonCursorCommands.map(cmd => (
<Button
key={cmd}
variant="outline"
size="sm"
onClick={() => addAllowedCommand(cmd)}
disabled={allowedCommands.includes(cmd)}
className="text-xs h-8"
>
{cmd}
</Button>
))}
</div>
</div>
<div className="space-y-2">
{allowedCommands.map(cmd => (
<div key={cmd} className="flex items-center justify-between bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
<span className="font-mono text-sm text-green-800 dark:text-green-200">
{cmd}
</span>
<Button
variant="ghost"
size="sm"
onClick={() => removeAllowedCommand(cmd)}
className="text-green-600 hover:text-green-700"
>
<X className="w-4 h-4" />
</Button>
</div>
))}
{allowedCommands.length === 0 && (
<div className="text-center py-6 text-gray-500 dark:text-gray-400">
No allowed commands configured
</div>
)}
</div>
</div>
{/* Disallowed Commands */}
<div className="space-y-4">
<div className="flex items-center gap-3">
<AlertTriangle className="w-5 h-5 text-red-500" />
<h3 className="text-lg font-medium text-foreground">
Blocked Shell Commands
</h3>
</div>
<p className="text-sm text-muted-foreground">
Shell commands that are automatically blocked
</p>
<div className="flex flex-col sm:flex-row gap-2">
<Input
value={newDisallowedCommand}
onChange={(e) => setNewDisallowedCommand(e.target.value)}
placeholder='e.g., "Shell(rm -rf)" or "Shell(sudo)"'
onKeyPress={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
addDisallowedCommand(newDisallowedCommand);
}
}}
className="flex-1 h-10"
/>
<Button
onClick={() => addDisallowedCommand(newDisallowedCommand)}
disabled={!newDisallowedCommand}
size="sm"
className="h-10 px-4"
>
<Plus className="w-4 h-4 mr-2 sm:mr-0" />
<span className="sm:hidden">Add</span>
</Button>
</div>
<div className="space-y-2">
{disallowedCommands.map(cmd => (
<div key={cmd} className="flex items-center justify-between bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3">
<span className="font-mono text-sm text-red-800 dark:text-red-200">
{cmd}
</span>
<Button
variant="ghost"
size="sm"
onClick={() => removeDisallowedCommand(cmd)}
className="text-red-600 hover:text-red-700"
>
<X className="w-4 h-4" />
</Button>
</div>
))}
{disallowedCommands.length === 0 && (
<div className="text-center py-6 text-gray-500 dark:text-gray-400">
No blocked commands configured
</div>
)}
</div>
</div>
{/* Help Section */}
<div className="bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded-lg p-4">
<h4 className="font-medium text-purple-900 dark:text-purple-100 mb-2">
Shell Command Examples:
</h4>
<ul className="text-sm text-purple-800 dark:text-purple-200 space-y-1">
<li><code className="bg-purple-100 dark:bg-purple-800 px-1 rounded">"Shell(ls)"</code> - Allow ls command</li>
<li><code className="bg-purple-100 dark:bg-purple-800 px-1 rounded">"Shell(git status)"</code> - Allow git status</li>
<li><code className="bg-purple-100 dark:bg-purple-800 px-1 rounded">"Shell(npm install)"</code> - Allow npm install</li>
<li><code className="bg-purple-100 dark:bg-purple-800 px-1 rounded">"Shell(rm -rf)"</code> - Block recursive delete</li>
</ul>
</div>
</div>
);
}
// Codex Permissions
function CodexPermissions({ permissionMode, setPermissionMode }) {
return (
<div className="space-y-6">
<div className="space-y-4">
<div className="flex items-center gap-3">
<Shield className="w-5 h-5 text-green-500" />
<h3 className="text-lg font-medium text-foreground">
Permission Mode
</h3>
</div>
<p className="text-sm text-muted-foreground">
Controls how Codex handles file modifications and command execution
</p>
{/* Default Mode */}
<div
className={`border rounded-lg p-4 cursor-pointer transition-all ${
permissionMode === 'default'
? 'bg-gray-100 dark:bg-gray-800 border-gray-400 dark:border-gray-500'
: 'bg-gray-50 dark:bg-gray-900/50 border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
onClick={() => setPermissionMode('default')}
>
<label className="flex items-start gap-3 cursor-pointer">
<input
type="radio"
name="codexPermissionMode"
checked={permissionMode === 'default'}
onChange={() => setPermissionMode('default')}
className="mt-1 w-4 h-4 text-green-600"
/>
<div>
<div className="font-medium text-foreground">Default</div>
<div className="text-sm text-muted-foreground">
Only trusted commands (ls, cat, grep, git status, etc.) run automatically.
Other commands are skipped. Can write to workspace.
</div>
</div>
</label>
</div>
{/* Accept Edits Mode */}
<div
className={`border rounded-lg p-4 cursor-pointer transition-all ${
permissionMode === 'acceptEdits'
? 'bg-green-50 dark:bg-green-900/20 border-green-400 dark:border-green-600'
: 'bg-gray-50 dark:bg-gray-900/50 border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
onClick={() => setPermissionMode('acceptEdits')}
>
<label className="flex items-start gap-3 cursor-pointer">
<input
type="radio"
name="codexPermissionMode"
checked={permissionMode === 'acceptEdits'}
onChange={() => setPermissionMode('acceptEdits')}
className="mt-1 w-4 h-4 text-green-600"
/>
<div>
<div className="font-medium text-green-900 dark:text-green-100">Accept Edits</div>
<div className="text-sm text-green-700 dark:text-green-300">
All commands run automatically within the workspace.
Full auto mode with sandboxed execution.
</div>
</div>
</label>
</div>
{/* Bypass Permissions Mode */}
<div
className={`border rounded-lg p-4 cursor-pointer transition-all ${
permissionMode === 'bypassPermissions'
? 'bg-orange-50 dark:bg-orange-900/20 border-orange-400 dark:border-orange-600'
: 'bg-gray-50 dark:bg-gray-900/50 border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
onClick={() => setPermissionMode('bypassPermissions')}
>
<label className="flex items-start gap-3 cursor-pointer">
<input
type="radio"
name="codexPermissionMode"
checked={permissionMode === 'bypassPermissions'}
onChange={() => setPermissionMode('bypassPermissions')}
className="mt-1 w-4 h-4 text-orange-600"
/>
<div>
<div className="font-medium text-orange-900 dark:text-orange-100 flex items-center gap-2">
Bypass Permissions
<AlertTriangle className="w-4 h-4" />
</div>
<div className="text-sm text-orange-700 dark:text-orange-300">
Full system access with no restrictions. All commands run automatically
with full disk and network access. Use with caution.
</div>
</div>
</label>
</div>
{/* Technical Details */}
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">
Technical details
</summary>
<div className="mt-2 p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg text-xs text-muted-foreground space-y-2">
<p><strong>Default:</strong> sandboxMode=workspace-write, approvalPolicy=untrusted. Trusted commands: cat, cd, grep, head, ls, pwd, tail, git status/log/diff/show, find (without -exec), etc.</p>
<p><strong>Accept Edits:</strong> sandboxMode=workspace-write, approvalPolicy=never. All commands auto-execute within project directory.</p>
<p><strong>Bypass Permissions:</strong> sandboxMode=danger-full-access, approvalPolicy=never. Full system access, use only in trusted environments.</p>
<p className="text-xs opacity-75">You can override this per-session using the mode button in the chat interface.</p>
</div>
</details>
</div>
</div>
);
}
// Main component
export default function PermissionsContent({ agent, ...props }) {
if (agent === 'claude') {
return <ClaudePermissions {...props} />;
}
if (agent === 'cursor') {
return <CursorPermissions {...props} />;
}
if (agent === 'codex') {
return <CodexPermissions {...props} />;
}
return null;
}

View File

@@ -3,9 +3,12 @@ export const authenticatedFetch = (url, options = {}) => {
const isPlatform = import.meta.env.VITE_IS_PLATFORM === 'true';
const token = localStorage.getItem('auth-token');
const defaultHeaders = {
'Content-Type': 'application/json',
};
const defaultHeaders = {};
// Only set Content-Type for non-FormData requests
if (!(options.body instanceof FormData)) {
defaultHeaders['Content-Type'] = 'application/json';
}
if (!isPlatform && token) {
defaultHeaders['Authorization'] = `Bearer ${token}`;
@@ -44,14 +47,23 @@ export const api = {
projects: () => authenticatedFetch('/api/projects'),
sessions: (projectName, limit = 5, offset = 0) =>
authenticatedFetch(`/api/projects/${projectName}/sessions?limit=${limit}&offset=${offset}`),
sessionMessages: (projectName, sessionId, limit = null, offset = 0) => {
sessionMessages: (projectName, sessionId, limit = null, offset = 0, provider = 'claude') => {
const params = new URLSearchParams();
if (limit !== null) {
params.append('limit', limit);
params.append('offset', offset);
}
const queryString = params.toString();
const url = `/api/projects/${projectName}/sessions/${sessionId}/messages${queryString ? `?${queryString}` : ''}`;
// Route to the correct endpoint based on provider
let url;
if (provider === 'codex') {
url = `/api/codex/sessions/${sessionId}/messages${queryString ? `?${queryString}` : ''}`;
} else if (provider === 'cursor') {
url = `/api/cursor/sessions/${sessionId}/messages${queryString ? `?${queryString}` : ''}`;
} else {
url = `/api/projects/${projectName}/sessions/${sessionId}/messages${queryString ? `?${queryString}` : ''}`;
}
return authenticatedFetch(url);
},
renameProject: (projectName, displayName) =>
@@ -63,6 +75,10 @@ export const api = {
authenticatedFetch(`/api/projects/${projectName}/sessions/${sessionId}`, {
method: 'DELETE',
}),
deleteCodexSession: (sessionId) =>
authenticatedFetch(`/api/codex/sessions/${sessionId}`, {
method: 'DELETE',
}),
deleteProject: (projectName) =>
authenticatedFetch(`/api/projects/${projectName}`, {
method: 'DELETE',

View File

@@ -17,7 +17,7 @@ export default defineConfig(({ command, mode }) => {
ws: true
},
'/shell': {
target: `ws://localhost:${env.PORT || 3002}`,
target: `ws://localhost:${env.PORT || 3001}`,
ws: true
}
}