mirror of
https://github.com/siteboon/claudecodeui.git
synced 2026-05-30 16:35:34 +08:00
Compare commits
90 Commits
fix/plugin
...
v1.17.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f20926394e | ||
|
|
b6e8ef6f3d | ||
|
|
090ad05867 | ||
|
|
2d3d924272 | ||
|
|
0d0740760a | ||
|
|
b498a25965 | ||
|
|
4e3dba304c | ||
|
|
c0bc3affb2 | ||
|
|
9fece98612 | ||
|
|
a4e55984ea | ||
|
|
0306f8d59b | ||
|
|
4c387808ed | ||
|
|
c193137aa5 | ||
|
|
450ce93ee4 | ||
|
|
7c1d2899fa | ||
|
|
58002df5d9 | ||
|
|
a82a225d23 | ||
|
|
be94e53a1a | ||
|
|
c79c022ff8 | ||
|
|
7cabb3da9b | ||
|
|
deec5f2f1b | ||
|
|
4f5212f93f | ||
|
|
b76f53c4bf | ||
|
|
474d324ea3 | ||
|
|
d8fbea8681 | ||
|
|
ae28b2d762 | ||
|
|
b8f06c8aa4 | ||
|
|
f6ed3cbd6d | ||
|
|
60a9f3dc32 | ||
|
|
d30d64ce93 | ||
|
|
022ac21369 | ||
|
|
3c6f353716 | ||
|
|
4d41bfd366 | ||
|
|
553c534f35 | ||
|
|
e435e70a6b | ||
|
|
0b6b33c3cc | ||
|
|
844602a4fe | ||
|
|
fc1ad17ba8 | ||
|
|
ed44d5e437 | ||
|
|
d99c581179 | ||
|
|
b8d80fdab7 | ||
|
|
720a771b2a | ||
|
|
189b1533b2 | ||
|
|
7f45540dbe | ||
|
|
fadbcc8259 | ||
|
|
fd5cced67f | ||
|
|
9524313363 | ||
|
|
8bc3c17793 | ||
|
|
1d081ae349 | ||
|
|
72e1f538f7 | ||
|
|
fa09eba829 | ||
|
|
79d7934a4b | ||
|
|
8e411187f3 | ||
|
|
a0bc4a8c72 | ||
|
|
d8e7a9e944 | ||
|
|
5f0676bdb3 | ||
|
|
905ae38bf5 | ||
|
|
56a132d34e | ||
|
|
060405c8d6 | ||
|
|
cbe4bd9adf | ||
|
|
f9bd56c20f | ||
|
|
c95aa04c85 | ||
|
|
4d55945c5d | ||
|
|
89334cda4e | ||
|
|
1d8b70f614 | ||
|
|
cdc03e754f | ||
|
|
8608d32dbd | ||
|
|
fdf2b09290 | ||
|
|
2c5e534121 | ||
|
|
806597d149 | ||
|
|
fb5cfd47c4 | ||
|
|
856033a9f6 | ||
|
|
527e8d040c | ||
|
|
a42d43ef5c | ||
|
|
b258e73e12 | ||
|
|
14f4831889 | ||
|
|
6659e07a50 | ||
|
|
98e16714d2 | ||
|
|
abcd239f25 | ||
|
|
6f9eb24a79 | ||
|
|
2f9d699107 | ||
|
|
a259c39c05 | ||
|
|
f861ae26ea | ||
|
|
6fad362cab | ||
|
|
f8d6daa37b | ||
|
|
f7b965d1be | ||
|
|
e2e77f20ba | ||
|
|
7b498085ea | ||
|
|
a5e4242ec0 | ||
|
|
f40c376ef5 |
@@ -57,7 +57,7 @@ A desktop and mobile UI for [Claude Code](https://docs.anthropic.com/en/docs/cla
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- [Node.js](https://nodejs.org/) v20 or higher
|
||||
- [Node.js](https://nodejs.org/) v22 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, and/or
|
||||
- [Codex](https://developers.openai.com/codex) installed and configured
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
|
||||
### 前置要求
|
||||
|
||||
- [Node.js](https://nodejs.org/) v20 或更高版本
|
||||
- [Node.js](https://nodejs.org/) v22 或更高版本
|
||||
- 已安装并配置 [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code),和/或
|
||||
- 已安装并配置 [Cursor CLI](https://docs.cursor.com/en/cli/overview),和/或
|
||||
- 已安装并配置 [Codex](https://developers.openai.com/codex)
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@siteboon/claude-code-ui",
|
||||
"version": "1.16.4",
|
||||
"version": "1.17.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@siteboon/claude-code-ui",
|
||||
"version": "1.16.4",
|
||||
"version": "1.17.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.1.29",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@siteboon/claude-code-ui",
|
||||
"version": "1.16.4",
|
||||
"version": "1.17.0",
|
||||
"description": "A web-based UI for Claude Code CLI",
|
||||
"type": "module",
|
||||
"main": "server/index.js",
|
||||
|
||||
192
server/index.js
192
server/index.js
@@ -63,8 +63,24 @@ import { initializeDatabase } from './database/db.js';
|
||||
import { validateApiKey, authenticateToken, authenticateWebSocket } from './middleware/auth.js';
|
||||
import { IS_PLATFORM } from './constants/config.js';
|
||||
|
||||
// File system watcher for projects folder
|
||||
let projectsWatcher = null;
|
||||
// File system watchers for provider project/session folders
|
||||
const PROVIDER_WATCH_PATHS = [
|
||||
{ provider: 'claude', rootPath: path.join(os.homedir(), '.claude', 'projects') },
|
||||
{ provider: 'cursor', rootPath: path.join(os.homedir(), '.cursor', 'chats') },
|
||||
{ provider: 'codex', rootPath: path.join(os.homedir(), '.codex', 'sessions') }
|
||||
];
|
||||
const WATCHER_IGNORED_PATTERNS = [
|
||||
'**/node_modules/**',
|
||||
'**/.git/**',
|
||||
'**/dist/**',
|
||||
'**/build/**',
|
||||
'**/*.tmp',
|
||||
'**/*.swp',
|
||||
'**/.DS_Store'
|
||||
];
|
||||
const WATCHER_DEBOUNCE_MS = 300;
|
||||
let projectsWatchers = [];
|
||||
let projectsWatcherDebounceTimer = null;
|
||||
const connectedClients = new Set();
|
||||
let isGetProjectsRunning = false; // Flag to prevent reentrant calls
|
||||
|
||||
@@ -81,94 +97,110 @@ function broadcastProgress(progress) {
|
||||
});
|
||||
}
|
||||
|
||||
// Setup file system watcher for Claude projects folder using chokidar
|
||||
// Setup file system watchers for Claude, Cursor, and Codex project/session folders
|
||||
async function setupProjectsWatcher() {
|
||||
const chokidar = (await import('chokidar')).default;
|
||||
const claudeProjectsPath = path.join(os.homedir(), '.claude', 'projects');
|
||||
|
||||
if (projectsWatcher) {
|
||||
projectsWatcher.close();
|
||||
if (projectsWatcherDebounceTimer) {
|
||||
clearTimeout(projectsWatcherDebounceTimer);
|
||||
projectsWatcherDebounceTimer = null;
|
||||
}
|
||||
|
||||
try {
|
||||
// Initialize chokidar watcher with optimized settings
|
||||
projectsWatcher = chokidar.watch(claudeProjectsPath, {
|
||||
ignored: [
|
||||
'**/node_modules/**',
|
||||
'**/.git/**',
|
||||
'**/dist/**',
|
||||
'**/build/**',
|
||||
'**/*.tmp',
|
||||
'**/*.swp',
|
||||
'**/.DS_Store'
|
||||
],
|
||||
persistent: true,
|
||||
ignoreInitial: true, // Don't fire events for existing files on startup
|
||||
followSymlinks: false,
|
||||
depth: 10, // Reasonable depth limit
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 100, // Wait 100ms for file to stabilize
|
||||
pollInterval: 50
|
||||
await Promise.all(
|
||||
projectsWatchers.map(async (watcher) => {
|
||||
try {
|
||||
await watcher.close();
|
||||
} catch (error) {
|
||||
console.error('[WARN] Failed to close watcher:', error);
|
||||
}
|
||||
});
|
||||
})
|
||||
);
|
||||
projectsWatchers = [];
|
||||
|
||||
// Debounce function to prevent excessive notifications
|
||||
let debounceTimer;
|
||||
const debouncedUpdate = async (eventType, filePath) => {
|
||||
clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(async () => {
|
||||
// Prevent reentrant calls
|
||||
if (isGetProjectsRunning) {
|
||||
return;
|
||||
const debouncedUpdate = (eventType, filePath, provider, rootPath) => {
|
||||
if (projectsWatcherDebounceTimer) {
|
||||
clearTimeout(projectsWatcherDebounceTimer);
|
||||
}
|
||||
|
||||
projectsWatcherDebounceTimer = setTimeout(async () => {
|
||||
// Prevent reentrant calls
|
||||
if (isGetProjectsRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
isGetProjectsRunning = true;
|
||||
|
||||
// Clear project directory cache when files change
|
||||
clearProjectDirectoryCache();
|
||||
|
||||
// Get updated projects list
|
||||
const updatedProjects = await getProjects(broadcastProgress);
|
||||
|
||||
// Notify all connected clients about the project changes
|
||||
const updateMessage = JSON.stringify({
|
||||
type: 'projects_updated',
|
||||
projects: updatedProjects,
|
||||
timestamp: new Date().toISOString(),
|
||||
changeType: eventType,
|
||||
changedFile: path.relative(rootPath, filePath),
|
||||
watchProvider: provider
|
||||
});
|
||||
|
||||
connectedClients.forEach(client => {
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
client.send(updateMessage);
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('[ERROR] Error handling project changes:', error);
|
||||
} finally {
|
||||
isGetProjectsRunning = false;
|
||||
}
|
||||
}, WATCHER_DEBOUNCE_MS);
|
||||
};
|
||||
|
||||
for (const { provider, rootPath } of PROVIDER_WATCH_PATHS) {
|
||||
try {
|
||||
// chokidar v4 emits ENOENT via the "error" event for missing roots and will not auto-recover.
|
||||
// Ensure provider folders exist before creating the watcher so watching stays active.
|
||||
await fsPromises.mkdir(rootPath, { recursive: true });
|
||||
|
||||
// Initialize chokidar watcher with optimized settings
|
||||
const watcher = chokidar.watch(rootPath, {
|
||||
ignored: WATCHER_IGNORED_PATTERNS,
|
||||
persistent: true,
|
||||
ignoreInitial: true, // Don't fire events for existing files on startup
|
||||
followSymlinks: false,
|
||||
depth: 10, // Reasonable depth limit
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 100, // Wait 100ms for file to stabilize
|
||||
pollInterval: 50
|
||||
}
|
||||
|
||||
try {
|
||||
isGetProjectsRunning = true;
|
||||
|
||||
// Clear project directory cache when files change
|
||||
clearProjectDirectoryCache();
|
||||
|
||||
// Get updated projects list
|
||||
const updatedProjects = await getProjects(broadcastProgress);
|
||||
|
||||
// Notify all connected clients about the project changes
|
||||
const updateMessage = JSON.stringify({
|
||||
type: 'projects_updated',
|
||||
projects: updatedProjects,
|
||||
timestamp: new Date().toISOString(),
|
||||
changeType: eventType,
|
||||
changedFile: path.relative(claudeProjectsPath, filePath)
|
||||
});
|
||||
|
||||
connectedClients.forEach(client => {
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
client.send(updateMessage);
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('[ERROR] Error handling project changes:', error);
|
||||
} finally {
|
||||
isGetProjectsRunning = false;
|
||||
}
|
||||
}, 300); // 300ms debounce (slightly faster than before)
|
||||
};
|
||||
|
||||
// Set up event listeners
|
||||
projectsWatcher
|
||||
.on('add', (filePath) => debouncedUpdate('add', filePath))
|
||||
.on('change', (filePath) => debouncedUpdate('change', filePath))
|
||||
.on('unlink', (filePath) => debouncedUpdate('unlink', filePath))
|
||||
.on('addDir', (dirPath) => debouncedUpdate('addDir', dirPath))
|
||||
.on('unlinkDir', (dirPath) => debouncedUpdate('unlinkDir', dirPath))
|
||||
.on('error', (error) => {
|
||||
console.error('[ERROR] Chokidar watcher error:', error);
|
||||
})
|
||||
.on('ready', () => {
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('[ERROR] Failed to setup projects watcher:', error);
|
||||
// Set up event listeners
|
||||
watcher
|
||||
.on('add', (filePath) => debouncedUpdate('add', filePath, provider, rootPath))
|
||||
.on('change', (filePath) => debouncedUpdate('change', filePath, provider, rootPath))
|
||||
.on('unlink', (filePath) => debouncedUpdate('unlink', filePath, provider, rootPath))
|
||||
.on('addDir', (dirPath) => debouncedUpdate('addDir', dirPath, provider, rootPath))
|
||||
.on('unlinkDir', (dirPath) => debouncedUpdate('unlinkDir', dirPath, provider, rootPath))
|
||||
.on('error', (error) => {
|
||||
console.error(`[ERROR] ${provider} watcher error:`, error);
|
||||
})
|
||||
.on('ready', () => {
|
||||
});
|
||||
|
||||
projectsWatchers.push(watcher);
|
||||
} catch (error) {
|
||||
console.error(`[ERROR] Failed to setup ${provider} watcher for ${rootPath}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
if (projectsWatchers.length === 0) {
|
||||
console.error('[ERROR] Failed to setup any provider watchers');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -203,6 +203,7 @@ export async function queryCodex(command, options = {}, ws) {
|
||||
let codex;
|
||||
let thread;
|
||||
let currentSessionId = sessionId;
|
||||
const abortController = new AbortController();
|
||||
|
||||
try {
|
||||
// Initialize Codex SDK
|
||||
@@ -232,6 +233,7 @@ export async function queryCodex(command, options = {}, ws) {
|
||||
thread,
|
||||
codex,
|
||||
status: 'running',
|
||||
abortController,
|
||||
startedAt: new Date().toISOString()
|
||||
});
|
||||
|
||||
@@ -243,7 +245,9 @@ export async function queryCodex(command, options = {}, ws) {
|
||||
});
|
||||
|
||||
// Execute with streaming
|
||||
const streamedTurn = await thread.runStreamed(command);
|
||||
const streamedTurn = await thread.runStreamed(command, {
|
||||
signal: abortController.signal
|
||||
});
|
||||
|
||||
for await (const event of streamedTurn.events) {
|
||||
// Check if session was aborted
|
||||
@@ -286,20 +290,27 @@ export async function queryCodex(command, options = {}, ws) {
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('[Codex] Error:', error);
|
||||
const session = currentSessionId ? activeCodexSessions.get(currentSessionId) : null;
|
||||
const wasAborted =
|
||||
session?.status === 'aborted' ||
|
||||
error?.name === 'AbortError' ||
|
||||
String(error?.message || '').toLowerCase().includes('aborted');
|
||||
|
||||
sendMessage(ws, {
|
||||
type: 'codex-error',
|
||||
error: error.message,
|
||||
sessionId: currentSessionId
|
||||
});
|
||||
if (!wasAborted) {
|
||||
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';
|
||||
session.status = session.status === 'aborted' ? 'aborted' : 'completed';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -318,9 +329,11 @@ export function abortCodexSession(sessionId) {
|
||||
}
|
||||
|
||||
session.status = 'aborted';
|
||||
|
||||
// The SDK doesn't have a direct abort method, but marking status
|
||||
// will cause the streaming loop to exit
|
||||
try {
|
||||
session.abortController?.abort();
|
||||
} catch (error) {
|
||||
console.warn(`[Codex] Failed to abort session ${sessionId}:`, error);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -384,6 +384,7 @@ async function getProjects(progressCallback = null) {
|
||||
const config = await loadProjectConfig();
|
||||
const projects = [];
|
||||
const existingProjects = new Set();
|
||||
const codexSessionsIndexRef = { sessionsByProject: null };
|
||||
let totalProjects = 0;
|
||||
let processedProjects = 0;
|
||||
let directories = [];
|
||||
@@ -419,8 +420,6 @@ async function getProjects(progressCallback = null) {
|
||||
});
|
||||
}
|
||||
|
||||
const projectPath = path.join(claudeDir, entry.name);
|
||||
|
||||
// Extract actual project directory from JSONL sessions
|
||||
const actualProjectDir = await extractProjectDirectory(entry.name);
|
||||
|
||||
@@ -435,7 +434,11 @@ async function getProjects(progressCallback = null) {
|
||||
displayName: customName || autoDisplayName,
|
||||
fullPath: fullPath,
|
||||
isCustomName: !!customName,
|
||||
sessions: []
|
||||
sessions: [],
|
||||
sessionMeta: {
|
||||
hasMore: false,
|
||||
total: 0
|
||||
}
|
||||
};
|
||||
|
||||
// Try to get sessions for this project (just first 5 for performance)
|
||||
@@ -448,6 +451,10 @@ async function getProjects(progressCallback = null) {
|
||||
};
|
||||
} catch (e) {
|
||||
console.warn(`Could not load sessions for project ${entry.name}:`, e.message);
|
||||
project.sessionMeta = {
|
||||
hasMore: false,
|
||||
total: 0
|
||||
};
|
||||
}
|
||||
|
||||
// Also fetch Cursor sessions for this project
|
||||
@@ -460,7 +467,9 @@ async function getProjects(progressCallback = null) {
|
||||
|
||||
// Also fetch Codex sessions for this project
|
||||
try {
|
||||
project.codexSessions = await getCodexSessions(actualProjectDir);
|
||||
project.codexSessions = await getCodexSessions(actualProjectDir, {
|
||||
indexRef: codexSessionsIndexRef,
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn(`Could not load Codex sessions for project ${entry.name}:`, e.message);
|
||||
project.codexSessions = [];
|
||||
@@ -525,7 +534,7 @@ async function getProjects(progressCallback = null) {
|
||||
}
|
||||
}
|
||||
|
||||
const project = {
|
||||
const project = {
|
||||
name: projectName,
|
||||
path: actualProjectDir,
|
||||
displayName: projectConfig.displayName || await generateDisplayName(projectName, actualProjectDir),
|
||||
@@ -533,9 +542,13 @@ async function getProjects(progressCallback = null) {
|
||||
isCustomName: !!projectConfig.displayName,
|
||||
isManuallyAdded: true,
|
||||
sessions: [],
|
||||
sessionMeta: {
|
||||
hasMore: false,
|
||||
total: 0
|
||||
},
|
||||
cursorSessions: [],
|
||||
codexSessions: []
|
||||
};
|
||||
};
|
||||
|
||||
// Try to fetch Cursor sessions for manual projects too
|
||||
try {
|
||||
@@ -546,7 +559,9 @@ async function getProjects(progressCallback = null) {
|
||||
|
||||
// Try to fetch Codex sessions for manual projects too
|
||||
try {
|
||||
project.codexSessions = await getCodexSessions(actualProjectDir);
|
||||
project.codexSessions = await getCodexSessions(actualProjectDir, {
|
||||
indexRef: codexSessionsIndexRef,
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn(`Could not load Codex sessions for manual project ${projectName}:`, e.message);
|
||||
}
|
||||
@@ -1244,75 +1259,114 @@ async function getCursorSessions(projectPath) {
|
||||
}
|
||||
|
||||
|
||||
function normalizeComparablePath(inputPath) {
|
||||
if (!inputPath || typeof inputPath !== 'string') {
|
||||
return '';
|
||||
}
|
||||
|
||||
const withoutLongPathPrefix = inputPath.startsWith('\\\\?\\')
|
||||
? inputPath.slice(4)
|
||||
: inputPath;
|
||||
const normalized = path.normalize(withoutLongPathPrefix.trim());
|
||||
|
||||
if (!normalized) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const resolved = path.resolve(normalized);
|
||||
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
|
||||
}
|
||||
|
||||
async function findCodexJsonlFiles(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 findCodexJsonlFiles(fullPath));
|
||||
} else if (entry.name.endsWith('.jsonl')) {
|
||||
files.push(fullPath);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Skip directories we can't read
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
async function buildCodexSessionsIndex() {
|
||||
const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
|
||||
const sessionsByProject = new Map();
|
||||
|
||||
try {
|
||||
await fs.access(codexSessionsDir);
|
||||
} catch (error) {
|
||||
return sessionsByProject;
|
||||
}
|
||||
|
||||
const jsonlFiles = await findCodexJsonlFiles(codexSessionsDir);
|
||||
|
||||
for (const filePath of jsonlFiles) {
|
||||
try {
|
||||
const sessionData = await parseCodexSessionFile(filePath);
|
||||
if (!sessionData || !sessionData.id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedProjectPath = normalizeComparablePath(sessionData.cwd);
|
||||
if (!normalizedProjectPath) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const session = {
|
||||
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,
|
||||
provider: 'codex',
|
||||
};
|
||||
|
||||
if (!sessionsByProject.has(normalizedProjectPath)) {
|
||||
sessionsByProject.set(normalizedProjectPath, []);
|
||||
}
|
||||
|
||||
sessionsByProject.get(normalizedProjectPath).push(session);
|
||||
} catch (error) {
|
||||
console.warn(`Could not parse Codex session file ${filePath}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
for (const sessions of sessionsByProject.values()) {
|
||||
sessions.sort((a, b) => new Date(b.lastActivity) - new Date(a.lastActivity));
|
||||
}
|
||||
|
||||
return sessionsByProject;
|
||||
}
|
||||
|
||||
// Fetch Codex sessions for a given project path
|
||||
async function getCodexSessions(projectPath, options = {}) {
|
||||
const { limit = 5 } = options;
|
||||
const { limit = 5, indexRef = null } = options;
|
||||
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
|
||||
const normalizedProjectPath = normalizeComparablePath(projectPath);
|
||||
if (!normalizedProjectPath) {
|
||||
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
|
||||
// Handle Windows long paths with \\?\ prefix
|
||||
const sessionCwd = sessionData?.cwd || '';
|
||||
const cleanSessionCwd = sessionCwd.startsWith('\\\\?\\') ? sessionCwd.slice(4) : sessionCwd;
|
||||
const cleanProjectPath = projectPath.startsWith('\\\\?\\') ? projectPath.slice(4) : projectPath;
|
||||
|
||||
if (sessionData && (sessionData.cwd === projectPath || cleanSessionCwd === cleanProjectPath || path.relative(cleanSessionCwd, cleanProjectPath) === '')) {
|
||||
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);
|
||||
}
|
||||
if (indexRef && !indexRef.sessionsByProject) {
|
||||
indexRef.sessionsByProject = await buildCodexSessionsIndex();
|
||||
}
|
||||
|
||||
// Sort sessions by last activity (newest first)
|
||||
sessions.sort((a, b) => new Date(b.lastActivity) - new Date(a.lastActivity));
|
||||
const sessionsByProject = indexRef?.sessionsByProject || await buildCodexSessionsIndex();
|
||||
const sessions = sessionsByProject.get(normalizedProjectPath) || [];
|
||||
|
||||
// Return limited sessions for performance (0 = unlimited for deletion)
|
||||
return limit > 0 ? sessions.slice(0, limit) : sessions;
|
||||
return limit > 0 ? sessions.slice(0, limit) : [...sessions];
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error fetching Codex sessions:', error);
|
||||
|
||||
@@ -209,6 +209,86 @@ Custom commands can be created in:
|
||||
};
|
||||
},
|
||||
|
||||
'/cost': async (args, context) => {
|
||||
const tokenUsage = context?.tokenUsage || {};
|
||||
const provider = context?.provider || 'claude';
|
||||
const model =
|
||||
context?.model ||
|
||||
(provider === 'cursor'
|
||||
? CURSOR_MODELS.DEFAULT
|
||||
: provider === 'codex'
|
||||
? CODEX_MODELS.DEFAULT
|
||||
: CLAUDE_MODELS.DEFAULT);
|
||||
|
||||
const used = Number(tokenUsage.used ?? tokenUsage.totalUsed ?? tokenUsage.total_tokens ?? 0) || 0;
|
||||
const total =
|
||||
Number(
|
||||
tokenUsage.total ??
|
||||
tokenUsage.contextWindow ??
|
||||
parseInt(process.env.CONTEXT_WINDOW || '160000', 10),
|
||||
) || 160000;
|
||||
const percentage = total > 0 ? Number(((used / total) * 100).toFixed(1)) : 0;
|
||||
|
||||
const inputTokensRaw =
|
||||
Number(
|
||||
tokenUsage.inputTokens ??
|
||||
tokenUsage.input ??
|
||||
tokenUsage.cumulativeInputTokens ??
|
||||
tokenUsage.promptTokens ??
|
||||
0,
|
||||
) || 0;
|
||||
const outputTokens =
|
||||
Number(
|
||||
tokenUsage.outputTokens ??
|
||||
tokenUsage.output ??
|
||||
tokenUsage.cumulativeOutputTokens ??
|
||||
tokenUsage.completionTokens ??
|
||||
0,
|
||||
) || 0;
|
||||
const cacheTokens =
|
||||
Number(
|
||||
tokenUsage.cacheReadTokens ??
|
||||
tokenUsage.cacheCreationTokens ??
|
||||
tokenUsage.cacheTokens ??
|
||||
tokenUsage.cachedTokens ??
|
||||
0,
|
||||
) || 0;
|
||||
|
||||
// If we only have total used tokens, treat them as input for display/estimation.
|
||||
const inputTokens =
|
||||
inputTokensRaw > 0 || outputTokens > 0 || cacheTokens > 0 ? inputTokensRaw + cacheTokens : used;
|
||||
|
||||
// Rough default rates by provider (USD / 1M tokens).
|
||||
const pricingByProvider = {
|
||||
claude: { input: 3, output: 15 },
|
||||
cursor: { input: 3, output: 15 },
|
||||
codex: { input: 1.5, output: 6 },
|
||||
};
|
||||
const rates = pricingByProvider[provider] || pricingByProvider.claude;
|
||||
|
||||
const inputCost = (inputTokens / 1_000_000) * rates.input;
|
||||
const outputCost = (outputTokens / 1_000_000) * rates.output;
|
||||
const totalCost = inputCost + outputCost;
|
||||
|
||||
return {
|
||||
type: 'builtin',
|
||||
action: 'cost',
|
||||
data: {
|
||||
tokenUsage: {
|
||||
used,
|
||||
total,
|
||||
percentage,
|
||||
},
|
||||
cost: {
|
||||
input: inputCost.toFixed(4),
|
||||
output: outputCost.toFixed(4),
|
||||
total: totalCost.toFixed(4),
|
||||
},
|
||||
model,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
'/status': async (args, context) => {
|
||||
// Read version from package.json
|
||||
const packageJsonPath = path.join(path.dirname(__dirname), '..', 'package.json');
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import express from 'express';
|
||||
import { exec } from 'child_process';
|
||||
import { exec, spawn } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import path from 'path';
|
||||
import { promises as fs } from 'fs';
|
||||
@@ -10,6 +10,43 @@ import { spawnCursor } from '../cursor-cli.js';
|
||||
const router = express.Router();
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
function spawnAsync(command, args, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
...options,
|
||||
shell: false,
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
child.stdout.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
child.stderr.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
child.on('error', (error) => {
|
||||
reject(error);
|
||||
});
|
||||
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) {
|
||||
resolve({ stdout, stderr });
|
||||
return;
|
||||
}
|
||||
|
||||
const error = new Error(`Command failed: ${command} ${args.join(' ')}`);
|
||||
error.code = code;
|
||||
error.stdout = stdout;
|
||||
error.stderr = stderr;
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Helper function to get the actual project path from the encoded project name
|
||||
async function getActualProjectPath(projectName) {
|
||||
try {
|
||||
@@ -60,19 +97,16 @@ async function validateGitRepository(projectPath) {
|
||||
}
|
||||
|
||||
try {
|
||||
// Use --show-toplevel to get the root of the git repository
|
||||
const { stdout: gitRoot } = await execAsync('git rev-parse --show-toplevel', { cwd: projectPath });
|
||||
const normalizedGitRoot = path.resolve(gitRoot.trim());
|
||||
const normalizedProjectPath = path.resolve(projectPath);
|
||||
|
||||
// Ensure the git root matches our project path (prevent using parent git repos)
|
||||
if (normalizedGitRoot !== normalizedProjectPath) {
|
||||
throw new Error(`Project directory is not a git repository. This directory is inside a git repository at ${normalizedGitRoot}, but git operations should be run from the repository root.`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.message.includes('Project directory is not a git repository')) {
|
||||
throw error;
|
||||
// Allow any directory that is inside a work tree (repo root or nested folder).
|
||||
const { stdout: insideWorkTreeOutput } = await execAsync('git rev-parse --is-inside-work-tree', { cwd: projectPath });
|
||||
const isInsideWorkTree = insideWorkTreeOutput.trim() === 'true';
|
||||
if (!isInsideWorkTree) {
|
||||
throw new Error('Not inside a git work tree');
|
||||
}
|
||||
|
||||
// Ensure git can resolve the repository root for this directory.
|
||||
await execAsync('git rev-parse --show-toplevel', { cwd: projectPath });
|
||||
} catch {
|
||||
throw new Error('Not a git repository. This directory does not contain a .git folder. Initialize a git repository with "git init" to use source control features.');
|
||||
}
|
||||
}
|
||||
@@ -445,11 +479,17 @@ router.get('/commits', async (req, res) => {
|
||||
|
||||
try {
|
||||
const projectPath = await getActualProjectPath(project);
|
||||
await validateGitRepository(projectPath);
|
||||
const parsedLimit = Number.parseInt(String(limit), 10);
|
||||
const safeLimit = Number.isFinite(parsedLimit) && parsedLimit > 0
|
||||
? Math.min(parsedLimit, 100)
|
||||
: 10;
|
||||
|
||||
// Get commit log with stats
|
||||
const { stdout } = await execAsync(
|
||||
`git log --pretty=format:'%H|%an|%ae|%ad|%s' --date=relative -n ${limit}`,
|
||||
{ cwd: projectPath }
|
||||
const { stdout } = await spawnAsync(
|
||||
'git',
|
||||
['log', '--pretty=format:%H|%an|%ae|%ad|%s', '--date=relative', '-n', String(safeLimit)],
|
||||
{ cwd: projectPath },
|
||||
);
|
||||
|
||||
const commits = stdout
|
||||
@@ -1125,4 +1165,4 @@ router.post('/delete-untracked', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
export default router;
|
||||
|
||||
1011
src/App.jsx
1011
src/App.jsx
File diff suppressed because it is too large
Load Diff
35
src/App.tsx
Normal file
35
src/App.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import { ThemeProvider } from './contexts/ThemeContext';
|
||||
import { AuthProvider } from './contexts/AuthContext';
|
||||
import { TaskMasterProvider } from './contexts/TaskMasterContext';
|
||||
import { TasksSettingsProvider } from './contexts/TasksSettingsContext';
|
||||
import { WebSocketProvider } from './contexts/WebSocketContext';
|
||||
import ProtectedRoute from './components/ProtectedRoute';
|
||||
import AppContent from './components/app/AppContent';
|
||||
import i18n from './i18n/config.js';
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ThemeProvider>
|
||||
<AuthProvider>
|
||||
<WebSocketProvider>
|
||||
<TasksSettingsProvider>
|
||||
<TaskMasterProvider>
|
||||
<ProtectedRoute>
|
||||
<Router basename={window.__ROUTER_BASENAME__ || ''}>
|
||||
<Routes>
|
||||
<Route path="/" element={<AppContent />} />
|
||||
<Route path="/session/:sessionId" element={<AppContent />} />
|
||||
</Routes>
|
||||
</Router>
|
||||
</ProtectedRoute>
|
||||
</TaskMasterProvider>
|
||||
</TasksSettingsProvider>
|
||||
</WebSocketProvider>
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
</I18nextProvider>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,53 +4,61 @@ import React, { useEffect, useRef } from 'react';
|
||||
* CommandMenu - Autocomplete dropdown for slash commands
|
||||
*
|
||||
* @param {Array} commands - Array of command objects to display
|
||||
* @param {number} selectedIndex - Currently selected command index
|
||||
* @param {number} selectedIndex - Currently selected command index (index in `commands`)
|
||||
* @param {Function} onSelect - Callback when a command is selected
|
||||
* @param {Function} onClose - Callback when menu should close
|
||||
* @param {Object} position - Position object { top, left } for absolute positioning
|
||||
* @param {boolean} isOpen - Whether the menu is open
|
||||
* @param {Array} frequentCommands - Array of frequently used command objects
|
||||
*/
|
||||
const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, position = { top: 0, left: 0 }, isOpen = false, frequentCommands = [] }) => {
|
||||
const CommandMenu = ({
|
||||
commands = [],
|
||||
selectedIndex = -1,
|
||||
onSelect,
|
||||
onClose,
|
||||
position = { top: 0, left: 0 },
|
||||
isOpen = false,
|
||||
frequentCommands = [],
|
||||
}) => {
|
||||
const menuRef = useRef(null);
|
||||
const selectedItemRef = useRef(null);
|
||||
|
||||
// Calculate responsive positioning
|
||||
// Calculate responsive menu positioning.
|
||||
// Mobile: dock above chat input. Desktop: clamp to viewport.
|
||||
const getMenuPosition = () => {
|
||||
const isMobile = window.innerWidth < 640;
|
||||
const viewportHeight = window.innerHeight;
|
||||
const menuHeight = 300; // Max height of menu
|
||||
|
||||
if (isMobile) {
|
||||
// On mobile, calculate bottom position dynamically to appear above the input
|
||||
// Use the bottom value which is calculated as: window.innerHeight - textarea.top + spacing
|
||||
const inputBottom = position.bottom || 90; // Use provided bottom or default
|
||||
// On mobile, calculate bottom position dynamically to appear above the input.
|
||||
// Use the bottom value calculated as: window.innerHeight - textarea.top + spacing.
|
||||
const inputBottom = position.bottom || 90;
|
||||
|
||||
return {
|
||||
position: 'fixed',
|
||||
bottom: `${inputBottom}px`, // Position above the input with spacing already included
|
||||
bottom: `${inputBottom}px`, // Position above the input with spacing already included.
|
||||
left: '16px',
|
||||
right: '16px',
|
||||
width: 'auto',
|
||||
maxWidth: 'calc(100vw - 32px)',
|
||||
maxHeight: 'min(50vh, 300px)' // Limit to smaller of 50vh or 300px
|
||||
maxHeight: 'min(50vh, 300px)', // Limit to smaller of 50vh or 300px.
|
||||
};
|
||||
}
|
||||
|
||||
// On desktop, use provided position but ensure it stays on screen
|
||||
// On desktop, use provided position but ensure it stays on screen.
|
||||
return {
|
||||
position: 'fixed',
|
||||
top: `${Math.max(16, Math.min(position.top, viewportHeight - 316))}px`,
|
||||
left: `${position.left}px`,
|
||||
width: 'min(400px, calc(100vw - 32px))',
|
||||
maxWidth: 'calc(100vw - 32px)',
|
||||
maxHeight: '300px'
|
||||
maxHeight: '300px',
|
||||
};
|
||||
};
|
||||
|
||||
const menuPosition = getMenuPosition();
|
||||
|
||||
// Close menu when clicking outside
|
||||
// Close menu when clicking outside.
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event) => {
|
||||
if (menuRef.current && !menuRef.current.contains(event.target) && isOpen) {
|
||||
@@ -64,9 +72,11 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
// Scroll selected item into view
|
||||
// Keep selected keyboard item visible while navigating.
|
||||
useEffect(() => {
|
||||
if (selectedItemRef.current && menuRef.current) {
|
||||
const menuRect = menuRef.current.getBoundingClientRect();
|
||||
@@ -84,7 +94,7 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
return null;
|
||||
}
|
||||
|
||||
// Show a message if no commands are available
|
||||
// Show a message if no commands are available.
|
||||
if (commands.length === 0) {
|
||||
return (
|
||||
<div
|
||||
@@ -100,7 +110,7 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
opacity: 1,
|
||||
transform: 'translateY(0)',
|
||||
transition: 'opacity 150ms ease-in-out, transform 150ms ease-in-out',
|
||||
textAlign: 'center'
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
No commands available
|
||||
@@ -108,11 +118,20 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
);
|
||||
}
|
||||
|
||||
// Add frequent commands as a special group if provided
|
||||
// Add frequent commands as a special group if provided.
|
||||
const hasFrequentCommands = frequentCommands.length > 0;
|
||||
|
||||
// Group commands by namespace
|
||||
const getCommandKey = (command) =>
|
||||
`${command.name}::${command.namespace || command.type || 'other'}::${command.path || ''}`;
|
||||
const frequentCommandKeys = new Set(frequentCommands.map(getCommandKey));
|
||||
|
||||
// Group commands by namespace for section rendering.
|
||||
// When frequent commands are shown, avoid duplicate rows in other sections.
|
||||
const groupedCommands = commands.reduce((groups, command) => {
|
||||
if (hasFrequentCommands && frequentCommandKeys.has(getCommandKey(command))) {
|
||||
return groups;
|
||||
}
|
||||
|
||||
const namespace = command.namespace || command.type || 'other';
|
||||
if (!groups[namespace]) {
|
||||
groups[namespace] = [];
|
||||
@@ -121,36 +140,33 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
return groups;
|
||||
}, {});
|
||||
|
||||
// Add frequent commands as a separate group
|
||||
// Add frequent commands as a separate group.
|
||||
if (hasFrequentCommands) {
|
||||
groupedCommands['frequent'] = frequentCommands;
|
||||
groupedCommands.frequent = frequentCommands;
|
||||
}
|
||||
|
||||
// Order: frequent, builtin, project, user, other
|
||||
// Order: frequent, builtin, project, user, other.
|
||||
const namespaceOrder = hasFrequentCommands
|
||||
? ['frequent', 'builtin', 'project', 'user', 'other']
|
||||
: ['builtin', 'project', 'user', 'other'];
|
||||
const orderedNamespaces = namespaceOrder.filter(ns => groupedCommands[ns]);
|
||||
const orderedNamespaces = namespaceOrder.filter((ns) => groupedCommands[ns]);
|
||||
|
||||
const namespaceLabels = {
|
||||
frequent: '⭐ Frequently Used',
|
||||
frequent: '\u2B50 Frequently Used',
|
||||
builtin: 'Built-in Commands',
|
||||
project: 'Project Commands',
|
||||
user: 'User Commands',
|
||||
other: 'Other Commands'
|
||||
other: 'Other Commands',
|
||||
};
|
||||
|
||||
// Calculate global index for each command
|
||||
let globalIndex = 0;
|
||||
const commandsWithIndex = [];
|
||||
orderedNamespaces.forEach(namespace => {
|
||||
groupedCommands[namespace].forEach(command => {
|
||||
commandsWithIndex.push({
|
||||
...command,
|
||||
globalIndex: globalIndex++,
|
||||
namespace
|
||||
});
|
||||
});
|
||||
// Keep all selection indices aligned to `commands` (filteredCommands from the hook).
|
||||
// This prevents mismatches between mouse selection (rendered list) and keyboard selection.
|
||||
const commandIndexByKey = new Map();
|
||||
commands.forEach((command, index) => {
|
||||
const key = getCommandKey(command);
|
||||
if (!commandIndexByKey.has(key)) {
|
||||
commandIndexByKey.set(key, index);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
@@ -169,7 +185,7 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
padding: '8px',
|
||||
opacity: isOpen ? 1 : 0,
|
||||
transform: isOpen ? 'translateY(0)' : 'translateY(-10px)',
|
||||
transition: 'opacity 150ms ease-in-out, transform 150ms ease-in-out'
|
||||
transition: 'opacity 150ms ease-in-out, transform 150ms ease-in-out',
|
||||
}}
|
||||
>
|
||||
{orderedNamespaces.map((namespace) => (
|
||||
@@ -182,25 +198,35 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
textTransform: 'uppercase',
|
||||
color: '#6b7280',
|
||||
padding: '8px 12px 4px',
|
||||
letterSpacing: '0.05em'
|
||||
letterSpacing: '0.05em',
|
||||
}}
|
||||
>
|
||||
{namespaceLabels[namespace] || namespace}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{groupedCommands[namespace].map((command) => {
|
||||
const cmdWithIndex = commandsWithIndex.find(c => c.name === command.name && c.namespace === namespace);
|
||||
const isSelected = cmdWithIndex && cmdWithIndex.globalIndex === selectedIndex;
|
||||
const commandKey = getCommandKey(command);
|
||||
const commandIndex = commandIndexByKey.get(commandKey) ?? -1;
|
||||
const isSelected = commandIndex === selectedIndex;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${namespace}-${command.name}`}
|
||||
key={`${namespace}-${command.name}-${command.path || ''}`}
|
||||
ref={isSelected ? selectedItemRef : null}
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
className="command-item"
|
||||
onMouseEnter={() => onSelect && onSelect(command, cmdWithIndex.globalIndex, true)}
|
||||
onClick={() => onSelect && onSelect(command, cmdWithIndex.globalIndex, false)}
|
||||
onMouseEnter={() => {
|
||||
if (onSelect && commandIndex >= 0) {
|
||||
onSelect(command, commandIndex, true);
|
||||
}
|
||||
}}
|
||||
onClick={() => {
|
||||
if (onSelect) {
|
||||
onSelect(command, commandIndex, false);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
@@ -209,9 +235,10 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
cursor: 'pointer',
|
||||
backgroundColor: isSelected ? '#eff6ff' : 'transparent',
|
||||
transition: 'background-color 100ms ease-in-out',
|
||||
marginBottom: '2px'
|
||||
marginBottom: '2px',
|
||||
}}
|
||||
onMouseDown={(e) => e.preventDefault()} // Prevent textarea blur
|
||||
// Prevent textarea blur when clicking a menu item.
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div
|
||||
@@ -219,20 +246,16 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '8px',
|
||||
marginBottom: command.description ? '4px' : 0
|
||||
marginBottom: command.description ? '4px' : 0,
|
||||
}}
|
||||
>
|
||||
{/* Command icon based on namespace */}
|
||||
<span
|
||||
style={{
|
||||
fontSize: '16px',
|
||||
flexShrink: 0
|
||||
}}
|
||||
>
|
||||
{namespace === 'builtin' && '⚡'}
|
||||
{namespace === 'project' && '📁'}
|
||||
{namespace === 'user' && '👤'}
|
||||
{namespace === 'other' && '📝'}
|
||||
<span style={{ fontSize: '16px', flexShrink: 0 }}>
|
||||
{namespace === 'builtin' && '\u26A1'}
|
||||
{namespace === 'project' && '\uD83D\uDCC1'}
|
||||
{namespace === 'user' && '\uD83D\uDC64'}
|
||||
{namespace === 'other' && '\uD83D\uDCDD'}
|
||||
{namespace === 'frequent' && '\u2B50'}
|
||||
</span>
|
||||
|
||||
{/* Command name */}
|
||||
@@ -241,7 +264,7 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
fontWeight: 600,
|
||||
fontSize: '14px',
|
||||
color: '#111827',
|
||||
fontFamily: 'monospace'
|
||||
fontFamily: 'monospace',
|
||||
}}
|
||||
>
|
||||
{command.name}
|
||||
@@ -257,7 +280,7 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
borderRadius: '4px',
|
||||
backgroundColor: '#f3f4f6',
|
||||
color: '#6b7280',
|
||||
fontWeight: 500
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{command.metadata.type}
|
||||
@@ -274,7 +297,7 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
marginLeft: '24px',
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis'
|
||||
textOverflow: 'ellipsis',
|
||||
}}
|
||||
>
|
||||
{command.description}
|
||||
@@ -289,10 +312,10 @@ const CommandMenu = ({ commands = [], selectedIndex = -1, onSelect, onClose, pos
|
||||
marginLeft: '8px',
|
||||
color: '#3b82f6',
|
||||
fontSize: '12px',
|
||||
fontWeight: 600
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
↵
|
||||
{'\u21B5'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -53,14 +53,28 @@ function GitPanel({ selectedProject, isMobile, onFileOpen }) {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedProject) {
|
||||
fetchGitStatus();
|
||||
fetchBranches();
|
||||
fetchRemoteStatus();
|
||||
if (activeView === 'history') {
|
||||
fetchRecentCommits();
|
||||
}
|
||||
// Clear stale repo-scoped state when project changes.
|
||||
setCurrentBranch('');
|
||||
setBranches([]);
|
||||
setGitStatus(null);
|
||||
setRemoteStatus(null);
|
||||
setSelectedFiles(new Set());
|
||||
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetchGitStatus();
|
||||
fetchBranches();
|
||||
fetchRemoteStatus();
|
||||
}, [selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject || activeView !== 'history') {
|
||||
return;
|
||||
}
|
||||
|
||||
fetchRecentCommits();
|
||||
}, [selectedProject, activeView]);
|
||||
|
||||
// Handle click outside dropdown
|
||||
@@ -88,6 +102,8 @@ function GitPanel({ selectedProject, isMobile, onFileOpen }) {
|
||||
if (data.error) {
|
||||
console.error('Git status error:', data.error);
|
||||
setGitStatus({ error: data.error, details: data.details });
|
||||
setCurrentBranch('');
|
||||
setSelectedFiles(new Set());
|
||||
} else {
|
||||
setGitStatus(data);
|
||||
setCurrentBranch(data.branch || 'main');
|
||||
@@ -117,6 +133,9 @@ function GitPanel({ selectedProject, isMobile, onFileOpen }) {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching git status:', error);
|
||||
setGitStatus({ error: 'Git operation failed', details: String(error) });
|
||||
setCurrentBranch('');
|
||||
setSelectedFiles(new Set());
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -129,9 +148,12 @@ function GitPanel({ selectedProject, isMobile, onFileOpen }) {
|
||||
|
||||
if (!data.error && data.branches) {
|
||||
setBranches(data.branches);
|
||||
} else {
|
||||
setBranches([]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching branches:', error);
|
||||
setBranches([]);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1400,4 +1422,4 @@ function GitPanel({ selectedProject, isMobile, onFileOpen }) {
|
||||
);
|
||||
}
|
||||
|
||||
export default GitPanel;
|
||||
export default GitPanel;
|
||||
|
||||
@@ -1,686 +0,0 @@
|
||||
/*
|
||||
* MainContent.jsx - Main Content Area with Session Protection Props Passthrough
|
||||
*
|
||||
* SESSION PROTECTION PASSTHROUGH:
|
||||
* ===============================
|
||||
*
|
||||
* This component serves as a passthrough layer for Session Protection functions:
|
||||
* - Receives session management functions from App.jsx
|
||||
* - Passes them down to ChatInterface.jsx
|
||||
*
|
||||
* No session protection logic is implemented here - it's purely a props bridge.
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ChatInterface from './ChatInterface';
|
||||
import FileTree from './FileTree';
|
||||
import CodeEditor from './CodeEditor';
|
||||
import StandaloneShell from './StandaloneShell';
|
||||
import GitPanel from './GitPanel';
|
||||
import ErrorBoundary from './ErrorBoundary';
|
||||
import ClaudeLogo from './ClaudeLogo';
|
||||
import CursorLogo from './CursorLogo';
|
||||
import TaskList from './TaskList';
|
||||
import TaskDetail from './TaskDetail';
|
||||
import PRDEditor from './PRDEditor';
|
||||
import Tooltip from './Tooltip';
|
||||
import { useTaskMaster } from '../contexts/TaskMasterContext';
|
||||
import { useTasksSettings } from '../contexts/TasksSettingsContext';
|
||||
import { api } from '../utils/api';
|
||||
|
||||
function MainContent({
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
ws,
|
||||
sendMessage,
|
||||
latestMessage,
|
||||
isMobile,
|
||||
isPWA, // ! Unused
|
||||
onMenuClick,
|
||||
isLoading,
|
||||
onInputFocusChange,
|
||||
// Session Protection Props: Functions passed down from App.jsx to manage active session state
|
||||
// These functions control when project updates are paused during active conversations
|
||||
onSessionActive, // Mark session as active when user sends message
|
||||
onSessionInactive, // Mark session as inactive when conversation completes/aborts
|
||||
onSessionProcessing, // Mark session as processing (thinking/working)
|
||||
onSessionNotProcessing, // Mark session as not processing (finished thinking)
|
||||
processingSessions, // Set of session IDs currently processing
|
||||
onReplaceTemporarySession, // Replace temporary session ID with real session ID from WebSocket
|
||||
onNavigateToSession, // Navigate to a specific session (for Claude CLI session duplication workaround)
|
||||
onShowSettings, // Show tools settings panel
|
||||
autoExpandTools, // Auto-expand tool accordions
|
||||
showRawParameters, // Show raw parameters in tool accordions
|
||||
showThinking, // Show thinking/reasoning sections
|
||||
autoScrollToBottom, // Auto-scroll to bottom when new messages arrive
|
||||
sendByCtrlEnter, // Send by Ctrl+Enter mode for East Asian language input
|
||||
externalMessageUpdate // Trigger for external CLI updates to current session
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [editingFile, setEditingFile] = useState(null);
|
||||
const [selectedTask, setSelectedTask] = useState(null);
|
||||
const [showTaskDetail, setShowTaskDetail] = useState(false);
|
||||
const [editorWidth, setEditorWidth] = useState(600);
|
||||
const [isResizing, setIsResizing] = useState(false);
|
||||
const [editorExpanded, setEditorExpanded] = useState(false);
|
||||
const resizeRef = useRef(null);
|
||||
|
||||
// PRD Editor state
|
||||
const [showPRDEditor, setShowPRDEditor] = useState(false);
|
||||
const [selectedPRD, setSelectedPRD] = useState(null);
|
||||
const [existingPRDs, setExistingPRDs] = useState([]);
|
||||
const [prdNotification, setPRDNotification] = useState(null);
|
||||
|
||||
// TaskMaster context
|
||||
const { tasks, currentProject, refreshTasks, setCurrentProject } = useTaskMaster();
|
||||
const { tasksEnabled, isTaskMasterInstalled, isTaskMasterReady } = useTasksSettings();
|
||||
|
||||
// Only show tasks tab if TaskMaster is installed and enabled
|
||||
const shouldShowTasksTab = tasksEnabled && isTaskMasterInstalled;
|
||||
|
||||
// Sync selectedProject with TaskMaster context
|
||||
useEffect(() => {
|
||||
if (selectedProject && selectedProject !== currentProject) {
|
||||
setCurrentProject(selectedProject);
|
||||
}
|
||||
}, [selectedProject, currentProject, setCurrentProject]);
|
||||
|
||||
// Switch away from tasks tab when tasks are disabled or TaskMaster is not installed
|
||||
useEffect(() => {
|
||||
if (!shouldShowTasksTab && activeTab === 'tasks') {
|
||||
setActiveTab('chat');
|
||||
}
|
||||
}, [shouldShowTasksTab, activeTab, setActiveTab]);
|
||||
|
||||
// Load existing PRDs when current project changes
|
||||
useEffect(() => {
|
||||
const loadExistingPRDs = async () => {
|
||||
if (!currentProject?.name) {
|
||||
setExistingPRDs([]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await api.get(`/taskmaster/prd/${encodeURIComponent(currentProject.name)}`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setExistingPRDs(data.prdFiles || []);
|
||||
} else {
|
||||
setExistingPRDs([]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load existing PRDs:', error);
|
||||
setExistingPRDs([]);
|
||||
}
|
||||
};
|
||||
|
||||
loadExistingPRDs();
|
||||
}, [currentProject?.name]);
|
||||
|
||||
const handleFileOpen = (filePath, diffInfo = null) => {
|
||||
// Create a file object that CodeEditor expects
|
||||
const file = {
|
||||
name: filePath.split('/').pop(),
|
||||
path: filePath,
|
||||
projectName: selectedProject?.name,
|
||||
diffInfo: diffInfo // Pass along diff information if available
|
||||
};
|
||||
setEditingFile(file);
|
||||
};
|
||||
|
||||
const handleCloseEditor = () => {
|
||||
setEditingFile(null);
|
||||
setEditorExpanded(false);
|
||||
};
|
||||
|
||||
const handleToggleEditorExpand = () => {
|
||||
setEditorExpanded(!editorExpanded);
|
||||
};
|
||||
|
||||
const handleTaskClick = (task) => {
|
||||
// If task is just an ID (from dependency click), find the full task object
|
||||
if (typeof task === 'object' && task.id && !task.title) {
|
||||
const fullTask = tasks?.find(t => t.id === task.id);
|
||||
if (fullTask) {
|
||||
setSelectedTask(fullTask);
|
||||
setShowTaskDetail(true);
|
||||
}
|
||||
} else {
|
||||
setSelectedTask(task);
|
||||
setShowTaskDetail(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTaskDetailClose = () => {
|
||||
setShowTaskDetail(false);
|
||||
setSelectedTask(null);
|
||||
};
|
||||
|
||||
const handleTaskStatusChange = (taskId, newStatus) => {
|
||||
// This would integrate with TaskMaster API to update task status
|
||||
console.log('Update task status:', taskId, newStatus);
|
||||
refreshTasks?.();
|
||||
};
|
||||
|
||||
// Handle resize functionality
|
||||
const handleMouseDown = (e) => {
|
||||
if (isMobile) return; // Disable resize on mobile
|
||||
setIsResizing(true);
|
||||
e.preventDefault();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const handleMouseMove = (e) => {
|
||||
if (!isResizing) return;
|
||||
|
||||
const container = resizeRef.current?.parentElement;
|
||||
if (!container) return;
|
||||
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const newWidth = containerRect.right - e.clientX;
|
||||
|
||||
// Min width: 300px, Max width: 80% of container
|
||||
const minWidth = 300;
|
||||
const maxWidth = containerRect.width * 0.8;
|
||||
|
||||
if (newWidth >= minWidth && newWidth <= maxWidth) {
|
||||
setEditorWidth(newWidth);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseUp = () => {
|
||||
setIsResizing(false);
|
||||
};
|
||||
|
||||
if (isResizing) {
|
||||
document.addEventListener('mousemove', handleMouseMove);
|
||||
document.addEventListener('mouseup', handleMouseUp);
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousemove', handleMouseMove);
|
||||
document.removeEventListener('mouseup', handleMouseUp);
|
||||
document.body.style.cursor = '';
|
||||
document.body.style.userSelect = '';
|
||||
};
|
||||
}, [isResizing]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
{/* Header with menu button for mobile */}
|
||||
{isMobile && (
|
||||
<div
|
||||
className="bg-background border-b border-border p-2 sm:p-3 pwa-header-safe flex-shrink-0"
|
||||
>
|
||||
<button
|
||||
onClick={onMenuClick}
|
||||
className="p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 pwa-menu-button"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center text-gray-500 dark:text-gray-400">
|
||||
<div className="w-12 h-12 mx-auto mb-4">
|
||||
<div
|
||||
className="w-full h-full rounded-full border-4 border-gray-200 border-t-blue-500"
|
||||
style={{
|
||||
animation: 'spin 1s linear infinite',
|
||||
WebkitAnimation: 'spin 1s linear infinite',
|
||||
MozAnimation: 'spin 1s linear infinite'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<h2 className="text-xl font-semibold mb-2">{t('mainContent.loading')}</h2>
|
||||
<p>{t('mainContent.settingUpWorkspace')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!selectedProject) {
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
{/* Header with menu button for mobile */}
|
||||
{isMobile && (
|
||||
<div
|
||||
className="bg-background border-b border-border p-2 sm:p-3 pwa-header-safe flex-shrink-0"
|
||||
>
|
||||
<button
|
||||
onClick={onMenuClick}
|
||||
className="p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 pwa-menu-button"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center text-gray-500 dark:text-gray-400 max-w-md mx-auto px-6">
|
||||
<div className="w-16 h-16 mx-auto mb-6 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center">
|
||||
<svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-5l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold mb-3 text-gray-900 dark:text-white">{t('mainContent.chooseProject')}</h2>
|
||||
<p className="text-gray-600 dark:text-gray-300 mb-6 leading-relaxed">
|
||||
{t('mainContent.selectProjectDescription')}
|
||||
</p>
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4 border border-blue-200 dark:border-blue-800">
|
||||
<p className="text-sm text-blue-700 dark:text-blue-300">
|
||||
💡 <strong>{t('mainContent.tip')}:</strong> {isMobile ? t('mainContent.createProjectMobile') : t('mainContent.createProjectDesktop')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
{/* Header with tabs */}
|
||||
<div
|
||||
className="bg-background border-b border-border p-2 sm:p-3 pwa-header-safe flex-shrink-0"
|
||||
>
|
||||
<div className="flex items-center justify-between relative">
|
||||
<div className="flex items-center space-x-2 min-w-0 flex-1">
|
||||
{isMobile && (
|
||||
<button
|
||||
onClick={onMenuClick}
|
||||
onTouchStart={(e) => {
|
||||
e.preventDefault();
|
||||
onMenuClick();
|
||||
}}
|
||||
className="p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 touch-manipulation active:scale-95 pwa-menu-button flex-shrink-0"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
<div className="min-w-0 flex items-center gap-2 flex-1 overflow-x-auto scrollbar-hide">
|
||||
{activeTab === 'chat' && selectedSession && (
|
||||
<div className="w-5 h-5 flex-shrink-0 flex items-center justify-center">
|
||||
{selectedSession.__provider === 'cursor' ? (
|
||||
<CursorLogo className="w-4 h-4" />
|
||||
) : (
|
||||
<ClaudeLogo className="w-4 h-4" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
{activeTab === 'chat' && selectedSession ? (
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-sm sm:text-base font-semibold text-gray-900 dark:text-white whitespace-nowrap overflow-x-auto scrollbar-hide">
|
||||
{selectedSession.__provider === 'cursor' ? (selectedSession.name || 'Untitled Session') : (selectedSession.summary || 'New Session')}
|
||||
</h2>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 truncate">
|
||||
{selectedProject.displayName}
|
||||
</div>
|
||||
</div>
|
||||
) : activeTab === 'chat' && !selectedSession ? (
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-sm sm:text-base font-semibold text-gray-900 dark:text-white">
|
||||
{t('mainContent.newSession')}
|
||||
</h2>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 truncate">
|
||||
{selectedProject.displayName}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-sm sm:text-base font-semibold text-gray-900 dark:text-white">
|
||||
{activeTab === 'files' ? t('mainContent.projectFiles') :
|
||||
activeTab === 'git' ? t('tabs.git') :
|
||||
(activeTab === 'tasks' && shouldShowTasksTab) ? 'TaskMaster' :
|
||||
'Project'}
|
||||
</h2>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 truncate">
|
||||
{selectedProject.displayName}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Modern Tab Navigation - Right Side */}
|
||||
<div className="flex-shrink-0 hidden sm:block">
|
||||
<div className="relative flex bg-gray-100 dark:bg-gray-800 rounded-lg p-1">
|
||||
<Tooltip content={t('tabs.chat')} position="bottom">
|
||||
<button
|
||||
onClick={() => setActiveTab('chat')}
|
||||
className={`relative px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md ${
|
||||
activeTab === 'chat'
|
||||
? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-200 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
<span className="flex items-center gap-1 sm:gap-1.5">
|
||||
<svg className="w-3 sm:w-3.5 h-3 sm:h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
|
||||
</svg>
|
||||
<span className="hidden md:hidden lg:inline">{t('tabs.chat')}</span>
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip content={t('tabs.shell')} position="bottom">
|
||||
<button
|
||||
onClick={() => setActiveTab('shell')}
|
||||
className={`relative px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition-all duration-200 ${
|
||||
activeTab === 'shell'
|
||||
? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-200 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
<span className="flex items-center gap-1 sm:gap-1.5">
|
||||
<svg className="w-3 sm:w-3.5 h-3 sm:h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<span className="hidden md:hidden lg:inline">{t('tabs.shell')}</span>
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip content={t('tabs.files')} position="bottom">
|
||||
<button
|
||||
onClick={() => setActiveTab('files')}
|
||||
className={`relative px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition-all duration-200 ${
|
||||
activeTab === 'files'
|
||||
? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-200 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
<span className="flex items-center gap-1 sm:gap-1.5">
|
||||
<svg className="w-3 sm:w-3.5 h-3 sm:h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-5l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
<span className="hidden md:hidden lg:inline">{t('tabs.files')}</span>
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip content={t('tabs.git')} position="bottom">
|
||||
<button
|
||||
onClick={() => setActiveTab('git')}
|
||||
className={`relative px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition-all duration-200 ${
|
||||
activeTab === 'git'
|
||||
? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-200 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
<span className="flex items-center gap-1 sm:gap-1.5">
|
||||
<svg className="w-3 sm:w-3.5 h-3 sm:h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
|
||||
</svg>
|
||||
<span className="hidden md:hidden lg:inline">{t('tabs.git')}</span>
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
{shouldShowTasksTab && (
|
||||
<Tooltip content={t('tabs.tasks')} position="bottom">
|
||||
<button
|
||||
onClick={() => setActiveTab('tasks')}
|
||||
className={`relative px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition-all duration-200 ${
|
||||
activeTab === 'tasks'
|
||||
? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-200 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
<span className="flex items-center gap-1 sm:gap-1.5">
|
||||
<svg className="w-3 sm:w-3.5 h-3 sm:h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
|
||||
</svg>
|
||||
<span className="hidden md:hidden lg:inline">{t('tabs.tasks')}</span>
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{/* <button
|
||||
onClick={() => setActiveTab('preview')}
|
||||
className={`relative px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition-all duration-200 ${
|
||||
activeTab === 'preview'
|
||||
? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-200 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
<span className="flex items-center gap-1 sm:gap-1.5">
|
||||
<svg className="w-3 sm:w-3.5 h-3 sm:h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
|
||||
</svg>
|
||||
<span className="hidden sm:inline">Preview</span>
|
||||
</span>
|
||||
</button> */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content Area with Right Sidebar */}
|
||||
<div className="flex-1 flex min-h-0 overflow-hidden">
|
||||
{/* Main Content */}
|
||||
<div className={`flex-1 flex flex-col min-h-0 overflow-hidden ${editingFile ? 'mr-0' : ''} ${editorExpanded ? 'hidden' : ''}`}>
|
||||
<div className={`h-full ${activeTab === 'chat' ? 'block' : 'hidden'}`}>
|
||||
<ErrorBoundary showDetails={true}>
|
||||
<ChatInterface
|
||||
selectedProject={selectedProject}
|
||||
selectedSession={selectedSession}
|
||||
ws={ws}
|
||||
sendMessage={sendMessage}
|
||||
latestMessage={latestMessage}
|
||||
onFileOpen={handleFileOpen}
|
||||
onInputFocusChange={onInputFocusChange}
|
||||
onSessionActive={onSessionActive}
|
||||
onSessionInactive={onSessionInactive}
|
||||
onSessionProcessing={onSessionProcessing}
|
||||
onSessionNotProcessing={onSessionNotProcessing}
|
||||
processingSessions={processingSessions}
|
||||
onReplaceTemporarySession={onReplaceTemporarySession}
|
||||
onNavigateToSession={onNavigateToSession}
|
||||
onShowSettings={onShowSettings}
|
||||
autoExpandTools={autoExpandTools}
|
||||
showRawParameters={showRawParameters}
|
||||
showThinking={showThinking}
|
||||
autoScrollToBottom={autoScrollToBottom}
|
||||
sendByCtrlEnter={sendByCtrlEnter}
|
||||
externalMessageUpdate={externalMessageUpdate}
|
||||
onShowAllTasks={tasksEnabled ? () => setActiveTab('tasks') : null}
|
||||
/>
|
||||
</ErrorBoundary>
|
||||
</div>
|
||||
{activeTab === 'files' && (
|
||||
<div className="h-full overflow-hidden">
|
||||
<FileTree selectedProject={selectedProject} />
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'shell' && (
|
||||
<div className="h-full w-full overflow-hidden">
|
||||
<StandaloneShell
|
||||
project={selectedProject}
|
||||
session={selectedSession}
|
||||
showHeader={false}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'git' && (
|
||||
<div className="h-full overflow-hidden">
|
||||
<GitPanel selectedProject={selectedProject} isMobile={isMobile} onFileOpen={handleFileOpen} />
|
||||
</div>
|
||||
)}
|
||||
{shouldShowTasksTab && (
|
||||
<div className={`h-full ${activeTab === 'tasks' ? 'block' : 'hidden'}`}>
|
||||
<div className="h-full flex flex-col overflow-hidden">
|
||||
<TaskList
|
||||
tasks={tasks || []}
|
||||
onTaskClick={handleTaskClick}
|
||||
showParentTasks={true}
|
||||
className="flex-1 overflow-y-auto p-4"
|
||||
currentProject={currentProject}
|
||||
onTaskCreated={refreshTasks}
|
||||
onShowPRDEditor={(prd = null) => {
|
||||
setSelectedPRD(prd);
|
||||
setShowPRDEditor(true);
|
||||
}}
|
||||
existingPRDs={existingPRDs}
|
||||
onRefreshPRDs={(showNotification = false) => {
|
||||
// Reload existing PRDs
|
||||
if (currentProject?.name) {
|
||||
api.get(`/taskmaster/prd/${encodeURIComponent(currentProject.name)}`)
|
||||
.then(response => response.ok ? response.json() : Promise.reject())
|
||||
.then(data => {
|
||||
setExistingPRDs(data.prdFiles || []);
|
||||
if (showNotification) {
|
||||
setPRDNotification('PRD saved successfully!');
|
||||
setTimeout(() => setPRDNotification(null), 3000);
|
||||
}
|
||||
})
|
||||
.catch(error => console.error('Failed to refresh PRDs:', error));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className={`h-full overflow-hidden ${activeTab === 'preview' ? 'block' : 'hidden'}`}>
|
||||
{/* <LivePreviewPanel
|
||||
selectedProject={selectedProject}
|
||||
serverStatus={serverStatus}
|
||||
serverUrl={serverUrl}
|
||||
availableScripts={availableScripts}
|
||||
onStartServer={(script) => {
|
||||
sendMessage({
|
||||
type: 'server:start',
|
||||
projectPath: selectedProject?.fullPath,
|
||||
script: script
|
||||
});
|
||||
}}
|
||||
onStopServer={() => {
|
||||
sendMessage({
|
||||
type: 'server:stop',
|
||||
projectPath: selectedProject?.fullPath
|
||||
});
|
||||
}}
|
||||
onScriptSelect={setCurrentScript}
|
||||
currentScript={currentScript}
|
||||
isMobile={isMobile}
|
||||
serverLogs={serverLogs}
|
||||
onClearLogs={() => setServerLogs([])}
|
||||
/> */}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Code Editor Right Sidebar - Desktop only, Mobile uses modal */}
|
||||
{editingFile && !isMobile && (
|
||||
<>
|
||||
{/* Resize Handle - Hidden when expanded */}
|
||||
{!editorExpanded && (
|
||||
<div
|
||||
ref={resizeRef}
|
||||
onMouseDown={handleMouseDown}
|
||||
className="flex-shrink-0 w-1 bg-gray-200 dark:bg-gray-700 hover:bg-blue-500 dark:hover:bg-blue-600 cursor-col-resize transition-colors relative group"
|
||||
title="Drag to resize"
|
||||
>
|
||||
{/* Visual indicator on hover */}
|
||||
<div className="absolute inset-y-0 left-1/2 -translate-x-1/2 w-1 bg-blue-500 dark:bg-blue-600 opacity-0 group-hover:opacity-100 transition-opacity" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Editor Sidebar */}
|
||||
<div
|
||||
className={`flex-shrink-0 border-l border-gray-200 dark:border-gray-700 h-full overflow-hidden ${editorExpanded ? 'flex-1' : ''}`}
|
||||
style={editorExpanded ? {} : { width: `${editorWidth}px` }}
|
||||
>
|
||||
<CodeEditor
|
||||
file={editingFile}
|
||||
onClose={handleCloseEditor}
|
||||
projectPath={selectedProject?.path}
|
||||
isSidebar={true}
|
||||
isExpanded={editorExpanded}
|
||||
onToggleExpand={handleToggleEditorExpand}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Code Editor Modal for Mobile */}
|
||||
{editingFile && isMobile && (
|
||||
<CodeEditor
|
||||
file={editingFile}
|
||||
onClose={handleCloseEditor}
|
||||
projectPath={selectedProject?.path}
|
||||
isSidebar={false}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Task Detail Modal */}
|
||||
{shouldShowTasksTab && showTaskDetail && selectedTask && (
|
||||
<TaskDetail
|
||||
task={selectedTask}
|
||||
isOpen={showTaskDetail}
|
||||
onClose={handleTaskDetailClose}
|
||||
onStatusChange={handleTaskStatusChange}
|
||||
onTaskClick={handleTaskClick}
|
||||
/>
|
||||
)}
|
||||
{/* PRD Editor Modal */}
|
||||
{showPRDEditor && (
|
||||
<PRDEditor
|
||||
project={currentProject}
|
||||
projectPath={currentProject?.fullPath || currentProject?.path}
|
||||
onClose={() => {
|
||||
setShowPRDEditor(false);
|
||||
setSelectedPRD(null);
|
||||
}}
|
||||
isNewFile={!selectedPRD?.isExisting}
|
||||
file={{
|
||||
name: selectedPRD?.name || 'prd.txt',
|
||||
content: selectedPRD?.content || ''
|
||||
}}
|
||||
onSave={async () => {
|
||||
setShowPRDEditor(false);
|
||||
setSelectedPRD(null);
|
||||
|
||||
// Reload existing PRDs with notification
|
||||
try {
|
||||
const response = await api.get(`/taskmaster/prd/${encodeURIComponent(currentProject.name)}`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setExistingPRDs(data.prdFiles || []);
|
||||
setPRDNotification('PRD saved successfully!');
|
||||
setTimeout(() => setPRDNotification(null), 3000);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh PRDs:', error);
|
||||
}
|
||||
|
||||
refreshTasks?.();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{/* PRD Notification */}
|
||||
{prdNotification && (
|
||||
<div className="fixed bottom-4 right-4 z-50 animate-in slide-in-from-bottom-2 duration-300">
|
||||
<div className="bg-green-600 text-white px-4 py-3 rounded-lg shadow-lg flex items-center gap-3">
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
<span className="font-medium">{prdNotification}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default React.memo(MainContent);
|
||||
@@ -17,31 +17,27 @@ import {
|
||||
} from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import DarkModeToggle from './DarkModeToggle';
|
||||
|
||||
import { useUiPreferences } from '../hooks/useUiPreferences';
|
||||
import { useTheme } from '../contexts/ThemeContext';
|
||||
import LanguageSelector from './LanguageSelector';
|
||||
|
||||
const QuickSettingsPanel = ({
|
||||
isOpen,
|
||||
onToggle,
|
||||
autoExpandTools,
|
||||
onAutoExpandChange,
|
||||
showRawParameters,
|
||||
onShowRawParametersChange,
|
||||
showThinking,
|
||||
onShowThinkingChange,
|
||||
autoScrollToBottom,
|
||||
onAutoScrollChange,
|
||||
sendByCtrlEnter,
|
||||
onSendByCtrlEnterChange,
|
||||
isMobile
|
||||
}) => {
|
||||
import { useDeviceSettings } from '../hooks/useDeviceSettings';
|
||||
|
||||
|
||||
const QuickSettingsPanel = () => {
|
||||
const { t } = useTranslation('settings');
|
||||
const [localIsOpen, setLocalIsOpen] = useState(isOpen);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [whisperMode, setWhisperMode] = useState(() => {
|
||||
return localStorage.getItem('whisperMode') || 'default';
|
||||
});
|
||||
const { isDarkMode } = useTheme();
|
||||
|
||||
const { isMobile } = useDeviceSettings({ trackPWA: false });
|
||||
|
||||
const { preferences, setPreference } = useUiPreferences();
|
||||
const { autoExpandTools, showRawParameters, showThinking, autoScrollToBottom, sendByCtrlEnter } = preferences;
|
||||
|
||||
// Draggable handle state
|
||||
const [handlePosition, setHandlePosition] = useState(() => {
|
||||
const saved = localStorage.getItem('quickSettingsHandlePosition');
|
||||
@@ -66,10 +62,6 @@ const QuickSettingsPanel = ({
|
||||
const constraintsRef = useRef({ min: 10, max: 90 }); // Percentage constraints
|
||||
const dragThreshold = 5; // Pixels to move before it's considered a drag
|
||||
|
||||
useEffect(() => {
|
||||
setLocalIsOpen(isOpen);
|
||||
}, [isOpen]);
|
||||
|
||||
// Save handle position to localStorage when it changes
|
||||
useEffect(() => {
|
||||
localStorage.setItem('quickSettingsHandlePosition', JSON.stringify({ y: handlePosition }));
|
||||
@@ -206,9 +198,7 @@ const QuickSettingsPanel = ({
|
||||
return;
|
||||
}
|
||||
|
||||
const newState = !localIsOpen;
|
||||
setLocalIsOpen(newState);
|
||||
onToggle(newState);
|
||||
setIsOpen((previous) => !previous);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -226,19 +216,19 @@ const QuickSettingsPanel = ({
|
||||
handleDragStart(e);
|
||||
}}
|
||||
className={`fixed ${
|
||||
localIsOpen ? 'right-64' : 'right-0'
|
||||
isOpen ? 'right-64' : 'right-0'
|
||||
} z-50 ${isDragging ? '' : 'transition-all duration-150 ease-out'} bg-white dark:bg-gray-800 border ${
|
||||
isDragging ? 'border-blue-500 dark:border-blue-400' : 'border-gray-200 dark:border-gray-700'
|
||||
} rounded-l-md p-2 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors shadow-lg ${
|
||||
isDragging ? 'cursor-grabbing' : 'cursor-pointer'
|
||||
} touch-none`}
|
||||
style={{ ...getPositionStyle(), touchAction: 'none', WebkitTouchCallout: 'none', WebkitUserSelect: 'none' }}
|
||||
aria-label={isDragging ? t('quickSettings.dragHandle.dragging') : localIsOpen ? t('quickSettings.dragHandle.closePanel') : t('quickSettings.dragHandle.openPanel')}
|
||||
aria-label={isDragging ? t('quickSettings.dragHandle.dragging') : isOpen ? t('quickSettings.dragHandle.closePanel') : t('quickSettings.dragHandle.openPanel')}
|
||||
title={isDragging ? t('quickSettings.dragHandle.draggingStatus') : t('quickSettings.dragHandle.toggleAndMove')}
|
||||
>
|
||||
{isDragging ? (
|
||||
<GripVertical className="h-5 w-5 text-blue-500 dark:text-blue-400" />
|
||||
) : localIsOpen ? (
|
||||
) : isOpen ? (
|
||||
<ChevronRight className="h-5 w-5 text-gray-600 dark:text-gray-400" />
|
||||
) : (
|
||||
<ChevronLeft className="h-5 w-5 text-gray-600 dark:text-gray-400" />
|
||||
@@ -248,7 +238,7 @@ const QuickSettingsPanel = ({
|
||||
{/* Panel */}
|
||||
<div
|
||||
className={`fixed top-0 right-0 h-full w-64 bg-background border-l border-border shadow-xl transform transition-transform duration-150 ease-out z-40 ${
|
||||
localIsOpen ? 'translate-x-0' : 'translate-x-full'
|
||||
isOpen ? 'translate-x-0' : 'translate-x-full'
|
||||
} ${isMobile ? 'h-screen' : ''}`}
|
||||
>
|
||||
<div className="h-full flex flex-col">
|
||||
@@ -292,7 +282,7 @@ const QuickSettingsPanel = ({
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={autoExpandTools}
|
||||
onChange={(e) => onAutoExpandChange(e.target.checked)}
|
||||
onChange={(e) => setPreference('autoExpandTools', e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 dark:border-gray-600 text-blue-600 dark:text-blue-500 focus:ring-blue-500 focus:ring-2 dark:focus:ring-blue-400 bg-gray-100 dark:bg-gray-800 checked:bg-blue-600 dark:checked:bg-blue-600"
|
||||
/>
|
||||
</label>
|
||||
@@ -305,7 +295,7 @@ const QuickSettingsPanel = ({
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showRawParameters}
|
||||
onChange={(e) => onShowRawParametersChange(e.target.checked)}
|
||||
onChange={(e) => setPreference('showRawParameters', e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 dark:border-gray-600 text-blue-600 dark:text-blue-500 focus:ring-blue-500 focus:ring-2 dark:focus:ring-blue-400 bg-gray-100 dark:bg-gray-800 checked:bg-blue-600 dark:checked:bg-blue-600"
|
||||
/>
|
||||
</label>
|
||||
@@ -318,7 +308,7 @@ const QuickSettingsPanel = ({
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showThinking}
|
||||
onChange={(e) => onShowThinkingChange(e.target.checked)}
|
||||
onChange={(e) => setPreference('showThinking', e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 dark:border-gray-600 text-blue-600 dark:text-blue-500 focus:ring-blue-500 focus:ring-2 dark:focus:ring-blue-400 bg-gray-100 dark:bg-gray-800 checked:bg-blue-600 dark:checked:bg-blue-600"
|
||||
/>
|
||||
</label>
|
||||
@@ -335,7 +325,7 @@ const QuickSettingsPanel = ({
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={autoScrollToBottom}
|
||||
onChange={(e) => onAutoScrollChange(e.target.checked)}
|
||||
onChange={(e) => setPreference('autoScrollToBottom', e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 dark:border-gray-600 text-blue-600 dark:text-blue-500 focus:ring-blue-500 focus:ring-2 dark:focus:ring-blue-400 bg-gray-100 dark:bg-gray-800 checked:bg-blue-600 dark:checked:bg-blue-600"
|
||||
/>
|
||||
</label>
|
||||
@@ -353,7 +343,7 @@ const QuickSettingsPanel = ({
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={sendByCtrlEnter}
|
||||
onChange={(e) => onSendByCtrlEnterChange(e.target.checked)}
|
||||
onChange={(e) => setPreference('sendByCtrlEnter', e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 dark:border-gray-600 text-blue-600 dark:text-blue-500 focus:ring-blue-500 focus:ring-2 dark:focus:ring-blue-400 bg-gray-100 dark:bg-gray-800 checked:bg-blue-600 dark:checked:bg-blue-600"
|
||||
/>
|
||||
</label>
|
||||
@@ -445,7 +435,7 @@ const QuickSettingsPanel = ({
|
||||
</div>
|
||||
|
||||
{/* Backdrop */}
|
||||
{localIsOpen && (
|
||||
{isOpen && (
|
||||
<div
|
||||
className="fixed inset-0 bg-background/80 backdrop-blur-sm z-30 transition-opacity duration-150 ease-out"
|
||||
onClick={handleToggle}
|
||||
|
||||
24
src/components/SessionProviderLogo.tsx
Normal file
24
src/components/SessionProviderLogo.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { SessionProvider } from '../types/app';
|
||||
import ClaudeLogo from './ClaudeLogo';
|
||||
import CodexLogo from './CodexLogo';
|
||||
import CursorLogo from './CursorLogo';
|
||||
|
||||
type SessionProviderLogoProps = {
|
||||
provider?: SessionProvider | string | null;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export default function SessionProviderLogo({
|
||||
provider = 'claude',
|
||||
className = 'w-5 h-5',
|
||||
}: SessionProviderLogoProps) {
|
||||
if (provider === 'cursor') {
|
||||
return <CursorLogo className={className} />;
|
||||
}
|
||||
|
||||
if (provider === 'codex') {
|
||||
return <CodexLogo className={className} />;
|
||||
}
|
||||
|
||||
return <ClaudeLogo className={className} />;
|
||||
}
|
||||
@@ -5,9 +5,6 @@ import { Badge } from './ui/badge';
|
||||
import { X, Plus, Settings as SettingsIcon, Shield, AlertTriangle, Moon, Sun, Server, Edit3, Trash2, Globe, Terminal, Zap, FolderOpen, LogIn, Key, GitBranch, Check } from 'lucide-react';
|
||||
import { useTheme } from '../contexts/ThemeContext';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ClaudeLogo from './ClaudeLogo';
|
||||
import CursorLogo from './CursorLogo';
|
||||
import CodexLogo from './CodexLogo';
|
||||
import CredentialsSettings from './CredentialsSettings';
|
||||
import GitSettings from './GitSettings';
|
||||
import TasksSettings from './TasksSettings';
|
||||
|
||||
@@ -51,6 +51,12 @@ function fallbackCopyToClipboard(text) {
|
||||
return copied;
|
||||
}
|
||||
|
||||
const CODEX_DEVICE_AUTH_URL = 'https://auth.openai.com/codex/device';
|
||||
|
||||
function isCodexLoginCommand(command) {
|
||||
return typeof command === 'string' && /\bcodex\s+login\b/i.test(command);
|
||||
}
|
||||
|
||||
function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell = false, onProcessComplete, minimal = false, autoConnect = false }) {
|
||||
const { t } = useTranslation('chat');
|
||||
const terminalRef = useRef(null);
|
||||
@@ -64,6 +70,7 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const [authUrl, setAuthUrl] = useState('');
|
||||
const [authUrlCopyStatus, setAuthUrlCopyStatus] = useState('idle');
|
||||
const [isAuthPanelHidden, setIsAuthPanelHidden] = useState(false);
|
||||
|
||||
const selectedProjectRef = useRef(selectedProject);
|
||||
const selectedSessionRef = useRef(selectedSession);
|
||||
@@ -144,6 +151,7 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
|
||||
authUrlRef.current = '';
|
||||
setAuthUrl('');
|
||||
setAuthUrlCopyStatus('idle');
|
||||
setIsAuthPanelHidden(false);
|
||||
|
||||
setTimeout(() => {
|
||||
if (fitAddon.current && terminal.current) {
|
||||
@@ -190,11 +198,13 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
|
||||
authUrlRef.current = data.url;
|
||||
setAuthUrl(data.url);
|
||||
setAuthUrlCopyStatus('idle');
|
||||
setIsAuthPanelHidden(false);
|
||||
} else if (data.type === 'url_open') {
|
||||
if (data.url) {
|
||||
authUrlRef.current = data.url;
|
||||
setAuthUrl(data.url);
|
||||
setAuthUrlCopyStatus('idle');
|
||||
setIsAuthPanelHidden(false);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -206,6 +216,7 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
|
||||
setIsConnected(false);
|
||||
setIsConnecting(false);
|
||||
setAuthUrlCopyStatus('idle');
|
||||
setIsAuthPanelHidden(false);
|
||||
|
||||
if (terminal.current) {
|
||||
terminal.current.clear();
|
||||
@@ -245,6 +256,7 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
|
||||
authUrlRef.current = '';
|
||||
setAuthUrl('');
|
||||
setAuthUrlCopyStatus('idle');
|
||||
setIsAuthPanelHidden(false);
|
||||
}, []);
|
||||
|
||||
const sessionDisplayName = useMemo(() => {
|
||||
@@ -283,6 +295,7 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
|
||||
authUrlRef.current = '';
|
||||
setAuthUrl('');
|
||||
setAuthUrlCopyStatus('idle');
|
||||
setIsAuthPanelHidden(false);
|
||||
|
||||
setTimeout(() => {
|
||||
setIsRestarting(false);
|
||||
@@ -369,17 +382,21 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
|
||||
terminal.current.open(terminalRef.current);
|
||||
|
||||
terminal.current.attachCustomKeyEventHandler((event) => {
|
||||
const activeAuthUrl = isCodexLoginCommand(initialCommandRef.current)
|
||||
? CODEX_DEVICE_AUTH_URL
|
||||
: authUrlRef.current;
|
||||
|
||||
if (
|
||||
event.type === 'keydown' &&
|
||||
minimal &&
|
||||
isPlainShellRef.current &&
|
||||
authUrlRef.current &&
|
||||
activeAuthUrl &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.altKey &&
|
||||
event.key?.toLowerCase() === 'c'
|
||||
) {
|
||||
copyAuthUrlToClipboard(authUrlRef.current).catch(() => {});
|
||||
copyAuthUrlToClipboard(activeAuthUrl).catch(() => {});
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -497,18 +514,32 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
|
||||
}
|
||||
|
||||
if (minimal) {
|
||||
const hasAuthUrl = Boolean(authUrl);
|
||||
const displayAuthUrl = isCodexLoginCommand(initialCommand)
|
||||
? CODEX_DEVICE_AUTH_URL
|
||||
: authUrl;
|
||||
const hasAuthUrl = Boolean(displayAuthUrl);
|
||||
const showMobileAuthPanel = hasAuthUrl && !isAuthPanelHidden;
|
||||
const showMobileAuthPanelToggle = hasAuthUrl && isAuthPanelHidden;
|
||||
|
||||
return (
|
||||
<div className="h-full w-full bg-gray-900 relative">
|
||||
<div ref={terminalRef} className="h-full w-full focus:outline-none" style={{ outline: 'none' }} />
|
||||
{hasAuthUrl && (
|
||||
<div className="absolute inset-x-0 bottom-14 z-20 border-t border-gray-700/80 bg-gray-900/95 p-3 backdrop-blur-sm">
|
||||
{showMobileAuthPanel && (
|
||||
<div className="absolute inset-x-0 bottom-14 z-20 border-t border-gray-700/80 bg-gray-900/95 p-3 backdrop-blur-sm md:hidden">
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-xs text-gray-300">Open or copy the login URL:</p>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="text-xs text-gray-300">Open or copy the login URL:</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsAuthPanelHidden(true)}
|
||||
className="rounded bg-gray-700 px-2 py-1 text-[10px] font-medium uppercase tracking-wide text-gray-100 hover:bg-gray-600"
|
||||
>
|
||||
Hide
|
||||
</button>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
value={authUrl}
|
||||
value={displayAuthUrl}
|
||||
readOnly
|
||||
onClick={(event) => event.currentTarget.select()}
|
||||
className="w-full rounded border border-gray-600 bg-gray-800 px-2 py-1 text-xs text-gray-100 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
@@ -518,7 +549,7 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
openAuthUrlInBrowser(authUrl);
|
||||
openAuthUrlInBrowser(displayAuthUrl);
|
||||
}}
|
||||
className="flex-1 rounded bg-blue-600 px-3 py-2 text-xs font-medium text-white hover:bg-blue-700"
|
||||
>
|
||||
@@ -527,7 +558,7 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
const copied = await copyAuthUrlToClipboard(authUrl);
|
||||
const copied = await copyAuthUrlToClipboard(displayAuthUrl);
|
||||
setAuthUrlCopyStatus(copied ? 'copied' : 'failed');
|
||||
}}
|
||||
className="flex-1 rounded bg-gray-700 px-3 py-2 text-xs font-medium text-white hover:bg-gray-600"
|
||||
@@ -538,6 +569,17 @@ function Shell({ selectedProject, selectedSession, initialCommand, isPlainShell
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{showMobileAuthPanelToggle && (
|
||||
<div className="absolute bottom-14 right-3 z-20 md:hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsAuthPanelHidden(false)}
|
||||
className="rounded bg-gray-800/95 px-3 py-2 text-xs font-medium text-gray-100 shadow-lg backdrop-blur-sm hover:bg-gray-700"
|
||||
>
|
||||
Show login URL
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -10,12 +10,12 @@ const TodoList = ({ todos, isResult = false }) => {
|
||||
const getStatusIcon = (status) => {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return <CheckCircle2 className="w-4 h-4 text-green-500 dark:text-green-400" />;
|
||||
return <CheckCircle2 className="w-3.5 h-3.5 text-green-500 dark:text-green-400" />;
|
||||
case 'in_progress':
|
||||
return <Clock className="w-4 h-4 text-blue-500 dark:text-blue-400" />;
|
||||
return <Clock className="w-3.5 h-3.5 text-blue-500 dark:text-blue-400" />;
|
||||
case 'pending':
|
||||
default:
|
||||
return <Circle className="w-4 h-4 text-gray-400 dark:text-gray-500" />;
|
||||
return <Circle className="w-3.5 h-3.5 text-gray-400 dark:text-gray-500" />;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -44,38 +44,38 @@ const TodoList = ({ todos, isResult = false }) => {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1.5">
|
||||
{isResult && (
|
||||
<div className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
|
||||
<div className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5">
|
||||
Todo List ({todos.length} {todos.length === 1 ? 'item' : 'items'})
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
{todos.map((todo, index) => (
|
||||
<div
|
||||
key={todo.id || `todo-${index}`}
|
||||
className="flex items-start gap-3 p-3 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-sm hover:shadow-md dark:shadow-gray-900/50 transition-shadow"
|
||||
className="flex items-start gap-2 p-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded transition-colors"
|
||||
>
|
||||
<div className="flex-shrink-0 mt-0.5">
|
||||
{getStatusIcon(todo.status)}
|
||||
</div>
|
||||
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-start justify-between gap-2 mb-2">
|
||||
<p className={`text-sm font-medium ${todo.status === 'completed' ? 'line-through text-gray-500 dark:text-gray-400' : 'text-gray-900 dark:text-gray-100'}`}>
|
||||
<div className="flex items-start justify-between gap-2 mb-0.5">
|
||||
<p className={`text-xs font-medium ${todo.status === 'completed' ? 'line-through text-gray-500 dark:text-gray-400' : 'text-gray-900 dark:text-gray-100'}`}>
|
||||
{todo.content}
|
||||
</p>
|
||||
|
||||
|
||||
<div className="flex gap-1 flex-shrink-0">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`text-xs px-2 py-0.5 ${getPriorityColor(todo.priority)}`}
|
||||
className={`text-[10px] px-1.5 py-px ${getPriorityColor(todo.priority)}`}
|
||||
>
|
||||
{todo.priority}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`text-xs px-2 py-0.5 ${getStatusColor(todo.status)}`}
|
||||
className={`text-[10px] px-1.5 py-px ${getStatusColor(todo.status)}`}
|
||||
>
|
||||
{todo.status.replace('_', ' ')}
|
||||
</Badge>
|
||||
@@ -88,4 +88,4 @@ const TodoList = ({ todos, isResult = false }) => {
|
||||
);
|
||||
};
|
||||
|
||||
export default TodoList;
|
||||
export default TodoList;
|
||||
|
||||
144
src/components/app/AppContent.tsx
Normal file
144
src/components/app/AppContent.tsx
Normal file
@@ -0,0 +1,144 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import Sidebar from '../sidebar/view/Sidebar';
|
||||
import MainContent from '../main-content/view/MainContent';
|
||||
import MobileNav from '../MobileNav';
|
||||
|
||||
import { useWebSocket } from '../../contexts/WebSocketContext';
|
||||
import { useDeviceSettings } from '../../hooks/useDeviceSettings';
|
||||
import { useSessionProtection } from '../../hooks/useSessionProtection';
|
||||
import { useProjectsState } from '../../hooks/useProjectsState';
|
||||
|
||||
export default function AppContent() {
|
||||
const navigate = useNavigate();
|
||||
const { sessionId } = useParams<{ sessionId?: string }>();
|
||||
const { t } = useTranslation('common');
|
||||
const { isMobile } = useDeviceSettings({ trackPWA: false });
|
||||
const { ws, sendMessage, latestMessage } = useWebSocket();
|
||||
|
||||
const {
|
||||
activeSessions,
|
||||
processingSessions,
|
||||
markSessionAsActive,
|
||||
markSessionAsInactive,
|
||||
markSessionAsProcessing,
|
||||
markSessionAsNotProcessing,
|
||||
replaceTemporarySession,
|
||||
} = useSessionProtection();
|
||||
|
||||
const {
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
activeTab,
|
||||
sidebarOpen,
|
||||
isLoadingProjects,
|
||||
isInputFocused,
|
||||
externalMessageUpdate,
|
||||
setActiveTab,
|
||||
setSidebarOpen,
|
||||
setIsInputFocused,
|
||||
setShowSettings,
|
||||
openSettings,
|
||||
fetchProjects,
|
||||
sidebarSharedProps,
|
||||
} = useProjectsState({
|
||||
sessionId,
|
||||
navigate,
|
||||
latestMessage,
|
||||
isMobile,
|
||||
activeSessions,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
window.refreshProjects = fetchProjects;
|
||||
|
||||
return () => {
|
||||
if (window.refreshProjects === fetchProjects) {
|
||||
delete window.refreshProjects;
|
||||
}
|
||||
};
|
||||
}, [fetchProjects]);
|
||||
|
||||
useEffect(() => {
|
||||
window.openSettings = openSettings;
|
||||
|
||||
return () => {
|
||||
if (window.openSettings === openSettings) {
|
||||
delete window.openSettings;
|
||||
}
|
||||
};
|
||||
}, [openSettings]);
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 flex bg-background">
|
||||
{!isMobile ? (
|
||||
<div className="h-full flex-shrink-0 border-r border-border bg-card">
|
||||
<Sidebar {...sidebarSharedProps} />
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={`fixed inset-0 z-50 flex transition-all duration-150 ease-out ${sidebarOpen ? 'opacity-100 visible' : 'opacity-0 invisible'
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
className="fixed inset-0 bg-background/80 backdrop-blur-sm transition-opacity duration-150 ease-out"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
setSidebarOpen(false);
|
||||
}}
|
||||
onTouchStart={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setSidebarOpen(false);
|
||||
}}
|
||||
aria-label={t('versionUpdate.ariaLabels.closeSidebar')}
|
||||
/>
|
||||
<div
|
||||
className={`relative w-[85vw] max-w-sm sm:w-80 h-full bg-card border-r border-border transform transition-transform duration-150 ease-out ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'
|
||||
}`}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onTouchStart={(event) => event.stopPropagation()}
|
||||
>
|
||||
<Sidebar {...sidebarSharedProps} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={`flex-1 flex flex-col min-w-0 ${isMobile && !isInputFocused ? 'pb-mobile-nav' : ''}`}>
|
||||
<MainContent
|
||||
selectedProject={selectedProject}
|
||||
selectedSession={selectedSession}
|
||||
activeTab={activeTab}
|
||||
setActiveTab={setActiveTab}
|
||||
ws={ws}
|
||||
sendMessage={sendMessage}
|
||||
latestMessage={latestMessage}
|
||||
isMobile={isMobile}
|
||||
onMenuClick={() => setSidebarOpen(true)}
|
||||
isLoading={isLoadingProjects}
|
||||
onInputFocusChange={setIsInputFocused}
|
||||
onSessionActive={markSessionAsActive}
|
||||
onSessionInactive={markSessionAsInactive}
|
||||
onSessionProcessing={markSessionAsProcessing}
|
||||
onSessionNotProcessing={markSessionAsNotProcessing}
|
||||
processingSessions={processingSessions}
|
||||
onReplaceTemporarySession={replaceTemporarySession}
|
||||
onNavigateToSession={(targetSessionId: string) => navigate(`/session/${targetSessionId}`)}
|
||||
onShowSettings={() => setShowSettings(true)}
|
||||
externalMessageUpdate={externalMessageUpdate}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isMobile && (
|
||||
<MobileNav
|
||||
activeTab={activeTab}
|
||||
setActiveTab={setActiveTab}
|
||||
isInputFocused={isInputFocused}
|
||||
/>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
44
src/components/chat/constants/thinkingModes.ts
Normal file
44
src/components/chat/constants/thinkingModes.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Brain, Zap, Sparkles, Atom } from 'lucide-react';
|
||||
|
||||
export const thinkingModes = [
|
||||
{
|
||||
id: 'none',
|
||||
name: 'Standard',
|
||||
description: 'Regular Claude response',
|
||||
icon: null,
|
||||
prefix: '',
|
||||
color: 'text-gray-600'
|
||||
},
|
||||
{
|
||||
id: 'think',
|
||||
name: 'Think',
|
||||
description: 'Basic extended thinking',
|
||||
icon: Brain,
|
||||
prefix: 'think',
|
||||
color: 'text-blue-600'
|
||||
},
|
||||
{
|
||||
id: 'think-hard',
|
||||
name: 'Think Hard',
|
||||
description: 'More thorough evaluation',
|
||||
icon: Zap,
|
||||
prefix: 'think hard',
|
||||
color: 'text-purple-600'
|
||||
},
|
||||
{
|
||||
id: 'think-harder',
|
||||
name: 'Think Harder',
|
||||
description: 'Deep analysis with alternatives',
|
||||
icon: Sparkles,
|
||||
prefix: 'think harder',
|
||||
color: 'text-indigo-600'
|
||||
},
|
||||
{
|
||||
id: 'ultrathink',
|
||||
name: 'Ultrathink',
|
||||
description: 'Maximum thinking budget',
|
||||
icon: Atom,
|
||||
prefix: 'ultrathink',
|
||||
color: 'text-red-600'
|
||||
}
|
||||
];
|
||||
957
src/components/chat/hooks/useChatComposerState.ts
Normal file
957
src/components/chat/hooks/useChatComposerState.ts
Normal file
@@ -0,0 +1,957 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type {
|
||||
ChangeEvent,
|
||||
ClipboardEvent,
|
||||
Dispatch,
|
||||
FormEvent,
|
||||
KeyboardEvent,
|
||||
MouseEvent,
|
||||
SetStateAction,
|
||||
TouchEvent,
|
||||
} from 'react';
|
||||
import { useDropzone } from 'react-dropzone';
|
||||
import { authenticatedFetch } from '../../../utils/api';
|
||||
|
||||
import { thinkingModes } from '../constants/thinkingModes';
|
||||
|
||||
import { grantClaudeToolPermission } from '../utils/chatPermissions';
|
||||
import { safeLocalStorage } from '../utils/chatStorage';
|
||||
import type {
|
||||
ChatMessage,
|
||||
PendingPermissionRequest,
|
||||
PermissionMode,
|
||||
} from '../types/types';
|
||||
import { useFileMentions } from './useFileMentions';
|
||||
import { type SlashCommand, useSlashCommands } from './useSlashCommands';
|
||||
import type { Project, ProjectSession, SessionProvider } from '../../../types/app';
|
||||
import { escapeRegExp } from '../utils/chatFormatting';
|
||||
|
||||
type PendingViewSession = {
|
||||
sessionId: string | null;
|
||||
startedAt: number;
|
||||
};
|
||||
|
||||
interface UseChatComposerStateArgs {
|
||||
selectedProject: Project | null;
|
||||
selectedSession: ProjectSession | null;
|
||||
currentSessionId: string | null;
|
||||
provider: SessionProvider;
|
||||
permissionMode: PermissionMode | string;
|
||||
cyclePermissionMode: () => void;
|
||||
cursorModel: string;
|
||||
claudeModel: string;
|
||||
codexModel: string;
|
||||
isLoading: boolean;
|
||||
canAbortSession: boolean;
|
||||
tokenBudget: Record<string, unknown> | null;
|
||||
sendMessage: (message: unknown) => void;
|
||||
sendByCtrlEnter?: boolean;
|
||||
onSessionActive?: (sessionId?: string | null) => void;
|
||||
onInputFocusChange?: (focused: boolean) => void;
|
||||
onFileOpen?: (filePath: string, diffInfo?: unknown) => void;
|
||||
onShowSettings?: () => void;
|
||||
pendingViewSessionRef: { current: PendingViewSession | null };
|
||||
scrollToBottom: () => void;
|
||||
setChatMessages: Dispatch<SetStateAction<ChatMessage[]>>;
|
||||
setSessionMessages?: Dispatch<SetStateAction<any[]>>;
|
||||
setIsLoading: (loading: boolean) => void;
|
||||
setCanAbortSession: (canAbort: boolean) => void;
|
||||
setClaudeStatus: (status: { text: string; tokens: number; can_interrupt: boolean } | null) => void;
|
||||
setIsUserScrolledUp: (isScrolledUp: boolean) => void;
|
||||
setPendingPermissionRequests: Dispatch<SetStateAction<PendingPermissionRequest[]>>;
|
||||
}
|
||||
|
||||
interface MentionableFile {
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
interface CommandExecutionResult {
|
||||
type: 'builtin' | 'custom';
|
||||
action?: string;
|
||||
data?: any;
|
||||
content?: string;
|
||||
hasBashCommands?: boolean;
|
||||
hasFileIncludes?: boolean;
|
||||
}
|
||||
|
||||
const createFakeSubmitEvent = () => {
|
||||
return { preventDefault: () => undefined } as unknown as FormEvent<HTMLFormElement>;
|
||||
};
|
||||
|
||||
const isTemporarySessionId = (sessionId: string | null | undefined) =>
|
||||
Boolean(sessionId && sessionId.startsWith('new-session-'));
|
||||
|
||||
export function useChatComposerState({
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
currentSessionId,
|
||||
provider,
|
||||
permissionMode,
|
||||
cyclePermissionMode,
|
||||
cursorModel,
|
||||
claudeModel,
|
||||
codexModel,
|
||||
isLoading,
|
||||
canAbortSession,
|
||||
tokenBudget,
|
||||
sendMessage,
|
||||
sendByCtrlEnter,
|
||||
onSessionActive,
|
||||
onInputFocusChange,
|
||||
onFileOpen,
|
||||
onShowSettings,
|
||||
pendingViewSessionRef,
|
||||
scrollToBottom,
|
||||
setChatMessages,
|
||||
setSessionMessages,
|
||||
setIsLoading,
|
||||
setCanAbortSession,
|
||||
setClaudeStatus,
|
||||
setIsUserScrolledUp,
|
||||
setPendingPermissionRequests,
|
||||
}: UseChatComposerStateArgs) {
|
||||
const [input, setInput] = useState(() => {
|
||||
if (typeof window !== 'undefined' && selectedProject) {
|
||||
return safeLocalStorage.getItem(`draft_input_${selectedProject.name}`) || '';
|
||||
}
|
||||
return '';
|
||||
});
|
||||
const [attachedImages, setAttachedImages] = useState<File[]>([]);
|
||||
const [uploadingImages, setUploadingImages] = useState<Map<string, number>>(new Map());
|
||||
const [imageErrors, setImageErrors] = useState<Map<string, string>>(new Map());
|
||||
const [isTextareaExpanded, setIsTextareaExpanded] = useState(false);
|
||||
const [thinkingMode, setThinkingMode] = useState('none');
|
||||
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const inputHighlightRef = useRef<HTMLDivElement>(null);
|
||||
const handleSubmitRef = useRef<
|
||||
((event: FormEvent<HTMLFormElement> | MouseEvent | TouchEvent | KeyboardEvent<HTMLTextAreaElement>) => Promise<void>) | null
|
||||
>(null);
|
||||
const inputValueRef = useRef(input);
|
||||
|
||||
const handleBuiltInCommand = useCallback(
|
||||
(result: CommandExecutionResult) => {
|
||||
const { action, data } = result;
|
||||
switch (action) {
|
||||
case 'clear':
|
||||
setChatMessages([]);
|
||||
setSessionMessages?.([]);
|
||||
break;
|
||||
|
||||
case 'help':
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: data.content,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'model':
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: `**Current Model**: ${data.current.model}\n\n**Available Models**:\n\nClaude: ${data.available.claude.join(', ')}\n\nCursor: ${data.available.cursor.join(', ')}`,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'cost': {
|
||||
const costMessage = `**Token Usage**: ${data.tokenUsage.used.toLocaleString()} / ${data.tokenUsage.total.toLocaleString()} (${data.tokenUsage.percentage}%)\n\n**Estimated Cost**:\n- Input: $${data.cost.input}\n- Output: $${data.cost.output}\n- **Total**: $${data.cost.total}\n\n**Model**: ${data.model}`;
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{ type: 'assistant', content: costMessage, timestamp: Date.now() },
|
||||
]);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'status': {
|
||||
const statusMessage = `**System Status**\n\n- Version: ${data.version}\n- Uptime: ${data.uptime}\n- Model: ${data.model}\n- Provider: ${data.provider}\n- Node.js: ${data.nodeVersion}\n- Platform: ${data.platform}`;
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{ type: 'assistant', content: statusMessage, timestamp: Date.now() },
|
||||
]);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'memory':
|
||||
if (data.error) {
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: `⚠️ ${data.message}`,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
]);
|
||||
} else {
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: `📝 ${data.message}\n\nPath: \`${data.path}\``,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
]);
|
||||
if (data.exists && onFileOpen) {
|
||||
onFileOpen(data.path);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'config':
|
||||
onShowSettings?.();
|
||||
break;
|
||||
|
||||
case 'rewind':
|
||||
if (data.error) {
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: `⚠️ ${data.message}`,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
]);
|
||||
} else {
|
||||
setChatMessages((previous) => previous.slice(0, -data.steps * 2));
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: `⏪ ${data.message}`,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn('Unknown built-in command action:', action);
|
||||
}
|
||||
},
|
||||
[onFileOpen, onShowSettings, setChatMessages, setSessionMessages],
|
||||
);
|
||||
|
||||
const handleCustomCommand = useCallback(async (result: CommandExecutionResult) => {
|
||||
const { content, hasBashCommands } = result;
|
||||
|
||||
if (hasBashCommands) {
|
||||
const confirmed = window.confirm(
|
||||
'This command contains bash commands that will be executed. Do you want to proceed?',
|
||||
);
|
||||
if (!confirmed) {
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: '❌ Command execution cancelled',
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const commandContent = content || '';
|
||||
setInput(commandContent);
|
||||
inputValueRef.current = commandContent;
|
||||
|
||||
// Defer submit to next tick so the command text is reflected in UI before dispatching.
|
||||
setTimeout(() => {
|
||||
if (handleSubmitRef.current) {
|
||||
handleSubmitRef.current(createFakeSubmitEvent());
|
||||
}
|
||||
}, 0);
|
||||
}, [setChatMessages]);
|
||||
|
||||
const executeCommand = useCallback(
|
||||
async (command: SlashCommand) => {
|
||||
if (!command || !selectedProject) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const commandMatch = input.match(new RegExp(`${escapeRegExp(command.name)}\\s*(.*)`));
|
||||
const args =
|
||||
commandMatch && commandMatch[1] ? commandMatch[1].trim().split(/\s+/) : [];
|
||||
|
||||
const context = {
|
||||
projectPath: selectedProject.fullPath || selectedProject.path,
|
||||
projectName: selectedProject.name,
|
||||
sessionId: currentSessionId,
|
||||
provider,
|
||||
model: provider === 'cursor' ? cursorModel : provider === 'codex' ? codexModel : claudeModel,
|
||||
tokenUsage: tokenBudget,
|
||||
};
|
||||
|
||||
const response = await authenticatedFetch('/api/commands/execute', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
commandName: command.name,
|
||||
commandPath: command.path,
|
||||
args,
|
||||
context,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = `Failed to execute command (${response.status})`;
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData?.message || errorData?.error || errorMessage;
|
||||
} catch {
|
||||
// Ignore JSON parse failures and use fallback message.
|
||||
}
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const result = (await response.json()) as CommandExecutionResult;
|
||||
if (result.type === 'builtin') {
|
||||
handleBuiltInCommand(result);
|
||||
setInput('');
|
||||
inputValueRef.current = '';
|
||||
} else if (result.type === 'custom') {
|
||||
await handleCustomCommand(result);
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error';
|
||||
console.error('Error executing command:', error);
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: `Error executing command: ${message}`,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
},
|
||||
[
|
||||
claudeModel,
|
||||
codexModel,
|
||||
currentSessionId,
|
||||
cursorModel,
|
||||
handleBuiltInCommand,
|
||||
handleCustomCommand,
|
||||
input,
|
||||
provider,
|
||||
selectedProject,
|
||||
setChatMessages,
|
||||
tokenBudget,
|
||||
],
|
||||
);
|
||||
|
||||
const {
|
||||
slashCommandsCount,
|
||||
filteredCommands,
|
||||
frequentCommands,
|
||||
commandQuery,
|
||||
showCommandMenu,
|
||||
selectedCommandIndex,
|
||||
resetCommandMenuState,
|
||||
handleCommandSelect,
|
||||
handleToggleCommandMenu,
|
||||
handleCommandInputChange,
|
||||
handleCommandMenuKeyDown,
|
||||
} = useSlashCommands({
|
||||
selectedProject,
|
||||
input,
|
||||
setInput,
|
||||
textareaRef,
|
||||
onExecuteCommand: executeCommand,
|
||||
});
|
||||
|
||||
const {
|
||||
showFileDropdown,
|
||||
filteredFiles,
|
||||
selectedFileIndex,
|
||||
renderInputWithMentions,
|
||||
selectFile,
|
||||
setCursorPosition,
|
||||
handleFileMentionsKeyDown,
|
||||
} = useFileMentions({
|
||||
selectedProject,
|
||||
input,
|
||||
setInput,
|
||||
textareaRef,
|
||||
});
|
||||
|
||||
const syncInputOverlayScroll = useCallback((target: HTMLTextAreaElement) => {
|
||||
if (!inputHighlightRef.current || !target) {
|
||||
return;
|
||||
}
|
||||
inputHighlightRef.current.scrollTop = target.scrollTop;
|
||||
inputHighlightRef.current.scrollLeft = target.scrollLeft;
|
||||
}, []);
|
||||
|
||||
const handleImageFiles = useCallback((files: File[]) => {
|
||||
const validFiles = files.filter((file) => {
|
||||
try {
|
||||
if (!file || typeof file !== 'object') {
|
||||
console.warn('Invalid file object:', file);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!file.type || !file.type.startsWith('image/')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!file.size || file.size > 5 * 1024 * 1024) {
|
||||
const fileName = file.name || 'Unknown file';
|
||||
setImageErrors((previous) => {
|
||||
const next = new Map(previous);
|
||||
next.set(fileName, 'File too large (max 5MB)');
|
||||
return next;
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error validating file:', error, file);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
if (validFiles.length > 0) {
|
||||
setAttachedImages((previous) => [...previous, ...validFiles].slice(0, 5));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handlePaste = useCallback(
|
||||
(event: ClipboardEvent<HTMLTextAreaElement>) => {
|
||||
const items = Array.from(event.clipboardData.items);
|
||||
|
||||
items.forEach((item) => {
|
||||
if (!item.type.startsWith('image/')) {
|
||||
return;
|
||||
}
|
||||
const file = item.getAsFile();
|
||||
if (file) {
|
||||
handleImageFiles([file]);
|
||||
}
|
||||
});
|
||||
|
||||
if (items.length === 0 && event.clipboardData.files.length > 0) {
|
||||
const files = Array.from(event.clipboardData.files);
|
||||
const imageFiles = files.filter((file) => file.type.startsWith('image/'));
|
||||
if (imageFiles.length > 0) {
|
||||
handleImageFiles(imageFiles);
|
||||
}
|
||||
}
|
||||
},
|
||||
[handleImageFiles],
|
||||
);
|
||||
|
||||
const { getRootProps, getInputProps, isDragActive, open } = useDropzone({
|
||||
accept: {
|
||||
'image/*': ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'],
|
||||
},
|
||||
maxSize: 5 * 1024 * 1024,
|
||||
maxFiles: 5,
|
||||
onDrop: handleImageFiles,
|
||||
noClick: true,
|
||||
noKeyboard: true,
|
||||
});
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (
|
||||
event: FormEvent<HTMLFormElement> | MouseEvent | TouchEvent | KeyboardEvent<HTMLTextAreaElement>,
|
||||
) => {
|
||||
event.preventDefault();
|
||||
const currentInput = inputValueRef.current;
|
||||
if (!currentInput.trim() || isLoading || !selectedProject) {
|
||||
return;
|
||||
}
|
||||
|
||||
let messageContent = currentInput;
|
||||
const selectedThinkingMode = thinkingModes.find((mode: { id: string; prefix?: string }) => mode.id === thinkingMode);
|
||||
if (selectedThinkingMode && selectedThinkingMode.prefix) {
|
||||
messageContent = `${selectedThinkingMode.prefix}: ${currentInput}`;
|
||||
}
|
||||
|
||||
let uploadedImages: unknown[] = [];
|
||||
if (attachedImages.length > 0) {
|
||||
const formData = new FormData();
|
||||
attachedImages.forEach((file) => {
|
||||
formData.append('images', file);
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await authenticatedFetch(`/api/projects/${selectedProject.name}/upload-images`, {
|
||||
method: 'POST',
|
||||
headers: {},
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to upload images');
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
uploadedImages = result.images;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error';
|
||||
console.error('Image upload failed:', error);
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'error',
|
||||
content: `Failed to upload images: ${message}`,
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const userMessage: ChatMessage = {
|
||||
type: 'user',
|
||||
content: currentInput,
|
||||
images: uploadedImages as any,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
setChatMessages((previous) => [...previous, userMessage]);
|
||||
setIsLoading(true);
|
||||
setCanAbortSession(true);
|
||||
setClaudeStatus({
|
||||
text: 'Processing',
|
||||
tokens: 0,
|
||||
can_interrupt: true,
|
||||
});
|
||||
|
||||
setIsUserScrolledUp(false);
|
||||
setTimeout(() => scrollToBottom(), 100);
|
||||
|
||||
const effectiveSessionId =
|
||||
currentSessionId || selectedSession?.id || sessionStorage.getItem('cursorSessionId');
|
||||
const sessionToActivate = effectiveSessionId || `new-session-${Date.now()}`;
|
||||
|
||||
if (!effectiveSessionId && !selectedSession?.id) {
|
||||
if (typeof window !== 'undefined') {
|
||||
// Reset stale pending IDs from previous interrupted runs before creating a new one.
|
||||
sessionStorage.removeItem('pendingSessionId');
|
||||
}
|
||||
pendingViewSessionRef.current = { sessionId: null, startedAt: Date.now() };
|
||||
}
|
||||
onSessionActive?.(sessionToActivate);
|
||||
|
||||
const getToolsSettings = () => {
|
||||
try {
|
||||
const settingsKey =
|
||||
provider === 'cursor'
|
||||
? 'cursor-tools-settings'
|
||||
: provider === 'codex'
|
||||
? 'codex-settings'
|
||||
: 'claude-settings';
|
||||
const savedSettings = safeLocalStorage.getItem(settingsKey);
|
||||
if (savedSettings) {
|
||||
return JSON.parse(savedSettings);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading tools settings:', error);
|
||||
}
|
||||
|
||||
return {
|
||||
allowedTools: [],
|
||||
disallowedTools: [],
|
||||
skipPermissions: false,
|
||||
};
|
||||
};
|
||||
|
||||
const toolsSettings = getToolsSettings();
|
||||
const resolvedProjectPath = selectedProject.fullPath || selectedProject.path || '';
|
||||
|
||||
if (provider === 'cursor') {
|
||||
sendMessage({
|
||||
type: 'cursor-command',
|
||||
command: messageContent,
|
||||
sessionId: effectiveSessionId,
|
||||
options: {
|
||||
cwd: resolvedProjectPath,
|
||||
projectPath: resolvedProjectPath,
|
||||
sessionId: effectiveSessionId,
|
||||
resume: Boolean(effectiveSessionId),
|
||||
model: cursorModel,
|
||||
skipPermissions: toolsSettings?.skipPermissions || false,
|
||||
toolsSettings,
|
||||
},
|
||||
});
|
||||
} else if (provider === 'codex') {
|
||||
sendMessage({
|
||||
type: 'codex-command',
|
||||
command: messageContent,
|
||||
sessionId: effectiveSessionId,
|
||||
options: {
|
||||
cwd: resolvedProjectPath,
|
||||
projectPath: resolvedProjectPath,
|
||||
sessionId: effectiveSessionId,
|
||||
resume: Boolean(effectiveSessionId),
|
||||
model: codexModel,
|
||||
permissionMode: permissionMode === 'plan' ? 'default' : permissionMode,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
sendMessage({
|
||||
type: 'claude-command',
|
||||
command: messageContent,
|
||||
options: {
|
||||
projectPath: resolvedProjectPath,
|
||||
cwd: resolvedProjectPath,
|
||||
sessionId: effectiveSessionId,
|
||||
resume: Boolean(effectiveSessionId),
|
||||
toolsSettings,
|
||||
permissionMode,
|
||||
model: claudeModel,
|
||||
images: uploadedImages,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
setInput('');
|
||||
inputValueRef.current = '';
|
||||
resetCommandMenuState();
|
||||
setAttachedImages([]);
|
||||
setUploadingImages(new Map());
|
||||
setImageErrors(new Map());
|
||||
setIsTextareaExpanded(false);
|
||||
setThinkingMode('none');
|
||||
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto';
|
||||
}
|
||||
|
||||
safeLocalStorage.removeItem(`draft_input_${selectedProject.name}`);
|
||||
},
|
||||
[
|
||||
attachedImages,
|
||||
claudeModel,
|
||||
codexModel,
|
||||
currentSessionId,
|
||||
cursorModel,
|
||||
isLoading,
|
||||
onSessionActive,
|
||||
pendingViewSessionRef,
|
||||
permissionMode,
|
||||
provider,
|
||||
resetCommandMenuState,
|
||||
scrollToBottom,
|
||||
selectedProject,
|
||||
selectedSession?.id,
|
||||
sendMessage,
|
||||
setCanAbortSession,
|
||||
setChatMessages,
|
||||
setClaudeStatus,
|
||||
setIsLoading,
|
||||
setIsUserScrolledUp,
|
||||
thinkingMode,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
handleSubmitRef.current = handleSubmit;
|
||||
}, [handleSubmit]);
|
||||
|
||||
useEffect(() => {
|
||||
inputValueRef.current = input;
|
||||
}, [input]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
const savedInput = safeLocalStorage.getItem(`draft_input_${selectedProject.name}`) || '';
|
||||
setInput((previous) => {
|
||||
const next = previous === savedInput ? previous : savedInput;
|
||||
inputValueRef.current = next;
|
||||
return next;
|
||||
});
|
||||
}, [selectedProject?.name]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
if (input !== '') {
|
||||
safeLocalStorage.setItem(`draft_input_${selectedProject.name}`, input);
|
||||
} else {
|
||||
safeLocalStorage.removeItem(`draft_input_${selectedProject.name}`);
|
||||
}
|
||||
}, [input, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!textareaRef.current) {
|
||||
return;
|
||||
}
|
||||
// Re-run when input changes so restored drafts get the same autosize behavior as typed text.
|
||||
textareaRef.current.style.height = 'auto';
|
||||
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
|
||||
const lineHeight = parseInt(window.getComputedStyle(textareaRef.current).lineHeight);
|
||||
const expanded = textareaRef.current.scrollHeight > lineHeight * 2;
|
||||
setIsTextareaExpanded(expanded);
|
||||
}, [input]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!textareaRef.current || input.trim()) {
|
||||
return;
|
||||
}
|
||||
textareaRef.current.style.height = 'auto';
|
||||
setIsTextareaExpanded(false);
|
||||
}, [input]);
|
||||
|
||||
const handleInputChange = useCallback(
|
||||
(event: ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newValue = event.target.value;
|
||||
const cursorPos = event.target.selectionStart;
|
||||
|
||||
setInput(newValue);
|
||||
inputValueRef.current = newValue;
|
||||
setCursorPosition(cursorPos);
|
||||
|
||||
if (!newValue.trim()) {
|
||||
event.target.style.height = 'auto';
|
||||
setIsTextareaExpanded(false);
|
||||
resetCommandMenuState();
|
||||
return;
|
||||
}
|
||||
|
||||
handleCommandInputChange(newValue, cursorPos);
|
||||
},
|
||||
[handleCommandInputChange, resetCommandMenuState, setCursorPosition],
|
||||
);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(event: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (handleCommandMenuKeyDown(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (handleFileMentionsKeyDown(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === 'Tab' && !showFileDropdown && !showCommandMenu) {
|
||||
event.preventDefault();
|
||||
cyclePermissionMode();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === 'Enter') {
|
||||
if (event.nativeEvent.isComposing) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ((event.ctrlKey || event.metaKey) && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
handleSubmit(event);
|
||||
} else if (!event.shiftKey && !event.ctrlKey && !event.metaKey && !sendByCtrlEnter) {
|
||||
event.preventDefault();
|
||||
handleSubmit(event);
|
||||
}
|
||||
}
|
||||
},
|
||||
[
|
||||
cyclePermissionMode,
|
||||
handleCommandMenuKeyDown,
|
||||
handleFileMentionsKeyDown,
|
||||
handleSubmit,
|
||||
sendByCtrlEnter,
|
||||
showCommandMenu,
|
||||
showFileDropdown,
|
||||
],
|
||||
);
|
||||
|
||||
const handleTextareaClick = useCallback(
|
||||
(event: MouseEvent<HTMLTextAreaElement>) => {
|
||||
setCursorPosition(event.currentTarget.selectionStart);
|
||||
},
|
||||
[setCursorPosition],
|
||||
);
|
||||
|
||||
const handleTextareaInput = useCallback(
|
||||
(event: FormEvent<HTMLTextAreaElement>) => {
|
||||
const target = event.currentTarget;
|
||||
target.style.height = 'auto';
|
||||
target.style.height = `${target.scrollHeight}px`;
|
||||
setCursorPosition(target.selectionStart);
|
||||
syncInputOverlayScroll(target);
|
||||
|
||||
const lineHeight = parseInt(window.getComputedStyle(target).lineHeight);
|
||||
setIsTextareaExpanded(target.scrollHeight > lineHeight * 2);
|
||||
},
|
||||
[setCursorPosition, syncInputOverlayScroll],
|
||||
);
|
||||
|
||||
const handleClearInput = useCallback(() => {
|
||||
setInput('');
|
||||
inputValueRef.current = '';
|
||||
resetCommandMenuState();
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto';
|
||||
textareaRef.current.focus();
|
||||
}
|
||||
setIsTextareaExpanded(false);
|
||||
}, [resetCommandMenuState]);
|
||||
|
||||
const handleAbortSession = useCallback(() => {
|
||||
if (!canAbortSession) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pendingSessionId =
|
||||
typeof window !== 'undefined' ? sessionStorage.getItem('pendingSessionId') : null;
|
||||
const cursorSessionId =
|
||||
typeof window !== 'undefined' ? sessionStorage.getItem('cursorSessionId') : null;
|
||||
|
||||
const candidateSessionIds = [
|
||||
currentSessionId,
|
||||
pendingViewSessionRef.current?.sessionId || null,
|
||||
pendingSessionId,
|
||||
provider === 'cursor' ? cursorSessionId : null,
|
||||
selectedSession?.id || null,
|
||||
];
|
||||
|
||||
const targetSessionId =
|
||||
candidateSessionIds.find((sessionId) => Boolean(sessionId) && !isTemporarySessionId(sessionId)) || null;
|
||||
|
||||
if (!targetSessionId) {
|
||||
console.warn('Abort requested but no concrete session ID is available yet.');
|
||||
return;
|
||||
}
|
||||
|
||||
sendMessage({
|
||||
type: 'abort-session',
|
||||
sessionId: targetSessionId,
|
||||
provider,
|
||||
});
|
||||
}, [canAbortSession, currentSessionId, pendingViewSessionRef, provider, selectedSession?.id, sendMessage]);
|
||||
|
||||
const handleTranscript = useCallback((text: string) => {
|
||||
if (!text.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
setInput((previousInput) => {
|
||||
const newInput = previousInput.trim() ? `${previousInput} ${text}` : text;
|
||||
inputValueRef.current = newInput;
|
||||
|
||||
setTimeout(() => {
|
||||
if (!textareaRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
textareaRef.current.style.height = 'auto';
|
||||
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
|
||||
const lineHeight = parseInt(window.getComputedStyle(textareaRef.current).lineHeight);
|
||||
setIsTextareaExpanded(textareaRef.current.scrollHeight > lineHeight * 2);
|
||||
}, 0);
|
||||
|
||||
return newInput;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleGrantToolPermission = useCallback(
|
||||
(suggestion: { entry: string; toolName: string }) => {
|
||||
if (!suggestion || provider !== 'claude') {
|
||||
return { success: false };
|
||||
}
|
||||
return grantClaudeToolPermission(suggestion.entry);
|
||||
},
|
||||
[provider],
|
||||
);
|
||||
|
||||
const handlePermissionDecision = useCallback(
|
||||
(
|
||||
requestIds: string | string[],
|
||||
decision: { allow?: boolean; message?: string; rememberEntry?: string | null; updatedInput?: unknown },
|
||||
) => {
|
||||
const ids = Array.isArray(requestIds) ? requestIds : [requestIds];
|
||||
const validIds = ids.filter(Boolean);
|
||||
if (validIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
validIds.forEach((requestId) => {
|
||||
sendMessage({
|
||||
type: 'claude-permission-response',
|
||||
requestId,
|
||||
allow: Boolean(decision?.allow),
|
||||
updatedInput: decision?.updatedInput,
|
||||
message: decision?.message,
|
||||
rememberEntry: decision?.rememberEntry,
|
||||
});
|
||||
});
|
||||
|
||||
setPendingPermissionRequests((previous) => {
|
||||
const next = previous.filter((request) => !validIds.includes(request.requestId));
|
||||
if (next.length === 0) {
|
||||
setClaudeStatus(null);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[sendMessage, setClaudeStatus, setPendingPermissionRequests],
|
||||
);
|
||||
|
||||
const handleInputFocusChange = useCallback(
|
||||
(focused: boolean) => {
|
||||
onInputFocusChange?.(focused);
|
||||
},
|
||||
[onInputFocusChange],
|
||||
);
|
||||
|
||||
return {
|
||||
input,
|
||||
setInput,
|
||||
textareaRef,
|
||||
inputHighlightRef,
|
||||
isTextareaExpanded,
|
||||
thinkingMode,
|
||||
setThinkingMode,
|
||||
slashCommandsCount,
|
||||
filteredCommands,
|
||||
frequentCommands,
|
||||
commandQuery,
|
||||
showCommandMenu,
|
||||
selectedCommandIndex,
|
||||
resetCommandMenuState,
|
||||
handleCommandSelect,
|
||||
handleToggleCommandMenu,
|
||||
showFileDropdown,
|
||||
filteredFiles: filteredFiles as MentionableFile[],
|
||||
selectedFileIndex,
|
||||
renderInputWithMentions,
|
||||
selectFile,
|
||||
attachedImages,
|
||||
setAttachedImages,
|
||||
uploadingImages,
|
||||
imageErrors,
|
||||
getRootProps,
|
||||
getInputProps,
|
||||
isDragActive,
|
||||
openImagePicker: open,
|
||||
handleSubmit,
|
||||
handleInputChange,
|
||||
handleKeyDown,
|
||||
handlePaste,
|
||||
handleTextareaClick,
|
||||
handleTextareaInput,
|
||||
syncInputOverlayScroll,
|
||||
handleClearInput,
|
||||
handleAbortSession,
|
||||
handleTranscript,
|
||||
handlePermissionDecision,
|
||||
handleGrantToolPermission,
|
||||
handleInputFocusChange,
|
||||
};
|
||||
}
|
||||
114
src/components/chat/hooks/useChatProviderState.ts
Normal file
114
src/components/chat/hooks/useChatProviderState.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { authenticatedFetch } from '../../../utils/api';
|
||||
import { CLAUDE_MODELS, CODEX_MODELS, CURSOR_MODELS } from '../../../../shared/modelConstants';
|
||||
import type { PendingPermissionRequest, PermissionMode, Provider } from '../types/types';
|
||||
import type { ProjectSession, SessionProvider } from '../../../types/app';
|
||||
|
||||
interface UseChatProviderStateArgs {
|
||||
selectedSession: ProjectSession | null;
|
||||
}
|
||||
|
||||
export function useChatProviderState({ selectedSession }: UseChatProviderStateArgs) {
|
||||
const [permissionMode, setPermissionMode] = useState<PermissionMode>('default');
|
||||
const [pendingPermissionRequests, setPendingPermissionRequests] = useState<PendingPermissionRequest[]>([]);
|
||||
const [provider, setProvider] = useState<SessionProvider>(() => {
|
||||
return (localStorage.getItem('selected-provider') as SessionProvider) || 'claude';
|
||||
});
|
||||
const [cursorModel, setCursorModel] = useState<string>(() => {
|
||||
return localStorage.getItem('cursor-model') || CURSOR_MODELS.DEFAULT;
|
||||
});
|
||||
const [claudeModel, setClaudeModel] = useState<string>(() => {
|
||||
return localStorage.getItem('claude-model') || CLAUDE_MODELS.DEFAULT;
|
||||
});
|
||||
const [codexModel, setCodexModel] = useState<string>(() => {
|
||||
return localStorage.getItem('codex-model') || CODEX_MODELS.DEFAULT;
|
||||
});
|
||||
|
||||
const lastProviderRef = useRef(provider);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedSession?.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
const savedMode = localStorage.getItem(`permissionMode-${selectedSession.id}`);
|
||||
setPermissionMode((savedMode as PermissionMode) || 'default');
|
||||
}, [selectedSession?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedSession?.__provider || selectedSession.__provider === provider) {
|
||||
return;
|
||||
}
|
||||
|
||||
setProvider(selectedSession.__provider);
|
||||
localStorage.setItem('selected-provider', selectedSession.__provider);
|
||||
}, [provider, selectedSession]);
|
||||
|
||||
useEffect(() => {
|
||||
if (lastProviderRef.current === provider) {
|
||||
return;
|
||||
}
|
||||
setPendingPermissionRequests([]);
|
||||
lastProviderRef.current = provider;
|
||||
}, [provider]);
|
||||
|
||||
useEffect(() => {
|
||||
setPendingPermissionRequests((previous) =>
|
||||
previous.filter((request) => !request.sessionId || request.sessionId === selectedSession?.id),
|
||||
);
|
||||
}, [selectedSession?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (provider !== 'cursor') {
|
||||
return;
|
||||
}
|
||||
|
||||
authenticatedFetch('/api/cursor/config')
|
||||
.then((response) => response.json())
|
||||
.then((data) => {
|
||||
if (!data.success || !data.config?.model?.modelId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const modelId = data.config.model.modelId as string;
|
||||
if (!localStorage.getItem('cursor-model')) {
|
||||
setCursorModel(modelId);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Error loading Cursor config:', error);
|
||||
});
|
||||
}, [provider]);
|
||||
|
||||
const cyclePermissionMode = useCallback(() => {
|
||||
const modes: PermissionMode[] =
|
||||
provider === 'codex'
|
||||
? ['default', 'acceptEdits', 'bypassPermissions']
|
||||
: ['default', 'acceptEdits', 'bypassPermissions', 'plan'];
|
||||
|
||||
const currentIndex = modes.indexOf(permissionMode);
|
||||
const nextIndex = (currentIndex + 1) % modes.length;
|
||||
const nextMode = modes[nextIndex];
|
||||
setPermissionMode(nextMode);
|
||||
|
||||
if (selectedSession?.id) {
|
||||
localStorage.setItem(`permissionMode-${selectedSession.id}`, nextMode);
|
||||
}
|
||||
}, [permissionMode, provider, selectedSession?.id]);
|
||||
|
||||
return {
|
||||
provider,
|
||||
setProvider,
|
||||
cursorModel,
|
||||
setCursorModel,
|
||||
claudeModel,
|
||||
setClaudeModel,
|
||||
codexModel,
|
||||
setCodexModel,
|
||||
permissionMode,
|
||||
setPermissionMode,
|
||||
pendingPermissionRequests,
|
||||
setPendingPermissionRequests,
|
||||
cyclePermissionMode,
|
||||
};
|
||||
}
|
||||
956
src/components/chat/hooks/useChatRealtimeHandlers.ts
Normal file
956
src/components/chat/hooks/useChatRealtimeHandlers.ts
Normal file
@@ -0,0 +1,956 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { Dispatch, MutableRefObject, SetStateAction } from 'react';
|
||||
import { decodeHtmlEntities, formatUsageLimitText } from '../utils/chatFormatting';
|
||||
import { safeLocalStorage } from '../utils/chatStorage';
|
||||
import type { ChatMessage, PendingPermissionRequest } from '../types/types';
|
||||
import type { Project, ProjectSession, SessionProvider } from '../../../types/app';
|
||||
|
||||
type PendingViewSession = {
|
||||
sessionId: string | null;
|
||||
startedAt: number;
|
||||
};
|
||||
|
||||
type LatestChatMessage = {
|
||||
type?: string;
|
||||
data?: any;
|
||||
sessionId?: string;
|
||||
requestId?: string;
|
||||
toolName?: string;
|
||||
input?: unknown;
|
||||
context?: unknown;
|
||||
error?: string;
|
||||
tool?: string;
|
||||
exitCode?: number;
|
||||
isProcessing?: boolean;
|
||||
actualSessionId?: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
|
||||
interface UseChatRealtimeHandlersArgs {
|
||||
latestMessage: LatestChatMessage | null;
|
||||
provider: SessionProvider;
|
||||
selectedProject: Project | null;
|
||||
selectedSession: ProjectSession | null;
|
||||
currentSessionId: string | null;
|
||||
setCurrentSessionId: (sessionId: string | null) => void;
|
||||
setChatMessages: Dispatch<SetStateAction<ChatMessage[]>>;
|
||||
setIsLoading: (loading: boolean) => void;
|
||||
setCanAbortSession: (canAbort: boolean) => void;
|
||||
setClaudeStatus: (status: { text: string; tokens: number; can_interrupt: boolean } | null) => void;
|
||||
setTokenBudget: (budget: Record<string, unknown> | null) => void;
|
||||
setIsSystemSessionChange: (isSystemSessionChange: boolean) => void;
|
||||
setPendingPermissionRequests: Dispatch<SetStateAction<PendingPermissionRequest[]>>;
|
||||
pendingViewSessionRef: MutableRefObject<PendingViewSession | null>;
|
||||
streamBufferRef: MutableRefObject<string>;
|
||||
streamTimerRef: MutableRefObject<number | null>;
|
||||
onSessionInactive?: (sessionId?: string | null) => void;
|
||||
onSessionProcessing?: (sessionId?: string | null) => void;
|
||||
onSessionNotProcessing?: (sessionId?: string | null) => void;
|
||||
onReplaceTemporarySession?: (sessionId?: string | null) => void;
|
||||
onNavigateToSession?: (sessionId: string) => void;
|
||||
}
|
||||
|
||||
const appendStreamingChunk = (
|
||||
setChatMessages: Dispatch<SetStateAction<ChatMessage[]>>,
|
||||
chunk: string,
|
||||
newline = false,
|
||||
) => {
|
||||
if (!chunk) {
|
||||
return;
|
||||
}
|
||||
|
||||
setChatMessages((previous) => {
|
||||
const updated = [...previous];
|
||||
const lastIndex = updated.length - 1;
|
||||
const last = updated[lastIndex];
|
||||
if (last && last.type === 'assistant' && !last.isToolUse && last.isStreaming) {
|
||||
const nextContent = newline
|
||||
? last.content
|
||||
? `${last.content}\n${chunk}`
|
||||
: chunk
|
||||
: `${last.content || ''}${chunk}`;
|
||||
// Clone the message instead of mutating in place so React can reliably detect state updates.
|
||||
updated[lastIndex] = { ...last, content: nextContent };
|
||||
} else {
|
||||
updated.push({ type: 'assistant', content: chunk, timestamp: new Date(), isStreaming: true });
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
const finalizeStreamingMessage = (setChatMessages: Dispatch<SetStateAction<ChatMessage[]>>) => {
|
||||
setChatMessages((previous) => {
|
||||
const updated = [...previous];
|
||||
const lastIndex = updated.length - 1;
|
||||
const last = updated[lastIndex];
|
||||
if (last && last.type === 'assistant' && last.isStreaming) {
|
||||
// Clone the message instead of mutating in place so React can reliably detect state updates.
|
||||
updated[lastIndex] = { ...last, isStreaming: false };
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
export function useChatRealtimeHandlers({
|
||||
latestMessage,
|
||||
provider,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
currentSessionId,
|
||||
setCurrentSessionId,
|
||||
setChatMessages,
|
||||
setIsLoading,
|
||||
setCanAbortSession,
|
||||
setClaudeStatus,
|
||||
setTokenBudget,
|
||||
setIsSystemSessionChange,
|
||||
setPendingPermissionRequests,
|
||||
pendingViewSessionRef,
|
||||
streamBufferRef,
|
||||
streamTimerRef,
|
||||
onSessionInactive,
|
||||
onSessionProcessing,
|
||||
onSessionNotProcessing,
|
||||
onReplaceTemporarySession,
|
||||
onNavigateToSession,
|
||||
}: UseChatRealtimeHandlersArgs) {
|
||||
const lastProcessedMessageRef = useRef<LatestChatMessage | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!latestMessage) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Guard against duplicate processing when dependency updates occur without a new message object.
|
||||
if (lastProcessedMessageRef.current === latestMessage) {
|
||||
return;
|
||||
}
|
||||
lastProcessedMessageRef.current = latestMessage;
|
||||
|
||||
const messageData = latestMessage.data?.message || latestMessage.data;
|
||||
const structuredMessageData =
|
||||
messageData && typeof messageData === 'object' ? (messageData as Record<string, any>) : null;
|
||||
const rawStructuredData =
|
||||
latestMessage.data && typeof latestMessage.data === 'object'
|
||||
? (latestMessage.data as Record<string, any>)
|
||||
: null;
|
||||
|
||||
const globalMessageTypes = ['projects_updated', 'taskmaster-project-updated', 'session-created'];
|
||||
const isGlobalMessage = globalMessageTypes.includes(String(latestMessage.type));
|
||||
const lifecycleMessageTypes = new Set([
|
||||
'claude-complete',
|
||||
'codex-complete',
|
||||
'cursor-result',
|
||||
'session-aborted',
|
||||
'claude-error',
|
||||
'cursor-error',
|
||||
'codex-error',
|
||||
]);
|
||||
|
||||
const isClaudeSystemInit =
|
||||
latestMessage.type === 'claude-response' &&
|
||||
structuredMessageData &&
|
||||
structuredMessageData.type === 'system' &&
|
||||
structuredMessageData.subtype === 'init';
|
||||
|
||||
const isCursorSystemInit =
|
||||
latestMessage.type === 'cursor-system' &&
|
||||
rawStructuredData &&
|
||||
rawStructuredData.type === 'system' &&
|
||||
rawStructuredData.subtype === 'init';
|
||||
|
||||
const systemInitSessionId = isClaudeSystemInit
|
||||
? structuredMessageData?.session_id
|
||||
: isCursorSystemInit
|
||||
? rawStructuredData?.session_id
|
||||
: null;
|
||||
|
||||
const activeViewSessionId =
|
||||
selectedSession?.id || currentSessionId || pendingViewSessionRef.current?.sessionId || null;
|
||||
const isSystemInitForView =
|
||||
systemInitSessionId && (!activeViewSessionId || systemInitSessionId === activeViewSessionId);
|
||||
const shouldBypassSessionFilter = isGlobalMessage || Boolean(isSystemInitForView);
|
||||
const isUnscopedError =
|
||||
!latestMessage.sessionId &&
|
||||
pendingViewSessionRef.current &&
|
||||
!pendingViewSessionRef.current.sessionId &&
|
||||
(latestMessage.type === 'claude-error' ||
|
||||
latestMessage.type === 'cursor-error' ||
|
||||
latestMessage.type === 'codex-error');
|
||||
|
||||
const handleBackgroundLifecycle = (sessionId?: string) => {
|
||||
if (!sessionId) {
|
||||
return;
|
||||
}
|
||||
onSessionInactive?.(sessionId);
|
||||
onSessionNotProcessing?.(sessionId);
|
||||
};
|
||||
|
||||
const collectSessionIds = (...sessionIds: Array<string | null | undefined>) =>
|
||||
Array.from(
|
||||
new Set(
|
||||
sessionIds.filter((sessionId): sessionId is string => typeof sessionId === 'string' && sessionId.length > 0),
|
||||
),
|
||||
);
|
||||
|
||||
const clearLoadingIndicators = () => {
|
||||
setIsLoading(false);
|
||||
setCanAbortSession(false);
|
||||
setClaudeStatus(null);
|
||||
};
|
||||
|
||||
const markSessionsAsCompleted = (...sessionIds: Array<string | null | undefined>) => {
|
||||
const normalizedSessionIds = collectSessionIds(...sessionIds);
|
||||
normalizedSessionIds.forEach((sessionId) => {
|
||||
onSessionInactive?.(sessionId);
|
||||
onSessionNotProcessing?.(sessionId);
|
||||
});
|
||||
};
|
||||
|
||||
if (!shouldBypassSessionFilter) {
|
||||
if (!activeViewSessionId) {
|
||||
if (latestMessage.sessionId && lifecycleMessageTypes.has(String(latestMessage.type))) {
|
||||
handleBackgroundLifecycle(latestMessage.sessionId);
|
||||
}
|
||||
if (!isUnscopedError) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!latestMessage.sessionId && !isUnscopedError) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (latestMessage.sessionId !== activeViewSessionId) {
|
||||
if (latestMessage.sessionId && lifecycleMessageTypes.has(String(latestMessage.type))) {
|
||||
handleBackgroundLifecycle(latestMessage.sessionId);
|
||||
}
|
||||
console.log(
|
||||
'Skipping message for different session:',
|
||||
latestMessage.sessionId,
|
||||
'current:',
|
||||
activeViewSessionId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
switch (latestMessage.type) {
|
||||
case 'session-created':
|
||||
if (latestMessage.sessionId && !currentSessionId) {
|
||||
sessionStorage.setItem('pendingSessionId', latestMessage.sessionId);
|
||||
if (pendingViewSessionRef.current && !pendingViewSessionRef.current.sessionId) {
|
||||
pendingViewSessionRef.current.sessionId = latestMessage.sessionId;
|
||||
}
|
||||
|
||||
setIsSystemSessionChange(true);
|
||||
onReplaceTemporarySession?.(latestMessage.sessionId);
|
||||
|
||||
setPendingPermissionRequests((previous) =>
|
||||
previous.map((request) =>
|
||||
request.sessionId ? request : { ...request, sessionId: latestMessage.sessionId },
|
||||
),
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'token-budget':
|
||||
if (latestMessage.data) {
|
||||
setTokenBudget(latestMessage.data);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'claude-response': {
|
||||
if (messageData && typeof messageData === 'object' && messageData.type) {
|
||||
if (messageData.type === 'content_block_delta' && messageData.delta?.text) {
|
||||
const decodedText = decodeHtmlEntities(messageData.delta.text);
|
||||
streamBufferRef.current += decodedText;
|
||||
if (!streamTimerRef.current) {
|
||||
streamTimerRef.current = window.setTimeout(() => {
|
||||
const chunk = streamBufferRef.current;
|
||||
streamBufferRef.current = '';
|
||||
streamTimerRef.current = null;
|
||||
appendStreamingChunk(setChatMessages, chunk, false);
|
||||
}, 100);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (messageData.type === 'content_block_stop') {
|
||||
if (streamTimerRef.current) {
|
||||
clearTimeout(streamTimerRef.current);
|
||||
streamTimerRef.current = null;
|
||||
}
|
||||
const chunk = streamBufferRef.current;
|
||||
streamBufferRef.current = '';
|
||||
appendStreamingChunk(setChatMessages, chunk, false);
|
||||
finalizeStreamingMessage(setChatMessages);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
structuredMessageData?.type === 'system' &&
|
||||
structuredMessageData.subtype === 'init' &&
|
||||
structuredMessageData.session_id &&
|
||||
currentSessionId &&
|
||||
structuredMessageData.session_id !== currentSessionId &&
|
||||
isSystemInitForView
|
||||
) {
|
||||
console.log('Claude CLI session duplication detected:', {
|
||||
originalSession: currentSessionId,
|
||||
newSession: structuredMessageData.session_id,
|
||||
});
|
||||
|
||||
setIsSystemSessionChange(true);
|
||||
onNavigateToSession?.(structuredMessageData.session_id);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
structuredMessageData?.type === 'system' &&
|
||||
structuredMessageData.subtype === 'init' &&
|
||||
structuredMessageData.session_id &&
|
||||
!currentSessionId &&
|
||||
isSystemInitForView
|
||||
) {
|
||||
console.log('New session init detected:', {
|
||||
newSession: structuredMessageData.session_id,
|
||||
});
|
||||
|
||||
setIsSystemSessionChange(true);
|
||||
onNavigateToSession?.(structuredMessageData.session_id);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
structuredMessageData?.type === 'system' &&
|
||||
structuredMessageData.subtype === 'init' &&
|
||||
structuredMessageData.session_id &&
|
||||
currentSessionId &&
|
||||
structuredMessageData.session_id === currentSessionId &&
|
||||
isSystemInitForView
|
||||
) {
|
||||
console.log('System init message for current session, ignoring');
|
||||
return;
|
||||
}
|
||||
|
||||
if (structuredMessageData && Array.isArray(structuredMessageData.content)) {
|
||||
structuredMessageData.content.forEach((part: any) => {
|
||||
if (part.type === 'tool_use') {
|
||||
const toolInput = part.input ? JSON.stringify(part.input, null, 2) : '';
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: '',
|
||||
timestamp: new Date(),
|
||||
isToolUse: true,
|
||||
toolName: part.name,
|
||||
toolInput,
|
||||
toolId: part.id,
|
||||
toolResult: null,
|
||||
},
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (part.type === 'text' && part.text?.trim()) {
|
||||
let content = decodeHtmlEntities(part.text);
|
||||
content = formatUsageLimitText(content);
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content,
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
});
|
||||
} else if (structuredMessageData && typeof structuredMessageData.content === 'string' && structuredMessageData.content.trim()) {
|
||||
let content = decodeHtmlEntities(structuredMessageData.content);
|
||||
content = formatUsageLimitText(content);
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content,
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
if (structuredMessageData?.role === 'user' && Array.isArray(structuredMessageData.content)) {
|
||||
structuredMessageData.content.forEach((part: any) => {
|
||||
if (part.type !== 'tool_result') {
|
||||
return;
|
||||
}
|
||||
|
||||
setChatMessages((previous) =>
|
||||
previous.map((message) => {
|
||||
if (message.isToolUse && message.toolId === part.tool_use_id) {
|
||||
return {
|
||||
...message,
|
||||
toolResult: {
|
||||
content: part.content,
|
||||
isError: part.is_error,
|
||||
timestamp: new Date(),
|
||||
},
|
||||
};
|
||||
}
|
||||
return message;
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'claude-output': {
|
||||
const cleaned = String(latestMessage.data || '');
|
||||
if (cleaned.trim()) {
|
||||
streamBufferRef.current += streamBufferRef.current ? `\n${cleaned}` : cleaned;
|
||||
if (!streamTimerRef.current) {
|
||||
streamTimerRef.current = window.setTimeout(() => {
|
||||
const chunk = streamBufferRef.current;
|
||||
streamBufferRef.current = '';
|
||||
streamTimerRef.current = null;
|
||||
appendStreamingChunk(setChatMessages, chunk, true);
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'claude-interactive-prompt':
|
||||
// Interactive prompts are parsed/rendered as text in the UI.
|
||||
// Normalize to string to keep ChatMessage.content shape consistent.
|
||||
{
|
||||
const interactiveContent =
|
||||
typeof latestMessage.data === 'string'
|
||||
? latestMessage.data
|
||||
: JSON.stringify(latestMessage.data ?? '', null, 2);
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: interactiveContent,
|
||||
timestamp: new Date(),
|
||||
isInteractivePrompt: true,
|
||||
},
|
||||
]);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'claude-permission-request':
|
||||
if (provider !== 'claude' || !latestMessage.requestId) {
|
||||
break;
|
||||
}
|
||||
{
|
||||
const requestId = latestMessage.requestId;
|
||||
|
||||
setPendingPermissionRequests((previous) => {
|
||||
if (previous.some((request) => request.requestId === requestId)) {
|
||||
return previous;
|
||||
}
|
||||
return [
|
||||
...previous,
|
||||
{
|
||||
requestId,
|
||||
toolName: latestMessage.toolName || 'UnknownTool',
|
||||
input: latestMessage.input,
|
||||
context: latestMessage.context,
|
||||
sessionId: latestMessage.sessionId || null,
|
||||
receivedAt: new Date(),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setCanAbortSession(true);
|
||||
setClaudeStatus({
|
||||
text: 'Waiting for permission',
|
||||
tokens: 0,
|
||||
can_interrupt: true,
|
||||
});
|
||||
break;
|
||||
|
||||
case 'claude-permission-cancelled':
|
||||
if (!latestMessage.requestId) {
|
||||
break;
|
||||
}
|
||||
setPendingPermissionRequests((previous) =>
|
||||
previous.filter((request) => request.requestId !== latestMessage.requestId),
|
||||
);
|
||||
break;
|
||||
|
||||
case 'claude-error':
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'error',
|
||||
content: `Error: ${latestMessage.error}`,
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'cursor-system':
|
||||
try {
|
||||
const cursorData = latestMessage.data;
|
||||
if (
|
||||
cursorData &&
|
||||
cursorData.type === 'system' &&
|
||||
cursorData.subtype === 'init' &&
|
||||
cursorData.session_id
|
||||
) {
|
||||
if (!isSystemInitForView) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentSessionId && cursorData.session_id !== currentSessionId) {
|
||||
console.log('Cursor session switch detected:', {
|
||||
originalSession: currentSessionId,
|
||||
newSession: cursorData.session_id,
|
||||
});
|
||||
setIsSystemSessionChange(true);
|
||||
onNavigateToSession?.(cursorData.session_id);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!currentSessionId) {
|
||||
console.log('Cursor new session init detected:', { newSession: cursorData.session_id });
|
||||
setIsSystemSessionChange(true);
|
||||
onNavigateToSession?.(cursorData.session_id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Error handling cursor-system message:', error);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'cursor-user':
|
||||
break;
|
||||
|
||||
case 'cursor-tool-use':
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: `Using tool: ${latestMessage.tool} ${
|
||||
latestMessage.input ? `with ${latestMessage.input}` : ''
|
||||
}`,
|
||||
timestamp: new Date(),
|
||||
isToolUse: true,
|
||||
toolName: latestMessage.tool,
|
||||
toolInput: latestMessage.input,
|
||||
},
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'cursor-error':
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'error',
|
||||
content: `Cursor error: ${latestMessage.error || 'Unknown error'}`,
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'cursor-result': {
|
||||
const cursorCompletedSessionId = latestMessage.sessionId || currentSessionId;
|
||||
const pendingCursorSessionId = sessionStorage.getItem('pendingSessionId');
|
||||
|
||||
clearLoadingIndicators();
|
||||
markSessionsAsCompleted(
|
||||
cursorCompletedSessionId,
|
||||
currentSessionId,
|
||||
selectedSession?.id,
|
||||
pendingCursorSessionId,
|
||||
);
|
||||
|
||||
try {
|
||||
const resultData = latestMessage.data || {};
|
||||
const textResult = typeof resultData.result === 'string' ? resultData.result : '';
|
||||
|
||||
if (streamTimerRef.current) {
|
||||
clearTimeout(streamTimerRef.current);
|
||||
streamTimerRef.current = null;
|
||||
}
|
||||
const pendingChunk = streamBufferRef.current;
|
||||
streamBufferRef.current = '';
|
||||
|
||||
setChatMessages((previous) => {
|
||||
const updated = [...previous];
|
||||
const lastIndex = updated.length - 1;
|
||||
const last = updated[lastIndex];
|
||||
if (last && last.type === 'assistant' && !last.isToolUse && last.isStreaming) {
|
||||
const finalContent =
|
||||
textResult && textResult.trim()
|
||||
? textResult
|
||||
: `${last.content || ''}${pendingChunk || ''}`;
|
||||
// Clone the message instead of mutating in place so React can reliably detect state updates.
|
||||
updated[lastIndex] = { ...last, content: finalContent, isStreaming: false };
|
||||
} else if (textResult && textResult.trim()) {
|
||||
updated.push({
|
||||
type: resultData.is_error ? 'error' : 'assistant',
|
||||
content: textResult,
|
||||
timestamp: new Date(),
|
||||
isStreaming: false,
|
||||
});
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('Error handling cursor-result message:', error);
|
||||
}
|
||||
|
||||
if (cursorCompletedSessionId && !currentSessionId && cursorCompletedSessionId === pendingCursorSessionId) {
|
||||
setCurrentSessionId(cursorCompletedSessionId);
|
||||
sessionStorage.removeItem('pendingSessionId');
|
||||
if (window.refreshProjects) {
|
||||
setTimeout(() => window.refreshProjects?.(), 500);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'cursor-output':
|
||||
try {
|
||||
const raw = String(latestMessage.data ?? '');
|
||||
const cleaned = raw
|
||||
.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')
|
||||
.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '')
|
||||
.trim();
|
||||
|
||||
if (cleaned) {
|
||||
streamBufferRef.current += streamBufferRef.current ? `\n${cleaned}` : cleaned;
|
||||
if (!streamTimerRef.current) {
|
||||
streamTimerRef.current = window.setTimeout(() => {
|
||||
const chunk = streamBufferRef.current;
|
||||
streamBufferRef.current = '';
|
||||
streamTimerRef.current = null;
|
||||
appendStreamingChunk(setChatMessages, chunk, true);
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Error handling cursor-output message:', error);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'claude-complete': {
|
||||
const pendingSessionId = sessionStorage.getItem('pendingSessionId');
|
||||
const completedSessionId =
|
||||
latestMessage.sessionId || currentSessionId || pendingSessionId;
|
||||
|
||||
clearLoadingIndicators();
|
||||
markSessionsAsCompleted(
|
||||
completedSessionId,
|
||||
currentSessionId,
|
||||
selectedSession?.id,
|
||||
pendingSessionId,
|
||||
);
|
||||
|
||||
if (pendingSessionId && !currentSessionId && latestMessage.exitCode === 0) {
|
||||
setCurrentSessionId(pendingSessionId);
|
||||
sessionStorage.removeItem('pendingSessionId');
|
||||
console.log('New session complete, ID set to:', pendingSessionId);
|
||||
}
|
||||
|
||||
if (selectedProject && latestMessage.exitCode === 0) {
|
||||
safeLocalStorage.removeItem(`chat_messages_${selectedProject.name}`);
|
||||
}
|
||||
setPendingPermissionRequests([]);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'codex-response': {
|
||||
const codexData = latestMessage.data;
|
||||
if (!codexData) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (codexData.type === 'item') {
|
||||
switch (codexData.itemType) {
|
||||
case 'agent_message':
|
||||
if (codexData.message?.content?.trim()) {
|
||||
const content = decodeHtmlEntities(codexData.message.content);
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content,
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'reasoning':
|
||||
if (codexData.message?.content?.trim()) {
|
||||
const content = decodeHtmlEntities(codexData.message.content);
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content,
|
||||
timestamp: new Date(),
|
||||
isThinking: true,
|
||||
},
|
||||
]);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'command_execution':
|
||||
if (codexData.command) {
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
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((change: { kind: string; path: string }) => `${change.kind}: ${change.path}`)
|
||||
.join('\n');
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: '',
|
||||
timestamp: new Date(),
|
||||
isToolUse: true,
|
||||
toolName: 'FileChanges',
|
||||
toolInput: changesList,
|
||||
toolResult: {
|
||||
content: `Status: ${codexData.status}`,
|
||||
isError: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'mcp_tool_call':
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
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((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'error',
|
||||
content: codexData.message.content,
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log('[Codex] Unhandled item type:', codexData.itemType, codexData);
|
||||
}
|
||||
}
|
||||
|
||||
if (codexData.type === 'turn_complete') {
|
||||
clearLoadingIndicators();
|
||||
markSessionsAsCompleted(latestMessage.sessionId, currentSessionId, selectedSession?.id);
|
||||
}
|
||||
|
||||
if (codexData.type === 'turn_failed') {
|
||||
clearLoadingIndicators();
|
||||
markSessionsAsCompleted(latestMessage.sessionId, currentSessionId, selectedSession?.id);
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'error',
|
||||
content: codexData.error?.message || 'Turn failed',
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'codex-complete': {
|
||||
const codexPendingSessionId = sessionStorage.getItem('pendingSessionId');
|
||||
const codexActualSessionId = latestMessage.actualSessionId || codexPendingSessionId;
|
||||
const codexCompletedSessionId =
|
||||
latestMessage.sessionId || currentSessionId || codexPendingSessionId;
|
||||
|
||||
clearLoadingIndicators();
|
||||
markSessionsAsCompleted(
|
||||
codexCompletedSessionId,
|
||||
codexActualSessionId,
|
||||
currentSessionId,
|
||||
selectedSession?.id,
|
||||
codexPendingSessionId,
|
||||
);
|
||||
|
||||
if (codexPendingSessionId && !currentSessionId) {
|
||||
setCurrentSessionId(codexActualSessionId);
|
||||
setIsSystemSessionChange(true);
|
||||
if (codexActualSessionId) {
|
||||
onNavigateToSession?.(codexActualSessionId);
|
||||
}
|
||||
sessionStorage.removeItem('pendingSessionId');
|
||||
console.log('Codex session complete, ID set to:', codexPendingSessionId);
|
||||
}
|
||||
|
||||
if (selectedProject) {
|
||||
safeLocalStorage.removeItem(`chat_messages_${selectedProject.name}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'codex-error':
|
||||
setIsLoading(false);
|
||||
setCanAbortSession(false);
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'error',
|
||||
content: latestMessage.error || 'An error occurred with Codex',
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'session-aborted': {
|
||||
const pendingSessionId =
|
||||
typeof window !== 'undefined' ? sessionStorage.getItem('pendingSessionId') : null;
|
||||
const abortedSessionId = latestMessage.sessionId || currentSessionId;
|
||||
const abortSucceeded = latestMessage.success !== false;
|
||||
|
||||
if (abortSucceeded) {
|
||||
clearLoadingIndicators();
|
||||
markSessionsAsCompleted(abortedSessionId, currentSessionId, selectedSession?.id, pendingSessionId);
|
||||
if (pendingSessionId && (!abortedSessionId || pendingSessionId === abortedSessionId)) {
|
||||
sessionStorage.removeItem('pendingSessionId');
|
||||
}
|
||||
|
||||
setPendingPermissionRequests([]);
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'assistant',
|
||||
content: 'Session interrupted by user.',
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
} else {
|
||||
setChatMessages((previous) => [
|
||||
...previous,
|
||||
{
|
||||
type: 'error',
|
||||
content: 'Stop request failed. The session is still running.',
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'session-status': {
|
||||
const statusSessionId = latestMessage.sessionId;
|
||||
const isCurrentSession =
|
||||
statusSessionId === currentSessionId || (selectedSession && statusSessionId === selectedSession.id);
|
||||
if (isCurrentSession && latestMessage.isProcessing) {
|
||||
setIsLoading(true);
|
||||
setCanAbortSession(true);
|
||||
onSessionProcessing?.(statusSessionId);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'claude-status': {
|
||||
const statusData = latestMessage.data;
|
||||
if (!statusData) {
|
||||
break;
|
||||
}
|
||||
|
||||
const statusInfo: { text: string; tokens: number; can_interrupt: boolean } = {
|
||||
text: 'Working...',
|
||||
tokens: 0,
|
||||
can_interrupt: true,
|
||||
};
|
||||
|
||||
if (statusData.message) {
|
||||
statusInfo.text = statusData.message;
|
||||
} else if (statusData.status) {
|
||||
statusInfo.text = statusData.status;
|
||||
} else if (typeof statusData === 'string') {
|
||||
statusInfo.text = statusData;
|
||||
}
|
||||
|
||||
if (statusData.tokens) {
|
||||
statusInfo.tokens = statusData.tokens;
|
||||
} else if (statusData.token_count) {
|
||||
statusInfo.tokens = statusData.token_count;
|
||||
}
|
||||
|
||||
if (statusData.can_interrupt !== undefined) {
|
||||
statusInfo.can_interrupt = statusData.can_interrupt;
|
||||
}
|
||||
|
||||
setClaudeStatus(statusInfo);
|
||||
setIsLoading(true);
|
||||
setCanAbortSession(statusInfo.can_interrupt);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}, [
|
||||
latestMessage,
|
||||
provider,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
currentSessionId,
|
||||
setCurrentSessionId,
|
||||
setChatMessages,
|
||||
setIsLoading,
|
||||
setCanAbortSession,
|
||||
setClaudeStatus,
|
||||
setTokenBudget,
|
||||
setIsSystemSessionChange,
|
||||
setPendingPermissionRequests,
|
||||
onSessionInactive,
|
||||
onSessionProcessing,
|
||||
onSessionNotProcessing,
|
||||
onReplaceTemporarySession,
|
||||
onNavigateToSession,
|
||||
]);
|
||||
}
|
||||
612
src/components/chat/hooks/useChatSessionState.ts
Normal file
612
src/components/chat/hooks/useChatSessionState.ts
Normal file
@@ -0,0 +1,612 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { MutableRefObject } from 'react';
|
||||
import { api, authenticatedFetch } from '../../../utils/api';
|
||||
import type { ChatMessage, Provider } from '../types/types';
|
||||
import type { Project, ProjectSession } from '../../../types/app';
|
||||
import { safeLocalStorage } from '../utils/chatStorage';
|
||||
import {
|
||||
convertCursorSessionMessages,
|
||||
convertSessionMessages,
|
||||
createCachedDiffCalculator,
|
||||
type DiffCalculator,
|
||||
} from '../utils/messageTransforms';
|
||||
|
||||
const MESSAGES_PER_PAGE = 20;
|
||||
const INITIAL_VISIBLE_MESSAGES = 100;
|
||||
|
||||
type PendingViewSession = {
|
||||
sessionId: string | null;
|
||||
startedAt: number;
|
||||
};
|
||||
|
||||
interface UseChatSessionStateArgs {
|
||||
selectedProject: Project | null;
|
||||
selectedSession: ProjectSession | null;
|
||||
ws: WebSocket | null;
|
||||
sendMessage: (message: unknown) => void;
|
||||
autoScrollToBottom?: boolean;
|
||||
externalMessageUpdate?: number;
|
||||
processingSessions?: Set<string>;
|
||||
resetStreamingState: () => void;
|
||||
pendingViewSessionRef: MutableRefObject<PendingViewSession | null>;
|
||||
}
|
||||
|
||||
interface ScrollRestoreState {
|
||||
height: number;
|
||||
top: number;
|
||||
}
|
||||
|
||||
export function useChatSessionState({
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
ws,
|
||||
sendMessage,
|
||||
autoScrollToBottom,
|
||||
externalMessageUpdate,
|
||||
processingSessions,
|
||||
resetStreamingState,
|
||||
pendingViewSessionRef,
|
||||
}: UseChatSessionStateArgs) {
|
||||
const [chatMessages, setChatMessages] = useState<ChatMessage[]>(() => {
|
||||
if (typeof window !== 'undefined' && selectedProject) {
|
||||
const saved = safeLocalStorage.getItem(`chat_messages_${selectedProject.name}`);
|
||||
if (saved) {
|
||||
try {
|
||||
return JSON.parse(saved) as ChatMessage[];
|
||||
} catch {
|
||||
console.error('Failed to parse saved chat messages, resetting');
|
||||
safeLocalStorage.removeItem(`chat_messages_${selectedProject.name}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [currentSessionId, setCurrentSessionId] = useState<string | null>(selectedSession?.id || null);
|
||||
const [sessionMessages, setSessionMessages] = useState<any[]>([]);
|
||||
const [isLoadingSessionMessages, setIsLoadingSessionMessages] = useState(false);
|
||||
const [isLoadingMoreMessages, setIsLoadingMoreMessages] = useState(false);
|
||||
const [hasMoreMessages, setHasMoreMessages] = useState(false);
|
||||
const [totalMessages, setTotalMessages] = useState(0);
|
||||
const [isSystemSessionChange, setIsSystemSessionChange] = useState(false);
|
||||
const [canAbortSession, setCanAbortSession] = useState(false);
|
||||
const [isUserScrolledUp, setIsUserScrolledUp] = useState(false);
|
||||
const [tokenBudget, setTokenBudget] = useState<Record<string, unknown> | null>(null);
|
||||
const [visibleMessageCount, setVisibleMessageCount] = useState(INITIAL_VISIBLE_MESSAGES);
|
||||
const [claudeStatus, setClaudeStatus] = useState<{ text: string; tokens: number; can_interrupt: boolean } | null>(null);
|
||||
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
||||
const isLoadingSessionRef = useRef(false);
|
||||
const isLoadingMoreRef = useRef(false);
|
||||
const topLoadLockRef = useRef(false);
|
||||
const pendingScrollRestoreRef = useRef<ScrollRestoreState | null>(null);
|
||||
const pendingInitialScrollRef = useRef(true);
|
||||
const messagesOffsetRef = useRef(0);
|
||||
const scrollPositionRef = useRef({ height: 0, top: 0 });
|
||||
|
||||
const createDiff = useMemo<DiffCalculator>(() => createCachedDiffCalculator(), []);
|
||||
|
||||
const loadSessionMessages = useCallback(
|
||||
async (projectName: string, sessionId: string, loadMore = false, provider: Provider | string = 'claude') => {
|
||||
if (!projectName || !sessionId) {
|
||||
return [] as any[];
|
||||
}
|
||||
|
||||
const isInitialLoad = !loadMore;
|
||||
if (isInitialLoad) {
|
||||
setIsLoadingSessionMessages(true);
|
||||
} else {
|
||||
setIsLoadingMoreMessages(true);
|
||||
}
|
||||
|
||||
try {
|
||||
const currentOffset = loadMore ? messagesOffsetRef.current : 0;
|
||||
const response = await (api.sessionMessages as any)(
|
||||
projectName,
|
||||
sessionId,
|
||||
MESSAGES_PER_PAGE,
|
||||
currentOffset,
|
||||
provider,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to load session messages');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
if (isInitialLoad && data.tokenUsage) {
|
||||
setTokenBudget(data.tokenUsage);
|
||||
}
|
||||
|
||||
if (data.hasMore !== undefined) {
|
||||
const loadedCount = data.messages?.length || 0;
|
||||
setHasMoreMessages(Boolean(data.hasMore));
|
||||
setTotalMessages(Number(data.total || 0));
|
||||
messagesOffsetRef.current = currentOffset + loadedCount;
|
||||
return data.messages || [];
|
||||
}
|
||||
|
||||
const messages = data.messages || [];
|
||||
setHasMoreMessages(false);
|
||||
setTotalMessages(messages.length);
|
||||
messagesOffsetRef.current = messages.length;
|
||||
return messages;
|
||||
} catch (error) {
|
||||
console.error('Error loading session messages:', error);
|
||||
return [];
|
||||
} finally {
|
||||
if (isInitialLoad) {
|
||||
setIsLoadingSessionMessages(false);
|
||||
} else {
|
||||
setIsLoadingMoreMessages(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const loadCursorSessionMessages = useCallback(async (projectPath: string, sessionId: string) => {
|
||||
if (!projectPath || !sessionId) {
|
||||
return [] as ChatMessage[];
|
||||
}
|
||||
|
||||
setIsLoadingSessionMessages(true);
|
||||
try {
|
||||
const url = `/api/cursor/sessions/${encodeURIComponent(sessionId)}?projectPath=${encodeURIComponent(projectPath)}`;
|
||||
const response = await authenticatedFetch(url);
|
||||
if (!response.ok) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const blobs = (data?.session?.messages || []) as any[];
|
||||
return convertCursorSessionMessages(blobs, projectPath);
|
||||
} catch (error) {
|
||||
console.error('Error loading Cursor session messages:', error);
|
||||
return [];
|
||||
} finally {
|
||||
setIsLoadingSessionMessages(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const convertedMessages = useMemo(() => {
|
||||
return convertSessionMessages(sessionMessages);
|
||||
}, [sessionMessages]);
|
||||
|
||||
const scrollToBottom = useCallback(() => {
|
||||
const container = scrollContainerRef.current;
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}, []);
|
||||
|
||||
const isNearBottom = useCallback(() => {
|
||||
const container = scrollContainerRef.current;
|
||||
if (!container) {
|
||||
return false;
|
||||
}
|
||||
const { scrollTop, scrollHeight, clientHeight } = container;
|
||||
return scrollHeight - scrollTop - clientHeight < 50;
|
||||
}, []);
|
||||
|
||||
const loadOlderMessages = useCallback(
|
||||
async (container: HTMLDivElement) => {
|
||||
if (!container || isLoadingMoreRef.current || isLoadingMoreMessages) {
|
||||
return false;
|
||||
}
|
||||
if (!hasMoreMessages || !selectedSession || !selectedProject) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const sessionProvider = selectedSession.__provider || 'claude';
|
||||
if (sessionProvider === 'cursor') {
|
||||
return false;
|
||||
}
|
||||
|
||||
isLoadingMoreRef.current = true;
|
||||
const previousScrollHeight = container.scrollHeight;
|
||||
const previousScrollTop = container.scrollTop;
|
||||
|
||||
try {
|
||||
const moreMessages = await loadSessionMessages(
|
||||
selectedProject.name,
|
||||
selectedSession.id,
|
||||
true,
|
||||
sessionProvider,
|
||||
);
|
||||
|
||||
if (moreMessages.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
pendingScrollRestoreRef.current = {
|
||||
height: previousScrollHeight,
|
||||
top: previousScrollTop,
|
||||
};
|
||||
setSessionMessages((previous) => [...moreMessages, ...previous]);
|
||||
// Keep the rendered window in sync with top-pagination so newly loaded history becomes visible.
|
||||
setVisibleMessageCount((previousCount) => previousCount + moreMessages.length);
|
||||
return true;
|
||||
} finally {
|
||||
isLoadingMoreRef.current = false;
|
||||
}
|
||||
},
|
||||
[hasMoreMessages, isLoadingMoreMessages, loadSessionMessages, selectedProject, selectedSession],
|
||||
);
|
||||
|
||||
const handleScroll = useCallback(async () => {
|
||||
const container = scrollContainerRef.current;
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nearBottom = isNearBottom();
|
||||
setIsUserScrolledUp(!nearBottom);
|
||||
|
||||
const scrolledNearTop = container.scrollTop < 100;
|
||||
if (!scrolledNearTop) {
|
||||
topLoadLockRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (topLoadLockRef.current) {
|
||||
// After a top-load restore, release the lock once user has moved away from absolute top.
|
||||
if (container.scrollTop > 20) {
|
||||
topLoadLockRef.current = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const didLoad = await loadOlderMessages(container);
|
||||
if (didLoad) {
|
||||
topLoadLockRef.current = true;
|
||||
}
|
||||
}, [isNearBottom, loadOlderMessages]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!pendingScrollRestoreRef.current || !scrollContainerRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { height, top } = pendingScrollRestoreRef.current;
|
||||
const container = scrollContainerRef.current;
|
||||
const newScrollHeight = container.scrollHeight;
|
||||
const scrollDiff = newScrollHeight - height;
|
||||
container.scrollTop = top + Math.max(scrollDiff, 0);
|
||||
pendingScrollRestoreRef.current = null;
|
||||
}, [chatMessages.length]);
|
||||
|
||||
useEffect(() => {
|
||||
pendingInitialScrollRef.current = true;
|
||||
topLoadLockRef.current = false;
|
||||
pendingScrollRestoreRef.current = null;
|
||||
setVisibleMessageCount(INITIAL_VISIBLE_MESSAGES);
|
||||
setIsUserScrolledUp(false);
|
||||
}, [selectedProject?.name, selectedSession?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingInitialScrollRef.current || !scrollContainerRef.current || isLoadingSessionMessages) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (chatMessages.length === 0) {
|
||||
pendingInitialScrollRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
pendingInitialScrollRef.current = false;
|
||||
setTimeout(() => {
|
||||
scrollToBottom();
|
||||
}, 200);
|
||||
}, [chatMessages.length, isLoadingSessionMessages, scrollToBottom]);
|
||||
|
||||
useEffect(() => {
|
||||
const loadMessages = async () => {
|
||||
if (selectedSession && selectedProject) {
|
||||
const provider = (localStorage.getItem('selected-provider') as Provider) || 'claude';
|
||||
isLoadingSessionRef.current = true;
|
||||
|
||||
const sessionChanged = currentSessionId !== null && currentSessionId !== selectedSession.id;
|
||||
if (sessionChanged) {
|
||||
if (!isSystemSessionChange) {
|
||||
resetStreamingState();
|
||||
pendingViewSessionRef.current = null;
|
||||
setChatMessages([]);
|
||||
setSessionMessages([]);
|
||||
setClaudeStatus(null);
|
||||
setCanAbortSession(false);
|
||||
}
|
||||
|
||||
messagesOffsetRef.current = 0;
|
||||
setHasMoreMessages(false);
|
||||
setTotalMessages(0);
|
||||
setTokenBudget(null);
|
||||
setIsLoading(false);
|
||||
|
||||
if (ws) {
|
||||
sendMessage({
|
||||
type: 'check-session-status',
|
||||
sessionId: selectedSession.id,
|
||||
provider,
|
||||
});
|
||||
}
|
||||
} else if (currentSessionId === null) {
|
||||
messagesOffsetRef.current = 0;
|
||||
setHasMoreMessages(false);
|
||||
setTotalMessages(0);
|
||||
|
||||
if (ws) {
|
||||
sendMessage({
|
||||
type: 'check-session-status',
|
||||
sessionId: selectedSession.id,
|
||||
provider,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (provider === 'cursor') {
|
||||
setCurrentSessionId(selectedSession.id);
|
||||
sessionStorage.setItem('cursorSessionId', selectedSession.id);
|
||||
|
||||
if (!isSystemSessionChange) {
|
||||
const projectPath = selectedProject.fullPath || selectedProject.path || '';
|
||||
const converted = await loadCursorSessionMessages(projectPath, selectedSession.id);
|
||||
setSessionMessages([]);
|
||||
setChatMessages(converted);
|
||||
} else {
|
||||
setIsSystemSessionChange(false);
|
||||
}
|
||||
} else {
|
||||
setCurrentSessionId(selectedSession.id);
|
||||
|
||||
if (!isSystemSessionChange) {
|
||||
const messages = await loadSessionMessages(
|
||||
selectedProject.name,
|
||||
selectedSession.id,
|
||||
false,
|
||||
selectedSession.__provider || 'claude',
|
||||
);
|
||||
setSessionMessages(messages);
|
||||
} else {
|
||||
setIsSystemSessionChange(false);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!isSystemSessionChange) {
|
||||
resetStreamingState();
|
||||
pendingViewSessionRef.current = null;
|
||||
setChatMessages([]);
|
||||
setSessionMessages([]);
|
||||
setClaudeStatus(null);
|
||||
setCanAbortSession(false);
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
setCurrentSessionId(null);
|
||||
sessionStorage.removeItem('cursorSessionId');
|
||||
messagesOffsetRef.current = 0;
|
||||
setHasMoreMessages(false);
|
||||
setTotalMessages(0);
|
||||
setTokenBudget(null);
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
isLoadingSessionRef.current = false;
|
||||
}, 250);
|
||||
};
|
||||
|
||||
loadMessages();
|
||||
}, [
|
||||
// Intentionally exclude currentSessionId: this effect sets it and should not retrigger another full load.
|
||||
isSystemSessionChange,
|
||||
loadCursorSessionMessages,
|
||||
loadSessionMessages,
|
||||
pendingViewSessionRef,
|
||||
resetStreamingState,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
sendMessage,
|
||||
ws,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!externalMessageUpdate || !selectedSession || !selectedProject) {
|
||||
return;
|
||||
}
|
||||
|
||||
const reloadExternalMessages = async () => {
|
||||
try {
|
||||
const provider = (localStorage.getItem('selected-provider') as Provider) || 'claude';
|
||||
|
||||
if (provider === 'cursor') {
|
||||
const projectPath = selectedProject.fullPath || selectedProject.path || '';
|
||||
const converted = await loadCursorSessionMessages(projectPath, selectedSession.id);
|
||||
setSessionMessages([]);
|
||||
setChatMessages(converted);
|
||||
return;
|
||||
}
|
||||
|
||||
const messages = await loadSessionMessages(
|
||||
selectedProject.name,
|
||||
selectedSession.id,
|
||||
false,
|
||||
selectedSession.__provider || 'claude',
|
||||
);
|
||||
setSessionMessages(messages);
|
||||
|
||||
const shouldAutoScroll = Boolean(autoScrollToBottom) && isNearBottom();
|
||||
if (shouldAutoScroll) {
|
||||
setTimeout(() => scrollToBottom(), 200);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error reloading messages from external update:', error);
|
||||
}
|
||||
};
|
||||
|
||||
reloadExternalMessages();
|
||||
}, [
|
||||
autoScrollToBottom,
|
||||
externalMessageUpdate,
|
||||
isNearBottom,
|
||||
loadCursorSessionMessages,
|
||||
loadSessionMessages,
|
||||
scrollToBottom,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSession?.id) {
|
||||
pendingViewSessionRef.current = null;
|
||||
}
|
||||
}, [pendingViewSessionRef, selectedSession?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (sessionMessages.length > 0) {
|
||||
setChatMessages(convertedMessages);
|
||||
}
|
||||
}, [convertedMessages, sessionMessages.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedProject && chatMessages.length > 0) {
|
||||
safeLocalStorage.setItem(`chat_messages_${selectedProject.name}`, JSON.stringify(chatMessages));
|
||||
}
|
||||
}, [chatMessages, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject || !selectedSession?.id || selectedSession.id.startsWith('new-session-')) {
|
||||
setTokenBudget(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionProvider = selectedSession.__provider || 'claude';
|
||||
if (sessionProvider !== 'claude') {
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
} else {
|
||||
setTokenBudget(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch initial token usage:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchInitialTokenUsage();
|
||||
}, [selectedProject, selectedSession?.id, selectedSession?.__provider]);
|
||||
|
||||
const visibleMessages = useMemo(() => {
|
||||
if (chatMessages.length <= visibleMessageCount) {
|
||||
return chatMessages;
|
||||
}
|
||||
return chatMessages.slice(-visibleMessageCount);
|
||||
}, [chatMessages, visibleMessageCount]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoScrollToBottom && scrollContainerRef.current) {
|
||||
const container = scrollContainerRef.current;
|
||||
scrollPositionRef.current = {
|
||||
height: container.scrollHeight,
|
||||
top: container.scrollTop,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!scrollContainerRef.current || chatMessages.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isLoadingMoreRef.current || isLoadingMoreMessages || pendingScrollRestoreRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (autoScrollToBottom) {
|
||||
if (!isUserScrolledUp) {
|
||||
setTimeout(() => scrollToBottom(), 50);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const container = scrollContainerRef.current;
|
||||
const prevHeight = scrollPositionRef.current.height;
|
||||
const prevTop = scrollPositionRef.current.top;
|
||||
const newHeight = container.scrollHeight;
|
||||
const heightDiff = newHeight - prevHeight;
|
||||
|
||||
if (heightDiff > 0 && prevTop > 0) {
|
||||
container.scrollTop = prevTop + heightDiff;
|
||||
}
|
||||
}, [autoScrollToBottom, chatMessages.length, isLoadingMoreMessages, isUserScrolledUp, scrollToBottom]);
|
||||
|
||||
useEffect(() => {
|
||||
const container = scrollContainerRef.current;
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
|
||||
container.addEventListener('scroll', handleScroll);
|
||||
return () => container.removeEventListener('scroll', handleScroll);
|
||||
}, [handleScroll]);
|
||||
|
||||
useEffect(() => {
|
||||
const activeViewSessionId = selectedSession?.id || currentSessionId;
|
||||
if (!activeViewSessionId || !processingSessions) {
|
||||
return;
|
||||
}
|
||||
|
||||
const shouldBeProcessing = processingSessions.has(activeViewSessionId);
|
||||
if (shouldBeProcessing && !isLoading) {
|
||||
setIsLoading(true);
|
||||
setCanAbortSession(true);
|
||||
}
|
||||
}, [currentSessionId, isLoading, processingSessions, selectedSession?.id]);
|
||||
|
||||
const loadEarlierMessages = useCallback(() => {
|
||||
setVisibleMessageCount((previousCount) => previousCount + 100);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
chatMessages,
|
||||
setChatMessages,
|
||||
isLoading,
|
||||
setIsLoading,
|
||||
currentSessionId,
|
||||
setCurrentSessionId,
|
||||
sessionMessages,
|
||||
setSessionMessages,
|
||||
isLoadingSessionMessages,
|
||||
isLoadingMoreMessages,
|
||||
hasMoreMessages,
|
||||
totalMessages,
|
||||
isSystemSessionChange,
|
||||
setIsSystemSessionChange,
|
||||
canAbortSession,
|
||||
setCanAbortSession,
|
||||
isUserScrolledUp,
|
||||
setIsUserScrolledUp,
|
||||
tokenBudget,
|
||||
setTokenBudget,
|
||||
visibleMessageCount,
|
||||
visibleMessages,
|
||||
loadEarlierMessages,
|
||||
claudeStatus,
|
||||
setClaudeStatus,
|
||||
createDiff,
|
||||
scrollContainerRef,
|
||||
scrollToBottom,
|
||||
isNearBottom,
|
||||
handleScroll,
|
||||
loadSessionMessages,
|
||||
loadCursorSessionMessages,
|
||||
};
|
||||
}
|
||||
268
src/components/chat/hooks/useFileMentions.tsx
Normal file
268
src/components/chat/hooks/useFileMentions.tsx
Normal file
@@ -0,0 +1,268 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import type { Dispatch, KeyboardEvent, RefObject, SetStateAction } from 'react';
|
||||
import { api } from '../../../utils/api';
|
||||
import { escapeRegExp } from '../utils/chatFormatting';
|
||||
import type { Project } from '../../../types/app';
|
||||
|
||||
interface ProjectFileNode {
|
||||
name: string;
|
||||
type: 'file' | 'directory';
|
||||
path?: string;
|
||||
children?: ProjectFileNode[];
|
||||
}
|
||||
|
||||
export interface MentionableFile {
|
||||
name: string;
|
||||
path: string;
|
||||
relativePath?: string;
|
||||
}
|
||||
|
||||
interface UseFileMentionsOptions {
|
||||
selectedProject: Project | null;
|
||||
input: string;
|
||||
setInput: Dispatch<SetStateAction<string>>;
|
||||
textareaRef: RefObject<HTMLTextAreaElement>;
|
||||
}
|
||||
|
||||
const flattenFileTree = (files: ProjectFileNode[], basePath = ''): MentionableFile[] => {
|
||||
let flattened: MentionableFile[] = [];
|
||||
|
||||
files.forEach((file) => {
|
||||
const fullPath = basePath ? `${basePath}/${file.name}` : file.name;
|
||||
if (file.type === 'directory' && file.children) {
|
||||
flattened = flattened.concat(flattenFileTree(file.children, fullPath));
|
||||
return;
|
||||
}
|
||||
|
||||
if (file.type === 'file') {
|
||||
flattened.push({
|
||||
name: file.name,
|
||||
path: fullPath,
|
||||
relativePath: file.path,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return flattened;
|
||||
};
|
||||
|
||||
export function useFileMentions({ selectedProject, input, setInput, textareaRef }: UseFileMentionsOptions) {
|
||||
const [fileList, setFileList] = useState<MentionableFile[]>([]);
|
||||
const [fileMentions, setFileMentions] = useState<string[]>([]);
|
||||
const [filteredFiles, setFilteredFiles] = useState<MentionableFile[]>([]);
|
||||
const [showFileDropdown, setShowFileDropdown] = useState(false);
|
||||
const [selectedFileIndex, setSelectedFileIndex] = useState(-1);
|
||||
const [cursorPosition, setCursorPosition] = useState(0);
|
||||
const [atSymbolPosition, setAtSymbolPosition] = useState(-1);
|
||||
|
||||
useEffect(() => {
|
||||
const abortController = new AbortController();
|
||||
|
||||
const fetchProjectFiles = async () => {
|
||||
const projectName = selectedProject?.name;
|
||||
setFileList([]);
|
||||
setFilteredFiles([]);
|
||||
if (!projectName) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const response = await api.getFiles(projectName, { signal: abortController.signal });
|
||||
if (!response.ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
const files = (await response.json()) as ProjectFileNode[];
|
||||
setFileList(flattenFileTree(files));
|
||||
} catch (error) {
|
||||
// Ignore aborts from rapid project switches; we only care about the latest request.
|
||||
if ((error as { name?: string })?.name === 'AbortError') {
|
||||
return;
|
||||
}
|
||||
console.error('Error fetching files:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchProjectFiles();
|
||||
return () => {
|
||||
abortController.abort();
|
||||
};
|
||||
}, [selectedProject?.name]);
|
||||
|
||||
useEffect(() => {
|
||||
const textBeforeCursor = input.slice(0, cursorPosition);
|
||||
const lastAtIndex = textBeforeCursor.lastIndexOf('@');
|
||||
|
||||
if (lastAtIndex === -1) {
|
||||
setShowFileDropdown(false);
|
||||
setAtSymbolPosition(-1);
|
||||
return;
|
||||
}
|
||||
|
||||
const textAfterAt = textBeforeCursor.slice(lastAtIndex + 1);
|
||||
if (textAfterAt.includes(' ')) {
|
||||
setShowFileDropdown(false);
|
||||
setAtSymbolPosition(-1);
|
||||
return;
|
||||
}
|
||||
|
||||
setAtSymbolPosition(lastAtIndex);
|
||||
setShowFileDropdown(true);
|
||||
setSelectedFileIndex(-1);
|
||||
|
||||
const matchingFiles = fileList
|
||||
.filter(
|
||||
(file) =>
|
||||
file.name.toLowerCase().includes(textAfterAt.toLowerCase()) ||
|
||||
file.path.toLowerCase().includes(textAfterAt.toLowerCase()),
|
||||
)
|
||||
.slice(0, 10);
|
||||
|
||||
setFilteredFiles(matchingFiles);
|
||||
}, [input, cursorPosition, fileList]);
|
||||
|
||||
const activeFileMentions = useMemo(() => {
|
||||
if (!input || fileMentions.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return fileMentions.filter((path) => input.includes(path));
|
||||
}, [fileMentions, input]);
|
||||
|
||||
const sortedFileMentions = useMemo(() => {
|
||||
if (activeFileMentions.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const uniqueMentions = Array.from(new Set(activeFileMentions));
|
||||
return uniqueMentions.sort((mentionA, mentionB) => mentionB.length - mentionA.length);
|
||||
}, [activeFileMentions]);
|
||||
|
||||
const fileMentionRegex = useMemo(() => {
|
||||
if (sortedFileMentions.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const pattern = sortedFileMentions.map(escapeRegExp).join('|');
|
||||
return new RegExp(`(${pattern})`, 'g');
|
||||
}, [sortedFileMentions]);
|
||||
|
||||
const fileMentionSet = useMemo(() => new Set(sortedFileMentions), [sortedFileMentions]);
|
||||
|
||||
const renderInputWithMentions = useCallback(
|
||||
(text: string) => {
|
||||
if (!text) {
|
||||
return '';
|
||||
}
|
||||
if (!fileMentionRegex) {
|
||||
return text;
|
||||
}
|
||||
|
||||
const parts = text.split(fileMentionRegex);
|
||||
return parts.map((part, index) =>
|
||||
fileMentionSet.has(part) ? (
|
||||
<span
|
||||
key={`mention-${index}`}
|
||||
className="bg-blue-200/70 -ml-0.5 dark:bg-blue-300/40 px-0.5 rounded-md box-decoration-clone text-transparent"
|
||||
>
|
||||
{part}
|
||||
</span>
|
||||
) : (
|
||||
<span key={`text-${index}`}>{part}</span>
|
||||
),
|
||||
);
|
||||
},
|
||||
[fileMentionRegex, fileMentionSet],
|
||||
);
|
||||
|
||||
const selectFile = useCallback(
|
||||
(file: MentionableFile) => {
|
||||
const textBeforeAt = input.slice(0, atSymbolPosition);
|
||||
const textAfterAtQuery = input.slice(atSymbolPosition);
|
||||
const spaceIndex = textAfterAtQuery.indexOf(' ');
|
||||
const textAfterQuery = spaceIndex !== -1 ? textAfterAtQuery.slice(spaceIndex) : '';
|
||||
|
||||
const newInput = `${textBeforeAt}${file.path} ${textAfterQuery}`;
|
||||
const newCursorPosition = textBeforeAt.length + file.path.length + 1;
|
||||
|
||||
if (textareaRef.current && !textareaRef.current.matches(':focus')) {
|
||||
textareaRef.current.focus();
|
||||
}
|
||||
|
||||
setInput(newInput);
|
||||
setCursorPosition(newCursorPosition);
|
||||
setFileMentions((previousMentions) =>
|
||||
previousMentions.includes(file.path) ? previousMentions : [...previousMentions, file.path],
|
||||
);
|
||||
|
||||
setShowFileDropdown(false);
|
||||
setAtSymbolPosition(-1);
|
||||
|
||||
if (!textareaRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
if (!textareaRef.current) {
|
||||
return;
|
||||
}
|
||||
textareaRef.current.setSelectionRange(newCursorPosition, newCursorPosition);
|
||||
if (!textareaRef.current.matches(':focus')) {
|
||||
textareaRef.current.focus();
|
||||
}
|
||||
});
|
||||
},
|
||||
[input, atSymbolPosition, textareaRef, setInput],
|
||||
);
|
||||
|
||||
const handleFileMentionsKeyDown = useCallback(
|
||||
(event: KeyboardEvent<HTMLTextAreaElement>): boolean => {
|
||||
if (!showFileDropdown || filteredFiles.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (event.key === 'ArrowDown') {
|
||||
event.preventDefault();
|
||||
setSelectedFileIndex((previousIndex) =>
|
||||
previousIndex < filteredFiles.length - 1 ? previousIndex + 1 : 0,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (event.key === 'ArrowUp') {
|
||||
event.preventDefault();
|
||||
setSelectedFileIndex((previousIndex) =>
|
||||
previousIndex > 0 ? previousIndex - 1 : filteredFiles.length - 1,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (event.key === 'Tab' || event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
if (selectedFileIndex >= 0) {
|
||||
selectFile(filteredFiles[selectedFileIndex]);
|
||||
} else if (filteredFiles.length > 0) {
|
||||
selectFile(filteredFiles[0]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
setShowFileDropdown(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
[showFileDropdown, filteredFiles, selectedFileIndex, selectFile],
|
||||
);
|
||||
|
||||
return {
|
||||
showFileDropdown,
|
||||
filteredFiles,
|
||||
selectedFileIndex,
|
||||
renderInputWithMentions,
|
||||
selectFile,
|
||||
setCursorPosition,
|
||||
handleFileMentionsKeyDown,
|
||||
};
|
||||
}
|
||||
375
src/components/chat/hooks/useSlashCommands.ts
Normal file
375
src/components/chat/hooks/useSlashCommands.ts
Normal file
@@ -0,0 +1,375 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { Dispatch, KeyboardEvent, RefObject, SetStateAction } from 'react';
|
||||
import Fuse from 'fuse.js';
|
||||
import { authenticatedFetch } from '../../../utils/api';
|
||||
import { safeLocalStorage } from '../utils/chatStorage';
|
||||
import type { Project } from '../../../types/app';
|
||||
|
||||
const COMMAND_QUERY_DEBOUNCE_MS = 150;
|
||||
|
||||
export interface SlashCommand {
|
||||
name: string;
|
||||
description?: string;
|
||||
namespace?: string;
|
||||
path?: string;
|
||||
type?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
interface UseSlashCommandsOptions {
|
||||
selectedProject: Project | null;
|
||||
input: string;
|
||||
setInput: Dispatch<SetStateAction<string>>;
|
||||
textareaRef: RefObject<HTMLTextAreaElement>;
|
||||
onExecuteCommand: (command: SlashCommand) => void | Promise<void>;
|
||||
}
|
||||
|
||||
const getCommandHistoryKey = (projectName: string) => `command_history_${projectName}`;
|
||||
|
||||
const readCommandHistory = (projectName: string): Record<string, number> => {
|
||||
const history = safeLocalStorage.getItem(getCommandHistoryKey(projectName));
|
||||
if (!history) {
|
||||
return {};
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(history);
|
||||
} catch (error) {
|
||||
console.error('Error parsing command history:', error);
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
const saveCommandHistory = (projectName: string, history: Record<string, number>) => {
|
||||
safeLocalStorage.setItem(getCommandHistoryKey(projectName), JSON.stringify(history));
|
||||
};
|
||||
|
||||
const isPromiseLike = (value: unknown): value is Promise<unknown> =>
|
||||
Boolean(value) && typeof (value as Promise<unknown>).then === 'function';
|
||||
|
||||
export function useSlashCommands({
|
||||
selectedProject,
|
||||
input,
|
||||
setInput,
|
||||
textareaRef,
|
||||
onExecuteCommand,
|
||||
}: UseSlashCommandsOptions) {
|
||||
const [slashCommands, setSlashCommands] = useState<SlashCommand[]>([]);
|
||||
const [filteredCommands, setFilteredCommands] = useState<SlashCommand[]>([]);
|
||||
const [showCommandMenu, setShowCommandMenu] = useState(false);
|
||||
const [commandQuery, setCommandQuery] = useState('');
|
||||
const [selectedCommandIndex, setSelectedCommandIndex] = useState(-1);
|
||||
const [slashPosition, setSlashPosition] = useState(-1);
|
||||
|
||||
const commandQueryTimerRef = useRef<number | null>(null);
|
||||
|
||||
const clearCommandQueryTimer = useCallback(() => {
|
||||
if (commandQueryTimerRef.current !== null) {
|
||||
window.clearTimeout(commandQueryTimerRef.current);
|
||||
commandQueryTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const resetCommandMenuState = useCallback(() => {
|
||||
setShowCommandMenu(false);
|
||||
setSlashPosition(-1);
|
||||
setCommandQuery('');
|
||||
setSelectedCommandIndex(-1);
|
||||
clearCommandQueryTimer();
|
||||
}, [clearCommandQueryTimer]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchCommands = async () => {
|
||||
if (!selectedProject) {
|
||||
setSlashCommands([]);
|
||||
setFilteredCommands([]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await authenticatedFetch('/api/commands/list', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
projectPath: selectedProject.path,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch commands');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const allCommands: SlashCommand[] = [
|
||||
...((data.builtIn || []) as SlashCommand[]).map((command) => ({
|
||||
...command,
|
||||
type: 'built-in',
|
||||
})),
|
||||
...((data.custom || []) as SlashCommand[]).map((command) => ({
|
||||
...command,
|
||||
type: 'custom',
|
||||
})),
|
||||
];
|
||||
|
||||
const parsedHistory = readCommandHistory(selectedProject.name);
|
||||
const sortedCommands = [...allCommands].sort((commandA, commandB) => {
|
||||
const commandAUsage = parsedHistory[commandA.name] || 0;
|
||||
const commandBUsage = parsedHistory[commandB.name] || 0;
|
||||
return commandBUsage - commandAUsage;
|
||||
});
|
||||
|
||||
setSlashCommands(sortedCommands);
|
||||
} catch (error) {
|
||||
console.error('Error fetching slash commands:', error);
|
||||
setSlashCommands([]);
|
||||
}
|
||||
};
|
||||
|
||||
fetchCommands();
|
||||
}, [selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!showCommandMenu) {
|
||||
setSelectedCommandIndex(-1);
|
||||
}
|
||||
}, [showCommandMenu]);
|
||||
|
||||
const fuse = useMemo(() => {
|
||||
if (!slashCommands.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Fuse(slashCommands, {
|
||||
keys: [
|
||||
{ name: 'name', weight: 2 },
|
||||
{ name: 'description', weight: 1 },
|
||||
],
|
||||
threshold: 0.4,
|
||||
includeScore: true,
|
||||
minMatchCharLength: 1,
|
||||
});
|
||||
}, [slashCommands]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!commandQuery) {
|
||||
setFilteredCommands(slashCommands);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!fuse) {
|
||||
setFilteredCommands([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const results = fuse.search(commandQuery);
|
||||
setFilteredCommands(results.map((result) => result.item));
|
||||
}, [commandQuery, slashCommands, fuse]);
|
||||
|
||||
const frequentCommands = useMemo(() => {
|
||||
if (!selectedProject || slashCommands.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const parsedHistory = readCommandHistory(selectedProject.name);
|
||||
|
||||
return slashCommands
|
||||
.map((command) => ({
|
||||
...command,
|
||||
usageCount: parsedHistory[command.name] || 0,
|
||||
}))
|
||||
.filter((command) => command.usageCount > 0)
|
||||
.sort((commandA, commandB) => commandB.usageCount - commandA.usageCount)
|
||||
.slice(0, 5);
|
||||
}, [selectedProject, slashCommands]);
|
||||
|
||||
const trackCommandUsage = useCallback(
|
||||
(command: SlashCommand) => {
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedHistory = readCommandHistory(selectedProject.name);
|
||||
parsedHistory[command.name] = (parsedHistory[command.name] || 0) + 1;
|
||||
saveCommandHistory(selectedProject.name, parsedHistory);
|
||||
},
|
||||
[selectedProject],
|
||||
);
|
||||
|
||||
const selectCommandFromKeyboard = useCallback(
|
||||
(command: SlashCommand) => {
|
||||
const textBeforeSlash = input.slice(0, slashPosition);
|
||||
const textAfterSlash = input.slice(slashPosition);
|
||||
const spaceIndex = textAfterSlash.indexOf(' ');
|
||||
const textAfterQuery = spaceIndex !== -1 ? textAfterSlash.slice(spaceIndex) : '';
|
||||
const newInput = `${textBeforeSlash}${command.name} ${textAfterQuery}`;
|
||||
|
||||
setInput(newInput);
|
||||
resetCommandMenuState();
|
||||
|
||||
const executionResult = onExecuteCommand(command);
|
||||
if (isPromiseLike(executionResult)) {
|
||||
executionResult.catch(() => {
|
||||
// Keep behavior silent; execution errors are handled by caller.
|
||||
});
|
||||
}
|
||||
},
|
||||
[input, slashPosition, setInput, resetCommandMenuState, onExecuteCommand],
|
||||
);
|
||||
|
||||
const handleCommandSelect = useCallback(
|
||||
(command: SlashCommand | null, index: number, isHover: boolean) => {
|
||||
if (!command || !selectedProject) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isHover) {
|
||||
setSelectedCommandIndex(index);
|
||||
return;
|
||||
}
|
||||
|
||||
trackCommandUsage(command);
|
||||
const executionResult = onExecuteCommand(command);
|
||||
|
||||
if (isPromiseLike(executionResult)) {
|
||||
executionResult.then(() => {
|
||||
resetCommandMenuState();
|
||||
});
|
||||
executionResult.catch(() => {
|
||||
// Keep behavior silent; execution errors are handled by caller.
|
||||
});
|
||||
} else {
|
||||
resetCommandMenuState();
|
||||
}
|
||||
},
|
||||
[selectedProject, trackCommandUsage, onExecuteCommand, resetCommandMenuState],
|
||||
);
|
||||
|
||||
const handleToggleCommandMenu = useCallback(() => {
|
||||
const isOpening = !showCommandMenu;
|
||||
setShowCommandMenu(isOpening);
|
||||
setCommandQuery('');
|
||||
setSelectedCommandIndex(-1);
|
||||
|
||||
if (isOpening) {
|
||||
setFilteredCommands(slashCommands);
|
||||
}
|
||||
|
||||
textareaRef.current?.focus();
|
||||
}, [showCommandMenu, slashCommands, textareaRef]);
|
||||
|
||||
const handleCommandInputChange = useCallback(
|
||||
(newValue: string, cursorPos: number) => {
|
||||
if (!newValue.trim()) {
|
||||
resetCommandMenuState();
|
||||
return;
|
||||
}
|
||||
|
||||
const textBeforeCursor = newValue.slice(0, cursorPos);
|
||||
const backticksBefore = (textBeforeCursor.match(/```/g) || []).length;
|
||||
const inCodeBlock = backticksBefore % 2 === 1;
|
||||
|
||||
if (inCodeBlock) {
|
||||
resetCommandMenuState();
|
||||
return;
|
||||
}
|
||||
|
||||
const slashPattern = /(^|\s)\/(\S*)$/;
|
||||
const match = textBeforeCursor.match(slashPattern);
|
||||
|
||||
if (!match) {
|
||||
resetCommandMenuState();
|
||||
return;
|
||||
}
|
||||
|
||||
const slashPos = (match.index || 0) + match[1].length;
|
||||
const query = match[2];
|
||||
|
||||
setSlashPosition(slashPos);
|
||||
setShowCommandMenu(true);
|
||||
setSelectedCommandIndex(-1);
|
||||
|
||||
clearCommandQueryTimer();
|
||||
commandQueryTimerRef.current = window.setTimeout(() => {
|
||||
setCommandQuery(query);
|
||||
}, COMMAND_QUERY_DEBOUNCE_MS);
|
||||
},
|
||||
[resetCommandMenuState, clearCommandQueryTimer],
|
||||
);
|
||||
|
||||
const handleCommandMenuKeyDown = useCallback(
|
||||
(event: KeyboardEvent<HTMLTextAreaElement>): boolean => {
|
||||
if (!showCommandMenu) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!filteredCommands.length) {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
resetCommandMenuState();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (event.key === 'ArrowDown') {
|
||||
event.preventDefault();
|
||||
setSelectedCommandIndex((previousIndex) =>
|
||||
previousIndex < filteredCommands.length - 1 ? previousIndex + 1 : 0,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (event.key === 'ArrowUp') {
|
||||
event.preventDefault();
|
||||
setSelectedCommandIndex((previousIndex) =>
|
||||
previousIndex > 0 ? previousIndex - 1 : filteredCommands.length - 1,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (event.key === 'Tab' || event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
if (selectedCommandIndex >= 0) {
|
||||
selectCommandFromKeyboard(filteredCommands[selectedCommandIndex]);
|
||||
} else if (filteredCommands.length > 0) {
|
||||
selectCommandFromKeyboard(filteredCommands[0]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
resetCommandMenuState();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
[showCommandMenu, filteredCommands, resetCommandMenuState, selectCommandFromKeyboard, selectedCommandIndex],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
clearCommandQueryTimer();
|
||||
},
|
||||
[clearCommandQueryTimer],
|
||||
);
|
||||
|
||||
return {
|
||||
slashCommands,
|
||||
slashCommandsCount: slashCommands.length,
|
||||
filteredCommands,
|
||||
frequentCommands,
|
||||
commandQuery,
|
||||
showCommandMenu,
|
||||
selectedCommandIndex,
|
||||
resetCommandMenuState,
|
||||
handleCommandSelect,
|
||||
handleToggleCommandMenu,
|
||||
handleCommandInputChange,
|
||||
handleCommandMenuKeyDown,
|
||||
};
|
||||
}
|
||||
224
src/components/chat/tools/README.md
Normal file
224
src/components/chat/tools/README.md
Normal file
@@ -0,0 +1,224 @@
|
||||
# Tool Rendering System
|
||||
|
||||
## Overview
|
||||
|
||||
Config-driven architecture for rendering tool executions in chat. All tool display behavior is defined in `toolConfigs.ts` — no scattered conditionals. Two base display patterns: **OneLineDisplay** for compact tools, **CollapsibleDisplay** for tools with expandable content.
|
||||
|
||||
Non-error tool results route through `ToolRenderer` with `mode="result"` (single source of truth). Error results are handled inline in `MessageComponent` with a red error box.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
tools/
|
||||
├── components/
|
||||
│ ├── OneLineDisplay.tsx # Compact one-line tool display
|
||||
│ ├── CollapsibleDisplay.tsx # Expandable tool display (uses children pattern)
|
||||
│ ├── CollapsibleSection.tsx # <details>/<summary> wrapper
|
||||
│ ├── ContentRenderers/
|
||||
│ │ ├── DiffViewer.tsx # File diff viewer (memoized)
|
||||
│ │ ├── MarkdownContent.tsx # Markdown renderer
|
||||
│ │ ├── FileListContent.tsx # Comma-separated clickable file list
|
||||
│ │ ├── TodoListContent.tsx # Todo items with status badges
|
||||
│ │ ├── TaskListContent.tsx # Task tracker with progress bar
|
||||
│ │ └── TextContent.tsx # Plain text / JSON / code
|
||||
├── configs/
|
||||
│ └── toolConfigs.ts # All tool configs + ToolDisplayConfig type
|
||||
├── ToolRenderer.tsx # Main router (React.memo wrapped)
|
||||
└── README.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Display Patterns
|
||||
|
||||
### OneLineDisplay
|
||||
|
||||
Used by: Bash, Read, Grep, Glob, TodoRead, TaskCreate, TaskUpdate, TaskGet
|
||||
|
||||
Renders as a single line with `border-l-2` accent. Supports multiple rendering modes based on `action`:
|
||||
|
||||
- **terminal** (`style: 'terminal'`) — Dark pill around command text, green `$` prompt
|
||||
- **open-file** — Shows filename only (truncated from full path), clickable to open
|
||||
- **jump-to-results** — Shows pattern with anchor link to result section
|
||||
- **copy** — Shows value with hover copy button
|
||||
- **none** — Plain display
|
||||
|
||||
```tsx
|
||||
<OneLineDisplay
|
||||
toolName="Read"
|
||||
icon="terminal" // Optional icon or style keyword
|
||||
label="Read" // Tool label
|
||||
value="/path/to/file.ts" // Main display value
|
||||
secondary="description" // Optional secondary text (italic)
|
||||
action="open-file" // Action type
|
||||
onAction={() => ...} // Click handler
|
||||
colorScheme={{ // Per-tool colors
|
||||
primary: 'text-...',
|
||||
border: 'border-...',
|
||||
icon: 'text-...'
|
||||
}}
|
||||
resultId="tool-result-x" // For jump-to-results anchor
|
||||
toolResult={...} // For conditional jump arrow
|
||||
toolId="x" // Tool use ID
|
||||
/>
|
||||
```
|
||||
|
||||
### CollapsibleDisplay
|
||||
|
||||
Used by: Edit, Write, ApplyPatch, Grep/Glob results, TodoWrite, TaskList/TaskGet results, ExitPlanMode, Default
|
||||
|
||||
Wraps `CollapsibleSection` (`<details>`/`<summary>`) with a `border-l-2` accent colored by tool category. Accepts **children** directly (not contentProps).
|
||||
|
||||
```tsx
|
||||
<CollapsibleDisplay
|
||||
toolName="Edit"
|
||||
toolId="123"
|
||||
title="filename.ts" // Section title (can be clickable)
|
||||
defaultOpen={false}
|
||||
onTitleClick={() => ...} // Makes title a clickable link (for edit tools)
|
||||
showRawParameters={true} // Show raw JSON toggle
|
||||
rawContent="..." // Raw JSON string
|
||||
toolCategory="edit" // Drives border color
|
||||
>
|
||||
<DiffViewer {...} /> // Content as children
|
||||
</CollapsibleDisplay>
|
||||
```
|
||||
|
||||
**Tool category colors** (via `border-l-2`):
|
||||
| Category | Tools | Color |
|
||||
|----------|-------|-------|
|
||||
| `edit` | Edit, Write, ApplyPatch | amber |
|
||||
| `bash` | Bash | green |
|
||||
| `search` | Grep, Glob | gray |
|
||||
| `todo` | TodoWrite, TodoRead | violet |
|
||||
| `task` | TaskCreate/Update/List/Get | violet |
|
||||
| `plan` | ExitPlanMode | indigo |
|
||||
| `default` | everything else | neutral gray |
|
||||
|
||||
---
|
||||
|
||||
## Content Renderers
|
||||
|
||||
Specialized components for different content types, rendered as children of `CollapsibleDisplay`:
|
||||
|
||||
| contentType | Component | Used by |
|
||||
|---|---|---|
|
||||
| `diff` | `DiffViewer` | Edit, Write, ApplyPatch |
|
||||
| `markdown` | `MarkdownContent` | ExitPlanMode |
|
||||
| `file-list` | `FileListContent` | Grep/Glob results |
|
||||
| `todo-list` | `TodoListContent` | TodoWrite, TodoRead |
|
||||
| `task` | `TaskListContent` | TaskList, TaskGet results |
|
||||
| `text` | `TextContent` | Default fallback |
|
||||
| `success-message` | inline SVG | TodoWrite result |
|
||||
|
||||
---
|
||||
|
||||
## Adding a New Tool
|
||||
|
||||
**Step 1:** Add config to `configs/toolConfigs.ts`
|
||||
|
||||
```typescript
|
||||
MyTool: {
|
||||
input: {
|
||||
type: 'one-line', // or 'collapsible'
|
||||
label: 'MyTool',
|
||||
getValue: (input) => input.some_field,
|
||||
action: 'open-file',
|
||||
colorScheme: {
|
||||
primary: 'text-purple-600 dark:text-purple-400',
|
||||
border: 'border-purple-400 dark:border-purple-500'
|
||||
}
|
||||
},
|
||||
result: {
|
||||
hideOnSuccess: true // Only show errors
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2:** If the tool needs a category color, add it to `getToolCategory()` in `ToolRenderer.tsx`.
|
||||
|
||||
**That's it.** The ToolRenderer auto-routes based on config.
|
||||
|
||||
---
|
||||
|
||||
## Configuration Reference
|
||||
|
||||
### ToolDisplayConfig
|
||||
|
||||
```typescript
|
||||
interface ToolDisplayConfig {
|
||||
input: {
|
||||
type: 'one-line' | 'collapsible' | 'hidden';
|
||||
|
||||
// One-line
|
||||
icon?: string;
|
||||
label?: string;
|
||||
getValue?: (input) => string;
|
||||
getSecondary?: (input) => string | undefined;
|
||||
action?: 'copy' | 'open-file' | 'jump-to-results' | 'none';
|
||||
style?: string; // 'terminal' for Bash
|
||||
wrapText?: boolean;
|
||||
colorScheme?: {
|
||||
primary?: string;
|
||||
secondary?: string;
|
||||
background?: string;
|
||||
border?: string;
|
||||
icon?: string;
|
||||
};
|
||||
|
||||
// Collapsible
|
||||
title?: string | ((input) => string);
|
||||
defaultOpen?: boolean;
|
||||
contentType?: 'diff' | 'markdown' | 'file-list' | 'todo-list' | 'text' | 'task';
|
||||
getContentProps?: (input, helpers?) => any;
|
||||
actionButton?: 'none';
|
||||
};
|
||||
|
||||
result?: {
|
||||
hidden?: boolean; // Never show
|
||||
hideOnSuccess?: boolean; // Only show errors
|
||||
type?: 'one-line' | 'collapsible' | 'special';
|
||||
title?: string | ((result) => string);
|
||||
defaultOpen?: boolean;
|
||||
contentType?: 'markdown' | 'file-list' | 'todo-list' | 'text' | 'success-message' | 'task';
|
||||
getMessage?: (result) => string;
|
||||
getContentProps?: (result) => any;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## All Configured Tools
|
||||
|
||||
| Tool | Input | Result | Notes |
|
||||
|------|-------|--------|-------|
|
||||
| Bash | terminal one-line | hide success | Dark command pill, green accent |
|
||||
| Read | one-line (open-file) | hidden | Shows filename, clicks to open |
|
||||
| Edit | collapsible (diff) | hide success | Amber border, clickable filename |
|
||||
| Write | collapsible (diff) | hide success | "New" badge on diff |
|
||||
| ApplyPatch | collapsible (diff) | hide success | "Patch" badge on diff |
|
||||
| Grep | one-line (jump) | collapsible file-list | Collapsed by default |
|
||||
| Glob | one-line (jump) | collapsible file-list | Collapsed by default |
|
||||
| TodoWrite | collapsible (todo-list) | success message | |
|
||||
| TodoRead | one-line | collapsible todo-list | |
|
||||
| TaskCreate | one-line | hide success | Shows task subject |
|
||||
| TaskUpdate | one-line | hide success | Shows `#id → status` |
|
||||
| TaskList | one-line | collapsible task | Progress bar, status icons |
|
||||
| TaskGet | one-line | collapsible task | Task details with status |
|
||||
| ExitPlanMode | collapsible (markdown) | collapsible markdown | Also registered as `exit_plan_mode` |
|
||||
| Default | collapsible (code) | collapsible text | Fallback for unknown tools |
|
||||
|
||||
---
|
||||
|
||||
## Performance
|
||||
|
||||
- **ToolRenderer** is wrapped with `React.memo` — skips re-render when props haven't changed
|
||||
- **parsedData** is memoized with `useMemo` — JSON parsing only runs when input changes
|
||||
- **DiffViewer** memoizes `createDiff()` — expensive diff computation cached
|
||||
- **MessageComponent** caches `localStorage` reads and timestamp formatting via `useMemo`
|
||||
- Tool results route through `ToolRenderer` (no duplicate rendering paths)
|
||||
- `CollapsibleDisplay` uses children pattern (no wasteful contentProps indirection)
|
||||
- Configs are static module-level objects — zero runtime overhead for lookups
|
||||
209
src/components/chat/tools/ToolRenderer.tsx
Normal file
209
src/components/chat/tools/ToolRenderer.tsx
Normal file
@@ -0,0 +1,209 @@
|
||||
import React, { memo, useMemo, useCallback } from 'react';
|
||||
import { getToolConfig } from './configs/toolConfigs';
|
||||
import { OneLineDisplay, CollapsibleDisplay, DiffViewer, MarkdownContent, FileListContent, TodoListContent, TaskListContent, TextContent } from './components';
|
||||
import type { Project } from '../../../types/app';
|
||||
|
||||
type DiffLine = {
|
||||
type: string;
|
||||
content: string;
|
||||
lineNum: number;
|
||||
};
|
||||
|
||||
interface ToolRendererProps {
|
||||
toolName: string;
|
||||
toolInput: any;
|
||||
toolResult?: any;
|
||||
toolId?: string;
|
||||
mode: 'input' | 'result';
|
||||
onFileOpen?: (filePath: string, diffInfo?: any) => void;
|
||||
createDiff?: (oldStr: string, newStr: string) => DiffLine[];
|
||||
selectedProject?: Project | null;
|
||||
autoExpandTools?: boolean;
|
||||
showRawParameters?: boolean;
|
||||
rawToolInput?: string;
|
||||
}
|
||||
|
||||
function getToolCategory(toolName: string): string {
|
||||
if (['Edit', 'Write', 'ApplyPatch'].includes(toolName)) return 'edit';
|
||||
if (['Grep', 'Glob'].includes(toolName)) return 'search';
|
||||
if (toolName === 'Bash') return 'bash';
|
||||
if (['TodoWrite', 'TodoRead'].includes(toolName)) return 'todo';
|
||||
if (['TaskCreate', 'TaskUpdate', 'TaskList', 'TaskGet'].includes(toolName)) return 'task';
|
||||
if (toolName === 'Task') return 'agent'; // Subagent task
|
||||
if (toolName === 'exit_plan_mode' || toolName === 'ExitPlanMode') return 'plan';
|
||||
return 'default';
|
||||
}
|
||||
|
||||
/**
|
||||
* Main tool renderer router
|
||||
* Routes to OneLineDisplay or CollapsibleDisplay based on tool config
|
||||
*/
|
||||
export const ToolRenderer: React.FC<ToolRendererProps> = memo(({
|
||||
toolName,
|
||||
toolInput,
|
||||
toolResult,
|
||||
toolId,
|
||||
mode,
|
||||
onFileOpen,
|
||||
createDiff,
|
||||
selectedProject,
|
||||
autoExpandTools = false,
|
||||
showRawParameters = false,
|
||||
rawToolInput
|
||||
}) => {
|
||||
const config = getToolConfig(toolName);
|
||||
const displayConfig: any = mode === 'input' ? config.input : config.result;
|
||||
|
||||
const parsedData = useMemo(() => {
|
||||
try {
|
||||
const rawData = mode === 'input' ? toolInput : toolResult;
|
||||
return typeof rawData === 'string' ? JSON.parse(rawData) : rawData;
|
||||
} catch {
|
||||
return mode === 'input' ? toolInput : toolResult;
|
||||
}
|
||||
}, [mode, toolInput, toolResult]);
|
||||
|
||||
const handleAction = useCallback(() => {
|
||||
if (displayConfig?.action === 'open-file' && onFileOpen) {
|
||||
const value = displayConfig.getValue?.(parsedData) || '';
|
||||
onFileOpen(value);
|
||||
}
|
||||
}, [displayConfig, parsedData, onFileOpen]);
|
||||
|
||||
// Keep hooks above this guard so hook call order stays stable across renders.
|
||||
if (!displayConfig) return null;
|
||||
|
||||
if (displayConfig.type === 'one-line') {
|
||||
const value = displayConfig.getValue?.(parsedData) || '';
|
||||
const secondary = displayConfig.getSecondary?.(parsedData);
|
||||
|
||||
return (
|
||||
<OneLineDisplay
|
||||
toolName={toolName}
|
||||
toolResult={toolResult}
|
||||
toolId={toolId}
|
||||
icon={displayConfig.icon}
|
||||
label={displayConfig.label}
|
||||
value={value}
|
||||
secondary={secondary}
|
||||
action={displayConfig.action}
|
||||
onAction={handleAction}
|
||||
style={displayConfig.style}
|
||||
wrapText={displayConfig.wrapText}
|
||||
colorScheme={displayConfig.colorScheme}
|
||||
resultId={mode === 'input' ? `tool-result-${toolId}` : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (displayConfig.type === 'collapsible') {
|
||||
const title = typeof displayConfig.title === 'function'
|
||||
? displayConfig.title(parsedData)
|
||||
: displayConfig.title || 'Details';
|
||||
|
||||
const defaultOpen = displayConfig.defaultOpen !== undefined
|
||||
? displayConfig.defaultOpen
|
||||
: autoExpandTools;
|
||||
|
||||
const contentProps = displayConfig.getContentProps?.(parsedData, {
|
||||
selectedProject,
|
||||
createDiff,
|
||||
onFileOpen
|
||||
}) || {};
|
||||
|
||||
// Build the content component based on contentType
|
||||
let contentComponent: React.ReactNode = null;
|
||||
|
||||
switch (displayConfig.contentType) {
|
||||
case 'diff':
|
||||
if (createDiff) {
|
||||
contentComponent = (
|
||||
<DiffViewer
|
||||
{...contentProps}
|
||||
createDiff={createDiff}
|
||||
onFileClick={() => onFileOpen?.(contentProps.filePath)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'markdown':
|
||||
contentComponent = <MarkdownContent content={contentProps.content || ''} />;
|
||||
break;
|
||||
|
||||
case 'file-list':
|
||||
contentComponent = (
|
||||
<FileListContent
|
||||
files={contentProps.files || []}
|
||||
onFileClick={onFileOpen}
|
||||
title={contentProps.title}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case 'todo-list':
|
||||
if (contentProps.todos?.length > 0) {
|
||||
contentComponent = (
|
||||
<TodoListContent
|
||||
todos={contentProps.todos}
|
||||
isResult={contentProps.isResult}
|
||||
/>
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'task':
|
||||
contentComponent = <TaskListContent content={contentProps.content || ''} />;
|
||||
break;
|
||||
|
||||
case 'text':
|
||||
contentComponent = (
|
||||
<TextContent
|
||||
content={contentProps.content || ''}
|
||||
format={contentProps.format || 'plain'}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case 'success-message': {
|
||||
const msg = displayConfig.getMessage?.(parsedData) || 'Success';
|
||||
contentComponent = (
|
||||
<div className="flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400">
|
||||
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
{msg}
|
||||
</div>
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// For edit tools, make the title (filename) clickable to open the file
|
||||
const handleTitleClick = (toolName === 'Edit' || toolName === 'Write' || toolName === 'ApplyPatch') && contentProps.filePath && onFileOpen
|
||||
? () => onFileOpen(contentProps.filePath, {
|
||||
old_string: contentProps.oldContent,
|
||||
new_string: contentProps.newContent
|
||||
})
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<CollapsibleDisplay
|
||||
toolName={toolName}
|
||||
toolId={toolId}
|
||||
title={title}
|
||||
defaultOpen={defaultOpen}
|
||||
onTitleClick={handleTitleClick}
|
||||
showRawParameters={mode === 'input' && showRawParameters}
|
||||
rawContent={rawToolInput}
|
||||
toolCategory={getToolCategory(toolName)}
|
||||
>
|
||||
{contentComponent}
|
||||
</CollapsibleDisplay>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
ToolRenderer.displayName = 'ToolRenderer';
|
||||
76
src/components/chat/tools/components/CollapsibleDisplay.tsx
Normal file
76
src/components/chat/tools/components/CollapsibleDisplay.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import React from 'react';
|
||||
import { CollapsibleSection } from './CollapsibleSection';
|
||||
|
||||
interface CollapsibleDisplayProps {
|
||||
toolName: string;
|
||||
toolId?: string;
|
||||
title: string;
|
||||
defaultOpen?: boolean;
|
||||
action?: React.ReactNode;
|
||||
onTitleClick?: () => void;
|
||||
children: React.ReactNode;
|
||||
showRawParameters?: boolean;
|
||||
rawContent?: string;
|
||||
className?: string;
|
||||
toolCategory?: string;
|
||||
}
|
||||
|
||||
const borderColorMap: Record<string, string> = {
|
||||
edit: 'border-l-amber-500 dark:border-l-amber-400',
|
||||
search: 'border-l-gray-400 dark:border-l-gray-500',
|
||||
bash: 'border-l-green-500 dark:border-l-green-400',
|
||||
todo: 'border-l-violet-500 dark:border-l-violet-400',
|
||||
task: 'border-l-violet-500 dark:border-l-violet-400',
|
||||
agent: 'border-l-purple-500 dark:border-l-purple-400',
|
||||
plan: 'border-l-indigo-500 dark:border-l-indigo-400',
|
||||
default: 'border-l-gray-300 dark:border-l-gray-600',
|
||||
};
|
||||
|
||||
export const CollapsibleDisplay: React.FC<CollapsibleDisplayProps> = ({
|
||||
toolName,
|
||||
title,
|
||||
defaultOpen = false,
|
||||
action,
|
||||
onTitleClick,
|
||||
children,
|
||||
showRawParameters = false,
|
||||
rawContent,
|
||||
className = '',
|
||||
toolCategory
|
||||
}) => {
|
||||
// Fall back to default styling for unknown/new categories so className never includes "undefined".
|
||||
const borderColor = borderColorMap[toolCategory || 'default'] || borderColorMap.default;
|
||||
|
||||
return (
|
||||
<div className={`border-l-2 ${borderColor} pl-3 py-0.5 my-1 ${className}`}>
|
||||
<CollapsibleSection
|
||||
title={title}
|
||||
toolName={toolName}
|
||||
open={defaultOpen}
|
||||
action={action}
|
||||
onTitleClick={onTitleClick}
|
||||
>
|
||||
{children}
|
||||
|
||||
{showRawParameters && rawContent && (
|
||||
<details className="relative mt-2 group/raw">
|
||||
<summary className="flex items-center gap-1.5 text-[11px] text-gray-400 dark:text-gray-500 cursor-pointer hover:text-gray-600 dark:hover:text-gray-300 py-0.5">
|
||||
<svg
|
||||
className="w-2.5 h-2.5 transition-transform duration-150 group-open/raw: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>
|
||||
raw params
|
||||
</summary>
|
||||
<pre className="mt-1 text-[11px] bg-gray-50 dark:bg-gray-900/50 border border-gray-200/40 dark:border-gray-700/40 p-2 rounded whitespace-pre-wrap break-words overflow-hidden text-gray-600 dark:text-gray-400 font-mono">
|
||||
{rawContent}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</CollapsibleSection>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
61
src/components/chat/tools/components/CollapsibleSection.tsx
Normal file
61
src/components/chat/tools/components/CollapsibleSection.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import React from 'react';
|
||||
|
||||
interface CollapsibleSectionProps {
|
||||
title: string;
|
||||
toolName?: string;
|
||||
open?: boolean;
|
||||
action?: React.ReactNode;
|
||||
onTitleClick?: () => void;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reusable collapsible section with consistent styling
|
||||
*/
|
||||
export const CollapsibleSection: React.FC<CollapsibleSectionProps> = ({
|
||||
title,
|
||||
toolName,
|
||||
open = false,
|
||||
action,
|
||||
onTitleClick,
|
||||
children,
|
||||
className = ''
|
||||
}) => {
|
||||
return (
|
||||
<details className={`relative group/details ${className}`} open={open}>
|
||||
<summary className="flex items-center gap-1.5 text-xs cursor-pointer py-0.5 select-none">
|
||||
<svg
|
||||
className="w-3 h-3 text-gray-400 dark:text-gray-500 transition-transform duration-150 group-open/details:rotate-90 flex-shrink-0"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
{toolName && (
|
||||
<span className="font-medium text-gray-500 dark:text-gray-400 flex-shrink-0">{toolName}</span>
|
||||
)}
|
||||
{toolName && (
|
||||
<span className="text-gray-300 dark:text-gray-600 text-[10px] flex-shrink-0">/</span>
|
||||
)}
|
||||
{onTitleClick ? (
|
||||
<button
|
||||
onClick={(e) => { e.preventDefault(); e.stopPropagation(); onTitleClick(); }}
|
||||
className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 font-mono hover:underline truncate flex-1 text-left transition-colors"
|
||||
>
|
||||
{title}
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-gray-600 dark:text-gray-400 truncate flex-1">
|
||||
{title}
|
||||
</span>
|
||||
)}
|
||||
{action && <span className="flex-shrink-0 ml-1">{action}</span>}
|
||||
</summary>
|
||||
<div className="mt-1.5 pl-[18px]">
|
||||
{children}
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
import React from 'react';
|
||||
|
||||
interface FileListItem {
|
||||
path: string;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
interface FileListContentProps {
|
||||
files: string[] | FileListItem[];
|
||||
onFileClick?: (filePath: string) => void;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a compact comma-separated list of clickable file names
|
||||
* Used by: Grep/Glob results
|
||||
*/
|
||||
export const FileListContent: React.FC<FileListContentProps> = ({
|
||||
files,
|
||||
onFileClick,
|
||||
title
|
||||
}) => {
|
||||
return (
|
||||
<div>
|
||||
{title && (
|
||||
<div className="text-[11px] text-gray-500 dark:text-gray-400 mb-1">
|
||||
{title}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-x-1 gap-y-0.5 max-h-48 overflow-y-auto">
|
||||
{files.map((file, index) => {
|
||||
const filePath = typeof file === 'string' ? file : file.path;
|
||||
const fileName = filePath.split('/').pop() || filePath;
|
||||
const handleClick = typeof file === 'string'
|
||||
? () => onFileClick?.(file)
|
||||
: file.onClick;
|
||||
|
||||
return (
|
||||
<span key={index} className="inline-flex items-center">
|
||||
<button
|
||||
onClick={handleClick}
|
||||
className="text-[11px] font-mono text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline transition-colors"
|
||||
title={filePath}
|
||||
>
|
||||
{fileName}
|
||||
</button>
|
||||
{index < files.length - 1 && (
|
||||
<span className="text-gray-300 dark:text-gray-600 text-[10px] ml-1">,</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import React from 'react';
|
||||
import { Markdown } from '../../../view/subcomponents/Markdown';
|
||||
|
||||
interface MarkdownContentProps {
|
||||
content: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders markdown content with proper styling
|
||||
* Used by: exit_plan_mode, long text results, etc.
|
||||
*/
|
||||
export const MarkdownContent: React.FC<MarkdownContentProps> = ({
|
||||
content,
|
||||
className = 'mt-1 prose prose-sm max-w-none dark:prose-invert'
|
||||
}) => {
|
||||
return (
|
||||
<Markdown className={className}>
|
||||
{content}
|
||||
</Markdown>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,125 @@
|
||||
import React from 'react';
|
||||
|
||||
interface TaskItem {
|
||||
id: string;
|
||||
subject: string;
|
||||
status: 'pending' | 'in_progress' | 'completed';
|
||||
owner?: string;
|
||||
blockedBy?: string[];
|
||||
}
|
||||
|
||||
interface TaskListContentProps {
|
||||
content: string;
|
||||
}
|
||||
|
||||
function parseTaskContent(content: string): TaskItem[] {
|
||||
const tasks: TaskItem[] = [];
|
||||
const lines = content.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
// Match patterns like: #15. [in_progress] Subject here
|
||||
// or: - #15 [in_progress] Subject (owner: agent)
|
||||
// or: #15. Subject here (status: in_progress)
|
||||
const match = line.match(/#(\d+)\.?\s*(?:\[(\w+)\]\s*)?(.+?)(?:\s*\((?:owner:\s*\w+)?\))?$/);
|
||||
if (match) {
|
||||
const [, id, status, subject] = match;
|
||||
const blockedMatch = line.match(/blockedBy:\s*\[([^\]]*)\]/);
|
||||
tasks.push({
|
||||
id,
|
||||
subject: subject.trim(),
|
||||
status: (status as TaskItem['status']) || 'pending',
|
||||
blockedBy: blockedMatch ? blockedMatch[1].split(',').map(s => s.trim()).filter(Boolean) : undefined
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return tasks;
|
||||
}
|
||||
|
||||
const statusConfig = {
|
||||
completed: {
|
||||
icon: (
|
||||
<svg className="w-3.5 h-3.5 text-green-500 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
),
|
||||
textClass: 'line-through text-gray-400 dark:text-gray-500',
|
||||
badgeClass: 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 border-green-200 dark:border-green-800'
|
||||
},
|
||||
in_progress: {
|
||||
icon: (
|
||||
<svg className="w-3.5 h-3.5 text-blue-500 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
),
|
||||
textClass: 'text-gray-900 dark:text-gray-100',
|
||||
badgeClass: 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 border-blue-200 dark:border-blue-800'
|
||||
},
|
||||
pending: {
|
||||
icon: (
|
||||
<svg className="w-3.5 h-3.5 text-gray-400 dark:text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<circle cx="12" cy="12" r="9" strokeWidth={2} />
|
||||
</svg>
|
||||
),
|
||||
textClass: 'text-gray-700 dark:text-gray-300',
|
||||
badgeClass: 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 border-gray-200 dark:border-gray-700'
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders task list results with proper status icons and compact layout
|
||||
* Parses text content from TaskList/TaskGet results
|
||||
*/
|
||||
export const TaskListContent: React.FC<TaskListContentProps> = ({ content }) => {
|
||||
const tasks = parseTaskContent(content);
|
||||
|
||||
// If we couldn't parse any tasks, fall back to text display
|
||||
if (tasks.length === 0) {
|
||||
return (
|
||||
<pre className="text-[11px] font-mono text-gray-600 dark:text-gray-400 whitespace-pre-wrap">
|
||||
{content}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
const completed = tasks.filter(t => t.status === 'completed').length;
|
||||
const total = tasks.length;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-1.5">
|
||||
<span className="text-[11px] text-gray-500 dark:text-gray-400">
|
||||
{completed}/{total} completed
|
||||
</span>
|
||||
<div className="flex-1 h-1 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-green-500 dark:bg-green-400 rounded-full transition-all"
|
||||
style={{ width: `${total > 0 ? (completed / total) * 100 : 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-px">
|
||||
{tasks.map((task) => {
|
||||
const config = statusConfig[task.status] || statusConfig.pending;
|
||||
return (
|
||||
<div
|
||||
key={task.id}
|
||||
className="flex items-center gap-1.5 py-0.5 group"
|
||||
>
|
||||
<span className="flex-shrink-0">{config.icon}</span>
|
||||
<span className="text-[11px] font-mono text-gray-400 dark:text-gray-500 flex-shrink-0">
|
||||
#{task.id}
|
||||
</span>
|
||||
<span className={`text-xs truncate flex-1 ${config.textClass}`}>
|
||||
{task.subject}
|
||||
</span>
|
||||
<span className={`text-[10px] px-1 py-px rounded border flex-shrink-0 ${config.badgeClass}`}>
|
||||
{task.status.replace('_', ' ')}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import React from 'react';
|
||||
|
||||
interface TextContentProps {
|
||||
content: string;
|
||||
format?: 'plain' | 'json' | 'code';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders plain text, JSON, or code content
|
||||
* Used by: Raw parameters, generic text results, JSON responses
|
||||
*/
|
||||
export const TextContent: React.FC<TextContentProps> = ({
|
||||
content,
|
||||
format = 'plain',
|
||||
className = ''
|
||||
}) => {
|
||||
if (format === 'json') {
|
||||
let formattedJson = content;
|
||||
try {
|
||||
const parsed = JSON.parse(content);
|
||||
formattedJson = JSON.stringify(parsed, null, 2);
|
||||
} catch (e) {
|
||||
// If parsing fails, use original content
|
||||
}
|
||||
|
||||
return (
|
||||
<pre className={`mt-1 text-xs bg-gray-900 dark:bg-gray-950 text-gray-100 p-2.5 rounded overflow-x-auto font-mono ${className}`}>
|
||||
{formattedJson}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
if (format === 'code') {
|
||||
return (
|
||||
<pre className={`mt-1 text-xs bg-gray-50 dark:bg-gray-800/50 border border-gray-200/50 dark:border-gray-700/50 p-2 rounded whitespace-pre-wrap break-words overflow-hidden text-gray-700 dark:text-gray-300 font-mono ${className}`}>
|
||||
{content}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
// Plain text
|
||||
return (
|
||||
<div className={`mt-1 text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap ${className}`}>
|
||||
{content}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
import React from 'react';
|
||||
import TodoList from '../../../../TodoList';
|
||||
|
||||
interface TodoListContentProps {
|
||||
todos: Array<{
|
||||
id?: string;
|
||||
content: string;
|
||||
status: string;
|
||||
priority?: string;
|
||||
}>;
|
||||
isResult?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a todo list
|
||||
* Used by: TodoWrite, TodoRead
|
||||
*/
|
||||
export const TodoListContent: React.FC<TodoListContentProps> = ({
|
||||
todos,
|
||||
isResult = false
|
||||
}) => {
|
||||
return <TodoList todos={todos} isResult={isResult} />;
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
export { MarkdownContent } from './MarkdownContent';
|
||||
export { FileListContent } from './FileListContent';
|
||||
export { TodoListContent } from './TodoListContent';
|
||||
export { TaskListContent } from './TaskListContent';
|
||||
export { TextContent } from './TextContent';
|
||||
88
src/components/chat/tools/components/DiffViewer.tsx
Normal file
88
src/components/chat/tools/components/DiffViewer.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import React, { useMemo } from 'react';
|
||||
|
||||
type DiffLine = {
|
||||
type: string;
|
||||
content: string;
|
||||
lineNum: number;
|
||||
};
|
||||
|
||||
interface DiffViewerProps {
|
||||
oldContent: string;
|
||||
newContent: string;
|
||||
filePath: string;
|
||||
createDiff: (oldStr: string, newStr: string) => DiffLine[];
|
||||
onFileClick?: () => void;
|
||||
badge?: string;
|
||||
badgeColor?: 'gray' | 'green';
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact diff viewer — VS Code-style
|
||||
*/
|
||||
export const DiffViewer: React.FC<DiffViewerProps> = ({
|
||||
oldContent,
|
||||
newContent,
|
||||
filePath,
|
||||
createDiff,
|
||||
onFileClick,
|
||||
badge = 'Diff',
|
||||
badgeColor = 'gray'
|
||||
}) => {
|
||||
const badgeClasses = badgeColor === 'green'
|
||||
? 'bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400'
|
||||
: 'bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400';
|
||||
|
||||
const diffLines = useMemo(
|
||||
() => createDiff(oldContent, newContent),
|
||||
[createDiff, oldContent, newContent]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="border border-gray-200/60 dark:border-gray-700/50 rounded overflow-hidden">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-2.5 py-1 bg-gray-50/80 dark:bg-gray-800/40 border-b border-gray-200/60 dark:border-gray-700/50">
|
||||
{onFileClick ? (
|
||||
<button
|
||||
onClick={onFileClick}
|
||||
className="text-[11px] font-mono text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 truncate cursor-pointer transition-colors"
|
||||
>
|
||||
{filePath}
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-[11px] font-mono text-gray-600 dark:text-gray-400 truncate">
|
||||
{filePath}
|
||||
</span>
|
||||
)}
|
||||
<span className={`text-[10px] font-medium px-1.5 py-px rounded ${badgeClasses} flex-shrink-0 ml-2`}>
|
||||
{badge}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Diff lines */}
|
||||
<div className="text-[11px] font-mono leading-[18px]">
|
||||
{diffLines.map((diffLine, i) => (
|
||||
<div key={i} className="flex">
|
||||
<span
|
||||
className={`w-6 text-center select-none flex-shrink-0 ${
|
||||
diffLine.type === 'removed'
|
||||
? 'bg-red-50 dark:bg-red-950/30 text-red-400 dark:text-red-500'
|
||||
: 'bg-green-50 dark:bg-green-950/30 text-green-400 dark:text-green-500'
|
||||
}`}
|
||||
>
|
||||
{diffLine.type === 'removed' ? '-' : '+'}
|
||||
</span>
|
||||
<span
|
||||
className={`px-2 flex-1 whitespace-pre-wrap ${
|
||||
diffLine.type === 'removed'
|
||||
? 'bg-red-50/50 dark:bg-red-950/20 text-red-800 dark:text-red-200'
|
||||
: 'bg-green-50/50 dark:bg-green-950/20 text-green-800 dark:text-green-200'
|
||||
}`}
|
||||
>
|
||||
{diffLine.content}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
233
src/components/chat/tools/components/OneLineDisplay.tsx
Normal file
233
src/components/chat/tools/components/OneLineDisplay.tsx
Normal file
@@ -0,0 +1,233 @@
|
||||
import React, { useState } from 'react';
|
||||
|
||||
type ActionType = 'copy' | 'open-file' | 'jump-to-results' | 'none';
|
||||
|
||||
interface OneLineDisplayProps {
|
||||
|
||||
toolName: string;
|
||||
icon?: string;
|
||||
label?: string;
|
||||
value: string;
|
||||
secondary?: string;
|
||||
action?: ActionType;
|
||||
onAction?: () => void;
|
||||
style?: string;
|
||||
wrapText?: boolean;
|
||||
colorScheme?: {
|
||||
primary?: string;
|
||||
secondary?: string;
|
||||
background?: string;
|
||||
border?: string;
|
||||
icon?: string;
|
||||
};
|
||||
resultId?: string;
|
||||
toolResult?: any;
|
||||
toolId?: string;
|
||||
}
|
||||
|
||||
// Fallback for environments where the async Clipboard API is unavailable or blocked.
|
||||
const copyWithLegacyExecCommand = (text: string): boolean => {
|
||||
if (typeof document === 'undefined' || !document.body) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = text;
|
||||
textarea.setAttribute('readonly', '');
|
||||
textarea.style.position = 'fixed';
|
||||
textarea.style.opacity = '0';
|
||||
textarea.style.left = '-9999px';
|
||||
document.body.appendChild(textarea);
|
||||
textarea.select();
|
||||
textarea.setSelectionRange(0, text.length);
|
||||
|
||||
let copied = false;
|
||||
try {
|
||||
copied = document.execCommand('copy');
|
||||
} catch {
|
||||
copied = false;
|
||||
} finally {
|
||||
document.body.removeChild(textarea);
|
||||
}
|
||||
|
||||
return copied;
|
||||
};
|
||||
|
||||
const copyTextToClipboard = async (text: string): Promise<boolean> => {
|
||||
if (
|
||||
typeof navigator !== 'undefined' &&
|
||||
typeof window !== 'undefined' &&
|
||||
window.isSecureContext &&
|
||||
navigator.clipboard?.writeText
|
||||
) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return true;
|
||||
} catch {
|
||||
// Fall back below when writeText is rejected (permissions/insecure contexts/browser limits).
|
||||
}
|
||||
}
|
||||
|
||||
return copyWithLegacyExecCommand(text);
|
||||
};
|
||||
|
||||
/**
|
||||
* Unified one-line display for simple tool inputs and results
|
||||
* Used by: Bash, Read, Grep/Glob (minimized), TodoRead, etc.
|
||||
*/
|
||||
export const OneLineDisplay: React.FC<OneLineDisplayProps> = ({
|
||||
toolName,
|
||||
icon,
|
||||
label,
|
||||
value,
|
||||
secondary,
|
||||
action = 'none',
|
||||
onAction,
|
||||
style,
|
||||
wrapText = false,
|
||||
colorScheme = {
|
||||
primary: 'text-gray-700 dark:text-gray-300',
|
||||
secondary: 'text-gray-500 dark:text-gray-400',
|
||||
background: '',
|
||||
border: 'border-gray-300 dark:border-gray-600',
|
||||
icon: 'text-gray-500 dark:text-gray-400'
|
||||
},
|
||||
resultId,
|
||||
toolResult,
|
||||
toolId
|
||||
}) => {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const isTerminal = style === 'terminal';
|
||||
|
||||
const handleAction = async () => {
|
||||
if (action === 'copy' && value) {
|
||||
const didCopy = await copyTextToClipboard(value);
|
||||
if (!didCopy) {
|
||||
return;
|
||||
}
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} else if (onAction) {
|
||||
onAction();
|
||||
}
|
||||
};
|
||||
|
||||
const renderCopyButton = () => (
|
||||
<button
|
||||
onClick={handleAction}
|
||||
className="opacity-0 group-hover:opacity-100 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-all ml-1 flex-shrink-0"
|
||||
title="Copy to clipboard"
|
||||
aria-label="Copy to clipboard"
|
||||
>
|
||||
{copied ? (
|
||||
<svg className="w-3 h-3 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
|
||||
// Terminal style: dark pill only around the command
|
||||
if (isTerminal) {
|
||||
return (
|
||||
<div className="group my-1">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="flex items-center gap-1.5 flex-shrink-0 pt-0.5">
|
||||
<svg className="w-3 h-3 text-green-500 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0 flex items-start gap-2">
|
||||
<div className="bg-gray-900 dark:bg-black rounded px-2.5 py-1 flex-1 min-w-0">
|
||||
<code className={`text-xs text-green-400 font-mono ${wrapText ? 'whitespace-pre-wrap break-all' : 'block truncate'}`}>
|
||||
<span className="text-green-600 dark:text-green-500 select-none">$ </span>{value}
|
||||
</code>
|
||||
</div>
|
||||
{action === 'copy' && renderCopyButton()}
|
||||
</div>
|
||||
</div>
|
||||
{secondary && (
|
||||
<div className="ml-7 mt-1">
|
||||
<span className="text-[11px] text-gray-400 dark:text-gray-500 italic">
|
||||
{secondary}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// File open style - show filename only, full path on hover
|
||||
if (action === 'open-file') {
|
||||
const displayName = value.split('/').pop() || value;
|
||||
return (
|
||||
<div className={`group flex items-center gap-1.5 border-l-2 ${colorScheme.border} pl-3 py-0.5 my-0.5`}>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 flex-shrink-0">{label || toolName}</span>
|
||||
<span className="text-gray-300 dark:text-gray-600 text-[10px]">/</span>
|
||||
<button
|
||||
onClick={handleAction}
|
||||
className="text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 font-mono hover:underline transition-colors truncate"
|
||||
title={value}
|
||||
>
|
||||
{displayName}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Search / jump-to-results style
|
||||
if (action === 'jump-to-results') {
|
||||
return (
|
||||
<div className={`group flex items-center gap-1.5 border-l-2 ${colorScheme.border} pl-3 py-0.5 my-0.5`}>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 flex-shrink-0">{label || toolName}</span>
|
||||
<span className="text-gray-300 dark:text-gray-600 text-[10px]">/</span>
|
||||
<span className={`text-xs font-mono truncate flex-1 min-w-0 ${colorScheme.primary}`}>
|
||||
{value}
|
||||
</span>
|
||||
{secondary && (
|
||||
<span className="text-[11px] text-gray-400 dark:text-gray-500 italic flex-shrink-0">
|
||||
{secondary}
|
||||
</span>
|
||||
)}
|
||||
{toolResult && (
|
||||
<a
|
||||
href={`#tool-result-${toolId}`}
|
||||
className="flex-shrink-0 text-[11px] text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 transition-colors flex items-center gap-0.5"
|
||||
>
|
||||
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Default one-line style
|
||||
return (
|
||||
<div className={`group flex items-center gap-1.5 ${colorScheme.background || ''} border-l-2 ${colorScheme.border} pl-3 py-0.5 my-0.5`}>
|
||||
{icon && icon !== 'terminal' && (
|
||||
<span className={`${colorScheme.icon} flex-shrink-0 text-xs`}>{icon}</span>
|
||||
)}
|
||||
{!icon && (label || toolName) && (
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 flex-shrink-0">{label || toolName}</span>
|
||||
)}
|
||||
{(icon || label || toolName) && (
|
||||
<span className="text-gray-300 dark:text-gray-600 text-[10px]">/</span>
|
||||
)}
|
||||
<span className={`text-xs font-mono ${wrapText ? 'whitespace-pre-wrap break-all' : 'truncate'} flex-1 min-w-0 ${colorScheme.primary}`}>
|
||||
{value}
|
||||
</span>
|
||||
{secondary && (
|
||||
<span className={`text-[11px] ${colorScheme.secondary} italic flex-shrink-0`}>
|
||||
{secondary}
|
||||
</span>
|
||||
)}
|
||||
{action === 'copy' && renderCopyButton()}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
5
src/components/chat/tools/components/index.ts
Normal file
5
src/components/chat/tools/components/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export { CollapsibleSection } from './CollapsibleSection';
|
||||
export { DiffViewer } from './DiffViewer';
|
||||
export { OneLineDisplay } from './OneLineDisplay';
|
||||
export { CollapsibleDisplay } from './CollapsibleDisplay';
|
||||
export * from './ContentRenderers';
|
||||
569
src/components/chat/tools/configs/toolConfigs.ts
Normal file
569
src/components/chat/tools/configs/toolConfigs.ts
Normal file
@@ -0,0 +1,569 @@
|
||||
/**
|
||||
* Centralized tool configuration registry
|
||||
* Defines display behavior for all tool types
|
||||
*/
|
||||
|
||||
export interface ToolDisplayConfig {
|
||||
input: {
|
||||
type: 'one-line' | 'collapsible' | 'hidden';
|
||||
// One-line config
|
||||
icon?: string;
|
||||
label?: string;
|
||||
getValue?: (input: any) => string;
|
||||
getSecondary?: (input: any) => string | undefined;
|
||||
action?: 'copy' | 'open-file' | 'jump-to-results' | 'none';
|
||||
style?: string;
|
||||
wrapText?: boolean;
|
||||
colorScheme?: {
|
||||
primary?: string;
|
||||
secondary?: string;
|
||||
background?: string;
|
||||
border?: string;
|
||||
icon?: string;
|
||||
};
|
||||
// Collapsible config
|
||||
title?: string | ((input: any) => string);
|
||||
defaultOpen?: boolean;
|
||||
contentType?: 'diff' | 'markdown' | 'file-list' | 'todo-list' | 'text' | 'task';
|
||||
getContentProps?: (input: any, helpers?: any) => any;
|
||||
actionButton?: 'file-button' | 'none';
|
||||
};
|
||||
result?: {
|
||||
hidden?: boolean;
|
||||
hideOnSuccess?: boolean;
|
||||
type?: 'one-line' | 'collapsible' | 'special';
|
||||
title?: string | ((result: any) => string);
|
||||
defaultOpen?: boolean;
|
||||
// Special result handlers
|
||||
contentType?: 'markdown' | 'file-list' | 'todo-list' | 'text' | 'success-message' | 'task';
|
||||
getMessage?: (result: any) => string;
|
||||
getContentProps?: (result: any) => any;
|
||||
};
|
||||
}
|
||||
|
||||
export const TOOL_CONFIGS: Record<string, ToolDisplayConfig> = {
|
||||
// ============================================================================
|
||||
// COMMAND TOOLS
|
||||
// ============================================================================
|
||||
|
||||
Bash: {
|
||||
input: {
|
||||
type: 'one-line',
|
||||
icon: 'terminal',
|
||||
getValue: (input) => input.command,
|
||||
getSecondary: (input) => input.description,
|
||||
action: 'copy',
|
||||
style: 'terminal',
|
||||
wrapText: true,
|
||||
colorScheme: {
|
||||
primary: 'text-green-400 font-mono',
|
||||
secondary: 'text-gray-400',
|
||||
background: '',
|
||||
border: 'border-green-500 dark:border-green-400',
|
||||
icon: 'text-green-500 dark:text-green-400'
|
||||
}
|
||||
},
|
||||
result: {
|
||||
hideOnSuccess: true,
|
||||
type: 'special'
|
||||
}
|
||||
},
|
||||
|
||||
// ============================================================================
|
||||
// FILE OPERATION TOOLS
|
||||
// ============================================================================
|
||||
|
||||
Read: {
|
||||
input: {
|
||||
type: 'one-line',
|
||||
label: 'Read',
|
||||
getValue: (input) => input.file_path || '',
|
||||
action: 'open-file',
|
||||
colorScheme: {
|
||||
primary: 'text-gray-700 dark:text-gray-300',
|
||||
background: '',
|
||||
border: 'border-gray-300 dark:border-gray-600',
|
||||
icon: 'text-gray-500 dark:text-gray-400'
|
||||
}
|
||||
},
|
||||
result: {
|
||||
hidden: true
|
||||
}
|
||||
},
|
||||
|
||||
Edit: {
|
||||
input: {
|
||||
type: 'collapsible',
|
||||
title: (input) => {
|
||||
const filename = input.file_path?.split('/').pop() || input.file_path || 'file';
|
||||
return `${filename}`;
|
||||
},
|
||||
defaultOpen: false,
|
||||
contentType: 'diff',
|
||||
actionButton: 'none',
|
||||
getContentProps: (input) => ({
|
||||
oldContent: input.old_string,
|
||||
newContent: input.new_string,
|
||||
filePath: input.file_path,
|
||||
badge: 'Edit',
|
||||
badgeColor: 'gray'
|
||||
})
|
||||
},
|
||||
result: {
|
||||
hideOnSuccess: true
|
||||
}
|
||||
},
|
||||
|
||||
Write: {
|
||||
input: {
|
||||
type: 'collapsible',
|
||||
title: (input) => {
|
||||
const filename = input.file_path?.split('/').pop() || input.file_path || 'file';
|
||||
return `${filename}`;
|
||||
},
|
||||
defaultOpen: false,
|
||||
contentType: 'diff',
|
||||
actionButton: 'none',
|
||||
getContentProps: (input) => ({
|
||||
oldContent: '',
|
||||
newContent: input.content,
|
||||
filePath: input.file_path,
|
||||
badge: 'New',
|
||||
badgeColor: 'green'
|
||||
})
|
||||
},
|
||||
result: {
|
||||
hideOnSuccess: true
|
||||
}
|
||||
},
|
||||
|
||||
ApplyPatch: {
|
||||
input: {
|
||||
type: 'collapsible',
|
||||
title: (input) => {
|
||||
const filename = input.file_path?.split('/').pop() || input.file_path || 'file';
|
||||
return `${filename}`;
|
||||
},
|
||||
defaultOpen: false,
|
||||
contentType: 'diff',
|
||||
actionButton: 'none',
|
||||
getContentProps: (input) => ({
|
||||
oldContent: input.old_string,
|
||||
newContent: input.new_string,
|
||||
filePath: input.file_path,
|
||||
badge: 'Patch',
|
||||
badgeColor: 'gray'
|
||||
})
|
||||
},
|
||||
result: {
|
||||
hideOnSuccess: true
|
||||
}
|
||||
},
|
||||
|
||||
// ============================================================================
|
||||
// SEARCH TOOLS
|
||||
// ============================================================================
|
||||
|
||||
Grep: {
|
||||
input: {
|
||||
type: 'one-line',
|
||||
label: 'Grep',
|
||||
getValue: (input) => input.pattern,
|
||||
getSecondary: (input) => input.path ? `in ${input.path}` : undefined,
|
||||
action: 'jump-to-results',
|
||||
colorScheme: {
|
||||
primary: 'text-gray-700 dark:text-gray-300',
|
||||
secondary: 'text-gray-500 dark:text-gray-400',
|
||||
background: '',
|
||||
border: 'border-gray-400 dark:border-gray-500',
|
||||
icon: 'text-gray-500 dark:text-gray-400'
|
||||
}
|
||||
},
|
||||
result: {
|
||||
type: 'collapsible',
|
||||
defaultOpen: false,
|
||||
title: (result) => {
|
||||
const toolData = result.toolUseResult || {};
|
||||
const count = toolData.numFiles || toolData.filenames?.length || 0;
|
||||
return `Found ${count} ${count === 1 ? 'file' : 'files'}`;
|
||||
},
|
||||
contentType: 'file-list',
|
||||
getContentProps: (result) => {
|
||||
const toolData = result.toolUseResult || {};
|
||||
return {
|
||||
files: toolData.filenames || []
|
||||
};
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
Glob: {
|
||||
input: {
|
||||
type: 'one-line',
|
||||
label: 'Glob',
|
||||
getValue: (input) => input.pattern,
|
||||
getSecondary: (input) => input.path ? `in ${input.path}` : undefined,
|
||||
action: 'jump-to-results',
|
||||
colorScheme: {
|
||||
primary: 'text-gray-700 dark:text-gray-300',
|
||||
secondary: 'text-gray-500 dark:text-gray-400',
|
||||
background: '',
|
||||
border: 'border-gray-400 dark:border-gray-500',
|
||||
icon: 'text-gray-500 dark:text-gray-400'
|
||||
}
|
||||
},
|
||||
result: {
|
||||
type: 'collapsible',
|
||||
defaultOpen: false,
|
||||
title: (result) => {
|
||||
const toolData = result.toolUseResult || {};
|
||||
const count = toolData.numFiles || toolData.filenames?.length || 0;
|
||||
return `Found ${count} ${count === 1 ? 'file' : 'files'}`;
|
||||
},
|
||||
contentType: 'file-list',
|
||||
getContentProps: (result) => {
|
||||
const toolData = result.toolUseResult || {};
|
||||
return {
|
||||
files: toolData.filenames || []
|
||||
};
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// ============================================================================
|
||||
// TODO TOOLS
|
||||
// ============================================================================
|
||||
|
||||
TodoWrite: {
|
||||
input: {
|
||||
type: 'collapsible',
|
||||
title: 'Updating todo list',
|
||||
defaultOpen: false,
|
||||
contentType: 'todo-list',
|
||||
getContentProps: (input) => ({
|
||||
todos: input.todos
|
||||
})
|
||||
},
|
||||
result: {
|
||||
type: 'collapsible',
|
||||
contentType: 'success-message',
|
||||
getMessage: () => 'Todo list updated'
|
||||
}
|
||||
},
|
||||
|
||||
TodoRead: {
|
||||
input: {
|
||||
type: 'one-line',
|
||||
label: 'TodoRead',
|
||||
getValue: () => 'reading list',
|
||||
action: 'none',
|
||||
colorScheme: {
|
||||
primary: 'text-gray-500 dark:text-gray-400',
|
||||
border: 'border-violet-400 dark:border-violet-500'
|
||||
}
|
||||
},
|
||||
result: {
|
||||
type: 'collapsible',
|
||||
contentType: 'todo-list',
|
||||
getContentProps: (result) => {
|
||||
try {
|
||||
const content = String(result.content || '');
|
||||
let todos = null;
|
||||
if (content.startsWith('[')) {
|
||||
todos = JSON.parse(content);
|
||||
}
|
||||
return { todos, isResult: true };
|
||||
} catch (e) {
|
||||
return { todos: [], isResult: true };
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// ============================================================================
|
||||
// TASK TOOLS (TaskCreate, TaskUpdate, TaskList, TaskGet)
|
||||
// ============================================================================
|
||||
|
||||
TaskCreate: {
|
||||
input: {
|
||||
type: 'one-line',
|
||||
label: 'Task',
|
||||
getValue: (input) => input.subject || 'Creating task',
|
||||
getSecondary: (input) => input.status || undefined,
|
||||
action: 'none',
|
||||
colorScheme: {
|
||||
primary: 'text-gray-700 dark:text-gray-300',
|
||||
border: 'border-violet-400 dark:border-violet-500',
|
||||
icon: 'text-violet-500 dark:text-violet-400'
|
||||
}
|
||||
},
|
||||
result: {
|
||||
hideOnSuccess: true
|
||||
}
|
||||
},
|
||||
|
||||
TaskUpdate: {
|
||||
input: {
|
||||
type: 'one-line',
|
||||
label: 'Task',
|
||||
getValue: (input) => {
|
||||
const parts = [];
|
||||
if (input.taskId) parts.push(`#${input.taskId}`);
|
||||
if (input.status) parts.push(input.status);
|
||||
if (input.subject) parts.push(`"${input.subject}"`);
|
||||
return parts.join(' → ') || 'updating';
|
||||
},
|
||||
action: 'none',
|
||||
colorScheme: {
|
||||
primary: 'text-gray-700 dark:text-gray-300',
|
||||
border: 'border-violet-400 dark:border-violet-500',
|
||||
icon: 'text-violet-500 dark:text-violet-400'
|
||||
}
|
||||
},
|
||||
result: {
|
||||
hideOnSuccess: true
|
||||
}
|
||||
},
|
||||
|
||||
TaskList: {
|
||||
input: {
|
||||
type: 'one-line',
|
||||
label: 'Tasks',
|
||||
getValue: () => 'listing tasks',
|
||||
action: 'none',
|
||||
colorScheme: {
|
||||
primary: 'text-gray-500 dark:text-gray-400',
|
||||
border: 'border-violet-400 dark:border-violet-500',
|
||||
icon: 'text-violet-500 dark:text-violet-400'
|
||||
}
|
||||
},
|
||||
result: {
|
||||
type: 'collapsible',
|
||||
defaultOpen: true,
|
||||
title: 'Task list',
|
||||
contentType: 'task',
|
||||
getContentProps: (result) => ({
|
||||
content: String(result?.content || '')
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
TaskGet: {
|
||||
input: {
|
||||
type: 'one-line',
|
||||
label: 'Task',
|
||||
getValue: (input) => input.taskId ? `#${input.taskId}` : 'fetching',
|
||||
action: 'none',
|
||||
colorScheme: {
|
||||
primary: 'text-gray-700 dark:text-gray-300',
|
||||
border: 'border-violet-400 dark:border-violet-500',
|
||||
icon: 'text-violet-500 dark:text-violet-400'
|
||||
}
|
||||
},
|
||||
result: {
|
||||
type: 'collapsible',
|
||||
defaultOpen: true,
|
||||
title: 'Task details',
|
||||
contentType: 'task',
|
||||
getContentProps: (result) => ({
|
||||
content: String(result?.content || '')
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
// ============================================================================
|
||||
// SUBAGENT TASK TOOL
|
||||
// ============================================================================
|
||||
|
||||
Task: {
|
||||
input: {
|
||||
type: 'collapsible',
|
||||
title: (input) => {
|
||||
const subagentType = input.subagent_type || 'Agent';
|
||||
const description = input.description || 'Running task';
|
||||
return `Subagent / ${subagentType}: ${description}`;
|
||||
},
|
||||
defaultOpen: true,
|
||||
contentType: 'markdown',
|
||||
getContentProps: (input) => {
|
||||
// If only prompt exists (and required fields), show just the prompt
|
||||
// Otherwise show all available fields
|
||||
const hasOnlyPrompt = input.prompt &&
|
||||
!input.model &&
|
||||
!input.resume;
|
||||
|
||||
if (hasOnlyPrompt) {
|
||||
return {
|
||||
content: input.prompt || ''
|
||||
};
|
||||
}
|
||||
|
||||
// Format multiple fields
|
||||
const parts = [];
|
||||
|
||||
if (input.model) {
|
||||
parts.push(`**Model:** ${input.model}`);
|
||||
}
|
||||
|
||||
if (input.prompt) {
|
||||
parts.push(`**Prompt:**\n${input.prompt}`);
|
||||
}
|
||||
|
||||
if (input.resume) {
|
||||
parts.push(`**Resuming from:** ${input.resume}`);
|
||||
}
|
||||
|
||||
return {
|
||||
content: parts.join('\n\n')
|
||||
};
|
||||
},
|
||||
colorScheme: {
|
||||
border: 'border-purple-500 dark:border-purple-400',
|
||||
icon: 'text-purple-500 dark:text-purple-400'
|
||||
}
|
||||
},
|
||||
result: {
|
||||
type: 'collapsible',
|
||||
title: (result) => {
|
||||
// Check if result has content with type array (agent results often have this structure)
|
||||
if (result && result.content && Array.isArray(result.content)) {
|
||||
return 'Subagent Response';
|
||||
}
|
||||
return 'Subagent Result';
|
||||
},
|
||||
defaultOpen: true,
|
||||
contentType: 'markdown',
|
||||
getContentProps: (result) => {
|
||||
// Handle agent results which may have complex structure
|
||||
if (result && result.content) {
|
||||
// If content is an array (typical for agent responses with multiple text blocks)
|
||||
if (Array.isArray(result.content)) {
|
||||
const textContent = result.content
|
||||
.filter((item: any) => item.type === 'text')
|
||||
.map((item: any) => item.text)
|
||||
.join('\n\n');
|
||||
return { content: textContent || 'No response text' };
|
||||
}
|
||||
// If content is already a string
|
||||
return { content: String(result.content) };
|
||||
}
|
||||
// Fallback to string representation
|
||||
return { content: String(result || 'No response') };
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// ============================================================================
|
||||
// PLAN TOOLS
|
||||
// ============================================================================
|
||||
|
||||
exit_plan_mode: {
|
||||
input: {
|
||||
type: 'collapsible',
|
||||
title: 'Implementation plan',
|
||||
defaultOpen: true,
|
||||
contentType: 'markdown',
|
||||
getContentProps: (input) => ({
|
||||
content: input.plan?.replace(/\\n/g, '\n') || input.plan
|
||||
})
|
||||
},
|
||||
result: {
|
||||
type: 'collapsible',
|
||||
contentType: 'markdown',
|
||||
getContentProps: (result) => {
|
||||
try {
|
||||
let parsed = result.content;
|
||||
if (typeof parsed === 'string') {
|
||||
parsed = JSON.parse(parsed);
|
||||
}
|
||||
return {
|
||||
content: parsed.plan?.replace(/\\n/g, '\n') || parsed.plan
|
||||
};
|
||||
} catch (e) {
|
||||
return { content: '' };
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Also register as ExitPlanMode (the actual tool name used by Claude)
|
||||
ExitPlanMode: {
|
||||
input: {
|
||||
type: 'collapsible',
|
||||
title: 'Implementation plan',
|
||||
defaultOpen: true,
|
||||
contentType: 'markdown',
|
||||
getContentProps: (input) => ({
|
||||
content: input.plan?.replace(/\\n/g, '\n') || input.plan
|
||||
})
|
||||
},
|
||||
result: {
|
||||
type: 'collapsible',
|
||||
contentType: 'markdown',
|
||||
getContentProps: (result) => {
|
||||
try {
|
||||
let parsed = result.content;
|
||||
if (typeof parsed === 'string') {
|
||||
parsed = JSON.parse(parsed);
|
||||
}
|
||||
return {
|
||||
content: parsed.plan?.replace(/\\n/g, '\n') || parsed.plan
|
||||
};
|
||||
} catch (e) {
|
||||
return { content: '' };
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// ============================================================================
|
||||
// DEFAULT FALLBACK
|
||||
// ============================================================================
|
||||
|
||||
Default: {
|
||||
input: {
|
||||
type: 'collapsible',
|
||||
title: 'Parameters',
|
||||
defaultOpen: false,
|
||||
contentType: 'text',
|
||||
getContentProps: (input) => ({
|
||||
content: typeof input === 'string' ? input : JSON.stringify(input, null, 2),
|
||||
format: 'code'
|
||||
})
|
||||
},
|
||||
result: {
|
||||
type: 'collapsible',
|
||||
contentType: 'text',
|
||||
getContentProps: (result) => ({
|
||||
content: String(result?.content || ''),
|
||||
format: 'plain'
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get configuration for a tool, with fallback to default
|
||||
*/
|
||||
export function getToolConfig(toolName: string): ToolDisplayConfig {
|
||||
return TOOL_CONFIGS[toolName] || TOOL_CONFIGS.Default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a tool result should be hidden
|
||||
*/
|
||||
export function shouldHideToolResult(toolName: string, toolResult: any): boolean {
|
||||
const config = getToolConfig(toolName);
|
||||
|
||||
if (!config.result) return false;
|
||||
|
||||
// Always hidden
|
||||
if (config.result.hidden) return true;
|
||||
|
||||
// Hide on success only
|
||||
if (config.result.hideOnSuccess && toolResult && !toolResult.isError) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
3
src/components/chat/tools/index.ts
Normal file
3
src/components/chat/tools/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export { ToolRenderer } from './ToolRenderer';
|
||||
export { getToolConfig, shouldHideToolResult } from './configs/toolConfigs';
|
||||
export * from './components';
|
||||
92
src/components/chat/types/types.ts
Normal file
92
src/components/chat/types/types.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import type { Project, ProjectSession, SessionProvider } from '../../../types/app';
|
||||
|
||||
export type Provider = SessionProvider;
|
||||
|
||||
export type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan';
|
||||
|
||||
export interface ChatImage {
|
||||
data: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ToolResult {
|
||||
content?: unknown;
|
||||
isError?: boolean;
|
||||
timestamp?: string | number | Date;
|
||||
toolUseResult?: unknown;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
type: string;
|
||||
content?: string;
|
||||
timestamp: string | number | Date;
|
||||
images?: ChatImage[];
|
||||
reasoning?: string;
|
||||
isThinking?: boolean;
|
||||
isStreaming?: boolean;
|
||||
isInteractivePrompt?: boolean;
|
||||
isToolUse?: boolean;
|
||||
toolName?: string;
|
||||
toolInput?: unknown;
|
||||
toolResult?: ToolResult | null;
|
||||
toolId?: string;
|
||||
toolCallId?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ClaudeSettings {
|
||||
allowedTools: string[];
|
||||
disallowedTools: string[];
|
||||
skipPermissions: boolean;
|
||||
projectSortOrder: string;
|
||||
lastUpdated?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ClaudePermissionSuggestion {
|
||||
toolName: string;
|
||||
entry: string;
|
||||
isAllowed: boolean;
|
||||
}
|
||||
|
||||
export interface PermissionGrantResult {
|
||||
success: boolean;
|
||||
alreadyAllowed?: boolean;
|
||||
updatedSettings?: ClaudeSettings;
|
||||
}
|
||||
|
||||
export interface PendingPermissionRequest {
|
||||
requestId: string;
|
||||
toolName: string;
|
||||
input?: unknown;
|
||||
context?: unknown;
|
||||
sessionId?: string | null;
|
||||
receivedAt?: Date;
|
||||
}
|
||||
|
||||
export interface ChatInterfaceProps {
|
||||
selectedProject: Project | null;
|
||||
selectedSession: ProjectSession | null;
|
||||
ws: WebSocket | null;
|
||||
sendMessage: (message: unknown) => void;
|
||||
latestMessage: any;
|
||||
onFileOpen?: (filePath: string, diffInfo?: any) => void;
|
||||
onInputFocusChange?: (focused: boolean) => void;
|
||||
onSessionActive?: (sessionId?: string | null) => void;
|
||||
onSessionInactive?: (sessionId?: string | null) => void;
|
||||
onSessionProcessing?: (sessionId?: string | null) => void;
|
||||
onSessionNotProcessing?: (sessionId?: string | null) => void;
|
||||
processingSessions?: Set<string>;
|
||||
onReplaceTemporarySession?: (sessionId?: string | null) => void;
|
||||
onNavigateToSession?: (targetSessionId: string) => void;
|
||||
onShowSettings?: () => void;
|
||||
autoExpandTools?: boolean;
|
||||
showRawParameters?: boolean;
|
||||
showThinking?: boolean;
|
||||
autoScrollToBottom?: boolean;
|
||||
sendByCtrlEnter?: boolean;
|
||||
externalMessageUpdate?: number;
|
||||
onTaskClick?: (...args: unknown[]) => void;
|
||||
onShowAllTasks?: (() => void) | null;
|
||||
}
|
||||
86
src/components/chat/utils/chatFormatting.ts
Normal file
86
src/components/chat/utils/chatFormatting.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
export function decodeHtmlEntities(text: string) {
|
||||
if (!text) return text;
|
||||
return text
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&');
|
||||
}
|
||||
|
||||
export function normalizeInlineCodeFences(text: string) {
|
||||
if (!text || typeof text !== 'string') return text;
|
||||
try {
|
||||
return text.replace(/```\s*([^\n\r]+?)\s*```/g, '`$1`');
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
export function unescapeWithMathProtection(text: string) {
|
||||
if (!text || typeof text !== 'string') return text;
|
||||
|
||||
const mathBlocks: string[] = [];
|
||||
const placeholderPrefix = '__MATH_BLOCK_';
|
||||
const placeholderSuffix = '__';
|
||||
|
||||
let processedText = text.replace(/\$\$([\s\S]*?)\$\$|\$([^\$\n]+?)\$/g, (match) => {
|
||||
const index = mathBlocks.length;
|
||||
mathBlocks.push(match);
|
||||
return `${placeholderPrefix}${index}${placeholderSuffix}`;
|
||||
});
|
||||
|
||||
processedText = processedText.replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\r/g, '\r');
|
||||
|
||||
processedText = processedText.replace(
|
||||
new RegExp(`${placeholderPrefix}(\\d+)${placeholderSuffix}`, 'g'),
|
||||
(match, index) => {
|
||||
return mathBlocks[parseInt(index, 10)];
|
||||
},
|
||||
);
|
||||
|
||||
return processedText;
|
||||
}
|
||||
|
||||
export function escapeRegExp(value: string) {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
export function formatUsageLimitText(text: string) {
|
||||
try {
|
||||
if (typeof text !== 'string') return text;
|
||||
return text.replace(/Claude AI usage limit reached\|(\d{10,13})/g, (match, ts) => {
|
||||
let timestampMs = parseInt(ts, 10);
|
||||
if (!Number.isFinite(timestampMs)) return match;
|
||||
if (timestampMs < 1e12) timestampMs *= 1000;
|
||||
const reset = new Date(timestampMs);
|
||||
|
||||
const timeStr = new Intl.DateTimeFormat(undefined, {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}).format(reset);
|
||||
|
||||
const offsetMinutesLocal = -reset.getTimezoneOffset();
|
||||
const sign = offsetMinutesLocal >= 0 ? '+' : '-';
|
||||
const abs = Math.abs(offsetMinutesLocal);
|
||||
const offH = Math.floor(abs / 60);
|
||||
const offM = abs % 60;
|
||||
const gmt = `GMT${sign}${offH}${offM ? ':' + String(offM).padStart(2, '0') : ''}`;
|
||||
const tzId = Intl.DateTimeFormat().resolvedOptions().timeZone || '';
|
||||
const cityRaw = tzId.split('/').pop() || '';
|
||||
const city = cityRaw
|
||||
.replace(/_/g, ' ')
|
||||
.toLowerCase()
|
||||
.replace(/\b\w/g, (char) => char.toUpperCase());
|
||||
const tzHuman = city ? `${gmt} (${city})` : gmt;
|
||||
|
||||
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
const dateReadable = `${reset.getDate()} ${months[reset.getMonth()]} ${reset.getFullYear()}`;
|
||||
|
||||
return `Claude usage limit reached. Your limit will reset at **${timeStr} ${tzHuman}** - ${dateReadable}`;
|
||||
});
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
64
src/components/chat/utils/chatPermissions.ts
Normal file
64
src/components/chat/utils/chatPermissions.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { safeJsonParse } from '../../../lib/utils.js';
|
||||
import type { ChatMessage, ClaudePermissionSuggestion, PermissionGrantResult } from '../types/types.js';
|
||||
import { CLAUDE_SETTINGS_KEY, getClaudeSettings, safeLocalStorage } from './chatStorage';
|
||||
|
||||
export function buildClaudeToolPermissionEntry(toolName?: string, toolInput?: unknown) {
|
||||
if (!toolName) return null;
|
||||
if (toolName !== 'Bash') return toolName;
|
||||
|
||||
const parsed = safeJsonParse(toolInput);
|
||||
const command = typeof parsed?.command === 'string' ? parsed.command.trim() : '';
|
||||
if (!command) return toolName;
|
||||
|
||||
const tokens = command.split(/\s+/);
|
||||
if (tokens.length === 0) return toolName;
|
||||
|
||||
if (tokens[0] === 'git' && tokens[1]) {
|
||||
return `Bash(${tokens[0]} ${tokens[1]}:*)`;
|
||||
}
|
||||
return `Bash(${tokens[0]}:*)`;
|
||||
}
|
||||
|
||||
export function formatToolInputForDisplay(input: unknown) {
|
||||
if (input === undefined || input === null) return '';
|
||||
if (typeof input === 'string') return input;
|
||||
try {
|
||||
return JSON.stringify(input, null, 2);
|
||||
} catch {
|
||||
return String(input);
|
||||
}
|
||||
}
|
||||
|
||||
export function getClaudePermissionSuggestion(
|
||||
message: ChatMessage | null | undefined,
|
||||
provider: string,
|
||||
): ClaudePermissionSuggestion | null {
|
||||
if (provider !== 'claude') return null;
|
||||
if (!message?.toolResult?.isError) return null;
|
||||
|
||||
const toolName = message?.toolName;
|
||||
const entry = buildClaudeToolPermissionEntry(toolName, message.toolInput);
|
||||
if (!entry) return null;
|
||||
|
||||
const settings = getClaudeSettings();
|
||||
const isAllowed = settings.allowedTools.includes(entry);
|
||||
return { toolName: toolName || 'UnknownTool', entry, isAllowed };
|
||||
}
|
||||
|
||||
export function grantClaudeToolPermission(entry: string | null): PermissionGrantResult {
|
||||
if (!entry) return { success: false };
|
||||
|
||||
const settings = getClaudeSettings();
|
||||
const alreadyAllowed = settings.allowedTools.includes(entry);
|
||||
const nextAllowed = alreadyAllowed ? settings.allowedTools : [...settings.allowedTools, entry];
|
||||
const nextDisallowed = settings.disallowedTools.filter((tool) => tool !== entry);
|
||||
const updatedSettings = {
|
||||
...settings,
|
||||
allowedTools: nextAllowed,
|
||||
disallowedTools: nextDisallowed,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
};
|
||||
|
||||
safeLocalStorage.setItem(CLAUDE_SETTINGS_KEY, JSON.stringify(updatedSettings));
|
||||
return { success: true, alreadyAllowed, updatedSettings };
|
||||
}
|
||||
105
src/components/chat/utils/chatStorage.ts
Normal file
105
src/components/chat/utils/chatStorage.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import type { ClaudeSettings } from '../types/types';
|
||||
|
||||
export const CLAUDE_SETTINGS_KEY = 'claude-settings';
|
||||
|
||||
export const safeLocalStorage = {
|
||||
setItem: (key: string, value: string) => {
|
||||
try {
|
||||
if (key.startsWith('chat_messages_') && typeof value === 'string') {
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
if (Array.isArray(parsed) && parsed.length > 50) {
|
||||
const truncated = parsed.slice(-50);
|
||||
value = JSON.stringify(truncated);
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.warn('Could not parse chat messages for truncation:', parseError);
|
||||
}
|
||||
}
|
||||
|
||||
localStorage.setItem(key, value);
|
||||
} catch (error: any) {
|
||||
if (error?.name === 'QuotaExceededError') {
|
||||
console.warn('localStorage quota exceeded, clearing old data');
|
||||
|
||||
const keys = Object.keys(localStorage);
|
||||
const chatKeys = keys.filter((k) => k.startsWith('chat_messages_')).sort();
|
||||
|
||||
if (chatKeys.length > 3) {
|
||||
chatKeys.slice(0, chatKeys.length - 3).forEach((k) => {
|
||||
localStorage.removeItem(k);
|
||||
});
|
||||
}
|
||||
|
||||
const draftKeys = keys.filter((k) => k.startsWith('draft_input_'));
|
||||
draftKeys.forEach((k) => {
|
||||
localStorage.removeItem(k);
|
||||
});
|
||||
|
||||
try {
|
||||
localStorage.setItem(key, value);
|
||||
} catch (retryError) {
|
||||
console.error('Failed to save to localStorage even after cleanup:', retryError);
|
||||
if (key.startsWith('chat_messages_') && typeof value === 'string') {
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
if (Array.isArray(parsed) && parsed.length > 10) {
|
||||
const minimal = parsed.slice(-10);
|
||||
localStorage.setItem(key, JSON.stringify(minimal));
|
||||
}
|
||||
} catch (finalError) {
|
||||
console.error('Final save attempt failed:', finalError);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error('localStorage error:', error);
|
||||
}
|
||||
}
|
||||
},
|
||||
getItem: (key: string): string | null => {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch (error) {
|
||||
console.error('localStorage getItem error:', error);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
removeItem: (key: string) => {
|
||||
try {
|
||||
localStorage.removeItem(key);
|
||||
} catch (error) {
|
||||
console.error('localStorage removeItem error:', error);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export function getClaudeSettings(): ClaudeSettings {
|
||||
const raw = safeLocalStorage.getItem(CLAUDE_SETTINGS_KEY);
|
||||
if (!raw) {
|
||||
return {
|
||||
allowedTools: [],
|
||||
disallowedTools: [],
|
||||
skipPermissions: false,
|
||||
projectSortOrder: 'name',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return {
|
||||
...parsed,
|
||||
allowedTools: Array.isArray(parsed.allowedTools) ? parsed.allowedTools : [],
|
||||
disallowedTools: Array.isArray(parsed.disallowedTools) ? parsed.disallowedTools : [],
|
||||
skipPermissions: Boolean(parsed.skipPermissions),
|
||||
projectSortOrder: parsed.projectSortOrder || 'name',
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
allowedTools: [],
|
||||
disallowedTools: [],
|
||||
skipPermissions: false,
|
||||
projectSortOrder: 'name',
|
||||
};
|
||||
}
|
||||
}
|
||||
38
src/components/chat/utils/messageKeys.ts
Normal file
38
src/components/chat/utils/messageKeys.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import type { ChatMessage } from '../types/types';
|
||||
|
||||
const toMessageKeyPart = (value: unknown): string | null => {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = String(value).trim();
|
||||
return normalized.length > 0 ? normalized : null;
|
||||
};
|
||||
|
||||
export const getIntrinsicMessageKey = (message: ChatMessage): string | null => {
|
||||
const candidates = [
|
||||
message.id,
|
||||
message.messageId,
|
||||
message.toolId,
|
||||
message.toolCallId,
|
||||
message.blobId,
|
||||
message.rowid,
|
||||
message.sequence,
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const keyPart = toMessageKeyPart(candidate);
|
||||
if (keyPart) {
|
||||
return `message-${message.type}-${keyPart}`;
|
||||
}
|
||||
}
|
||||
|
||||
const timestamp = new Date(message.timestamp).getTime();
|
||||
if (!Number.isFinite(timestamp)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const contentPreview = typeof message.content === 'string' ? message.content.slice(0, 48) : '';
|
||||
const toolName = typeof message.toolName === 'string' ? message.toolName : '';
|
||||
return `message-${message.type}-${timestamp}-${toolName}-${contentPreview}`;
|
||||
};
|
||||
508
src/components/chat/utils/messageTransforms.ts
Normal file
508
src/components/chat/utils/messageTransforms.ts
Normal file
@@ -0,0 +1,508 @@
|
||||
import type { ChatMessage } from '../types/types';
|
||||
import { decodeHtmlEntities, unescapeWithMathProtection } from './chatFormatting';
|
||||
|
||||
export interface DiffLine {
|
||||
type: 'added' | 'removed';
|
||||
content: string;
|
||||
lineNum: number;
|
||||
}
|
||||
|
||||
export type DiffCalculator = (oldStr: string, newStr: string) => DiffLine[];
|
||||
|
||||
type CursorBlob = {
|
||||
id?: string;
|
||||
sequence?: number;
|
||||
rowid?: number;
|
||||
content?: any;
|
||||
};
|
||||
|
||||
const asArray = <T>(value: unknown): T[] => (Array.isArray(value) ? (value as T[]) : []);
|
||||
|
||||
const normalizeToolInput = (value: unknown): string => {
|
||||
if (value === null || value === undefined || value === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.stringify(value, null, 2);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
};
|
||||
|
||||
const toAbsolutePath = (projectPath: string, filePath?: string) => {
|
||||
if (!filePath) {
|
||||
return filePath;
|
||||
}
|
||||
return filePath.startsWith('/') ? filePath : `${projectPath}/${filePath}`;
|
||||
};
|
||||
|
||||
export const calculateDiff = (oldStr: string, newStr: string): DiffLine[] => {
|
||||
const oldLines = oldStr.split('\n');
|
||||
const newLines = newStr.split('\n');
|
||||
|
||||
// Use LCS alignment so insertions/deletions don't cascade into a full-file "changed" diff.
|
||||
const lcsTable: number[][] = Array.from({ length: oldLines.length + 1 }, () =>
|
||||
new Array<number>(newLines.length + 1).fill(0),
|
||||
);
|
||||
for (let oldIndex = oldLines.length - 1; oldIndex >= 0; oldIndex -= 1) {
|
||||
for (let newIndex = newLines.length - 1; newIndex >= 0; newIndex -= 1) {
|
||||
if (oldLines[oldIndex] === newLines[newIndex]) {
|
||||
lcsTable[oldIndex][newIndex] = lcsTable[oldIndex + 1][newIndex + 1] + 1;
|
||||
} else {
|
||||
lcsTable[oldIndex][newIndex] = Math.max(
|
||||
lcsTable[oldIndex + 1][newIndex],
|
||||
lcsTable[oldIndex][newIndex + 1],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const diffLines: DiffLine[] = [];
|
||||
let oldIndex = 0;
|
||||
let newIndex = 0;
|
||||
|
||||
while (oldIndex < oldLines.length && newIndex < newLines.length) {
|
||||
const oldLine = oldLines[oldIndex];
|
||||
const newLine = newLines[newIndex];
|
||||
|
||||
if (oldLine === newLine) {
|
||||
oldIndex += 1;
|
||||
newIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lcsTable[oldIndex + 1][newIndex] >= lcsTable[oldIndex][newIndex + 1]) {
|
||||
diffLines.push({ type: 'removed', content: oldLine, lineNum: oldIndex + 1 });
|
||||
oldIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
diffLines.push({ type: 'added', content: newLine, lineNum: newIndex + 1 });
|
||||
newIndex += 1;
|
||||
}
|
||||
|
||||
while (oldIndex < oldLines.length) {
|
||||
diffLines.push({ type: 'removed', content: oldLines[oldIndex], lineNum: oldIndex + 1 });
|
||||
oldIndex += 1;
|
||||
}
|
||||
|
||||
while (newIndex < newLines.length) {
|
||||
diffLines.push({ type: 'added', content: newLines[newIndex], lineNum: newIndex + 1 });
|
||||
newIndex += 1;
|
||||
}
|
||||
|
||||
return diffLines;
|
||||
};
|
||||
|
||||
export const createCachedDiffCalculator = (): DiffCalculator => {
|
||||
const cache = new Map<string, DiffLine[]>();
|
||||
|
||||
return (oldStr: string, newStr: string) => {
|
||||
const key = JSON.stringify([oldStr, newStr]);
|
||||
const cached = cache.get(key);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const calculated = calculateDiff(oldStr, newStr);
|
||||
cache.set(key, calculated);
|
||||
if (cache.size > 100) {
|
||||
const firstKey = cache.keys().next().value;
|
||||
if (firstKey) {
|
||||
cache.delete(firstKey);
|
||||
}
|
||||
}
|
||||
return calculated;
|
||||
};
|
||||
};
|
||||
|
||||
export const convertCursorSessionMessages = (blobs: CursorBlob[], projectPath: string): ChatMessage[] => {
|
||||
const converted: ChatMessage[] = [];
|
||||
const toolUseMap: Record<string, ChatMessage> = {};
|
||||
|
||||
for (let blobIdx = 0; blobIdx < blobs.length; blobIdx += 1) {
|
||||
const blob = blobs[blobIdx];
|
||||
const content = blob.content;
|
||||
let text = '';
|
||||
let role: ChatMessage['type'] = 'assistant';
|
||||
let reasoningText: string | null = null;
|
||||
|
||||
try {
|
||||
if (content?.role && content?.content) {
|
||||
if (content.role === 'system') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (content.role === 'tool') {
|
||||
const toolItems = asArray<any>(content.content);
|
||||
for (const item of toolItems) {
|
||||
if (item?.type !== 'tool-result') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const toolName = item.toolName === 'ApplyPatch' ? 'Edit' : item.toolName || 'Unknown Tool';
|
||||
const toolCallId = item.toolCallId || content.id;
|
||||
const result = item.result || '';
|
||||
|
||||
if (toolCallId && toolUseMap[toolCallId]) {
|
||||
toolUseMap[toolCallId].toolResult = {
|
||||
content: result,
|
||||
isError: false,
|
||||
};
|
||||
} else {
|
||||
converted.push({
|
||||
type: 'assistant',
|
||||
content: '',
|
||||
timestamp: new Date(Date.now() + blobIdx * 1000),
|
||||
blobId: blob.id,
|
||||
sequence: blob.sequence,
|
||||
rowid: blob.rowid,
|
||||
isToolUse: true,
|
||||
toolName,
|
||||
toolId: toolCallId,
|
||||
toolInput: normalizeToolInput(null),
|
||||
toolResult: {
|
||||
content: result,
|
||||
isError: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
role = content.role === 'user' ? 'user' : 'assistant';
|
||||
|
||||
if (Array.isArray(content.content)) {
|
||||
const textParts: string[] = [];
|
||||
|
||||
for (const part of content.content) {
|
||||
if (part?.type === 'text' && part?.text) {
|
||||
textParts.push(decodeHtmlEntities(part.text));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (part?.type === 'reasoning' && part?.text) {
|
||||
reasoningText = decodeHtmlEntities(part.text);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (part?.type === 'tool-call' || part?.type === 'tool_use') {
|
||||
if (textParts.length > 0 || reasoningText) {
|
||||
converted.push({
|
||||
type: role,
|
||||
content: textParts.join('\n'),
|
||||
reasoning: reasoningText ?? undefined,
|
||||
timestamp: new Date(Date.now() + blobIdx * 1000),
|
||||
blobId: blob.id,
|
||||
sequence: blob.sequence,
|
||||
rowid: blob.rowid,
|
||||
});
|
||||
textParts.length = 0;
|
||||
reasoningText = null;
|
||||
}
|
||||
|
||||
const toolNameRaw = part.toolName || part.name || 'Unknown Tool';
|
||||
const toolName = toolNameRaw === 'ApplyPatch' ? 'Edit' : toolNameRaw;
|
||||
const toolId = part.toolCallId || part.id || `tool_${blobIdx}`;
|
||||
let toolInput = part.args || part.input;
|
||||
|
||||
if (toolName === 'Edit' && part.args) {
|
||||
if (part.args.patch) {
|
||||
const patchLines = String(part.args.patch).split('\n');
|
||||
const oldLines: string[] = [];
|
||||
const newLines: string[] = [];
|
||||
let inPatch = false;
|
||||
|
||||
patchLines.forEach((line) => {
|
||||
if (line.startsWith('@@')) {
|
||||
inPatch = true;
|
||||
return;
|
||||
}
|
||||
if (!inPatch) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (line.startsWith('-')) {
|
||||
oldLines.push(line.slice(1));
|
||||
} else if (line.startsWith('+')) {
|
||||
newLines.push(line.slice(1));
|
||||
} else if (line.startsWith(' ')) {
|
||||
oldLines.push(line.slice(1));
|
||||
newLines.push(line.slice(1));
|
||||
}
|
||||
});
|
||||
|
||||
toolInput = {
|
||||
file_path: toAbsolutePath(projectPath, part.args.file_path),
|
||||
old_string: oldLines.join('\n') || part.args.patch,
|
||||
new_string: newLines.join('\n') || part.args.patch,
|
||||
};
|
||||
} else {
|
||||
toolInput = part.args;
|
||||
}
|
||||
} else if (toolName === 'Read' && part.args) {
|
||||
const filePath = part.args.path || part.args.file_path;
|
||||
toolInput = {
|
||||
file_path: toAbsolutePath(projectPath, filePath),
|
||||
};
|
||||
} else if (toolName === 'Write' && part.args) {
|
||||
const filePath = part.args.path || part.args.file_path;
|
||||
toolInput = {
|
||||
file_path: toAbsolutePath(projectPath, filePath),
|
||||
content: part.args.contents || part.args.content,
|
||||
};
|
||||
}
|
||||
|
||||
const toolMessage: ChatMessage = {
|
||||
type: 'assistant',
|
||||
content: '',
|
||||
timestamp: new Date(Date.now() + blobIdx * 1000),
|
||||
blobId: blob.id,
|
||||
sequence: blob.sequence,
|
||||
rowid: blob.rowid,
|
||||
isToolUse: true,
|
||||
toolName,
|
||||
toolId,
|
||||
toolInput: normalizeToolInput(toolInput),
|
||||
toolResult: null,
|
||||
};
|
||||
converted.push(toolMessage);
|
||||
toolUseMap[toolId] = toolMessage;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof part === 'string') {
|
||||
textParts.push(part);
|
||||
}
|
||||
}
|
||||
|
||||
if (textParts.length > 0) {
|
||||
text = textParts.join('\n');
|
||||
if (reasoningText && !text) {
|
||||
converted.push({
|
||||
type: role,
|
||||
content: '',
|
||||
reasoning: reasoningText,
|
||||
timestamp: new Date(Date.now() + blobIdx * 1000),
|
||||
blobId: blob.id,
|
||||
sequence: blob.sequence,
|
||||
rowid: blob.rowid,
|
||||
});
|
||||
text = '';
|
||||
}
|
||||
} else {
|
||||
text = '';
|
||||
}
|
||||
} else if (typeof content.content === 'string') {
|
||||
text = content.content;
|
||||
}
|
||||
} else if (content?.message?.role && content?.message?.content) {
|
||||
if (content.message.role === 'system') {
|
||||
continue;
|
||||
}
|
||||
|
||||
role = content.message.role === 'user' ? 'user' : 'assistant';
|
||||
if (Array.isArray(content.message.content)) {
|
||||
text = content.message.content
|
||||
.map((part: any) => (typeof part === 'string' ? part : part?.text || ''))
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
} else if (typeof content.message.content === 'string') {
|
||||
text = content.message.content;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('Error parsing blob content:', error);
|
||||
}
|
||||
|
||||
if (text && text.trim()) {
|
||||
const message: ChatMessage = {
|
||||
type: role,
|
||||
content: text,
|
||||
timestamp: new Date(Date.now() + blobIdx * 1000),
|
||||
blobId: blob.id,
|
||||
sequence: blob.sequence,
|
||||
rowid: blob.rowid,
|
||||
};
|
||||
if (reasoningText) {
|
||||
message.reasoning = reasoningText;
|
||||
}
|
||||
converted.push(message);
|
||||
}
|
||||
}
|
||||
|
||||
converted.sort((messageA, messageB) => {
|
||||
if (messageA.sequence !== undefined && messageB.sequence !== undefined) {
|
||||
return Number(messageA.sequence) - Number(messageB.sequence);
|
||||
}
|
||||
if (messageA.rowid !== undefined && messageB.rowid !== undefined) {
|
||||
return Number(messageA.rowid) - Number(messageB.rowid);
|
||||
}
|
||||
return new Date(messageA.timestamp).getTime() - new Date(messageB.timestamp).getTime();
|
||||
});
|
||||
|
||||
return converted;
|
||||
};
|
||||
|
||||
export const convertSessionMessages = (rawMessages: any[]): ChatMessage[] => {
|
||||
const converted: ChatMessage[] = [];
|
||||
const toolResults = new Map<
|
||||
string,
|
||||
{ content: unknown; isError: boolean; timestamp: Date; toolUseResult: unknown }
|
||||
>();
|
||||
|
||||
rawMessages.forEach((message) => {
|
||||
if (message.message?.role === 'user' && Array.isArray(message.message?.content)) {
|
||||
message.message.content.forEach((part: any) => {
|
||||
if (part.type !== 'tool_result') {
|
||||
return;
|
||||
}
|
||||
toolResults.set(part.tool_use_id, {
|
||||
content: part.content,
|
||||
isError: Boolean(part.is_error),
|
||||
timestamp: new Date(message.timestamp || Date.now()),
|
||||
toolUseResult: message.toolUseResult || null,
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
rawMessages.forEach((message) => {
|
||||
if (message.message?.role === 'user' && message.message?.content) {
|
||||
let content = '';
|
||||
if (Array.isArray(message.message.content)) {
|
||||
const textParts: string[] = [];
|
||||
message.message.content.forEach((part: any) => {
|
||||
if (part.type === 'text') {
|
||||
textParts.push(decodeHtmlEntities(part.text));
|
||||
}
|
||||
});
|
||||
content = textParts.join('\n');
|
||||
} else if (typeof message.message.content === 'string') {
|
||||
content = decodeHtmlEntities(message.message.content);
|
||||
} else {
|
||||
content = decodeHtmlEntities(String(message.message.content));
|
||||
}
|
||||
|
||||
const shouldSkip =
|
||||
!content ||
|
||||
content.startsWith('<command-name>') ||
|
||||
content.startsWith('<command-message>') ||
|
||||
content.startsWith('<command-args>') ||
|
||||
content.startsWith('<local-command-stdout>') ||
|
||||
content.startsWith('<system-reminder>') ||
|
||||
content.startsWith('Caveat:') ||
|
||||
content.startsWith('This session is being continued from a previous') ||
|
||||
content.startsWith('[Request interrupted');
|
||||
|
||||
if (!shouldSkip) {
|
||||
converted.push({
|
||||
type: 'user',
|
||||
content: unescapeWithMathProtection(content),
|
||||
timestamp: message.timestamp || new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === 'thinking' && message.message?.content) {
|
||||
converted.push({
|
||||
type: 'assistant',
|
||||
content: unescapeWithMathProtection(message.message.content),
|
||||
timestamp: message.timestamp || new Date().toISOString(),
|
||||
isThinking: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === 'tool_use' && message.toolName) {
|
||||
converted.push({
|
||||
type: 'assistant',
|
||||
content: '',
|
||||
timestamp: message.timestamp || new Date().toISOString(),
|
||||
isToolUse: true,
|
||||
toolName: message.toolName,
|
||||
toolInput: normalizeToolInput(message.toolInput),
|
||||
toolCallId: message.toolCallId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === 'tool_result') {
|
||||
for (let index = converted.length - 1; index >= 0; index -= 1) {
|
||||
const convertedMessage = converted[index];
|
||||
if (!convertedMessage.isToolUse || convertedMessage.toolResult) {
|
||||
continue;
|
||||
}
|
||||
if (!message.toolCallId || convertedMessage.toolCallId === message.toolCallId) {
|
||||
convertedMessage.toolResult = {
|
||||
content: message.output || '',
|
||||
isError: false,
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.message?.role === 'assistant' && message.message?.content) {
|
||||
if (Array.isArray(message.message.content)) {
|
||||
message.message.content.forEach((part: any) => {
|
||||
if (part.type === 'text') {
|
||||
let text = part.text;
|
||||
if (typeof text === 'string') {
|
||||
text = unescapeWithMathProtection(text);
|
||||
}
|
||||
converted.push({
|
||||
type: 'assistant',
|
||||
content: text,
|
||||
timestamp: message.timestamp || new Date().toISOString(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (part.type === 'tool_use') {
|
||||
const toolResult = toolResults.get(part.id);
|
||||
converted.push({
|
||||
type: 'assistant',
|
||||
content: '',
|
||||
timestamp: message.timestamp || new Date().toISOString(),
|
||||
isToolUse: true,
|
||||
toolName: part.name,
|
||||
toolInput: normalizeToolInput(part.input),
|
||||
toolResult: toolResult
|
||||
? {
|
||||
content:
|
||||
typeof toolResult.content === 'string'
|
||||
? toolResult.content
|
||||
: JSON.stringify(toolResult.content),
|
||||
isError: toolResult.isError,
|
||||
toolUseResult: toolResult.toolUseResult,
|
||||
}
|
||||
: null,
|
||||
toolError: toolResult?.isError || false,
|
||||
toolResultTimestamp: toolResult?.timestamp || new Date(),
|
||||
});
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof message.message.content === 'string') {
|
||||
converted.push({
|
||||
type: 'assistant',
|
||||
content: unescapeWithMathProtection(message.message.content),
|
||||
timestamp: message.timestamp || new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return converted;
|
||||
};
|
||||
384
src/components/chat/view/ChatInterface.tsx
Normal file
384
src/components/chat/view/ChatInterface.tsx
Normal file
@@ -0,0 +1,384 @@
|
||||
import React, { useCallback, useEffect, useRef } from 'react';
|
||||
import QuickSettingsPanel from '../../QuickSettingsPanel';
|
||||
import { useTasksSettings } from '../../../contexts/TasksSettingsContext';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ChatMessagesPane from './subcomponents/ChatMessagesPane';
|
||||
import ChatComposer from './subcomponents/ChatComposer';
|
||||
import type { ChatInterfaceProps } from '../types/types';
|
||||
import { useChatProviderState } from '../hooks/useChatProviderState';
|
||||
import { useChatSessionState } from '../hooks/useChatSessionState';
|
||||
import { useChatRealtimeHandlers } from '../hooks/useChatRealtimeHandlers';
|
||||
import { useChatComposerState } from '../hooks/useChatComposerState';
|
||||
import type { Provider } from '../types/types';
|
||||
|
||||
type PendingViewSession = {
|
||||
sessionId: string | null;
|
||||
startedAt: number;
|
||||
};
|
||||
|
||||
function ChatInterface({
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
ws,
|
||||
sendMessage,
|
||||
latestMessage,
|
||||
onFileOpen,
|
||||
onInputFocusChange,
|
||||
onSessionActive,
|
||||
onSessionInactive,
|
||||
onSessionProcessing,
|
||||
onSessionNotProcessing,
|
||||
processingSessions,
|
||||
onReplaceTemporarySession,
|
||||
onNavigateToSession,
|
||||
onShowSettings,
|
||||
autoExpandTools,
|
||||
showRawParameters,
|
||||
showThinking,
|
||||
autoScrollToBottom,
|
||||
sendByCtrlEnter,
|
||||
externalMessageUpdate,
|
||||
onShowAllTasks,
|
||||
}: ChatInterfaceProps) {
|
||||
const { tasksEnabled, isTaskMasterInstalled } = useTasksSettings();
|
||||
const { t } = useTranslation('chat');
|
||||
|
||||
const streamBufferRef = useRef('');
|
||||
const streamTimerRef = useRef<number | null>(null);
|
||||
const pendingViewSessionRef = useRef<PendingViewSession | null>(null);
|
||||
|
||||
const resetStreamingState = useCallback(() => {
|
||||
if (streamTimerRef.current) {
|
||||
clearTimeout(streamTimerRef.current);
|
||||
streamTimerRef.current = null;
|
||||
}
|
||||
streamBufferRef.current = '';
|
||||
}, []);
|
||||
|
||||
const {
|
||||
provider,
|
||||
setProvider,
|
||||
cursorModel,
|
||||
setCursorModel,
|
||||
claudeModel,
|
||||
setClaudeModel,
|
||||
codexModel,
|
||||
setCodexModel,
|
||||
permissionMode,
|
||||
pendingPermissionRequests,
|
||||
setPendingPermissionRequests,
|
||||
cyclePermissionMode,
|
||||
} = useChatProviderState({
|
||||
selectedSession,
|
||||
});
|
||||
|
||||
const {
|
||||
chatMessages,
|
||||
setChatMessages,
|
||||
isLoading,
|
||||
setIsLoading,
|
||||
currentSessionId,
|
||||
setCurrentSessionId,
|
||||
sessionMessages,
|
||||
setSessionMessages,
|
||||
isLoadingSessionMessages,
|
||||
isLoadingMoreMessages,
|
||||
hasMoreMessages,
|
||||
totalMessages,
|
||||
isSystemSessionChange,
|
||||
setIsSystemSessionChange,
|
||||
canAbortSession,
|
||||
setCanAbortSession,
|
||||
isUserScrolledUp,
|
||||
setIsUserScrolledUp,
|
||||
tokenBudget,
|
||||
setTokenBudget,
|
||||
visibleMessageCount,
|
||||
visibleMessages,
|
||||
loadEarlierMessages,
|
||||
claudeStatus,
|
||||
setClaudeStatus,
|
||||
createDiff,
|
||||
scrollContainerRef,
|
||||
scrollToBottom,
|
||||
handleScroll,
|
||||
} = useChatSessionState({
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
ws,
|
||||
sendMessage,
|
||||
autoScrollToBottom,
|
||||
externalMessageUpdate,
|
||||
processingSessions,
|
||||
resetStreamingState,
|
||||
pendingViewSessionRef,
|
||||
});
|
||||
|
||||
const {
|
||||
input,
|
||||
setInput,
|
||||
textareaRef,
|
||||
inputHighlightRef,
|
||||
isTextareaExpanded,
|
||||
thinkingMode,
|
||||
setThinkingMode,
|
||||
slashCommandsCount,
|
||||
filteredCommands,
|
||||
frequentCommands,
|
||||
commandQuery,
|
||||
showCommandMenu,
|
||||
selectedCommandIndex,
|
||||
resetCommandMenuState,
|
||||
handleCommandSelect,
|
||||
handleToggleCommandMenu,
|
||||
showFileDropdown,
|
||||
filteredFiles,
|
||||
selectedFileIndex,
|
||||
renderInputWithMentions,
|
||||
selectFile,
|
||||
attachedImages,
|
||||
setAttachedImages,
|
||||
uploadingImages,
|
||||
imageErrors,
|
||||
getRootProps,
|
||||
getInputProps,
|
||||
isDragActive,
|
||||
openImagePicker,
|
||||
handleSubmit,
|
||||
handleInputChange,
|
||||
handleKeyDown,
|
||||
handlePaste,
|
||||
handleTextareaClick,
|
||||
handleTextareaInput,
|
||||
syncInputOverlayScroll,
|
||||
handleClearInput,
|
||||
handleAbortSession,
|
||||
handleTranscript,
|
||||
handlePermissionDecision,
|
||||
handleGrantToolPermission,
|
||||
handleInputFocusChange,
|
||||
} = useChatComposerState({
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
currentSessionId,
|
||||
provider,
|
||||
permissionMode,
|
||||
cyclePermissionMode,
|
||||
cursorModel,
|
||||
claudeModel,
|
||||
codexModel,
|
||||
isLoading,
|
||||
canAbortSession,
|
||||
tokenBudget,
|
||||
sendMessage,
|
||||
sendByCtrlEnter,
|
||||
onSessionActive,
|
||||
onInputFocusChange,
|
||||
onFileOpen,
|
||||
onShowSettings,
|
||||
pendingViewSessionRef,
|
||||
scrollToBottom,
|
||||
setChatMessages,
|
||||
setSessionMessages,
|
||||
setIsLoading,
|
||||
setCanAbortSession,
|
||||
setClaudeStatus,
|
||||
setIsUserScrolledUp,
|
||||
setPendingPermissionRequests,
|
||||
});
|
||||
|
||||
useChatRealtimeHandlers({
|
||||
latestMessage,
|
||||
provider,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
currentSessionId,
|
||||
setCurrentSessionId,
|
||||
setChatMessages,
|
||||
setIsLoading,
|
||||
setCanAbortSession,
|
||||
setClaudeStatus,
|
||||
setTokenBudget,
|
||||
setIsSystemSessionChange,
|
||||
setPendingPermissionRequests,
|
||||
pendingViewSessionRef,
|
||||
streamBufferRef,
|
||||
streamTimerRef,
|
||||
onSessionInactive,
|
||||
onSessionProcessing,
|
||||
onSessionNotProcessing,
|
||||
onReplaceTemporarySession,
|
||||
onNavigateToSession,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading || !canAbortSession) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleGlobalEscape = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Escape' || event.repeat || event.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
handleAbortSession();
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleGlobalEscape, { capture: true });
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleGlobalEscape, { capture: true });
|
||||
};
|
||||
}, [canAbortSession, handleAbortSession, isLoading]);
|
||||
|
||||
useEffect(() => {
|
||||
const processingSessionId = selectedSession?.id || currentSessionId;
|
||||
if (processingSessionId && isLoading && onSessionProcessing) {
|
||||
onSessionProcessing(processingSessionId);
|
||||
}
|
||||
}, [currentSessionId, isLoading, onSessionProcessing, selectedSession?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
resetStreamingState();
|
||||
};
|
||||
}, [resetStreamingState]);
|
||||
|
||||
if (!selectedProject) {
|
||||
const selectedProviderLabel =
|
||||
provider === 'cursor'
|
||||
? t('messageTypes.cursor')
|
||||
: provider === 'codex'
|
||||
? t('messageTypes.codex')
|
||||
: t('messageTypes.claude');
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="text-center text-gray-500 dark:text-gray-400">
|
||||
<p>
|
||||
{t('projectSelection.startChatWithProvider', {
|
||||
provider: selectedProviderLabel,
|
||||
defaultValue: 'Select a project to start chatting with {{provider}}',
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="h-full flex flex-col">
|
||||
<ChatMessagesPane
|
||||
scrollContainerRef={scrollContainerRef}
|
||||
onWheel={handleScroll}
|
||||
onTouchMove={handleScroll}
|
||||
isLoadingSessionMessages={isLoadingSessionMessages}
|
||||
chatMessages={chatMessages}
|
||||
selectedSession={selectedSession}
|
||||
currentSessionId={currentSessionId}
|
||||
provider={provider}
|
||||
setProvider={(nextProvider) => setProvider(nextProvider as Provider)}
|
||||
textareaRef={textareaRef}
|
||||
claudeModel={claudeModel}
|
||||
setClaudeModel={setClaudeModel}
|
||||
cursorModel={cursorModel}
|
||||
setCursorModel={setCursorModel}
|
||||
codexModel={codexModel}
|
||||
setCodexModel={setCodexModel}
|
||||
tasksEnabled={tasksEnabled}
|
||||
isTaskMasterInstalled={isTaskMasterInstalled}
|
||||
onShowAllTasks={onShowAllTasks}
|
||||
setInput={setInput}
|
||||
isLoadingMoreMessages={isLoadingMoreMessages}
|
||||
hasMoreMessages={hasMoreMessages}
|
||||
totalMessages={totalMessages}
|
||||
sessionMessagesCount={sessionMessages.length}
|
||||
visibleMessageCount={visibleMessageCount}
|
||||
visibleMessages={visibleMessages}
|
||||
loadEarlierMessages={loadEarlierMessages}
|
||||
createDiff={createDiff}
|
||||
onFileOpen={onFileOpen}
|
||||
onShowSettings={onShowSettings}
|
||||
onGrantToolPermission={handleGrantToolPermission}
|
||||
autoExpandTools={autoExpandTools}
|
||||
showRawParameters={showRawParameters}
|
||||
showThinking={showThinking}
|
||||
selectedProject={selectedProject}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
|
||||
<ChatComposer
|
||||
pendingPermissionRequests={pendingPermissionRequests}
|
||||
handlePermissionDecision={handlePermissionDecision}
|
||||
handleGrantToolPermission={handleGrantToolPermission}
|
||||
claudeStatus={claudeStatus}
|
||||
isLoading={isLoading}
|
||||
onAbortSession={handleAbortSession}
|
||||
provider={provider}
|
||||
permissionMode={permissionMode}
|
||||
onModeSwitch={cyclePermissionMode}
|
||||
thinkingMode={thinkingMode}
|
||||
setThinkingMode={setThinkingMode}
|
||||
tokenBudget={tokenBudget}
|
||||
slashCommandsCount={slashCommandsCount}
|
||||
onToggleCommandMenu={handleToggleCommandMenu}
|
||||
hasInput={Boolean(input.trim())}
|
||||
onClearInput={handleClearInput}
|
||||
isUserScrolledUp={isUserScrolledUp}
|
||||
hasMessages={chatMessages.length > 0}
|
||||
onScrollToBottom={scrollToBottom}
|
||||
onSubmit={handleSubmit}
|
||||
isDragActive={isDragActive}
|
||||
attachedImages={attachedImages}
|
||||
onRemoveImage={(index) =>
|
||||
setAttachedImages((previous) =>
|
||||
previous.filter((_, currentIndex) => currentIndex !== index),
|
||||
)
|
||||
}
|
||||
uploadingImages={uploadingImages}
|
||||
imageErrors={imageErrors}
|
||||
showFileDropdown={showFileDropdown}
|
||||
filteredFiles={filteredFiles}
|
||||
selectedFileIndex={selectedFileIndex}
|
||||
onSelectFile={selectFile}
|
||||
filteredCommands={filteredCommands}
|
||||
selectedCommandIndex={selectedCommandIndex}
|
||||
onCommandSelect={handleCommandSelect}
|
||||
onCloseCommandMenu={resetCommandMenuState}
|
||||
isCommandMenuOpen={showCommandMenu}
|
||||
frequentCommands={commandQuery ? [] : frequentCommands}
|
||||
getRootProps={getRootProps as (...args: unknown[]) => Record<string, unknown>}
|
||||
getInputProps={getInputProps as (...args: unknown[]) => Record<string, unknown>}
|
||||
openImagePicker={openImagePicker}
|
||||
inputHighlightRef={inputHighlightRef}
|
||||
renderInputWithMentions={renderInputWithMentions}
|
||||
textareaRef={textareaRef}
|
||||
input={input}
|
||||
onInputChange={handleInputChange}
|
||||
onTextareaClick={handleTextareaClick}
|
||||
onTextareaKeyDown={handleKeyDown}
|
||||
onTextareaPaste={handlePaste}
|
||||
onTextareaScrollSync={syncInputOverlayScroll}
|
||||
onTextareaInput={handleTextareaInput}
|
||||
onInputFocusChange={handleInputFocusChange}
|
||||
placeholder={t('input.placeholder', {
|
||||
provider:
|
||||
provider === 'cursor'
|
||||
? t('messageTypes.cursor')
|
||||
: provider === 'codex'
|
||||
? t('messageTypes.codex')
|
||||
: t('messageTypes.claude'),
|
||||
})}
|
||||
isTextareaExpanded={isTextareaExpanded}
|
||||
sendByCtrlEnter={sendByCtrlEnter}
|
||||
onTranscript={handleTranscript}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<QuickSettingsPanel />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default React.memo(ChatInterface);
|
||||
@@ -0,0 +1,37 @@
|
||||
import { SessionProvider } from '../../../../types/app';
|
||||
import SessionProviderLogo from '../../../SessionProviderLogo';
|
||||
import type { Provider } from '../../types/types';
|
||||
|
||||
type AssistantThinkingIndicatorProps = {
|
||||
selectedProvider: SessionProvider;
|
||||
}
|
||||
|
||||
|
||||
export default function AssistantThinkingIndicator({ selectedProvider }: AssistantThinkingIndicatorProps) {
|
||||
return (
|
||||
<div className="chat-message assistant">
|
||||
<div className="w-full">
|
||||
<div className="flex items-center space-x-3 mb-2">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-sm flex-shrink-0 p-1 bg-transparent">
|
||||
<SessionProviderLogo provider={selectedProvider} className="w-full h-full" />
|
||||
</div>
|
||||
<div className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{selectedProvider === 'cursor' ? 'Cursor' : selectedProvider === 'codex' ? 'Codex' : 'Claude'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-full text-sm text-gray-500 dark:text-gray-400 pl-3 sm:pl-0">
|
||||
<div className="flex items-center space-x-1">
|
||||
<div className="animate-pulse">.</div>
|
||||
<div className="animate-pulse" style={{ animationDelay: '0.2s' }}>
|
||||
.
|
||||
</div>
|
||||
<div className="animate-pulse" style={{ animationDelay: '0.4s' }}>
|
||||
.
|
||||
</div>
|
||||
<span className="ml-2">Thinking...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
346
src/components/chat/view/subcomponents/ChatComposer.tsx
Normal file
346
src/components/chat/view/subcomponents/ChatComposer.tsx
Normal file
@@ -0,0 +1,346 @@
|
||||
import CommandMenu from '../../../CommandMenu';
|
||||
import ClaudeStatus from '../../../ClaudeStatus';
|
||||
import { MicButton } from '../../../MicButton.jsx';
|
||||
import ImageAttachment from './ImageAttachment';
|
||||
import PermissionRequestsBanner from './PermissionRequestsBanner';
|
||||
import ChatInputControls from './ChatInputControls';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type {
|
||||
ChangeEvent,
|
||||
ClipboardEvent,
|
||||
Dispatch,
|
||||
FormEvent,
|
||||
KeyboardEvent,
|
||||
MouseEvent,
|
||||
ReactNode,
|
||||
RefObject,
|
||||
SetStateAction,
|
||||
TouchEvent,
|
||||
} from 'react';
|
||||
import type { PendingPermissionRequest, PermissionMode, Provider } from '../../types/types';
|
||||
|
||||
interface MentionableFile {
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
interface SlashCommand {
|
||||
name: string;
|
||||
description?: string;
|
||||
namespace?: string;
|
||||
path?: string;
|
||||
type?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
interface ChatComposerProps {
|
||||
pendingPermissionRequests: PendingPermissionRequest[];
|
||||
handlePermissionDecision: (
|
||||
requestIds: string | string[],
|
||||
decision: { allow?: boolean; message?: string; rememberEntry?: string | null; updatedInput?: unknown },
|
||||
) => void;
|
||||
handleGrantToolPermission: (suggestion: { entry: string; toolName: string }) => { success: boolean };
|
||||
claudeStatus: { text: string; tokens: number; can_interrupt: boolean } | null;
|
||||
isLoading: boolean;
|
||||
onAbortSession: () => void;
|
||||
provider: Provider | string;
|
||||
permissionMode: PermissionMode | string;
|
||||
onModeSwitch: () => void;
|
||||
thinkingMode: string;
|
||||
setThinkingMode: Dispatch<SetStateAction<string>>;
|
||||
tokenBudget: { used?: number; total?: number } | null;
|
||||
slashCommandsCount: number;
|
||||
onToggleCommandMenu: () => void;
|
||||
hasInput: boolean;
|
||||
onClearInput: () => void;
|
||||
isUserScrolledUp: boolean;
|
||||
hasMessages: boolean;
|
||||
onScrollToBottom: () => void;
|
||||
onSubmit: (event: FormEvent<HTMLFormElement> | MouseEvent<HTMLButtonElement> | TouchEvent<HTMLButtonElement>) => void;
|
||||
isDragActive: boolean;
|
||||
attachedImages: File[];
|
||||
onRemoveImage: (index: number) => void;
|
||||
uploadingImages: Map<string, number>;
|
||||
imageErrors: Map<string, string>;
|
||||
showFileDropdown: boolean;
|
||||
filteredFiles: MentionableFile[];
|
||||
selectedFileIndex: number;
|
||||
onSelectFile: (file: MentionableFile) => void;
|
||||
filteredCommands: SlashCommand[];
|
||||
selectedCommandIndex: number;
|
||||
onCommandSelect: (command: SlashCommand, index: number, isHover: boolean) => void;
|
||||
onCloseCommandMenu: () => void;
|
||||
isCommandMenuOpen: boolean;
|
||||
frequentCommands: SlashCommand[];
|
||||
getRootProps: (...args: unknown[]) => Record<string, unknown>;
|
||||
getInputProps: (...args: unknown[]) => Record<string, unknown>;
|
||||
openImagePicker: () => void;
|
||||
inputHighlightRef: RefObject<HTMLDivElement>;
|
||||
renderInputWithMentions: (text: string) => ReactNode;
|
||||
textareaRef: RefObject<HTMLTextAreaElement>;
|
||||
input: string;
|
||||
onInputChange: (event: ChangeEvent<HTMLTextAreaElement>) => void;
|
||||
onTextareaClick: (event: MouseEvent<HTMLTextAreaElement>) => void;
|
||||
onTextareaKeyDown: (event: KeyboardEvent<HTMLTextAreaElement>) => void;
|
||||
onTextareaPaste: (event: ClipboardEvent<HTMLTextAreaElement>) => void;
|
||||
onTextareaScrollSync: (target: HTMLTextAreaElement) => void;
|
||||
onTextareaInput: (event: FormEvent<HTMLTextAreaElement>) => void;
|
||||
onInputFocusChange?: (focused: boolean) => void;
|
||||
placeholder: string;
|
||||
isTextareaExpanded: boolean;
|
||||
sendByCtrlEnter?: boolean;
|
||||
onTranscript: (text: string) => void;
|
||||
}
|
||||
|
||||
export default function ChatComposer({
|
||||
pendingPermissionRequests,
|
||||
handlePermissionDecision,
|
||||
handleGrantToolPermission,
|
||||
claudeStatus,
|
||||
isLoading,
|
||||
onAbortSession,
|
||||
provider,
|
||||
permissionMode,
|
||||
onModeSwitch,
|
||||
thinkingMode,
|
||||
setThinkingMode,
|
||||
tokenBudget,
|
||||
slashCommandsCount,
|
||||
onToggleCommandMenu,
|
||||
hasInput,
|
||||
onClearInput,
|
||||
isUserScrolledUp,
|
||||
hasMessages,
|
||||
onScrollToBottom,
|
||||
onSubmit,
|
||||
isDragActive,
|
||||
attachedImages,
|
||||
onRemoveImage,
|
||||
uploadingImages,
|
||||
imageErrors,
|
||||
showFileDropdown,
|
||||
filteredFiles,
|
||||
selectedFileIndex,
|
||||
onSelectFile,
|
||||
filteredCommands,
|
||||
selectedCommandIndex,
|
||||
onCommandSelect,
|
||||
onCloseCommandMenu,
|
||||
isCommandMenuOpen,
|
||||
frequentCommands,
|
||||
getRootProps,
|
||||
getInputProps,
|
||||
openImagePicker,
|
||||
inputHighlightRef,
|
||||
renderInputWithMentions,
|
||||
textareaRef,
|
||||
input,
|
||||
onInputChange,
|
||||
onTextareaClick,
|
||||
onTextareaKeyDown,
|
||||
onTextareaPaste,
|
||||
onTextareaScrollSync,
|
||||
onTextareaInput,
|
||||
onInputFocusChange,
|
||||
placeholder,
|
||||
isTextareaExpanded,
|
||||
sendByCtrlEnter,
|
||||
onTranscript,
|
||||
}: ChatComposerProps) {
|
||||
const { t } = useTranslation('chat');
|
||||
const AnyCommandMenu = CommandMenu as any;
|
||||
const textareaRect = textareaRef.current?.getBoundingClientRect();
|
||||
const commandMenuPosition = {
|
||||
top: textareaRect ? Math.max(16, textareaRect.top - 316) : 0,
|
||||
left: textareaRect ? textareaRect.left : 16,
|
||||
bottom: textareaRect ? window.innerHeight - textareaRect.top + 8 : 90,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-2 sm:p-4 md:p-4 flex-shrink-0 pb-2 sm:pb-4 md:pb-6">
|
||||
<div className="flex-1">
|
||||
<ClaudeStatus
|
||||
status={claudeStatus}
|
||||
isLoading={isLoading}
|
||||
onAbort={onAbortSession}
|
||||
provider={provider}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="max-w-4xl mx-auto mb-3">
|
||||
<PermissionRequestsBanner
|
||||
pendingPermissionRequests={pendingPermissionRequests}
|
||||
handlePermissionDecision={handlePermissionDecision}
|
||||
handleGrantToolPermission={handleGrantToolPermission}
|
||||
/>
|
||||
|
||||
<ChatInputControls
|
||||
permissionMode={permissionMode}
|
||||
onModeSwitch={onModeSwitch}
|
||||
provider={provider}
|
||||
thinkingMode={thinkingMode}
|
||||
setThinkingMode={setThinkingMode}
|
||||
tokenBudget={tokenBudget}
|
||||
slashCommandsCount={slashCommandsCount}
|
||||
onToggleCommandMenu={onToggleCommandMenu}
|
||||
hasInput={hasInput}
|
||||
onClearInput={onClearInput}
|
||||
isUserScrolledUp={isUserScrolledUp}
|
||||
hasMessages={hasMessages}
|
||||
onScrollToBottom={onScrollToBottom}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<form onSubmit={onSubmit as (event: FormEvent<HTMLFormElement>) => void} className="relative max-w-4xl mx-auto">
|
||||
{isDragActive && (
|
||||
<div className="absolute inset-0 bg-blue-500/20 border-2 border-dashed border-blue-500 rounded-lg flex items-center justify-center z-50">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-lg">
|
||||
<svg className="w-8 h-8 text-blue-500 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
|
||||
/>
|
||||
</svg>
|
||||
<p className="text-sm font-medium">Drop images here</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{attachedImages.length > 0 && (
|
||||
<div className="mb-2 p-2 bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{attachedImages.map((file, index) => (
|
||||
<ImageAttachment
|
||||
key={index}
|
||||
file={file}
|
||||
onRemove={() => onRemoveImage(index)}
|
||||
uploadProgress={uploadingImages.get(file.name)}
|
||||
error={imageErrors.get(file.name)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showFileDropdown && filteredFiles.length > 0 && (
|
||||
<div className="absolute bottom-full left-0 right-0 mb-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg max-h-48 overflow-y-auto z-50 backdrop-blur-sm">
|
||||
{filteredFiles.map((file, index) => (
|
||||
<div
|
||||
key={file.path}
|
||||
className={`px-4 py-3 cursor-pointer border-b border-gray-100 dark:border-gray-700 last:border-b-0 touch-manipulation ${
|
||||
index === selectedFileIndex
|
||||
? 'bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300'
|
||||
: 'hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300'
|
||||
}`}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onSelectFile(file);
|
||||
}}
|
||||
>
|
||||
<div className="font-medium text-sm">{file.name}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 font-mono">{file.path}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<AnyCommandMenu
|
||||
commands={filteredCommands}
|
||||
selectedIndex={selectedCommandIndex}
|
||||
onSelect={onCommandSelect}
|
||||
onClose={onCloseCommandMenu}
|
||||
position={commandMenuPosition}
|
||||
isOpen={isCommandMenuOpen}
|
||||
frequentCommands={frequentCommands}
|
||||
/>
|
||||
|
||||
<div
|
||||
{...getRootProps()}
|
||||
className={`relative bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-600 focus-within:ring-2 focus-within:ring-blue-500 dark:focus-within:ring-blue-500 focus-within:border-blue-500 transition-all duration-200 overflow-hidden ${
|
||||
isTextareaExpanded ? 'chat-input-expanded' : ''
|
||||
}`}
|
||||
>
|
||||
<input {...getInputProps()} />
|
||||
<div ref={inputHighlightRef} aria-hidden="true" className="absolute inset-0 pointer-events-none overflow-hidden rounded-2xl">
|
||||
<div className="chat-input-placeholder block w-full pl-12 pr-20 sm:pr-40 py-1.5 sm:py-4 text-transparent text-base leading-6 whitespace-pre-wrap break-words">
|
||||
{renderInputWithMentions(input)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative z-10">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={onInputChange}
|
||||
onClick={onTextareaClick}
|
||||
onKeyDown={onTextareaKeyDown}
|
||||
onPaste={onTextareaPaste}
|
||||
onScroll={(event) => onTextareaScrollSync(event.target as HTMLTextAreaElement)}
|
||||
onFocus={() => onInputFocusChange?.(true)}
|
||||
onBlur={() => onInputFocusChange?.(false)}
|
||||
onInput={onTextareaInput}
|
||||
placeholder={placeholder}
|
||||
disabled={isLoading}
|
||||
className="chat-input-placeholder block w-full pl-12 pr-20 sm:pr-40 py-1.5 sm:py-4 bg-transparent rounded-2xl focus:outline-none text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 disabled:opacity-50 resize-none min-h-[50px] sm:min-h-[80px] max-h-[40vh] sm:max-h-[300px] overflow-y-auto text-base leading-6 transition-all duration-200"
|
||||
style={{ height: '50px' }}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={openImagePicker}
|
||||
className="absolute left-2 top-1/2 transform -translate-y-1/2 p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
|
||||
title={t('input.attachImages')}
|
||||
>
|
||||
<svg className="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<div className="absolute right-16 sm:right-16 top-1/2 transform -translate-y-1/2" style={{ display: 'none' }}>
|
||||
<MicButton onTranscript={onTranscript} className="w-10 h-10 sm:w-10 sm:h-10" />
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!input.trim() || isLoading}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
onSubmit(event);
|
||||
}}
|
||||
onTouchStart={(event) => {
|
||||
event.preventDefault();
|
||||
onSubmit(event);
|
||||
}}
|
||||
className="absolute right-2 top-1/2 transform -translate-y-1/2 w-12 h-12 sm:w-12 sm:h-12 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:ring-offset-gray-800"
|
||||
>
|
||||
<svg className="w-4 h-4 sm:w-5 sm:h-5 text-white transform rotate-90" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<div
|
||||
className={`absolute bottom-1 left-12 right-14 sm:right-40 text-xs text-gray-400 dark:text-gray-500 pointer-events-none hidden sm:block transition-opacity duration-200 ${
|
||||
input.trim() ? 'opacity-0' : 'opacity-100'
|
||||
}`}
|
||||
>
|
||||
{sendByCtrlEnter ? t('input.hintText.ctrlEnter') : t('input.hintText.enter')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
138
src/components/chat/view/subcomponents/ChatInputControls.tsx
Normal file
138
src/components/chat/view/subcomponents/ChatInputControls.tsx
Normal file
@@ -0,0 +1,138 @@
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ThinkingModeSelector from './ThinkingModeSelector';
|
||||
import TokenUsagePie from './TokenUsagePie';
|
||||
import type { PermissionMode, Provider } from '../../types/types';
|
||||
|
||||
interface ChatInputControlsProps {
|
||||
permissionMode: PermissionMode | string;
|
||||
onModeSwitch: () => void;
|
||||
provider: Provider | string;
|
||||
thinkingMode: string;
|
||||
setThinkingMode: React.Dispatch<React.SetStateAction<string>>;
|
||||
tokenBudget: { used?: number; total?: number } | null;
|
||||
slashCommandsCount: number;
|
||||
onToggleCommandMenu: () => void;
|
||||
hasInput: boolean;
|
||||
onClearInput: () => void;
|
||||
isUserScrolledUp: boolean;
|
||||
hasMessages: boolean;
|
||||
onScrollToBottom: () => void;
|
||||
}
|
||||
|
||||
export default function ChatInputControls({
|
||||
permissionMode,
|
||||
onModeSwitch,
|
||||
provider,
|
||||
thinkingMode,
|
||||
setThinkingMode,
|
||||
tokenBudget,
|
||||
slashCommandsCount,
|
||||
onToggleCommandMenu,
|
||||
hasInput,
|
||||
onClearInput,
|
||||
isUserScrolledUp,
|
||||
hasMessages,
|
||||
onScrollToBottom,
|
||||
}: ChatInputControlsProps) {
|
||||
const { t } = useTranslation('chat');
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onModeSwitch}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium border transition-all duration-200 ${
|
||||
permissionMode === 'default'
|
||||
? 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:bg-gray-200 dark:hover:bg-gray-600'
|
||||
: permissionMode === 'acceptEdits'
|
||||
? 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 border-green-300 dark:border-green-600 hover:bg-green-100 dark:hover:bg-green-900/30'
|
||||
: permissionMode === 'bypassPermissions'
|
||||
? 'bg-orange-50 dark:bg-orange-900/20 text-orange-700 dark:text-orange-300 border-orange-300 dark:border-orange-600 hover:bg-orange-100 dark:hover:bg-orange-900/30'
|
||||
: 'bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 border-blue-300 dark:border-blue-600 hover:bg-blue-100 dark:hover:bg-blue-900/30'
|
||||
}`}
|
||||
title={t('input.clickToChangeMode')}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={`w-2 h-2 rounded-full ${
|
||||
permissionMode === 'default'
|
||||
? 'bg-gray-500'
|
||||
: permissionMode === 'acceptEdits'
|
||||
? 'bg-green-500'
|
||||
: permissionMode === 'bypassPermissions'
|
||||
? 'bg-orange-500'
|
||||
: 'bg-blue-500'
|
||||
}`}
|
||||
/>
|
||||
<span>
|
||||
{permissionMode === 'default' && t('codex.modes.default')}
|
||||
{permissionMode === 'acceptEdits' && t('codex.modes.acceptEdits')}
|
||||
{permissionMode === 'bypassPermissions' && t('codex.modes.bypassPermissions')}
|
||||
{permissionMode === 'plan' && t('codex.modes.plan')}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{provider === 'claude' && (
|
||||
<ThinkingModeSelector selectedMode={thinkingMode} onModeChange={setThinkingMode} onClose={() => {}} className="" />
|
||||
)}
|
||||
|
||||
<TokenUsagePie used={tokenBudget?.used || 0} total={tokenBudget?.total || parseInt(import.meta.env.VITE_CONTEXT_WINDOW) || 160000} />
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleCommandMenu}
|
||||
className="relative w-8 h-8 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 rounded-full flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:ring-offset-gray-800"
|
||||
title={t('input.showAllCommands')}
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z"
|
||||
/>
|
||||
</svg>
|
||||
{slashCommandsCount > 0 && (
|
||||
<span
|
||||
className="absolute -top-1 -right-1 bg-blue-600 text-white text-xs font-bold rounded-full w-5 h-5 flex items-center justify-center"
|
||||
style={{ fontSize: '10px' }}
|
||||
>
|
||||
{slashCommandsCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{hasInput && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClearInput}
|
||||
className="w-8 h-8 bg-white dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-full flex items-center justify-center transition-all duration-200 group shadow-sm"
|
||||
title={t('input.clearInput', { defaultValue: 'Clear input' })}
|
||||
>
|
||||
<svg
|
||||
className="w-4 h-4 text-gray-600 dark:text-gray-300 group-hover:text-gray-800 dark:group-hover:text-gray-100 transition-colors"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{isUserScrolledUp && hasMessages && (
|
||||
<button
|
||||
onClick={onScrollToBottom}
|
||||
className="w-8 h-8 bg-blue-600 hover:bg-blue-700 text-white rounded-full shadow-lg flex items-center justify-center transition-all duration-200 hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:ring-offset-gray-800"
|
||||
title={t('input.scrollToBottom', { defaultValue: 'Scroll to bottom' })}
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 14l-7 7m0 0l-7-7m7 7V3" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
208
src/components/chat/view/subcomponents/ChatMessagesPane.tsx
Normal file
208
src/components/chat/view/subcomponents/ChatMessagesPane.tsx
Normal file
@@ -0,0 +1,208 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useCallback, useRef } from 'react';
|
||||
import type { Dispatch, RefObject, SetStateAction } from 'react';
|
||||
|
||||
import MessageComponent from './MessageComponent';
|
||||
import ProviderSelectionEmptyState from './ProviderSelectionEmptyState';
|
||||
import type { ChatMessage } from '../../types/types';
|
||||
import type { Project, ProjectSession, SessionProvider } from '../../../../types/app';
|
||||
import AssistantThinkingIndicator from './AssistantThinkingIndicator';
|
||||
import { getIntrinsicMessageKey } from '../../utils/messageKeys';
|
||||
|
||||
interface ChatMessagesPaneProps {
|
||||
scrollContainerRef: RefObject<HTMLDivElement>;
|
||||
onWheel: () => void;
|
||||
onTouchMove: () => void;
|
||||
isLoadingSessionMessages: boolean;
|
||||
chatMessages: ChatMessage[];
|
||||
selectedSession: ProjectSession | null;
|
||||
currentSessionId: string | null;
|
||||
provider: SessionProvider;
|
||||
setProvider: (provider: SessionProvider) => void;
|
||||
textareaRef: RefObject<HTMLTextAreaElement>;
|
||||
claudeModel: string;
|
||||
setClaudeModel: (model: string) => void;
|
||||
cursorModel: string;
|
||||
setCursorModel: (model: string) => void;
|
||||
codexModel: string;
|
||||
setCodexModel: (model: string) => void;
|
||||
tasksEnabled: boolean;
|
||||
isTaskMasterInstalled: boolean | null;
|
||||
onShowAllTasks?: (() => void) | null;
|
||||
setInput: Dispatch<SetStateAction<string>>;
|
||||
isLoadingMoreMessages: boolean;
|
||||
hasMoreMessages: boolean;
|
||||
totalMessages: number;
|
||||
sessionMessagesCount: number;
|
||||
visibleMessageCount: number;
|
||||
visibleMessages: ChatMessage[];
|
||||
loadEarlierMessages: () => void;
|
||||
createDiff: any;
|
||||
onFileOpen?: (filePath: string, diffInfo?: unknown) => void;
|
||||
onShowSettings?: () => void;
|
||||
onGrantToolPermission: (suggestion: { entry: string; toolName: string }) => { success: boolean };
|
||||
autoExpandTools?: boolean;
|
||||
showRawParameters?: boolean;
|
||||
showThinking?: boolean;
|
||||
selectedProject: Project;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export default function ChatMessagesPane({
|
||||
scrollContainerRef,
|
||||
onWheel,
|
||||
onTouchMove,
|
||||
isLoadingSessionMessages,
|
||||
chatMessages,
|
||||
selectedSession,
|
||||
currentSessionId,
|
||||
provider,
|
||||
setProvider,
|
||||
textareaRef,
|
||||
claudeModel,
|
||||
setClaudeModel,
|
||||
cursorModel,
|
||||
setCursorModel,
|
||||
codexModel,
|
||||
setCodexModel,
|
||||
tasksEnabled,
|
||||
isTaskMasterInstalled,
|
||||
onShowAllTasks,
|
||||
setInput,
|
||||
isLoadingMoreMessages,
|
||||
hasMoreMessages,
|
||||
totalMessages,
|
||||
sessionMessagesCount,
|
||||
visibleMessageCount,
|
||||
visibleMessages,
|
||||
loadEarlierMessages,
|
||||
createDiff,
|
||||
onFileOpen,
|
||||
onShowSettings,
|
||||
onGrantToolPermission,
|
||||
autoExpandTools,
|
||||
showRawParameters,
|
||||
showThinking,
|
||||
selectedProject,
|
||||
isLoading,
|
||||
}: ChatMessagesPaneProps) {
|
||||
const { t } = useTranslation('chat');
|
||||
const messageKeyMapRef = useRef<WeakMap<ChatMessage, string>>(new WeakMap());
|
||||
const allocatedKeysRef = useRef<Set<string>>(new Set());
|
||||
const generatedMessageKeyCounterRef = useRef(0);
|
||||
|
||||
// Keep keys stable across prepends so existing MessageComponent instances retain local state.
|
||||
const getMessageKey = useCallback((message: ChatMessage) => {
|
||||
const existingKey = messageKeyMapRef.current.get(message);
|
||||
if (existingKey) {
|
||||
return existingKey;
|
||||
}
|
||||
|
||||
const intrinsicKey = getIntrinsicMessageKey(message);
|
||||
let candidateKey = intrinsicKey;
|
||||
|
||||
if (!candidateKey || allocatedKeysRef.current.has(candidateKey)) {
|
||||
do {
|
||||
generatedMessageKeyCounterRef.current += 1;
|
||||
candidateKey = intrinsicKey
|
||||
? `${intrinsicKey}-${generatedMessageKeyCounterRef.current}`
|
||||
: `message-generated-${generatedMessageKeyCounterRef.current}`;
|
||||
} while (allocatedKeysRef.current.has(candidateKey));
|
||||
}
|
||||
|
||||
allocatedKeysRef.current.add(candidateKey);
|
||||
messageKeyMapRef.current.set(message, candidateKey);
|
||||
return candidateKey;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
onWheel={onWheel}
|
||||
onTouchMove={onTouchMove}
|
||||
className="flex-1 overflow-y-auto overflow-x-hidden px-0 py-3 sm:p-4 space-y-3 sm:space-y-4 relative"
|
||||
>
|
||||
{isLoadingSessionMessages && chatMessages.length === 0 ? (
|
||||
<div className="text-center text-gray-500 dark:text-gray-400 mt-8">
|
||||
<div className="flex items-center justify-center space-x-2">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-400" />
|
||||
<p>{t('session.loading.sessionMessages')}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : chatMessages.length === 0 ? (
|
||||
<ProviderSelectionEmptyState
|
||||
selectedSession={selectedSession}
|
||||
currentSessionId={currentSessionId}
|
||||
provider={provider}
|
||||
setProvider={setProvider}
|
||||
textareaRef={textareaRef}
|
||||
claudeModel={claudeModel}
|
||||
setClaudeModel={setClaudeModel}
|
||||
cursorModel={cursorModel}
|
||||
setCursorModel={setCursorModel}
|
||||
codexModel={codexModel}
|
||||
setCodexModel={setCodexModel}
|
||||
tasksEnabled={tasksEnabled}
|
||||
isTaskMasterInstalled={isTaskMasterInstalled}
|
||||
onShowAllTasks={onShowAllTasks}
|
||||
setInput={setInput}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{isLoadingMoreMessages && (
|
||||
<div className="text-center text-gray-500 dark:text-gray-400 py-3">
|
||||
<div className="flex items-center justify-center space-x-2">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-400" />
|
||||
<p className="text-sm">{t('session.loading.olderMessages')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasMoreMessages && !isLoadingMoreMessages && (
|
||||
<div className="text-center text-gray-500 dark:text-gray-400 text-sm py-2 border-b border-gray-200 dark:border-gray-700">
|
||||
{totalMessages > 0 && (
|
||||
<span>
|
||||
{t('session.messages.showingOf', { shown: sessionMessagesCount, total: totalMessages })} |
|
||||
<span className="text-xs">{t('session.messages.scrollToLoad')}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!hasMoreMessages && chatMessages.length > visibleMessageCount && (
|
||||
<div className="text-center text-gray-500 dark:text-gray-400 text-sm py-2 border-b border-gray-200 dark:border-gray-700">
|
||||
{t('session.messages.showingLast', { count: visibleMessageCount, total: chatMessages.length })} |
|
||||
<button className="ml-1 text-blue-600 hover:text-blue-700 underline" onClick={loadEarlierMessages}>
|
||||
{t('session.messages.loadEarlier')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{visibleMessages.map((message, index) => {
|
||||
const prevMessage = index > 0 ? visibleMessages[index - 1] : null;
|
||||
return (
|
||||
<MessageComponent
|
||||
key={getMessageKey(message)}
|
||||
message={message}
|
||||
index={index}
|
||||
prevMessage={prevMessage}
|
||||
createDiff={createDiff}
|
||||
onFileOpen={onFileOpen}
|
||||
onShowSettings={onShowSettings}
|
||||
onGrantToolPermission={onGrantToolPermission}
|
||||
autoExpandTools={autoExpandTools}
|
||||
showRawParameters={showRawParameters}
|
||||
showThinking={showThinking}
|
||||
selectedProject={selectedProject}
|
||||
provider={provider}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
|
||||
{isLoading && <AssistantThinkingIndicator selectedProvider={provider} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
50
src/components/chat/view/subcomponents/ImageAttachment.tsx
Normal file
50
src/components/chat/view/subcomponents/ImageAttachment.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
interface ImageAttachmentProps {
|
||||
file: File;
|
||||
onRemove: () => void;
|
||||
uploadProgress?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
const ImageAttachment = ({ file, onRemove, uploadProgress, error }: ImageAttachmentProps) => {
|
||||
const [preview, setPreview] = useState<string | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
const url = URL.createObjectURL(file);
|
||||
setPreview(url);
|
||||
return () => URL.revokeObjectURL(url);
|
||||
}, [file]);
|
||||
|
||||
return (
|
||||
<div className="relative group">
|
||||
<img src={preview} alt={file.name} className="w-20 h-20 object-cover rounded" />
|
||||
{uploadProgress !== undefined && uploadProgress < 100 && (
|
||||
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
|
||||
<div className="text-white text-xs">{uploadProgress}%</div>
|
||||
</div>
|
||||
)}
|
||||
{error && (
|
||||
<div className="absolute inset-0 bg-red-500/50 flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRemove}
|
||||
className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 focus:opacity-100 transition-opacity"
|
||||
aria-label="Remove image"
|
||||
>
|
||||
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ImageAttachment;
|
||||
|
||||
|
||||
188
src/components/chat/view/subcomponents/Markdown.tsx
Normal file
188
src/components/chat/view/subcomponents/Markdown.tsx
Normal file
@@ -0,0 +1,188 @@
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import remarkMath from 'remark-math';
|
||||
import rehypeKatex from 'rehype-katex';
|
||||
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
|
||||
import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { normalizeInlineCodeFences } from '../../utils/chatFormatting';
|
||||
|
||||
type MarkdownProps = {
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
type CodeBlockProps = {
|
||||
node?: any;
|
||||
inline?: boolean;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
};
|
||||
|
||||
const CodeBlock = ({ node, inline, className, children, ...props }: CodeBlockProps) => {
|
||||
const { t } = useTranslation('chat');
|
||||
const [copied, setCopied] = useState(false);
|
||||
const raw = Array.isArray(children) ? children.join('') : String(children ?? '');
|
||||
const looksMultiline = /[\r\n]/.test(raw);
|
||||
const inlineDetected = inline || (node && node.type === 'inlineCode');
|
||||
const shouldInline = inlineDetected || !looksMultiline;
|
||||
|
||||
if (shouldInline) {
|
||||
return (
|
||||
<code
|
||||
className={`font-mono text-[0.9em] px-1.5 py-0.5 rounded-md bg-gray-100 text-gray-900 border border-gray-200 dark:bg-gray-800/60 dark:text-gray-100 dark:border-gray-700 whitespace-pre-wrap break-words ${
|
||||
className || ''
|
||||
}`}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</code>
|
||||
);
|
||||
}
|
||||
|
||||
const match = /language-(\w+)/.exec(className || '');
|
||||
const language = match ? match[1] : 'text';
|
||||
const textToCopy = raw;
|
||||
|
||||
const handleCopy = () => {
|
||||
const doSet = () => {
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
};
|
||||
try {
|
||||
if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
|
||||
navigator.clipboard.writeText(textToCopy).then(doSet).catch(() => {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = textToCopy;
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.opacity = '0';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
try {
|
||||
document.execCommand('copy');
|
||||
} catch {}
|
||||
document.body.removeChild(ta);
|
||||
doSet();
|
||||
});
|
||||
} else {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = textToCopy;
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.opacity = '0';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
try {
|
||||
document.execCommand('copy');
|
||||
} catch {}
|
||||
document.body.removeChild(ta);
|
||||
doSet();
|
||||
}
|
||||
} catch {}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative group my-2">
|
||||
{language && language !== 'text' && (
|
||||
<div className="absolute top-2 left-3 z-10 text-xs text-gray-400 font-medium uppercase">{language}</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopy}
|
||||
className="absolute top-2 right-2 z-10 opacity-0 group-hover:opacity-100 focus:opacity-100 active:opacity-100 transition-opacity text-xs px-2 py-1 rounded-md bg-gray-700/80 hover:bg-gray-700 text-white border border-gray-600"
|
||||
title={copied ? t('codeBlock.copied') : t('codeBlock.copyCode')}
|
||||
aria-label={copied ? t('codeBlock.copied') : t('codeBlock.copyCode')}
|
||||
>
|
||||
{copied ? (
|
||||
<span className="flex items-center gap-1">
|
||||
<svg className="w-3.5 h-3.5" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
{t('codeBlock.copied')}
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1">
|
||||
<svg
|
||||
className="w-3.5 h-3.5"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
|
||||
<path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"></path>
|
||||
</svg>
|
||||
{t('codeBlock.copy')}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<SyntaxHighlighter
|
||||
language={language}
|
||||
style={oneDark}
|
||||
customStyle={{
|
||||
margin: 0,
|
||||
borderRadius: '0.5rem',
|
||||
fontSize: '0.875rem',
|
||||
padding: language && language !== 'text' ? '2rem 1rem 1rem 1rem' : '1rem',
|
||||
}}
|
||||
codeTagProps={{
|
||||
style: {
|
||||
fontFamily:
|
||||
'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
||||
},
|
||||
}}
|
||||
>
|
||||
{raw}
|
||||
</SyntaxHighlighter>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const markdownComponents = {
|
||||
code: CodeBlock,
|
||||
blockquote: ({ children }: { children?: React.ReactNode }) => (
|
||||
<blockquote className="border-l-4 border-gray-300 dark:border-gray-600 pl-4 italic text-gray-600 dark:text-gray-400 my-2">
|
||||
{children}
|
||||
</blockquote>
|
||||
),
|
||||
a: ({ href, children }: { href?: string; children?: React.ReactNode }) => (
|
||||
<a href={href} className="text-blue-600 dark:text-blue-400 hover:underline" target="_blank" rel="noopener noreferrer">
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
p: ({ children }: { children?: React.ReactNode }) => <div className="mb-2 last:mb-0">{children}</div>,
|
||||
table: ({ children }: { children?: React.ReactNode }) => (
|
||||
<div className="overflow-x-auto my-2">
|
||||
<table className="min-w-full border-collapse border border-gray-200 dark:border-gray-700">{children}</table>
|
||||
</div>
|
||||
),
|
||||
thead: ({ children }: { children?: React.ReactNode }) => <thead className="bg-gray-50 dark:bg-gray-800">{children}</thead>,
|
||||
th: ({ children }: { children?: React.ReactNode }) => (
|
||||
<th className="px-3 py-2 text-left text-sm font-semibold border border-gray-200 dark:border-gray-700">{children}</th>
|
||||
),
|
||||
td: ({ children }: { children?: React.ReactNode }) => (
|
||||
<td className="px-3 py-2 align-top text-sm border border-gray-200 dark:border-gray-700">{children}</td>
|
||||
),
|
||||
};
|
||||
|
||||
export function Markdown({ children, className }: MarkdownProps) {
|
||||
const content = normalizeInlineCodeFences(String(children ?? ''));
|
||||
const remarkPlugins = useMemo(() => [remarkGfm, remarkMath], []);
|
||||
const rehypePlugins = useMemo(() => [rehypeKatex], []);
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<ReactMarkdown remarkPlugins={remarkPlugins} rehypePlugins={rehypePlugins} components={markdownComponents as any}>
|
||||
{content}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
446
src/components/chat/view/subcomponents/MessageComponent.tsx
Normal file
446
src/components/chat/view/subcomponents/MessageComponent.tsx
Normal file
@@ -0,0 +1,446 @@
|
||||
import React, { memo, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import SessionProviderLogo from '../../../SessionProviderLogo';
|
||||
import type {
|
||||
ChatMessage,
|
||||
ClaudePermissionSuggestion,
|
||||
PermissionGrantResult,
|
||||
Provider,
|
||||
} from '../../types/types';
|
||||
import { Markdown } from './Markdown';
|
||||
import { formatUsageLimitText } from '../../utils/chatFormatting';
|
||||
import { getClaudePermissionSuggestion } from '../../utils/chatPermissions';
|
||||
import type { Project } from '../../../../types/app';
|
||||
import { ToolRenderer, shouldHideToolResult } from '../../tools';
|
||||
|
||||
type DiffLine = {
|
||||
type: string;
|
||||
content: string;
|
||||
lineNum: number;
|
||||
};
|
||||
|
||||
interface MessageComponentProps {
|
||||
message: ChatMessage;
|
||||
index: number;
|
||||
prevMessage: ChatMessage | null;
|
||||
createDiff: (oldStr: string, newStr: string) => DiffLine[];
|
||||
onFileOpen?: (filePath: string, diffInfo?: unknown) => void;
|
||||
onShowSettings?: () => void;
|
||||
onGrantToolPermission?: (suggestion: ClaudePermissionSuggestion) => PermissionGrantResult | null | undefined;
|
||||
autoExpandTools?: boolean;
|
||||
showRawParameters?: boolean;
|
||||
showThinking?: boolean;
|
||||
selectedProject?: Project | null;
|
||||
provider: Provider | string;
|
||||
}
|
||||
|
||||
type InteractiveOption = {
|
||||
number: string;
|
||||
text: string;
|
||||
isSelected: boolean;
|
||||
};
|
||||
|
||||
type PermissionGrantState = 'idle' | 'granted' | 'error';
|
||||
|
||||
const MessageComponent = memo(({ message, index, prevMessage, createDiff, onFileOpen, onShowSettings, onGrantToolPermission, autoExpandTools, showRawParameters, showThinking, selectedProject, provider }: MessageComponentProps) => {
|
||||
const { t } = useTranslation('chat');
|
||||
const isGrouped = prevMessage && prevMessage.type === message.type &&
|
||||
((prevMessage.type === 'assistant') ||
|
||||
(prevMessage.type === 'user') ||
|
||||
(prevMessage.type === 'tool') ||
|
||||
(prevMessage.type === 'error'));
|
||||
const messageRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const [isExpanded, setIsExpanded] = React.useState(false);
|
||||
const permissionSuggestion = getClaudePermissionSuggestion(message, provider);
|
||||
const [permissionGrantState, setPermissionGrantState] = React.useState<PermissionGrantState>('idle');
|
||||
|
||||
|
||||
React.useEffect(() => {
|
||||
setPermissionGrantState('idle');
|
||||
}, [permissionSuggestion?.entry, message.toolId]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const node = messageRef.current;
|
||||
if (!autoExpandTools || !node || !message.isToolUse) return;
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (entry.isIntersecting && !isExpanded) {
|
||||
setIsExpanded(true);
|
||||
const details = node.querySelectorAll<HTMLDetailsElement>('details');
|
||||
details.forEach((detail) => {
|
||||
detail.open = true;
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
{ threshold: 0.1 }
|
||||
);
|
||||
|
||||
observer.observe(node);
|
||||
|
||||
return () => {
|
||||
observer.unobserve(node);
|
||||
};
|
||||
}, [autoExpandTools, isExpanded, message.isToolUse]);
|
||||
|
||||
const formattedTime = useMemo(() => new Date(message.timestamp).toLocaleTimeString(), [message.timestamp]);
|
||||
const shouldHideThinkingMessage = Boolean(message.isThinking && !showThinking);
|
||||
|
||||
if (shouldHideThinkingMessage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={messageRef}
|
||||
className={`chat-message ${message.type} ${isGrouped ? 'grouped' : ''} ${message.type === 'user' ? 'flex justify-end px-3 sm:px-0' : 'px-3 sm:px-0'}`}
|
||||
>
|
||||
{message.type === 'user' ? (
|
||||
/* User message bubble on the right */
|
||||
<div className="flex items-end space-x-0 sm:space-x-3 w-full sm:w-auto sm:max-w-[85%] md:max-w-md lg:max-w-lg xl:max-w-xl">
|
||||
<div className="bg-blue-600 text-white rounded-2xl rounded-br-md px-3 sm:px-4 py-2 shadow-sm flex-1 sm:flex-initial">
|
||||
<div className="text-sm whitespace-pre-wrap break-words">
|
||||
{message.content}
|
||||
</div>
|
||||
{message.images && message.images.length > 0 && (
|
||||
<div className="mt-2 grid grid-cols-2 gap-2">
|
||||
{message.images.map((img, idx) => (
|
||||
<img
|
||||
key={img.name || idx}
|
||||
src={img.data}
|
||||
alt={img.name}
|
||||
className="rounded-lg max-w-full h-auto cursor-pointer hover:opacity-90 transition-opacity"
|
||||
onClick={() => window.open(img.data, '_blank')}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="text-xs text-blue-100 mt-1 text-right">
|
||||
{formattedTime}
|
||||
</div>
|
||||
</div>
|
||||
{!isGrouped && (
|
||||
<div className="hidden sm:flex w-8 h-8 bg-blue-600 rounded-full items-center justify-center text-white text-sm flex-shrink-0">
|
||||
U
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
/* Claude/Error/Tool messages on the left */
|
||||
<div className="w-full">
|
||||
{!isGrouped && (
|
||||
<div className="flex items-center space-x-3 mb-2">
|
||||
{message.type === 'error' ? (
|
||||
<div className="w-8 h-8 bg-red-600 rounded-full flex items-center justify-center text-white text-sm flex-shrink-0">
|
||||
!
|
||||
</div>
|
||||
) : message.type === 'tool' ? (
|
||||
<div className="w-8 h-8 bg-gray-600 dark:bg-gray-700 rounded-full flex items-center justify-center text-white text-sm flex-shrink-0">
|
||||
🔧
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-sm flex-shrink-0 p-1">
|
||||
<SessionProviderLogo provider={provider} className="w-full h-full" />
|
||||
</div>
|
||||
)}
|
||||
<div className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{message.type === 'error' ? t('messageTypes.error') : message.type === 'tool' ? t('messageTypes.tool') : (provider === 'cursor' ? t('messageTypes.cursor') : provider === 'codex' ? t('messageTypes.codex') : t('messageTypes.claude'))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="w-full">
|
||||
|
||||
{message.isToolUse ? (
|
||||
<>
|
||||
<div className="flex flex-col">
|
||||
<div className="flex flex-col">
|
||||
<Markdown className="prose prose-sm max-w-none dark:prose-invert">
|
||||
{String(message.displayText || '')}
|
||||
</Markdown>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{message.toolInput && (
|
||||
<ToolRenderer
|
||||
toolName={message.toolName || 'UnknownTool'}
|
||||
toolInput={message.toolInput}
|
||||
toolResult={message.toolResult}
|
||||
toolId={message.toolId}
|
||||
mode="input"
|
||||
onFileOpen={onFileOpen}
|
||||
createDiff={createDiff}
|
||||
selectedProject={selectedProject}
|
||||
autoExpandTools={autoExpandTools}
|
||||
showRawParameters={showRawParameters}
|
||||
rawToolInput={typeof message.toolInput === 'string' ? message.toolInput : undefined}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Tool Result Section */}
|
||||
{message.toolResult && !shouldHideToolResult(message.toolName || 'UnknownTool', message.toolResult) && (
|
||||
message.toolResult.isError ? (
|
||||
// Error results - red error box with content
|
||||
<div
|
||||
id={`tool-result-${message.toolId}`}
|
||||
className="relative mt-2 p-3 rounded border scroll-mt-4 bg-red-50/50 dark:bg-red-950/10 border-red-200/60 dark:border-red-800/40"
|
||||
>
|
||||
<div className="relative flex items-center gap-1.5 mb-2">
|
||||
<svg className="w-4 h-4 text-red-500 dark:text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
<span className="text-xs font-medium text-red-700 dark:text-red-300">{t('messageTypes.error')}</span>
|
||||
</div>
|
||||
<div className="relative text-sm text-red-900 dark:text-red-100">
|
||||
<Markdown className="prose prose-sm max-w-none prose-red dark:prose-invert">
|
||||
{String(message.toolResult.content || '')}
|
||||
</Markdown>
|
||||
{permissionSuggestion && (
|
||||
<div className="mt-4 border-t border-red-200/60 dark:border-red-800/60 pt-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (!onGrantToolPermission) return;
|
||||
const result = onGrantToolPermission(permissionSuggestion);
|
||||
if (result?.success) {
|
||||
setPermissionGrantState('granted');
|
||||
} else {
|
||||
setPermissionGrantState('error');
|
||||
}
|
||||
}}
|
||||
disabled={permissionSuggestion.isAllowed || permissionGrantState === 'granted'}
|
||||
className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${
|
||||
permissionSuggestion.isAllowed || permissionGrantState === 'granted'
|
||||
? 'bg-green-100 dark:bg-green-900/30 border-green-300/70 dark:border-green-800/60 text-green-800 dark:text-green-200 cursor-default'
|
||||
: 'bg-white/80 dark:bg-gray-900/40 border-red-300/70 dark:border-red-800/60 text-red-700 dark:text-red-200 hover:bg-white dark:hover:bg-gray-900/70'
|
||||
}`}
|
||||
>
|
||||
{permissionSuggestion.isAllowed || permissionGrantState === 'granted'
|
||||
? t('permissions.added')
|
||||
: t('permissions.grant', { tool: permissionSuggestion.toolName })}
|
||||
</button>
|
||||
{onShowSettings && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); onShowSettings(); }}
|
||||
className="text-xs text-red-700 dark:text-red-200 underline hover:text-red-800 dark:hover:text-red-100"
|
||||
>
|
||||
{t('permissions.openSettings')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-2 text-xs text-red-700/90 dark:text-red-200/80">
|
||||
{t('permissions.addTo', { entry: permissionSuggestion.entry })}
|
||||
</div>
|
||||
{permissionGrantState === 'error' && (
|
||||
<div className="mt-2 text-xs text-red-700 dark:text-red-200">
|
||||
{t('permissions.error')}
|
||||
</div>
|
||||
)}
|
||||
{(permissionSuggestion.isAllowed || permissionGrantState === 'granted') && (
|
||||
<div className="mt-2 text-xs text-green-700 dark:text-green-200">
|
||||
{t('permissions.retry')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
// Non-error results - route through ToolRenderer (single source of truth)
|
||||
<div id={`tool-result-${message.toolId}`} className="scroll-mt-4">
|
||||
<ToolRenderer
|
||||
toolName={message.toolName || 'UnknownTool'}
|
||||
toolInput={message.toolInput}
|
||||
toolResult={message.toolResult}
|
||||
toolId={message.toolId}
|
||||
mode="result"
|
||||
onFileOpen={onFileOpen}
|
||||
createDiff={createDiff}
|
||||
selectedProject={selectedProject}
|
||||
autoExpandTools={autoExpandTools}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</>
|
||||
) : message.isInteractivePrompt ? (
|
||||
// Special handling for interactive prompts
|
||||
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-8 h-8 bg-amber-500 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
|
||||
<svg className="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h4 className="font-semibold text-amber-900 dark:text-amber-100 text-base mb-3">
|
||||
{t('interactive.title')}
|
||||
</h4>
|
||||
{(() => {
|
||||
const lines = (message.content || '').split('\n').filter((line) => line.trim());
|
||||
const questionLine = lines.find((line) => line.includes('?')) || lines[0] || '';
|
||||
const options: InteractiveOption[] = [];
|
||||
|
||||
// Parse the menu options
|
||||
lines.forEach((line) => {
|
||||
// Match lines like "❯ 1. Yes" or " 2. No"
|
||||
const optionMatch = line.match(/[❯\s]*(\d+)\.\s+(.+)/);
|
||||
if (optionMatch) {
|
||||
const isSelected = line.includes('❯');
|
||||
options.push({
|
||||
number: optionMatch[1],
|
||||
text: optionMatch[2].trim(),
|
||||
isSelected
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<p className="text-sm text-amber-800 dark:text-amber-200 mb-4">
|
||||
{questionLine}
|
||||
</p>
|
||||
|
||||
{/* Option buttons */}
|
||||
<div className="space-y-2 mb-4">
|
||||
{options.map((option) => (
|
||||
<button
|
||||
key={option.number}
|
||||
className={`w-full text-left px-4 py-3 rounded-lg border-2 transition-all ${
|
||||
option.isSelected
|
||||
? 'bg-amber-600 dark:bg-amber-700 text-white border-amber-600 dark:border-amber-700 shadow-md'
|
||||
: 'bg-white dark:bg-gray-800 text-amber-900 dark:text-amber-100 border-amber-300 dark:border-amber-700'
|
||||
} cursor-not-allowed opacity-75`}
|
||||
disabled
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${
|
||||
option.isSelected
|
||||
? 'bg-white/20'
|
||||
: 'bg-amber-100 dark:bg-amber-800/50'
|
||||
}`}>
|
||||
{option.number}
|
||||
</span>
|
||||
<span className="text-sm sm:text-base font-medium flex-1">
|
||||
{option.text}
|
||||
</span>
|
||||
{option.isSelected && (
|
||||
<span className="text-lg">❯</span>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="bg-amber-100 dark:bg-amber-800/30 rounded-lg p-3">
|
||||
<p className="text-amber-900 dark:text-amber-100 text-sm font-medium mb-1">
|
||||
{t('interactive.waiting')}
|
||||
</p>
|
||||
<p className="text-amber-800 dark:text-amber-200 text-xs">
|
||||
{t('interactive.instruction')}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
</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>{t('thinking.emoji')}</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 */}
|
||||
{showThinking && message.reasoning && (
|
||||
<details className="mb-3">
|
||||
<summary className="cursor-pointer text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 font-medium">
|
||||
{t('thinking.emoji')}
|
||||
</summary>
|
||||
<div className="mt-2 pl-4 border-l-2 border-gray-300 dark:border-gray-600 italic text-gray-600 dark:text-gray-400 text-sm">
|
||||
<div className="whitespace-pre-wrap">
|
||||
{message.reasoning}
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
|
||||
{(() => {
|
||||
const content = formatUsageLimitText(String(message.content || ''));
|
||||
|
||||
// Detect if content is pure JSON (starts with { or [)
|
||||
const trimmedContent = content.trim();
|
||||
if ((trimmedContent.startsWith('{') || trimmedContent.startsWith('[')) &&
|
||||
(trimmedContent.endsWith('}') || trimmedContent.endsWith(']'))) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmedContent);
|
||||
const formatted = JSON.stringify(parsed, null, 2);
|
||||
|
||||
return (
|
||||
<div className="my-2">
|
||||
<div className="flex items-center gap-2 mb-2 text-sm text-gray-600 dark:text-gray-400">
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<span className="font-medium">{t('json.response')}</span>
|
||||
</div>
|
||||
<div className="bg-gray-800 dark:bg-gray-900 border border-gray-600/30 dark:border-gray-700 rounded-lg overflow-hidden">
|
||||
<pre className="p-4 overflow-x-auto">
|
||||
<code className="text-gray-100 dark:text-gray-200 text-sm font-mono block whitespace-pre">
|
||||
{formatted}
|
||||
</code>
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
} catch {
|
||||
// Not valid JSON, fall through to normal rendering
|
||||
}
|
||||
}
|
||||
|
||||
// Normal rendering for non-JSON content
|
||||
return message.type === 'assistant' ? (
|
||||
<Markdown className="prose prose-sm max-w-none dark:prose-invert prose-gray">
|
||||
{content}
|
||||
</Markdown>
|
||||
) : (
|
||||
<div className="whitespace-pre-wrap">
|
||||
{content}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isGrouped && (
|
||||
<div className="text-[11px] text-gray-400 dark:text-gray-500 mt-1">
|
||||
{formattedTime}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export default MessageComponent;
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import React from 'react';
|
||||
import type { PendingPermissionRequest } from '../../types/types';
|
||||
import { buildClaudeToolPermissionEntry, formatToolInputForDisplay } from '../../utils/chatPermissions';
|
||||
import { getClaudeSettings } from '../../utils/chatStorage';
|
||||
|
||||
interface PermissionRequestsBannerProps {
|
||||
pendingPermissionRequests: PendingPermissionRequest[];
|
||||
handlePermissionDecision: (
|
||||
requestIds: string | string[],
|
||||
decision: { allow?: boolean; message?: string; rememberEntry?: string | null; updatedInput?: unknown },
|
||||
) => void;
|
||||
handleGrantToolPermission: (suggestion: { entry: string; toolName: string }) => { success: boolean };
|
||||
}
|
||||
|
||||
export default function PermissionRequestsBanner({
|
||||
pendingPermissionRequests,
|
||||
handlePermissionDecision,
|
||||
handleGrantToolPermission,
|
||||
}: PermissionRequestsBannerProps) {
|
||||
if (!pendingPermissionRequests.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mb-3 space-y-2">
|
||||
{pendingPermissionRequests.map((request) => {
|
||||
const rawInput = formatToolInputForDisplay(request.input);
|
||||
const permissionEntry = buildClaudeToolPermissionEntry(request.toolName, rawInput);
|
||||
const settings = getClaudeSettings();
|
||||
const alreadyAllowed = permissionEntry ? settings.allowedTools.includes(permissionEntry) : false;
|
||||
const rememberLabel = alreadyAllowed ? 'Allow (saved)' : 'Allow & remember';
|
||||
const matchingRequestIds = permissionEntry
|
||||
? pendingPermissionRequests
|
||||
.filter(
|
||||
(item) =>
|
||||
buildClaudeToolPermissionEntry(item.toolName, formatToolInputForDisplay(item.input)) === permissionEntry,
|
||||
)
|
||||
.map((item) => item.requestId)
|
||||
: [request.requestId];
|
||||
|
||||
return (
|
||||
<div
|
||||
key={request.requestId}
|
||||
className="rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 p-3 shadow-sm"
|
||||
>
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<div className="text-sm font-semibold text-amber-900 dark:text-amber-100">Permission required</div>
|
||||
<div className="text-xs text-amber-800 dark:text-amber-200">
|
||||
Tool: <span className="font-mono">{request.toolName}</span>
|
||||
</div>
|
||||
</div>
|
||||
{permissionEntry && (
|
||||
<div className="text-xs text-amber-700 dark:text-amber-300">
|
||||
Allow rule: <span className="font-mono">{permissionEntry}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{rawInput && (
|
||||
<details className="mt-2">
|
||||
<summary className="cursor-pointer text-xs text-amber-800 dark:text-amber-200 hover:text-amber-900 dark:hover:text-amber-100">
|
||||
View tool input
|
||||
</summary>
|
||||
<pre className="mt-2 max-h-40 overflow-auto rounded-md bg-white/80 dark:bg-gray-900/60 border border-amber-200/60 dark:border-amber-800/60 p-2 text-xs text-amber-900 dark:text-amber-100 whitespace-pre-wrap">
|
||||
{rawInput}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handlePermissionDecision(request.requestId, { allow: true })}
|
||||
className="inline-flex items-center gap-2 rounded-md bg-amber-600 text-white text-xs font-medium px-3 py-1.5 hover:bg-amber-700 transition-colors"
|
||||
>
|
||||
Allow once
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (permissionEntry && !alreadyAllowed) {
|
||||
handleGrantToolPermission({ entry: permissionEntry, toolName: request.toolName });
|
||||
}
|
||||
handlePermissionDecision(matchingRequestIds, { allow: true, rememberEntry: permissionEntry });
|
||||
}}
|
||||
className={`inline-flex items-center gap-2 rounded-md text-xs font-medium px-3 py-1.5 border transition-colors ${
|
||||
permissionEntry
|
||||
? 'border-amber-300 text-amber-800 hover:bg-amber-100 dark:border-amber-700 dark:text-amber-100 dark:hover:bg-amber-900/30'
|
||||
: 'border-gray-300 text-gray-400 cursor-not-allowed'
|
||||
}`}
|
||||
disabled={!permissionEntry}
|
||||
>
|
||||
{rememberLabel}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handlePermissionDecision(request.requestId, { allow: false, message: 'User denied tool use' })}
|
||||
className="inline-flex items-center gap-2 rounded-md text-xs font-medium px-3 py-1.5 border border-red-300 text-red-700 hover:bg-red-50 dark:border-red-800 dark:text-red-200 dark:hover:bg-red-900/30 transition-colors"
|
||||
>
|
||||
Deny
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import SessionProviderLogo from '../../../SessionProviderLogo';
|
||||
import NextTaskBanner from '../../../NextTaskBanner.jsx';
|
||||
import { CLAUDE_MODELS, CURSOR_MODELS, CODEX_MODELS } from '../../../../../shared/modelConstants';
|
||||
import type { ProjectSession, SessionProvider } from '../../../../types/app';
|
||||
|
||||
interface ProviderSelectionEmptyStateProps {
|
||||
selectedSession: ProjectSession | null;
|
||||
currentSessionId: string | null;
|
||||
provider: SessionProvider;
|
||||
setProvider: (next: SessionProvider) => void;
|
||||
textareaRef: React.RefObject<HTMLTextAreaElement>;
|
||||
claudeModel: string;
|
||||
setClaudeModel: (model: string) => void;
|
||||
cursorModel: string;
|
||||
setCursorModel: (model: string) => void;
|
||||
codexModel: string;
|
||||
setCodexModel: (model: string) => void;
|
||||
tasksEnabled: boolean;
|
||||
isTaskMasterInstalled: boolean | null;
|
||||
onShowAllTasks?: (() => void) | null;
|
||||
setInput: React.Dispatch<React.SetStateAction<string>>;
|
||||
}
|
||||
|
||||
export default function ProviderSelectionEmptyState({
|
||||
selectedSession,
|
||||
currentSessionId,
|
||||
provider,
|
||||
setProvider,
|
||||
textareaRef,
|
||||
claudeModel,
|
||||
setClaudeModel,
|
||||
cursorModel,
|
||||
setCursorModel,
|
||||
codexModel,
|
||||
setCodexModel,
|
||||
tasksEnabled,
|
||||
isTaskMasterInstalled,
|
||||
onShowAllTasks,
|
||||
setInput,
|
||||
}: ProviderSelectionEmptyStateProps) {
|
||||
const { t } = useTranslation('chat');
|
||||
// Reuse one translated prompt so task-start behavior stays consistent across empty and session states.
|
||||
const nextTaskPrompt = t('tasks.nextTaskPrompt', { defaultValue: 'Start the next task' });
|
||||
|
||||
const selectProvider = (nextProvider: SessionProvider) => {
|
||||
setProvider(nextProvider);
|
||||
localStorage.setItem('selected-provider', nextProvider);
|
||||
setTimeout(() => textareaRef.current?.focus(), 100);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
{!selectedSession && !currentSessionId && (
|
||||
<div className="text-center px-6 sm:px-4 py-8">
|
||||
<h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-3">{t('providerSelection.title')}</h2>
|
||||
<p className="text-gray-600 dark:text-gray-400 mb-8">{t('providerSelection.description')}</p>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-4 justify-center items-center mb-8">
|
||||
<button
|
||||
onClick={() => selectProvider('claude')}
|
||||
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 === 'claude'
|
||||
? 'border-blue-500 shadow-lg ring-2 ring-blue-500/20'
|
||||
: 'border-gray-200 dark:border-gray-700 hover:border-blue-400'
|
||||
}`}
|
||||
>
|
||||
<div className="flex flex-col items-center justify-center h-full gap-3">
|
||||
<SessionProviderLogo provider="claude" className="w-10 h-10" />
|
||||
<div>
|
||||
<p className="font-semibold text-gray-900 dark:text-white">Claude Code</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">{t('providerSelection.providerInfo.anthropic')}</p>
|
||||
</div>
|
||||
</div>
|
||||
{provider === 'claude' && (
|
||||
<div className="absolute top-2 right-2">
|
||||
<div className="w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center">
|
||||
<svg className="w-3 h-3 text-white" 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>
|
||||
|
||||
<button
|
||||
onClick={() => selectProvider('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 === 'cursor'
|
||||
? 'border-purple-500 shadow-lg ring-2 ring-purple-500/20'
|
||||
: 'border-gray-200 dark:border-gray-700 hover:border-purple-400'
|
||||
}`}
|
||||
>
|
||||
<div className="flex flex-col items-center justify-center h-full gap-3">
|
||||
<SessionProviderLogo provider="cursor" className="w-10 h-10" />
|
||||
<div>
|
||||
<p className="font-semibold text-gray-900 dark:text-white">Cursor</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">{t('providerSelection.providerInfo.cursorEditor')}</p>
|
||||
</div>
|
||||
</div>
|
||||
{provider === 'cursor' && (
|
||||
<div className="absolute top-2 right-2">
|
||||
<div className="w-5 h-5 bg-purple-500 rounded-full flex items-center justify-center">
|
||||
<svg className="w-3 h-3 text-white" 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>
|
||||
|
||||
<button
|
||||
onClick={() => selectProvider('codex')}
|
||||
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'
|
||||
}`}
|
||||
>
|
||||
<div className="flex flex-col items-center justify-center h-full gap-3">
|
||||
<SessionProviderLogo provider="codex" 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">{t('providerSelection.providerInfo.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>
|
||||
|
||||
<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">{t('providerSelection.selectModel')}</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]"
|
||||
>
|
||||
{CLAUDE_MODELS.OPTIONS.map(({ value, label }) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</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]"
|
||||
>
|
||||
{CODEX_MODELS.OPTIONS.map(({ value, label }) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</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'}
|
||||
>
|
||||
{CURSOR_MODELS.OPTIONS.map(({ value, label }) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{provider === 'claude'
|
||||
? t('providerSelection.readyPrompt.claude', { model: claudeModel })
|
||||
: provider === 'cursor'
|
||||
? t('providerSelection.readyPrompt.cursor', { model: cursorModel })
|
||||
: provider === 'codex'
|
||||
? t('providerSelection.readyPrompt.codex', { model: codexModel })
|
||||
: t('providerSelection.readyPrompt.default')}
|
||||
</p>
|
||||
|
||||
{provider && tasksEnabled && isTaskMasterInstalled && (
|
||||
<div className="mt-4 px-4 sm:px-0">
|
||||
<NextTaskBanner onStartTask={() => setInput(nextTaskPrompt)} onShowAllTasks={onShowAllTasks} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{selectedSession && (
|
||||
<div className="text-center text-gray-500 dark:text-gray-400 px-6 sm:px-4">
|
||||
<p className="font-bold text-lg sm:text-xl mb-3">{t('session.continue.title')}</p>
|
||||
<p className="text-sm sm:text-base leading-relaxed">{t('session.continue.description')}</p>
|
||||
|
||||
{tasksEnabled && isTaskMasterInstalled && (
|
||||
<div className="mt-4 px-4 sm:px-0">
|
||||
<NextTaskBanner onStartTask={() => setInput(nextTaskPrompt)} onShowAllTasks={onShowAllTasks} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,55 +1,21 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import { Brain, Zap, Sparkles, Atom, X } from 'lucide-react';
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { Brain, X } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const thinkingModes = [
|
||||
{
|
||||
id: 'none',
|
||||
name: 'Standard',
|
||||
description: 'Regular Claude response',
|
||||
icon: null,
|
||||
prefix: '',
|
||||
color: 'text-gray-600'
|
||||
},
|
||||
{
|
||||
id: 'think',
|
||||
name: 'Think',
|
||||
description: 'Basic extended thinking',
|
||||
icon: Brain,
|
||||
prefix: 'think',
|
||||
color: 'text-blue-600'
|
||||
},
|
||||
{
|
||||
id: 'think-hard',
|
||||
name: 'Think Hard',
|
||||
description: 'More thorough evaluation',
|
||||
icon: Zap,
|
||||
prefix: 'think hard',
|
||||
color: 'text-purple-600'
|
||||
},
|
||||
{
|
||||
id: 'think-harder',
|
||||
name: 'Think Harder',
|
||||
description: 'Deep analysis with alternatives',
|
||||
icon: Sparkles,
|
||||
prefix: 'think harder',
|
||||
color: 'text-indigo-600'
|
||||
},
|
||||
{
|
||||
id: 'ultrathink',
|
||||
name: 'Ultrathink',
|
||||
description: 'Maximum thinking budget',
|
||||
icon: Atom,
|
||||
prefix: 'ultrathink',
|
||||
color: 'text-red-600'
|
||||
}
|
||||
];
|
||||
import { thinkingModes } from '../../constants/thinkingModes';
|
||||
|
||||
function ThinkingModeSelector({ selectedMode, onModeChange, onClose, className = '' }) {
|
||||
type ThinkingModeSelectorProps = {
|
||||
selectedMode: string;
|
||||
onModeChange: (modeId: string) => void;
|
||||
onClose?: () => void;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
function ThinkingModeSelector({ selectedMode, onModeChange, onClose, className = '' }: ThinkingModeSelectorProps) {
|
||||
const { t } = useTranslation('chat');
|
||||
|
||||
// Mapping from mode ID to translation key
|
||||
const modeKeyMap = {
|
||||
const modeKeyMap: Record<string, string> = {
|
||||
'think-hard': 'thinkHard',
|
||||
'think-harder': 'thinkHarder'
|
||||
};
|
||||
@@ -65,11 +31,11 @@ function ThinkingModeSelector({ selectedMode, onModeChange, onClose, className =
|
||||
});
|
||||
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const dropdownRef = useRef(null);
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||
setIsOpen(false);
|
||||
if (onClose) onClose();
|
||||
}
|
||||
@@ -87,11 +53,10 @@ function ThinkingModeSelector({ selectedMode, onModeChange, onClose, className =
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className={`w-10 h-10 sm:w-10 sm:h-10 rounded-full flex items-center justify-center transition-all duration-200 ${
|
||||
selectedMode === 'none'
|
||||
className={`w-10 h-10 sm:w-10 sm:h-10 rounded-full flex items-center justify-center transition-all duration-200 ${selectedMode === 'none'
|
||||
? 'bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600'
|
||||
: 'bg-blue-100 hover:bg-blue-200 dark:bg-blue-900 dark:hover:bg-blue-800'
|
||||
}`}
|
||||
}`}
|
||||
title={t('thinkingMode.buttonTitle', { mode: currentMode.name })}
|
||||
>
|
||||
<IconComponent className={`w-5 h-5 ${currentMode.color}`} />
|
||||
@@ -123,7 +88,7 @@ function ThinkingModeSelector({ selectedMode, onModeChange, onClose, className =
|
||||
{translatedModes.map((mode) => {
|
||||
const ModeIcon = mode.icon;
|
||||
const isSelected = mode.id === selectedMode;
|
||||
|
||||
|
||||
return (
|
||||
<button
|
||||
key={mode.id}
|
||||
@@ -132,9 +97,8 @@ function ThinkingModeSelector({ selectedMode, onModeChange, onClose, className =
|
||||
setIsOpen(false);
|
||||
if (onClose) onClose();
|
||||
}}
|
||||
className={`w-full px-4 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors ${
|
||||
isSelected ? 'bg-gray-50 dark:bg-gray-700' : ''
|
||||
}`}
|
||||
className={`w-full px-4 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors ${isSelected ? 'bg-gray-50 dark:bg-gray-700' : ''
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className={`mt-0.5 ${mode.icon ? mode.color : 'text-gray-400'}`}>
|
||||
@@ -142,9 +106,8 @@ function ThinkingModeSelector({ selectedMode, onModeChange, onClose, className =
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`font-medium text-sm ${
|
||||
isSelected ? 'text-gray-900 dark:text-white' : 'text-gray-700 dark:text-gray-300'
|
||||
}`}>
|
||||
<span className={`font-medium text-sm ${isSelected ? 'text-gray-900 dark:text-white' : 'text-gray-700 dark:text-gray-300'
|
||||
}`}>
|
||||
{mode.name}
|
||||
</span>
|
||||
{isSelected && (
|
||||
@@ -179,5 +142,4 @@ function ThinkingModeSelector({ selectedMode, onModeChange, onClose, className =
|
||||
);
|
||||
}
|
||||
|
||||
export default ThinkingModeSelector;
|
||||
export { thinkingModes };
|
||||
export default ThinkingModeSelector;
|
||||
@@ -1,9 +1,12 @@
|
||||
import React from 'react';
|
||||
type TokenUsagePieProps = {
|
||||
used: number;
|
||||
total: number;
|
||||
};
|
||||
|
||||
function TokenUsagePie({ used, total }) {
|
||||
export default function TokenUsagePie({ used, total }: TokenUsagePieProps) {
|
||||
// Token usage visualization component
|
||||
// Only bail out on missing values or non‐positive totals; allow used===0 to render 0%
|
||||
if (used == null || total == null || total <= 0) return null;
|
||||
if (used == null || total == null || total <= 0) return null;
|
||||
|
||||
const percentage = Math.min(100, (used / total) * 100);
|
||||
const radius = 10;
|
||||
@@ -48,6 +51,4 @@ function TokenUsagePie({ used, total }) {
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default TokenUsagePie;
|
||||
}
|
||||
110
src/components/main-content/hooks/useEditorSidebar.ts
Normal file
110
src/components/main-content/hooks/useEditorSidebar.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { MouseEvent as ReactMouseEvent } from 'react';
|
||||
import type { Project } from '../../../types/app';
|
||||
import type { DiffInfo, EditingFile } from '../types/types';
|
||||
|
||||
type UseEditorSidebarOptions = {
|
||||
selectedProject: Project | null;
|
||||
isMobile: boolean;
|
||||
initialWidth?: number;
|
||||
};
|
||||
|
||||
export function useEditorSidebar({
|
||||
selectedProject,
|
||||
isMobile,
|
||||
initialWidth = 600,
|
||||
}: UseEditorSidebarOptions) {
|
||||
const [editingFile, setEditingFile] = useState<EditingFile | null>(null);
|
||||
const [editorWidth, setEditorWidth] = useState(initialWidth);
|
||||
const [editorExpanded, setEditorExpanded] = useState(false);
|
||||
const [isResizing, setIsResizing] = useState(false);
|
||||
const resizeHandleRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const handleFileOpen = useCallback(
|
||||
(filePath: string, diffInfo: DiffInfo | null = null) => {
|
||||
const normalizedPath = filePath.replace(/\\/g, '/');
|
||||
const fileName = normalizedPath.split('/').pop() || filePath;
|
||||
|
||||
setEditingFile({
|
||||
name: fileName,
|
||||
path: filePath,
|
||||
projectName: selectedProject?.name,
|
||||
diffInfo,
|
||||
});
|
||||
},
|
||||
[selectedProject?.name],
|
||||
);
|
||||
|
||||
const handleCloseEditor = useCallback(() => {
|
||||
setEditingFile(null);
|
||||
setEditorExpanded(false);
|
||||
}, []);
|
||||
|
||||
const handleToggleEditorExpand = useCallback(() => {
|
||||
setEditorExpanded((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
const handleResizeStart = useCallback(
|
||||
(event: ReactMouseEvent<HTMLDivElement>) => {
|
||||
if (isMobile) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsResizing(true);
|
||||
event.preventDefault();
|
||||
},
|
||||
[isMobile],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleMouseMove = (event: globalThis.MouseEvent) => {
|
||||
if (!isResizing) {
|
||||
return;
|
||||
}
|
||||
|
||||
const container = resizeHandleRef.current?.parentElement;
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const newWidth = containerRect.right - event.clientX;
|
||||
|
||||
const minWidth = 300;
|
||||
const maxWidth = containerRect.width * 0.8;
|
||||
|
||||
if (newWidth >= minWidth && newWidth <= maxWidth) {
|
||||
setEditorWidth(newWidth);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseUp = () => {
|
||||
setIsResizing(false);
|
||||
};
|
||||
|
||||
if (isResizing) {
|
||||
document.addEventListener('mousemove', handleMouseMove);
|
||||
document.addEventListener('mouseup', handleMouseUp);
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousemove', handleMouseMove);
|
||||
document.removeEventListener('mouseup', handleMouseUp);
|
||||
document.body.style.cursor = '';
|
||||
document.body.style.userSelect = '';
|
||||
};
|
||||
}, [isResizing]);
|
||||
|
||||
return {
|
||||
editingFile,
|
||||
editorWidth,
|
||||
editorExpanded,
|
||||
resizeHandleRef,
|
||||
handleFileOpen,
|
||||
handleCloseEditor,
|
||||
handleToggleEditorExpand,
|
||||
handleResizeStart,
|
||||
};
|
||||
}
|
||||
50
src/components/main-content/hooks/useMobileMenuHandlers.ts
Normal file
50
src/components/main-content/hooks/useMobileMenuHandlers.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { useCallback, useRef } from 'react';
|
||||
import type { MouseEvent, TouchEvent } from 'react';
|
||||
|
||||
type MenuEvent = MouseEvent<HTMLButtonElement> | TouchEvent<HTMLButtonElement>;
|
||||
|
||||
export function useMobileMenuHandlers(onMenuClick: () => void) {
|
||||
const suppressNextMenuClickRef = useRef(false);
|
||||
|
||||
const openMobileMenu = useCallback(
|
||||
(event?: MenuEvent) => {
|
||||
if (event) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
onMenuClick();
|
||||
},
|
||||
[onMenuClick],
|
||||
);
|
||||
|
||||
const handleMobileMenuTouchEnd = useCallback(
|
||||
(event: TouchEvent<HTMLButtonElement>) => {
|
||||
suppressNextMenuClickRef.current = true;
|
||||
openMobileMenu(event);
|
||||
|
||||
window.setTimeout(() => {
|
||||
suppressNextMenuClickRef.current = false;
|
||||
}, 350);
|
||||
},
|
||||
[openMobileMenu],
|
||||
);
|
||||
|
||||
const handleMobileMenuClick = useCallback(
|
||||
(event: MouseEvent<HTMLButtonElement>) => {
|
||||
if (suppressNextMenuClickRef.current) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
|
||||
openMobileMenu(event);
|
||||
},
|
||||
[openMobileMenu],
|
||||
);
|
||||
|
||||
return {
|
||||
handleMobileMenuClick,
|
||||
handleMobileMenuTouchEnd,
|
||||
};
|
||||
}
|
||||
107
src/components/main-content/types/types.ts
Normal file
107
src/components/main-content/types/types.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import type { Dispatch, MouseEvent, RefObject, SetStateAction } from 'react';
|
||||
import type { AppTab, Project, ProjectSession } from '../../../types/app';
|
||||
|
||||
export type SessionLifecycleHandler = (sessionId?: string | null) => void;
|
||||
|
||||
export interface DiffInfo {
|
||||
old_string?: string;
|
||||
new_string?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface EditingFile {
|
||||
name: string;
|
||||
path: string;
|
||||
projectName?: string;
|
||||
diffInfo?: DiffInfo | null;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface TaskMasterTask {
|
||||
id: string | number;
|
||||
title?: string;
|
||||
description?: string;
|
||||
status?: string;
|
||||
priority?: string;
|
||||
details?: string;
|
||||
testStrategy?: string;
|
||||
parentId?: string | number;
|
||||
dependencies?: Array<string | number>;
|
||||
subtasks?: TaskMasterTask[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface TaskReference {
|
||||
id: string | number;
|
||||
title?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type TaskSelection = TaskMasterTask | TaskReference;
|
||||
|
||||
export interface PrdFile {
|
||||
name: string;
|
||||
content?: string;
|
||||
isExisting?: boolean;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface MainContentProps {
|
||||
selectedProject: Project | null;
|
||||
selectedSession: ProjectSession | null;
|
||||
activeTab: AppTab;
|
||||
setActiveTab: Dispatch<SetStateAction<AppTab>>;
|
||||
ws: WebSocket | null;
|
||||
sendMessage: (message: unknown) => void;
|
||||
latestMessage: unknown;
|
||||
isMobile: boolean;
|
||||
onMenuClick: () => void;
|
||||
isLoading: boolean;
|
||||
onInputFocusChange: (focused: boolean) => void;
|
||||
onSessionActive: SessionLifecycleHandler;
|
||||
onSessionInactive: SessionLifecycleHandler;
|
||||
onSessionProcessing: SessionLifecycleHandler;
|
||||
onSessionNotProcessing: SessionLifecycleHandler;
|
||||
processingSessions: Set<string>;
|
||||
onReplaceTemporarySession: SessionLifecycleHandler;
|
||||
onNavigateToSession: (targetSessionId: string) => void;
|
||||
onShowSettings: () => void;
|
||||
externalMessageUpdate: number;
|
||||
}
|
||||
|
||||
export interface MainContentHeaderProps {
|
||||
activeTab: AppTab;
|
||||
setActiveTab: Dispatch<SetStateAction<AppTab>>;
|
||||
selectedProject: Project;
|
||||
selectedSession: ProjectSession | null;
|
||||
shouldShowTasksTab: boolean;
|
||||
isMobile: boolean;
|
||||
onMenuClick: () => void;
|
||||
}
|
||||
|
||||
export interface MainContentStateViewProps {
|
||||
mode: 'loading' | 'empty';
|
||||
isMobile: boolean;
|
||||
onMenuClick: () => void;
|
||||
}
|
||||
|
||||
export interface MobileMenuButtonProps {
|
||||
onMenuClick: () => void;
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
export interface EditorSidebarProps {
|
||||
editingFile: EditingFile | null;
|
||||
isMobile: boolean;
|
||||
editorExpanded: boolean;
|
||||
editorWidth: number;
|
||||
resizeHandleRef: RefObject<HTMLDivElement>;
|
||||
onResizeStart: (event: MouseEvent<HTMLDivElement>) => void;
|
||||
onCloseEditor: () => void;
|
||||
onToggleEditorExpand: () => void;
|
||||
projectPath?: string;
|
||||
}
|
||||
|
||||
export interface TaskMasterPanelProps {
|
||||
isVisible: boolean;
|
||||
}
|
||||
181
src/components/main-content/view/MainContent.tsx
Normal file
181
src/components/main-content/view/MainContent.tsx
Normal file
@@ -0,0 +1,181 @@
|
||||
import React, { useEffect } from 'react';
|
||||
|
||||
import ChatInterface from '../../chat/view/ChatInterface';
|
||||
import FileTree from '../../FileTree';
|
||||
import StandaloneShell from '../../StandaloneShell';
|
||||
import GitPanel from '../../GitPanel';
|
||||
import ErrorBoundary from '../../ErrorBoundary';
|
||||
|
||||
import MainContentHeader from './subcomponents/MainContentHeader';
|
||||
import MainContentStateView from './subcomponents/MainContentStateView';
|
||||
import EditorSidebar from './subcomponents/EditorSidebar';
|
||||
import TaskMasterPanel from './subcomponents/TaskMasterPanel';
|
||||
import type { MainContentProps } from '../types/types';
|
||||
|
||||
import { useTaskMaster } from '../../../contexts/TaskMasterContext';
|
||||
import { useTasksSettings } from '../../../contexts/TasksSettingsContext';
|
||||
import { useUiPreferences } from '../../../hooks/useUiPreferences';
|
||||
import { useEditorSidebar } from '../hooks/useEditorSidebar';
|
||||
import type { Project } from '../../../types/app';
|
||||
|
||||
const AnyStandaloneShell = StandaloneShell as any;
|
||||
const AnyGitPanel = GitPanel as any;
|
||||
|
||||
type TaskMasterContextValue = {
|
||||
currentProject?: Project | null;
|
||||
setCurrentProject?: ((project: Project) => void) | null;
|
||||
};
|
||||
|
||||
type TasksSettingsContextValue = {
|
||||
tasksEnabled: boolean;
|
||||
isTaskMasterInstalled: boolean | null;
|
||||
isTaskMasterReady: boolean | null;
|
||||
};
|
||||
|
||||
function MainContent({
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
ws,
|
||||
sendMessage,
|
||||
latestMessage,
|
||||
isMobile,
|
||||
onMenuClick,
|
||||
isLoading,
|
||||
onInputFocusChange,
|
||||
onSessionActive,
|
||||
onSessionInactive,
|
||||
onSessionProcessing,
|
||||
onSessionNotProcessing,
|
||||
processingSessions,
|
||||
onReplaceTemporarySession,
|
||||
onNavigateToSession,
|
||||
onShowSettings,
|
||||
externalMessageUpdate,
|
||||
}: MainContentProps) {
|
||||
const { preferences } = useUiPreferences();
|
||||
const { autoExpandTools, showRawParameters, showThinking, autoScrollToBottom, sendByCtrlEnter } = preferences;
|
||||
|
||||
const { currentProject, setCurrentProject } = useTaskMaster() as TaskMasterContextValue;
|
||||
const { tasksEnabled, isTaskMasterInstalled } = useTasksSettings() as TasksSettingsContextValue;
|
||||
|
||||
const shouldShowTasksTab = Boolean(tasksEnabled && isTaskMasterInstalled);
|
||||
|
||||
const {
|
||||
editingFile,
|
||||
editorWidth,
|
||||
editorExpanded,
|
||||
resizeHandleRef,
|
||||
handleFileOpen,
|
||||
handleCloseEditor,
|
||||
handleToggleEditorExpand,
|
||||
handleResizeStart,
|
||||
} = useEditorSidebar({
|
||||
selectedProject,
|
||||
isMobile,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedProject && selectedProject !== currentProject) {
|
||||
setCurrentProject?.(selectedProject);
|
||||
}
|
||||
}, [selectedProject, currentProject, setCurrentProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldShowTasksTab && activeTab === 'tasks') {
|
||||
setActiveTab('chat');
|
||||
}
|
||||
}, [shouldShowTasksTab, activeTab, setActiveTab]);
|
||||
|
||||
if (isLoading) {
|
||||
return <MainContentStateView mode="loading" isMobile={isMobile} onMenuClick={onMenuClick} />;
|
||||
}
|
||||
|
||||
if (!selectedProject) {
|
||||
return <MainContentStateView mode="empty" isMobile={isMobile} onMenuClick={onMenuClick} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<MainContentHeader
|
||||
activeTab={activeTab}
|
||||
setActiveTab={setActiveTab}
|
||||
selectedProject={selectedProject}
|
||||
selectedSession={selectedSession}
|
||||
shouldShowTasksTab={shouldShowTasksTab}
|
||||
isMobile={isMobile}
|
||||
onMenuClick={onMenuClick}
|
||||
/>
|
||||
|
||||
<div className="flex-1 flex min-h-0 overflow-hidden">
|
||||
<div className={`flex-1 flex flex-col min-h-0 overflow-hidden ${editorExpanded ? 'hidden' : ''}`}>
|
||||
<div className={`h-full ${activeTab === 'chat' ? 'block' : 'hidden'}`}>
|
||||
<ErrorBoundary showDetails>
|
||||
<ChatInterface
|
||||
selectedProject={selectedProject}
|
||||
selectedSession={selectedSession}
|
||||
ws={ws}
|
||||
sendMessage={sendMessage}
|
||||
latestMessage={latestMessage}
|
||||
onFileOpen={handleFileOpen}
|
||||
onInputFocusChange={onInputFocusChange}
|
||||
onSessionActive={onSessionActive}
|
||||
onSessionInactive={onSessionInactive}
|
||||
onSessionProcessing={onSessionProcessing}
|
||||
onSessionNotProcessing={onSessionNotProcessing}
|
||||
processingSessions={processingSessions}
|
||||
onReplaceTemporarySession={onReplaceTemporarySession}
|
||||
onNavigateToSession={onNavigateToSession}
|
||||
onShowSettings={onShowSettings}
|
||||
autoExpandTools={autoExpandTools}
|
||||
showRawParameters={showRawParameters}
|
||||
showThinking={showThinking}
|
||||
autoScrollToBottom={autoScrollToBottom}
|
||||
sendByCtrlEnter={sendByCtrlEnter}
|
||||
externalMessageUpdate={externalMessageUpdate}
|
||||
onShowAllTasks={tasksEnabled ? () => setActiveTab('tasks') : null}
|
||||
/>
|
||||
</ErrorBoundary>
|
||||
</div>
|
||||
|
||||
{activeTab === 'files' && (
|
||||
<div className="h-full overflow-hidden">
|
||||
<FileTree selectedProject={selectedProject} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'shell' && (
|
||||
<div className="h-full w-full overflow-hidden">
|
||||
<AnyStandaloneShell project={selectedProject} session={selectedSession} showHeader={false} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'git' && (
|
||||
<div className="h-full overflow-hidden">
|
||||
<AnyGitPanel selectedProject={selectedProject} isMobile={isMobile} onFileOpen={handleFileOpen} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{shouldShowTasksTab && <TaskMasterPanel isVisible={activeTab === 'tasks'} />}
|
||||
|
||||
<div className={`h-full overflow-hidden ${activeTab === 'preview' ? 'block' : 'hidden'}`} />
|
||||
</div>
|
||||
|
||||
<EditorSidebar
|
||||
editingFile={editingFile}
|
||||
isMobile={isMobile}
|
||||
editorExpanded={editorExpanded}
|
||||
editorWidth={editorWidth}
|
||||
resizeHandleRef={resizeHandleRef}
|
||||
onResizeStart={handleResizeStart}
|
||||
onCloseEditor={handleCloseEditor}
|
||||
onToggleEditorExpand={handleToggleEditorExpand}
|
||||
projectPath={selectedProject.path}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default React.memo(MainContent);
|
||||
@@ -0,0 +1,60 @@
|
||||
import CodeEditor from '../../../CodeEditor';
|
||||
import type { EditorSidebarProps } from '../../types/types';
|
||||
|
||||
const AnyCodeEditor = CodeEditor as any;
|
||||
|
||||
export default function EditorSidebar({
|
||||
editingFile,
|
||||
isMobile,
|
||||
editorExpanded,
|
||||
editorWidth,
|
||||
resizeHandleRef,
|
||||
onResizeStart,
|
||||
onCloseEditor,
|
||||
onToggleEditorExpand,
|
||||
projectPath,
|
||||
}: EditorSidebarProps) {
|
||||
if (!editingFile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<AnyCodeEditor
|
||||
file={editingFile}
|
||||
onClose={onCloseEditor}
|
||||
projectPath={projectPath}
|
||||
isSidebar={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{!editorExpanded && (
|
||||
<div
|
||||
ref={resizeHandleRef}
|
||||
onMouseDown={onResizeStart}
|
||||
className="flex-shrink-0 w-1 bg-gray-200 dark:bg-gray-700 hover:bg-blue-500 dark:hover:bg-blue-600 cursor-col-resize transition-colors relative group"
|
||||
title="Drag to resize"
|
||||
>
|
||||
<div className="absolute inset-y-0 left-1/2 -translate-x-1/2 w-1 bg-blue-500 dark:bg-blue-600 opacity-0 group-hover:opacity-100 transition-opacity" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={`flex-shrink-0 border-l border-gray-200 dark:border-gray-700 h-full overflow-hidden ${editorExpanded ? 'flex-1' : ''}`}
|
||||
style={editorExpanded ? undefined : { width: `${editorWidth}px` }}
|
||||
>
|
||||
<AnyCodeEditor
|
||||
file={editingFile}
|
||||
onClose={onCloseEditor}
|
||||
projectPath={projectPath}
|
||||
isSidebar
|
||||
isExpanded={editorExpanded}
|
||||
onToggleExpand={onToggleEditorExpand}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import MobileMenuButton from './MobileMenuButton';
|
||||
import MainContentTabSwitcher from './MainContentTabSwitcher';
|
||||
import MainContentTitle from './MainContentTitle';
|
||||
import type { MainContentHeaderProps } from '../../types/types';
|
||||
|
||||
export default function MainContentHeader({
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
shouldShowTasksTab,
|
||||
isMobile,
|
||||
onMenuClick,
|
||||
}: MainContentHeaderProps) {
|
||||
return (
|
||||
<div className="bg-background border-b border-border p-2 sm:p-3 pwa-header-safe flex-shrink-0">
|
||||
<div className="flex items-center justify-between relative">
|
||||
<div className="flex items-center space-x-2 min-w-0 flex-1">
|
||||
{isMobile && <MobileMenuButton onMenuClick={onMenuClick} />}
|
||||
<MainContentTitle
|
||||
activeTab={activeTab}
|
||||
selectedProject={selectedProject}
|
||||
selectedSession={selectedSession}
|
||||
shouldShowTasksTab={shouldShowTasksTab}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex-shrink-0 hidden sm:block">
|
||||
<MainContentTabSwitcher
|
||||
activeTab={activeTab}
|
||||
setActiveTab={setActiveTab}
|
||||
shouldShowTasksTab={shouldShowTasksTab}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import MobileMenuButton from './MobileMenuButton';
|
||||
import type { MainContentStateViewProps } from '../../types/types';
|
||||
|
||||
export default function MainContentStateView({ mode, isMobile, onMenuClick }: MainContentStateViewProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const isLoading = mode === 'loading';
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
{isMobile && (
|
||||
<div className="bg-background border-b border-border p-2 sm:p-3 pwa-header-safe flex-shrink-0">
|
||||
<MobileMenuButton onMenuClick={onMenuClick} compact />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center text-gray-500 dark:text-gray-400">
|
||||
<div className="w-12 h-12 mx-auto mb-4">
|
||||
<div
|
||||
className="w-full h-full rounded-full border-4 border-gray-200 border-t-blue-500"
|
||||
style={{
|
||||
animation: 'spin 1s linear infinite',
|
||||
WebkitAnimation: 'spin 1s linear infinite',
|
||||
MozAnimation: 'spin 1s linear infinite',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<h2 className="text-xl font-semibold mb-2">{t('mainContent.loading')}</h2>
|
||||
<p>{t('mainContent.settingUpWorkspace')}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center text-gray-500 dark:text-gray-400 max-w-md mx-auto px-6">
|
||||
<div className="w-16 h-16 mx-auto mb-6 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center">
|
||||
<svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-5l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold mb-3 text-gray-900 dark:text-white">{t('mainContent.chooseProject')}</h2>
|
||||
<p className="text-gray-600 dark:text-gray-300 mb-6 leading-relaxed">{t('mainContent.selectProjectDescription')}</p>
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4 border border-blue-200 dark:border-blue-800">
|
||||
<p className="text-sm text-blue-700 dark:text-blue-300">
|
||||
<strong>{t('mainContent.tip')}:</strong> {isMobile ? t('mainContent.createProjectMobile') : t('mainContent.createProjectDesktop')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import Tooltip from '../../../Tooltip';
|
||||
import type { AppTab } from '../../../../types/app';
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
type MainContentTabSwitcherProps = {
|
||||
activeTab: AppTab;
|
||||
setActiveTab: Dispatch<SetStateAction<AppTab>>;
|
||||
shouldShowTasksTab: boolean;
|
||||
};
|
||||
|
||||
type TabDefinition = {
|
||||
id: AppTab;
|
||||
labelKey: string;
|
||||
iconPath: string;
|
||||
};
|
||||
|
||||
const BASE_TABS: TabDefinition[] = [
|
||||
{
|
||||
id: 'chat',
|
||||
labelKey: 'tabs.chat',
|
||||
iconPath:
|
||||
'M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z',
|
||||
},
|
||||
{
|
||||
id: 'shell',
|
||||
labelKey: 'tabs.shell',
|
||||
iconPath: 'M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2z',
|
||||
},
|
||||
{
|
||||
id: 'files',
|
||||
labelKey: 'tabs.files',
|
||||
iconPath: 'M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-5l-2-2H5a2 2 0 00-2 2z',
|
||||
},
|
||||
{
|
||||
id: 'git',
|
||||
labelKey: 'tabs.git',
|
||||
iconPath: 'M13 10V3L4 14h7v7l9-11h-7z',
|
||||
},
|
||||
];
|
||||
|
||||
const TASKS_TAB: TabDefinition = {
|
||||
id: 'tasks',
|
||||
labelKey: 'tabs.tasks',
|
||||
iconPath:
|
||||
'M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4',
|
||||
};
|
||||
|
||||
function getButtonClasses(tabId: AppTab, activeTab: AppTab) {
|
||||
const base = 'relative px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium rounded-md transition-all duration-200';
|
||||
|
||||
if (tabId === activeTab) {
|
||||
return `${base} bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm`;
|
||||
}
|
||||
|
||||
return `${base} text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-200 dark:hover:bg-gray-700`;
|
||||
}
|
||||
|
||||
export default function MainContentTabSwitcher({
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
shouldShowTasksTab,
|
||||
}: MainContentTabSwitcherProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const tabs = shouldShowTasksTab ? [...BASE_TABS, TASKS_TAB] : BASE_TABS;
|
||||
|
||||
return (
|
||||
<div className="relative flex bg-gray-100 dark:bg-gray-800 rounded-lg p-1">
|
||||
{tabs.map((tab) => (
|
||||
<Tooltip key={tab.id} content={t(tab.labelKey)} position="bottom">
|
||||
<button onClick={() => setActiveTab(tab.id)} className={getButtonClasses(tab.id, activeTab)}>
|
||||
<span className="flex items-center gap-1 sm:gap-1.5">
|
||||
<svg className="w-3 sm:w-3.5 h-3 sm:h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={tab.iconPath} />
|
||||
</svg>
|
||||
<span className="hidden md:hidden lg:inline">{t(tab.labelKey)}</span>
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import SessionProviderLogo from '../../../SessionProviderLogo';
|
||||
import type { AppTab, Project, ProjectSession } from '../../../../types/app';
|
||||
|
||||
type MainContentTitleProps = {
|
||||
activeTab: AppTab;
|
||||
selectedProject: Project;
|
||||
selectedSession: ProjectSession | null;
|
||||
shouldShowTasksTab: boolean;
|
||||
};
|
||||
|
||||
function getTabTitle(activeTab: AppTab, shouldShowTasksTab: boolean, t: (key: string) => string) {
|
||||
if (activeTab === 'files') {
|
||||
return t('mainContent.projectFiles');
|
||||
}
|
||||
|
||||
if (activeTab === 'git') {
|
||||
return t('tabs.git');
|
||||
}
|
||||
|
||||
if (activeTab === 'tasks' && shouldShowTasksTab) {
|
||||
return 'TaskMaster';
|
||||
}
|
||||
|
||||
return 'Project';
|
||||
}
|
||||
|
||||
function getSessionTitle(session: ProjectSession): string {
|
||||
if (session.__provider === 'cursor') {
|
||||
return (session.name as string) || 'Untitled Session';
|
||||
}
|
||||
|
||||
return (session.summary as string) || 'New Session';
|
||||
}
|
||||
|
||||
export default function MainContentTitle({
|
||||
activeTab,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
shouldShowTasksTab,
|
||||
}: MainContentTitleProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const showSessionIcon = activeTab === 'chat' && Boolean(selectedSession);
|
||||
const showChatNewSession = activeTab === 'chat' && !selectedSession;
|
||||
|
||||
return (
|
||||
<div className="min-w-0 flex items-center gap-2 flex-1 overflow-x-auto scrollbar-hide">
|
||||
{showSessionIcon && (
|
||||
<div className="w-5 h-5 flex-shrink-0 flex items-center justify-center">
|
||||
<SessionProviderLogo provider={selectedSession?.__provider} className="w-4 h-4" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
{activeTab === 'chat' && selectedSession ? (
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-sm sm:text-base font-semibold text-gray-900 dark:text-white whitespace-nowrap overflow-x-auto scrollbar-hide">
|
||||
{getSessionTitle(selectedSession)}
|
||||
</h2>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 truncate">{selectedProject.displayName}</div>
|
||||
</div>
|
||||
) : showChatNewSession ? (
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-sm sm:text-base font-semibold text-gray-900 dark:text-white">{t('mainContent.newSession')}</h2>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 truncate">{selectedProject.displayName}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-sm sm:text-base font-semibold text-gray-900 dark:text-white">
|
||||
{getTabTitle(activeTab, shouldShowTasksTab, t)}
|
||||
</h2>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 truncate">{selectedProject.displayName}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { MobileMenuButtonProps } from '../../types/types';
|
||||
import { useMobileMenuHandlers } from '../../hooks/useMobileMenuHandlers';
|
||||
|
||||
export default function MobileMenuButton({ onMenuClick, compact = false }: MobileMenuButtonProps) {
|
||||
const { handleMobileMenuClick, handleMobileMenuTouchEnd } = useMobileMenuHandlers(onMenuClick);
|
||||
|
||||
const buttonClasses = compact
|
||||
? 'p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 pwa-menu-button'
|
||||
: 'p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 touch-manipulation active:scale-95 pwa-menu-button flex-shrink-0';
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleMobileMenuClick}
|
||||
onTouchEnd={handleMobileMenuTouchEnd}
|
||||
className={buttonClasses}
|
||||
aria-label="Open menu"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import TaskList from '../../../TaskList';
|
||||
import TaskDetail from '../../../TaskDetail';
|
||||
import PRDEditor from '../../../PRDEditor';
|
||||
import { useTaskMaster } from '../../../../contexts/TaskMasterContext';
|
||||
import { api } from '../../../../utils/api';
|
||||
import type { Project } from '../../../../types/app';
|
||||
import type { PrdFile, TaskMasterPanelProps, TaskMasterTask, TaskSelection } from '../../types/types';
|
||||
|
||||
const AnyTaskList = TaskList as any;
|
||||
const AnyTaskDetail = TaskDetail as any;
|
||||
const AnyPRDEditor = PRDEditor as any;
|
||||
|
||||
type TaskMasterContextValue = {
|
||||
tasks?: TaskMasterTask[];
|
||||
currentProject?: Project | null;
|
||||
refreshTasks?: (() => void) | null;
|
||||
};
|
||||
|
||||
type PrdListResponse = {
|
||||
prdFiles?: PrdFile[];
|
||||
prds?: PrdFile[];
|
||||
};
|
||||
|
||||
const PRD_SAVED_MESSAGE = 'PRD saved successfully!';
|
||||
|
||||
function getPrdFiles(data: PrdListResponse): PrdFile[] {
|
||||
return data.prdFiles || data.prds || [];
|
||||
}
|
||||
|
||||
export default function TaskMasterPanel({ isVisible }: TaskMasterPanelProps) {
|
||||
const { tasks = [], currentProject, refreshTasks } = useTaskMaster() as TaskMasterContextValue;
|
||||
|
||||
const [selectedTask, setSelectedTask] = useState<TaskMasterTask | null>(null);
|
||||
const [showTaskDetail, setShowTaskDetail] = useState(false);
|
||||
|
||||
const [showPRDEditor, setShowPRDEditor] = useState(false);
|
||||
const [selectedPRD, setSelectedPRD] = useState<PrdFile | null>(null);
|
||||
const [existingPRDs, setExistingPRDs] = useState<PrdFile[]>([]);
|
||||
const [prdNotification, setPRDNotification] = useState<string | null>(null);
|
||||
|
||||
const prdNotificationTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const showPrdNotification = useCallback((message: string) => {
|
||||
if (prdNotificationTimeoutRef.current) {
|
||||
clearTimeout(prdNotificationTimeoutRef.current);
|
||||
}
|
||||
|
||||
setPRDNotification(message);
|
||||
prdNotificationTimeoutRef.current = setTimeout(() => {
|
||||
setPRDNotification(null);
|
||||
prdNotificationTimeoutRef.current = null;
|
||||
}, 3000);
|
||||
}, []);
|
||||
|
||||
const loadExistingPrds = useCallback(async () => {
|
||||
if (!currentProject?.name) {
|
||||
setExistingPRDs([]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await api.get(`/taskmaster/prd/${encodeURIComponent(currentProject.name)}`);
|
||||
if (!response.ok) {
|
||||
setExistingPRDs([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = (await response.json()) as PrdListResponse;
|
||||
setExistingPRDs(getPrdFiles(data));
|
||||
} catch (error) {
|
||||
console.error('Failed to load existing PRDs:', error);
|
||||
setExistingPRDs([]);
|
||||
}
|
||||
}, [currentProject?.name]);
|
||||
|
||||
const refreshPrds = useCallback(
|
||||
async (showNotification = false) => {
|
||||
await loadExistingPrds();
|
||||
|
||||
if (showNotification) {
|
||||
showPrdNotification(PRD_SAVED_MESSAGE);
|
||||
}
|
||||
},
|
||||
[loadExistingPrds, showPrdNotification],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void loadExistingPrds();
|
||||
}, [loadExistingPrds]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (prdNotificationTimeoutRef.current) {
|
||||
clearTimeout(prdNotificationTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleTaskClick = useCallback(
|
||||
(task: TaskSelection) => {
|
||||
if (!task || typeof task !== 'object' || !('id' in task)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!('title' in task) || !task.title) {
|
||||
const fullTask = tasks.find((candidate) => String(candidate.id) === String(task.id));
|
||||
if (fullTask) {
|
||||
setSelectedTask(fullTask);
|
||||
setShowTaskDetail(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedTask(task as TaskMasterTask);
|
||||
setShowTaskDetail(true);
|
||||
},
|
||||
[tasks],
|
||||
);
|
||||
|
||||
const handleTaskDetailClose = useCallback(() => {
|
||||
setShowTaskDetail(false);
|
||||
setSelectedTask(null);
|
||||
}, []);
|
||||
|
||||
const handleTaskStatusChange = useCallback(
|
||||
(taskId: string | number, newStatus: string) => {
|
||||
console.log('Update task status:', taskId, newStatus);
|
||||
refreshTasks?.();
|
||||
},
|
||||
[refreshTasks],
|
||||
);
|
||||
|
||||
const handleOpenPrdEditor = useCallback((prd: PrdFile | null = null) => {
|
||||
setSelectedPRD(prd);
|
||||
setShowPRDEditor(true);
|
||||
}, []);
|
||||
|
||||
const handleClosePrdEditor = useCallback(() => {
|
||||
setShowPRDEditor(false);
|
||||
setSelectedPRD(null);
|
||||
}, []);
|
||||
|
||||
const handlePrdSave = useCallback(async () => {
|
||||
handleClosePrdEditor();
|
||||
await refreshPrds(true);
|
||||
refreshTasks?.();
|
||||
}, [handleClosePrdEditor, refreshPrds, refreshTasks]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={`h-full ${isVisible ? 'block' : 'hidden'}`}>
|
||||
<div className="h-full flex flex-col overflow-hidden">
|
||||
<AnyTaskList
|
||||
tasks={tasks}
|
||||
onTaskClick={handleTaskClick}
|
||||
showParentTasks
|
||||
className="flex-1 overflow-y-auto p-4"
|
||||
currentProject={currentProject}
|
||||
onTaskCreated={refreshTasks || undefined}
|
||||
onShowPRDEditor={handleOpenPrdEditor}
|
||||
existingPRDs={existingPRDs}
|
||||
onRefreshPRDs={(showNotification = false) => {
|
||||
void refreshPrds(showNotification);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showTaskDetail && selectedTask && (
|
||||
<AnyTaskDetail
|
||||
task={selectedTask}
|
||||
isOpen={showTaskDetail}
|
||||
onClose={handleTaskDetailClose}
|
||||
onStatusChange={handleTaskStatusChange}
|
||||
onTaskClick={handleTaskClick}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showPRDEditor && (
|
||||
<AnyPRDEditor
|
||||
project={currentProject}
|
||||
projectPath={currentProject?.fullPath || currentProject?.path}
|
||||
onClose={handleClosePrdEditor}
|
||||
isNewFile={!selectedPRD?.isExisting}
|
||||
file={{
|
||||
name: selectedPRD?.name || 'prd.txt',
|
||||
content: selectedPRD?.content || '',
|
||||
}}
|
||||
onSave={handlePrdSave}
|
||||
/>
|
||||
)}
|
||||
|
||||
{prdNotification && (
|
||||
<div className="fixed bottom-4 right-4 z-50 animate-in slide-in-from-bottom-2 duration-300">
|
||||
<div className="bg-green-600 text-white px-4 py-3 rounded-lg shadow-lg flex items-center gap-3">
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
<span className="font-medium">{prdNotification}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
219
src/components/modals/VersionUpgradeModal.tsx
Normal file
219
src/components/modals/VersionUpgradeModal.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { authenticatedFetch } from "../../utils/api";
|
||||
import { ReleaseInfo } from "../../types/sharedTypes";
|
||||
|
||||
interface VersionUpgradeModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
releaseInfo: ReleaseInfo | null;
|
||||
currentVersion: string;
|
||||
latestVersion: string | null;
|
||||
}
|
||||
|
||||
export default function VersionUpgradeModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
releaseInfo,
|
||||
currentVersion,
|
||||
latestVersion
|
||||
}: VersionUpgradeModalProps) {
|
||||
const { t } = useTranslation('common');
|
||||
const [isUpdating, setIsUpdating] = useState(false);
|
||||
const [updateOutput, setUpdateOutput] = useState('');
|
||||
const [updateError, setUpdateError] = useState('');
|
||||
|
||||
const handleUpdateNow = useCallback(async () => {
|
||||
setIsUpdating(true);
|
||||
setUpdateOutput('Starting update...\n');
|
||||
setUpdateError('');
|
||||
|
||||
try {
|
||||
// Call the backend API to run the update command
|
||||
const response = await authenticatedFetch('/api/system/update', {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
setUpdateOutput(prev => prev + data.output + '\n');
|
||||
setUpdateOutput(prev => prev + '\n✅ Update completed successfully!\n');
|
||||
setUpdateOutput(prev => prev + 'Please restart the server to apply changes.\n');
|
||||
} else {
|
||||
setUpdateError(data.error || 'Update failed');
|
||||
setUpdateOutput(prev => prev + '\n❌ Update failed: ' + (data.error || 'Unknown error') + '\n');
|
||||
}
|
||||
} catch (error: any) {
|
||||
setUpdateError(error.message);
|
||||
setUpdateOutput(prev => prev + '\n❌ Update failed: ' + error.message + '\n');
|
||||
} finally {
|
||||
setIsUpdating(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||
{/* Backdrop */}
|
||||
<button
|
||||
className="fixed inset-0 bg-black/50 backdrop-blur-sm"
|
||||
onClick={onClose}
|
||||
aria-label={t('versionUpdate.ariaLabels.closeModal')}
|
||||
/>
|
||||
|
||||
{/* Modal */}
|
||||
<div className="relative bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 w-full max-w-2xl mx-4 p-6 space-y-4 max-h-[90vh] overflow-y-auto">
|
||||
{/* Header */}
|
||||
<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-lg flex items-center justify-center">
|
||||
<svg className="w-5 h-5 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M9 19l3 3m0 0l3-3m-3 3V10" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">{t('versionUpdate.title')}</h2>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{releaseInfo?.title || t('versionUpdate.newVersionReady')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Version Info */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-between items-center p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">{t('versionUpdate.currentVersion')}</span>
|
||||
<span className="text-sm text-gray-900 dark:text-white font-mono">{currentVersion}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-700">
|
||||
<span className="text-sm font-medium text-blue-700 dark:text-blue-300">{t('versionUpdate.latestVersion')}</span>
|
||||
<span className="text-sm text-blue-900 dark:text-blue-100 font-mono">{latestVersion}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Changelog */}
|
||||
{releaseInfo?.body && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-white">{t('versionUpdate.whatsNew')}</h3>
|
||||
{releaseInfo?.htmlUrl && (
|
||||
<a
|
||||
href={releaseInfo.htmlUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline flex items-center gap-1"
|
||||
>
|
||||
{t('versionUpdate.viewFullRelease')}
|
||||
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
|
||||
</svg>
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
<div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4 border border-gray-200 dark:border-gray-600 max-h-64 overflow-y-auto">
|
||||
<div className="text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap prose prose-sm dark:prose-invert max-w-none">
|
||||
{cleanChangelog(releaseInfo.body)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Update Output */}
|
||||
{(updateOutput || updateError) && (
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-white">{t('versionUpdate.updateProgress')}</h3>
|
||||
<div className="bg-gray-900 dark:bg-gray-950 rounded-lg p-4 border border-gray-700 max-h-48 overflow-y-auto">
|
||||
<pre className="text-xs text-green-400 font-mono whitespace-pre-wrap">{updateOutput}</pre>
|
||||
</div>
|
||||
{updateError && (
|
||||
<div className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700 dark:border-red-900/40 dark:bg-red-900/20 dark:text-red-200">
|
||||
{updateError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Upgrade Instructions */}
|
||||
{!isUpdating && !updateOutput && (
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-white">{t('versionUpdate.manualUpgrade')}</h3>
|
||||
<div className="bg-gray-100 dark:bg-gray-800 rounded-lg p-3 border">
|
||||
<code className="text-sm text-gray-800 dark:text-gray-200 font-mono">
|
||||
git checkout main && git pull && npm install
|
||||
</code>
|
||||
</div>
|
||||
<p className="text-xs text-gray-600 dark:text-gray-400">
|
||||
{t('versionUpdate.manualUpgradeHint')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 pt-2">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="flex-1 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors"
|
||||
>
|
||||
{updateOutput ? t('versionUpdate.buttons.close') : t('versionUpdate.buttons.later')}
|
||||
</button>
|
||||
{!updateOutput && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText('git checkout main && git pull && npm install');
|
||||
}}
|
||||
className="flex-1 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors"
|
||||
>
|
||||
{t('versionUpdate.buttons.copyCommand')}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleUpdateNow}
|
||||
disabled={isUpdating}
|
||||
className="flex-1 px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 disabled:cursor-not-allowed rounded-md transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
{isUpdating ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
{t('versionUpdate.buttons.updating')}
|
||||
</>
|
||||
) : (
|
||||
t('versionUpdate.buttons.updateNow')
|
||||
)}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Clean up changelog by removing GitHub-specific metadata
|
||||
const cleanChangelog = (body: string) => {
|
||||
if (!body) return '';
|
||||
|
||||
return body
|
||||
// Remove full commit hashes (40 character hex strings)
|
||||
.replace(/\b[0-9a-f]{40}\b/gi, '')
|
||||
// Remove short commit hashes (7-10 character hex strings at start of line or after dash/space)
|
||||
.replace(/(?:^|\s|-)([0-9a-f]{7,10})\b/gi, '')
|
||||
// Remove "Full Changelog" links
|
||||
.replace(/\*\*Full Changelog\*\*:.*$/gim, '')
|
||||
// Remove compare links (e.g., https://github.com/.../compare/v1.0.0...v1.0.1)
|
||||
.replace(/https?:\/\/github\.com\/[^\/]+\/[^\/]+\/compare\/[^\s)]+/gi, '')
|
||||
// Clean up multiple consecutive empty lines
|
||||
.replace(/\n\s*\n\s*\n/g, '\n\n')
|
||||
// Trim whitespace
|
||||
.trim();
|
||||
};
|
||||
@@ -1,16 +1,13 @@
|
||||
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';
|
||||
import SessionProviderLogo from '../SessionProviderLogo';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
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',
|
||||
@@ -20,7 +17,6 @@ const agentConfig = {
|
||||
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',
|
||||
@@ -30,7 +26,6 @@ const agentConfig = {
|
||||
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',
|
||||
@@ -42,12 +37,11 @@ const agentConfig = {
|
||||
export default function AccountContent({ agent, authStatus, onLogin }) {
|
||||
const { t } = useTranslation('settings');
|
||||
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" />
|
||||
<SessionProviderLogo provider={agent} className="w-6 h-6" />
|
||||
<div>
|
||||
<h3 className="text-lg font-medium text-foreground">{config.name}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t(`agents.account.${agent}.description`)}</p>
|
||||
|
||||
@@ -1,23 +1,18 @@
|
||||
import ClaudeLogo from '../ClaudeLogo';
|
||||
import CursorLogo from '../CursorLogo';
|
||||
import CodexLogo from '../CodexLogo';
|
||||
import SessionProviderLogo from '../SessionProviderLogo';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const agentConfig = {
|
||||
claude: {
|
||||
name: 'Claude',
|
||||
color: 'blue',
|
||||
Logo: ClaudeLogo,
|
||||
},
|
||||
cursor: {
|
||||
name: 'Cursor',
|
||||
color: 'purple',
|
||||
Logo: CursorLogo,
|
||||
},
|
||||
codex: {
|
||||
name: 'Codex',
|
||||
color: 'gray',
|
||||
Logo: CodexLogo,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -46,7 +41,6 @@ export default function AgentListItem({ agentId, authStatus, isSelected, onClick
|
||||
const { t } = useTranslation('settings');
|
||||
const config = agentConfig[agentId];
|
||||
const colors = colorClasses[config.color];
|
||||
const { Logo } = config;
|
||||
|
||||
// Mobile: horizontal layout with bottom border
|
||||
if (isMobile) {
|
||||
@@ -60,7 +54,7 @@ export default function AgentListItem({ agentId, authStatus, isSelected, onClick
|
||||
}`}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1">
|
||||
<Logo className="w-5 h-5" />
|
||||
<SessionProviderLogo provider={agentId} 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}`} />
|
||||
@@ -81,7 +75,7 @@ export default function AgentListItem({ agentId, authStatus, isSelected, onClick
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Logo className="w-4 h-4" />
|
||||
<SessionProviderLogo provider={agentId} className="w-4 h-4" />
|
||||
<span className="font-medium text-foreground">{config.name}</span>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground pl-6">
|
||||
|
||||
469
src/components/sidebar/hooks/useSidebarController.ts
Normal file
469
src/components/sidebar/hooks/useSidebarController.ts
Normal file
@@ -0,0 +1,469 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import type React from 'react';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { api } from '../../../utils/api';
|
||||
import type { Project, ProjectSession } from '../../../types/app';
|
||||
import type {
|
||||
AdditionalSessionsByProject,
|
||||
DeleteProjectConfirmation,
|
||||
LoadingSessionsByProject,
|
||||
ProjectSortOrder,
|
||||
SessionDeleteConfirmation,
|
||||
SessionWithProvider,
|
||||
} from '../types/types';
|
||||
import {
|
||||
filterProjects,
|
||||
getAllSessions,
|
||||
loadStarredProjects,
|
||||
persistStarredProjects,
|
||||
readProjectSortOrder,
|
||||
sortProjects,
|
||||
} from '../utils/utils';
|
||||
|
||||
type UseSidebarControllerArgs = {
|
||||
projects: Project[];
|
||||
selectedProject: Project | null;
|
||||
selectedSession: ProjectSession | null;
|
||||
isLoading: boolean;
|
||||
isMobile: boolean;
|
||||
t: TFunction;
|
||||
onRefresh: () => Promise<void> | void;
|
||||
onProjectSelect: (project: Project) => void;
|
||||
onSessionSelect: (session: ProjectSession) => void;
|
||||
onSessionDelete?: (sessionId: string) => void;
|
||||
onProjectDelete?: (projectName: string) => void;
|
||||
setCurrentProject: (project: Project) => void;
|
||||
setSidebarVisible: (visible: boolean) => void;
|
||||
sidebarVisible: boolean;
|
||||
};
|
||||
|
||||
export function useSidebarController({
|
||||
projects,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
isLoading,
|
||||
isMobile,
|
||||
t,
|
||||
onRefresh,
|
||||
onProjectSelect,
|
||||
onSessionSelect,
|
||||
onSessionDelete,
|
||||
onProjectDelete,
|
||||
setCurrentProject,
|
||||
setSidebarVisible,
|
||||
sidebarVisible,
|
||||
}: UseSidebarControllerArgs) {
|
||||
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(new Set());
|
||||
const [editingProject, setEditingProject] = useState<string | null>(null);
|
||||
const [showNewProject, setShowNewProject] = useState(false);
|
||||
const [editingName, setEditingName] = useState('');
|
||||
const [loadingSessions, setLoadingSessions] = useState<LoadingSessionsByProject>({});
|
||||
const [additionalSessions, setAdditionalSessions] = useState<AdditionalSessionsByProject>({});
|
||||
const [initialSessionsLoaded, setInitialSessionsLoaded] = useState<Set<string>>(new Set());
|
||||
const [currentTime, setCurrentTime] = useState(new Date());
|
||||
const [projectSortOrder, setProjectSortOrder] = useState<ProjectSortOrder>('name');
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [projectHasMoreOverrides, setProjectHasMoreOverrides] = useState<Record<string, boolean>>({});
|
||||
const [editingSession, setEditingSession] = useState<string | null>(null);
|
||||
const [editingSessionName, setEditingSessionName] = useState('');
|
||||
const [searchFilter, setSearchFilter] = useState('');
|
||||
const [deletingProjects, setDeletingProjects] = useState<Set<string>>(new Set());
|
||||
const [deleteConfirmation, setDeleteConfirmation] = useState<DeleteProjectConfirmation | null>(null);
|
||||
const [sessionDeleteConfirmation, setSessionDeleteConfirmation] = useState<SessionDeleteConfirmation | null>(null);
|
||||
const [showVersionModal, setShowVersionModal] = useState(false);
|
||||
const [starredProjects, setStarredProjects] = useState<Set<string>>(() => loadStarredProjects());
|
||||
|
||||
const isSidebarCollapsed = !isMobile && !sidebarVisible;
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
setCurrentTime(new Date());
|
||||
}, 60000);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setAdditionalSessions({});
|
||||
setInitialSessionsLoaded(new Set());
|
||||
setProjectHasMoreOverrides({});
|
||||
}, [projects]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSession && selectedProject) {
|
||||
setExpandedProjects((prev) => {
|
||||
if (prev.has(selectedProject.name)) {
|
||||
return prev;
|
||||
}
|
||||
const next = new Set(prev);
|
||||
next.add(selectedProject.name);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, [selectedSession, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (projects.length > 0 && !isLoading) {
|
||||
const loadedProjects = new Set<string>();
|
||||
projects.forEach((project) => {
|
||||
if (project.sessions && project.sessions.length >= 0) {
|
||||
loadedProjects.add(project.name);
|
||||
}
|
||||
});
|
||||
setInitialSessionsLoaded(loadedProjects);
|
||||
}
|
||||
}, [projects, isLoading]);
|
||||
|
||||
useEffect(() => {
|
||||
const loadSortOrder = () => {
|
||||
setProjectSortOrder(readProjectSortOrder());
|
||||
};
|
||||
|
||||
loadSortOrder();
|
||||
|
||||
const handleStorageChange = (event: StorageEvent) => {
|
||||
if (event.key === 'claude-settings') {
|
||||
loadSortOrder();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('storage', handleStorageChange);
|
||||
|
||||
const interval = setInterval(() => {
|
||||
if (document.hasFocus()) {
|
||||
loadSortOrder();
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('storage', handleStorageChange);
|
||||
clearInterval(interval);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleTouchClick = useCallback(
|
||||
(callback: () => void) =>
|
||||
(event: React.TouchEvent<HTMLElement>) => {
|
||||
const target = event.target as HTMLElement;
|
||||
if (target.closest('.overflow-y-auto') || target.closest('[data-scroll-container]')) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
callback();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const toggleProject = useCallback((projectName: string) => {
|
||||
setExpandedProjects((prev) => {
|
||||
const next = new Set<string>();
|
||||
if (!prev.has(projectName)) {
|
||||
next.add(projectName);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSessionClick = useCallback(
|
||||
(session: SessionWithProvider, projectName: string) => {
|
||||
onSessionSelect({ ...session, __projectName: projectName });
|
||||
},
|
||||
[onSessionSelect],
|
||||
);
|
||||
|
||||
const toggleStarProject = useCallback((projectName: string) => {
|
||||
setStarredProjects((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(projectName)) {
|
||||
next.delete(projectName);
|
||||
} else {
|
||||
next.add(projectName);
|
||||
}
|
||||
|
||||
persistStarredProjects(next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const isProjectStarred = useCallback(
|
||||
(projectName: string) => starredProjects.has(projectName),
|
||||
[starredProjects],
|
||||
);
|
||||
|
||||
const getProjectSessions = useCallback(
|
||||
(project: Project) => getAllSessions(project, additionalSessions),
|
||||
[additionalSessions],
|
||||
);
|
||||
|
||||
const projectsWithSessionMeta = useMemo(
|
||||
() =>
|
||||
projects.map((project) => {
|
||||
const hasMoreOverride = projectHasMoreOverrides[project.name];
|
||||
if (hasMoreOverride === undefined) {
|
||||
return project;
|
||||
}
|
||||
|
||||
return {
|
||||
...project,
|
||||
sessionMeta: { ...project.sessionMeta, hasMore: hasMoreOverride },
|
||||
};
|
||||
}),
|
||||
[projectHasMoreOverrides, projects],
|
||||
);
|
||||
|
||||
const sortedProjects = useMemo(
|
||||
() => sortProjects(projectsWithSessionMeta, projectSortOrder, starredProjects, additionalSessions),
|
||||
[additionalSessions, projectSortOrder, projectsWithSessionMeta, starredProjects],
|
||||
);
|
||||
|
||||
const filteredProjects = useMemo(
|
||||
() => filterProjects(sortedProjects, searchFilter),
|
||||
[searchFilter, sortedProjects],
|
||||
);
|
||||
|
||||
const startEditing = useCallback((project: Project) => {
|
||||
setEditingProject(project.name);
|
||||
setEditingName(project.displayName);
|
||||
}, []);
|
||||
|
||||
const cancelEditing = useCallback(() => {
|
||||
setEditingProject(null);
|
||||
setEditingName('');
|
||||
}, []);
|
||||
|
||||
const saveProjectName = useCallback(
|
||||
async (projectName: string) => {
|
||||
try {
|
||||
const response = await api.renameProject(projectName, editingName);
|
||||
if (response.ok) {
|
||||
if (window.refreshProjects) {
|
||||
await window.refreshProjects();
|
||||
} else {
|
||||
window.location.reload();
|
||||
}
|
||||
} else {
|
||||
console.error('Failed to rename project');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error renaming project:', error);
|
||||
} finally {
|
||||
setEditingProject(null);
|
||||
setEditingName('');
|
||||
}
|
||||
},
|
||||
[editingName],
|
||||
);
|
||||
|
||||
const showDeleteSessionConfirmation = useCallback(
|
||||
(
|
||||
projectName: string,
|
||||
sessionId: string,
|
||||
sessionTitle: string,
|
||||
provider: SessionDeleteConfirmation['provider'] = 'claude',
|
||||
) => {
|
||||
setSessionDeleteConfirmation({ projectName, sessionId, sessionTitle, provider });
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const confirmDeleteSession = useCallback(async () => {
|
||||
if (!sessionDeleteConfirmation) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { projectName, sessionId, provider } = sessionDeleteConfirmation;
|
||||
setSessionDeleteConfirmation(null);
|
||||
|
||||
try {
|
||||
const response =
|
||||
provider === 'codex'
|
||||
? await api.deleteCodexSession(sessionId)
|
||||
: await api.deleteSession(projectName, sessionId);
|
||||
|
||||
if (response.ok) {
|
||||
onSessionDelete?.(sessionId);
|
||||
} else {
|
||||
const errorText = await response.text();
|
||||
console.error('[Sidebar] Failed to delete session:', {
|
||||
status: response.status,
|
||||
error: errorText,
|
||||
});
|
||||
alert(t('messages.deleteSessionFailed'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Sidebar] Error deleting session:', error);
|
||||
alert(t('messages.deleteSessionError'));
|
||||
}
|
||||
}, [onSessionDelete, sessionDeleteConfirmation, t]);
|
||||
|
||||
const requestProjectDelete = useCallback(
|
||||
(project: Project) => {
|
||||
setDeleteConfirmation({
|
||||
project,
|
||||
sessionCount: getProjectSessions(project).length,
|
||||
});
|
||||
},
|
||||
[getProjectSessions],
|
||||
);
|
||||
|
||||
const confirmDeleteProject = useCallback(async () => {
|
||||
if (!deleteConfirmation) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { project, sessionCount } = deleteConfirmation;
|
||||
const isEmpty = sessionCount === 0;
|
||||
|
||||
setDeleteConfirmation(null);
|
||||
setDeletingProjects((prev) => new Set([...prev, project.name]));
|
||||
|
||||
try {
|
||||
const response = await api.deleteProject(project.name, !isEmpty);
|
||||
|
||||
if (response.ok) {
|
||||
onProjectDelete?.(project.name);
|
||||
} else {
|
||||
const error = (await response.json()) as { error?: string };
|
||||
alert(error.error || t('messages.deleteProjectFailed'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting project:', error);
|
||||
alert(t('messages.deleteProjectError'));
|
||||
} finally {
|
||||
setDeletingProjects((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(project.name);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, [deleteConfirmation, onProjectDelete, t]);
|
||||
|
||||
const loadMoreSessions = useCallback(
|
||||
async (project: Project) => {
|
||||
const hasMoreOverride = projectHasMoreOverrides[project.name];
|
||||
const canLoadMore =
|
||||
hasMoreOverride !== undefined ? hasMoreOverride : project.sessionMeta?.hasMore === true;
|
||||
if (!canLoadMore || loadingSessions[project.name]) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadingSessions((prev) => ({ ...prev, [project.name]: true }));
|
||||
|
||||
try {
|
||||
const currentSessionCount =
|
||||
(project.sessions?.length || 0) + (additionalSessions[project.name]?.length || 0);
|
||||
const response = await api.sessions(project.name, 5, currentSessionCount);
|
||||
|
||||
if (!response.ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = (await response.json()) as {
|
||||
sessions?: ProjectSession[];
|
||||
hasMore?: boolean;
|
||||
};
|
||||
|
||||
setAdditionalSessions((prev) => ({
|
||||
...prev,
|
||||
[project.name]: [...(prev[project.name] || []), ...(result.sessions || [])],
|
||||
}));
|
||||
|
||||
if (result.hasMore === false) {
|
||||
// Keep hasMore state in local hook state instead of mutating the project prop object.
|
||||
setProjectHasMoreOverrides((prev) => ({ ...prev, [project.name]: false }));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading more sessions:', error);
|
||||
} finally {
|
||||
setLoadingSessions((prev) => ({ ...prev, [project.name]: false }));
|
||||
}
|
||||
},
|
||||
[additionalSessions, loadingSessions, projectHasMoreOverrides],
|
||||
);
|
||||
|
||||
const handleProjectSelect = useCallback(
|
||||
(project: Project) => {
|
||||
onProjectSelect(project);
|
||||
setCurrentProject(project);
|
||||
},
|
||||
[onProjectSelect, setCurrentProject],
|
||||
);
|
||||
|
||||
const refreshProjects = useCallback(async () => {
|
||||
setIsRefreshing(true);
|
||||
try {
|
||||
await onRefresh();
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
}, [onRefresh]);
|
||||
|
||||
const updateSessionSummary = useCallback(
|
||||
async (_projectName: string, _sessionId: string, _summary: string) => {
|
||||
// Session rename endpoint is not currently exposed on the API.
|
||||
setEditingSession(null);
|
||||
setEditingSessionName('');
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const collapseSidebar = useCallback(() => {
|
||||
setSidebarVisible(false);
|
||||
}, [setSidebarVisible]);
|
||||
|
||||
const expandSidebar = useCallback(() => {
|
||||
setSidebarVisible(true);
|
||||
}, [setSidebarVisible]);
|
||||
|
||||
return {
|
||||
isSidebarCollapsed,
|
||||
expandedProjects,
|
||||
editingProject,
|
||||
showNewProject,
|
||||
editingName,
|
||||
loadingSessions,
|
||||
additionalSessions,
|
||||
initialSessionsLoaded,
|
||||
currentTime,
|
||||
projectSortOrder,
|
||||
isRefreshing,
|
||||
editingSession,
|
||||
editingSessionName,
|
||||
searchFilter,
|
||||
deletingProjects,
|
||||
deleteConfirmation,
|
||||
sessionDeleteConfirmation,
|
||||
showVersionModal,
|
||||
starredProjects,
|
||||
filteredProjects,
|
||||
handleTouchClick,
|
||||
toggleProject,
|
||||
handleSessionClick,
|
||||
toggleStarProject,
|
||||
isProjectStarred,
|
||||
getProjectSessions,
|
||||
startEditing,
|
||||
cancelEditing,
|
||||
saveProjectName,
|
||||
showDeleteSessionConfirmation,
|
||||
confirmDeleteSession,
|
||||
requestProjectDelete,
|
||||
confirmDeleteProject,
|
||||
loadMoreSessions,
|
||||
handleProjectSelect,
|
||||
refreshProjects,
|
||||
updateSessionSummary,
|
||||
collapseSidebar,
|
||||
expandSidebar,
|
||||
setShowNewProject,
|
||||
setEditingName,
|
||||
setEditingSession,
|
||||
setEditingSessionName,
|
||||
setSearchFilter,
|
||||
setDeleteConfirmation,
|
||||
setSessionDeleteConfirmation,
|
||||
setShowVersionModal,
|
||||
};
|
||||
}
|
||||
62
src/components/sidebar/types/types.ts
Normal file
62
src/components/sidebar/types/types.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import type React from 'react';
|
||||
import type { LoadingProgress, Project, ProjectSession, SessionProvider } from '../../../types/app';
|
||||
|
||||
export type ProjectSortOrder = 'name' | 'date';
|
||||
|
||||
export type SessionWithProvider = ProjectSession & {
|
||||
__provider: SessionProvider;
|
||||
};
|
||||
|
||||
export type AdditionalSessionsByProject = Record<string, ProjectSession[]>;
|
||||
export type LoadingSessionsByProject = Record<string, boolean>;
|
||||
|
||||
export type DeleteProjectConfirmation = {
|
||||
project: Project;
|
||||
sessionCount: number;
|
||||
};
|
||||
|
||||
export type SessionDeleteConfirmation = {
|
||||
projectName: string;
|
||||
sessionId: string;
|
||||
sessionTitle: string;
|
||||
provider: SessionProvider;
|
||||
};
|
||||
|
||||
export type SidebarProps = {
|
||||
projects: Project[];
|
||||
selectedProject: Project | null;
|
||||
selectedSession: ProjectSession | null;
|
||||
onProjectSelect: (project: Project) => void;
|
||||
onSessionSelect: (session: ProjectSession) => void;
|
||||
onNewSession: (project: Project) => void;
|
||||
onSessionDelete?: (sessionId: string) => void;
|
||||
onProjectDelete?: (projectName: string) => void;
|
||||
isLoading: boolean;
|
||||
loadingProgress: LoadingProgress | null;
|
||||
onRefresh: () => Promise<void> | void;
|
||||
onShowSettings: () => void;
|
||||
showSettings: boolean;
|
||||
settingsInitialTab: string;
|
||||
onCloseSettings: () => void;
|
||||
isMobile: boolean;
|
||||
};
|
||||
|
||||
export type SessionViewModel = {
|
||||
isCursorSession: boolean;
|
||||
isCodexSession: boolean;
|
||||
isActive: boolean;
|
||||
sessionName: string;
|
||||
sessionTime: string;
|
||||
messageCount: number;
|
||||
};
|
||||
|
||||
export type MCPServerStatus = {
|
||||
hasMCPServer?: boolean;
|
||||
isConfigured?: boolean;
|
||||
} | null;
|
||||
|
||||
export type TouchHandlerFactory = (
|
||||
callback: () => void,
|
||||
) => (event: React.TouchEvent<HTMLElement>) => void;
|
||||
|
||||
export type SettingsProject = Pick<Project, 'name' | 'displayName' | 'fullPath' | 'path'>;
|
||||
223
src/components/sidebar/utils/utils.ts
Normal file
223
src/components/sidebar/utils/utils.ts
Normal file
@@ -0,0 +1,223 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { Project } from '../../../types/app';
|
||||
import type {
|
||||
AdditionalSessionsByProject,
|
||||
ProjectSortOrder,
|
||||
SettingsProject,
|
||||
SessionViewModel,
|
||||
SessionWithProvider,
|
||||
} from '../types/types';
|
||||
|
||||
export const readProjectSortOrder = (): ProjectSortOrder => {
|
||||
try {
|
||||
const rawSettings = localStorage.getItem('claude-settings');
|
||||
if (!rawSettings) {
|
||||
return 'name';
|
||||
}
|
||||
|
||||
const settings = JSON.parse(rawSettings) as { projectSortOrder?: ProjectSortOrder };
|
||||
return settings.projectSortOrder === 'date' ? 'date' : 'name';
|
||||
} catch {
|
||||
return 'name';
|
||||
}
|
||||
};
|
||||
|
||||
export const loadStarredProjects = (): Set<string> => {
|
||||
try {
|
||||
const saved = localStorage.getItem('starredProjects');
|
||||
return saved ? new Set<string>(JSON.parse(saved)) : new Set<string>();
|
||||
} catch {
|
||||
return new Set<string>();
|
||||
}
|
||||
};
|
||||
|
||||
export const persistStarredProjects = (starredProjects: Set<string>) => {
|
||||
try {
|
||||
localStorage.setItem('starredProjects', JSON.stringify([...starredProjects]));
|
||||
} catch {
|
||||
// Keep UI responsive even if storage fails.
|
||||
}
|
||||
};
|
||||
|
||||
export const getSessionDate = (session: SessionWithProvider): Date => {
|
||||
if (session.__provider === 'cursor') {
|
||||
return new Date(session.createdAt || 0);
|
||||
}
|
||||
|
||||
if (session.__provider === 'codex') {
|
||||
return new Date(session.createdAt || session.lastActivity || 0);
|
||||
}
|
||||
|
||||
return new Date(session.lastActivity || 0);
|
||||
};
|
||||
|
||||
export const getSessionName = (session: SessionWithProvider, t: TFunction): string => {
|
||||
if (session.__provider === 'cursor') {
|
||||
return session.name || t('projects.untitledSession');
|
||||
}
|
||||
|
||||
if (session.__provider === 'codex') {
|
||||
return session.summary || session.name || t('projects.codexSession');
|
||||
}
|
||||
|
||||
return session.summary || t('projects.newSession');
|
||||
};
|
||||
|
||||
export const getSessionTime = (session: SessionWithProvider): string => {
|
||||
if (session.__provider === 'cursor') {
|
||||
return String(session.createdAt || '');
|
||||
}
|
||||
|
||||
if (session.__provider === 'codex') {
|
||||
return String(session.createdAt || session.lastActivity || '');
|
||||
}
|
||||
|
||||
return String(session.lastActivity || '');
|
||||
};
|
||||
|
||||
export const createSessionViewModel = (
|
||||
session: SessionWithProvider,
|
||||
currentTime: Date,
|
||||
t: TFunction,
|
||||
): SessionViewModel => {
|
||||
const sessionDate = getSessionDate(session);
|
||||
const diffInMinutes = Math.floor((currentTime.getTime() - sessionDate.getTime()) / (1000 * 60));
|
||||
|
||||
return {
|
||||
isCursorSession: session.__provider === 'cursor',
|
||||
isCodexSession: session.__provider === 'codex',
|
||||
isActive: diffInMinutes < 10,
|
||||
sessionName: getSessionName(session, t),
|
||||
sessionTime: getSessionTime(session),
|
||||
messageCount: Number(session.messageCount || 0),
|
||||
};
|
||||
};
|
||||
|
||||
export const getAllSessions = (
|
||||
project: Project,
|
||||
additionalSessions: AdditionalSessionsByProject,
|
||||
): SessionWithProvider[] => {
|
||||
const claudeSessions = [
|
||||
...(project.sessions || []),
|
||||
...(additionalSessions[project.name] || []),
|
||||
].map((session) => ({ ...session, __provider: 'claude' as const }));
|
||||
|
||||
const cursorSessions = (project.cursorSessions || []).map((session) => ({
|
||||
...session,
|
||||
__provider: 'cursor' as const,
|
||||
}));
|
||||
|
||||
const codexSessions = (project.codexSessions || []).map((session) => ({
|
||||
...session,
|
||||
__provider: 'codex' as const,
|
||||
}));
|
||||
|
||||
return [...claudeSessions, ...cursorSessions, ...codexSessions].sort(
|
||||
(a, b) => getSessionDate(b).getTime() - getSessionDate(a).getTime(),
|
||||
);
|
||||
};
|
||||
|
||||
export const getProjectLastActivity = (
|
||||
project: Project,
|
||||
additionalSessions: AdditionalSessionsByProject,
|
||||
): Date => {
|
||||
const sessions = getAllSessions(project, additionalSessions);
|
||||
if (sessions.length === 0) {
|
||||
return new Date(0);
|
||||
}
|
||||
|
||||
return sessions.reduce((latest, session) => {
|
||||
const sessionDate = getSessionDate(session);
|
||||
return sessionDate > latest ? sessionDate : latest;
|
||||
}, new Date(0));
|
||||
};
|
||||
|
||||
export const sortProjects = (
|
||||
projects: Project[],
|
||||
projectSortOrder: ProjectSortOrder,
|
||||
starredProjects: Set<string>,
|
||||
additionalSessions: AdditionalSessionsByProject,
|
||||
): Project[] => {
|
||||
const byName = [...projects];
|
||||
|
||||
byName.sort((projectA, projectB) => {
|
||||
const aStarred = starredProjects.has(projectA.name);
|
||||
const bStarred = starredProjects.has(projectB.name);
|
||||
|
||||
if (aStarred && !bStarred) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!aStarred && bStarred) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (projectSortOrder === 'date') {
|
||||
return (
|
||||
getProjectLastActivity(projectB, additionalSessions).getTime() -
|
||||
getProjectLastActivity(projectA, additionalSessions).getTime()
|
||||
);
|
||||
}
|
||||
|
||||
return (projectA.displayName || projectA.name).localeCompare(projectB.displayName || projectB.name);
|
||||
});
|
||||
|
||||
return byName;
|
||||
};
|
||||
|
||||
export const filterProjects = (projects: Project[], searchFilter: string): Project[] => {
|
||||
const normalizedSearch = searchFilter.trim().toLowerCase();
|
||||
if (!normalizedSearch) {
|
||||
return projects;
|
||||
}
|
||||
|
||||
return projects.filter((project) => {
|
||||
const displayName = (project.displayName || project.name).toLowerCase();
|
||||
const projectName = project.name.toLowerCase();
|
||||
return displayName.includes(normalizedSearch) || projectName.includes(normalizedSearch);
|
||||
});
|
||||
};
|
||||
|
||||
export const getTaskIndicatorStatus = (
|
||||
project: Project,
|
||||
mcpServerStatus: { hasMCPServer?: boolean; isConfigured?: boolean } | null,
|
||||
) => {
|
||||
const projectConfigured = Boolean(project.taskmaster?.hasTaskmaster);
|
||||
const mcpConfigured = Boolean(mcpServerStatus?.hasMCPServer && mcpServerStatus?.isConfigured);
|
||||
|
||||
if (projectConfigured && mcpConfigured) {
|
||||
return 'fully-configured';
|
||||
}
|
||||
|
||||
if (projectConfigured) {
|
||||
return 'taskmaster-only';
|
||||
}
|
||||
|
||||
if (mcpConfigured) {
|
||||
return 'mcp-only';
|
||||
}
|
||||
|
||||
return 'not-configured';
|
||||
};
|
||||
|
||||
export const normalizeProjectForSettings = (project: Project): SettingsProject => {
|
||||
const fallbackPath =
|
||||
typeof project.fullPath === 'string' && project.fullPath.length > 0
|
||||
? project.fullPath
|
||||
: typeof project.path === 'string'
|
||||
? project.path
|
||||
: '';
|
||||
|
||||
return {
|
||||
name: project.name,
|
||||
displayName:
|
||||
typeof project.displayName === 'string' && project.displayName.trim().length > 0
|
||||
? project.displayName
|
||||
: project.name,
|
||||
fullPath: fallbackPath,
|
||||
path:
|
||||
typeof project.path === 'string' && project.path.length > 0
|
||||
? project.path
|
||||
: fallbackPath,
|
||||
};
|
||||
};
|
||||
245
src/components/sidebar/view/Sidebar.tsx
Normal file
245
src/components/sidebar/view/Sidebar.tsx
Normal file
@@ -0,0 +1,245 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useDeviceSettings } from '../../../hooks/useDeviceSettings';
|
||||
import { useVersionCheck } from '../../../hooks/useVersionCheck';
|
||||
import { useUiPreferences } from '../../../hooks/useUiPreferences';
|
||||
import { useSidebarController } from '../hooks/useSidebarController';
|
||||
import { useTaskMaster } from '../../../contexts/TaskMasterContext';
|
||||
import { useTasksSettings } from '../../../contexts/TasksSettingsContext';
|
||||
import SidebarCollapsed from './subcomponents/SidebarCollapsed';
|
||||
import SidebarContent from './subcomponents/SidebarContent';
|
||||
import SidebarModals from './subcomponents/SidebarModals';
|
||||
import type { Project } from '../../../types/app';
|
||||
import type { SidebarProjectListProps } from './subcomponents/SidebarProjectList';
|
||||
import type { MCPServerStatus, SidebarProps } from '../types/types';
|
||||
|
||||
type TaskMasterSidebarContext = {
|
||||
setCurrentProject: (project: Project) => void;
|
||||
mcpServerStatus: MCPServerStatus;
|
||||
};
|
||||
|
||||
function Sidebar({
|
||||
projects,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
onProjectSelect,
|
||||
onSessionSelect,
|
||||
onNewSession,
|
||||
onSessionDelete,
|
||||
onProjectDelete,
|
||||
isLoading,
|
||||
loadingProgress,
|
||||
onRefresh,
|
||||
onShowSettings,
|
||||
showSettings,
|
||||
settingsInitialTab,
|
||||
onCloseSettings,
|
||||
isMobile,
|
||||
}: SidebarProps) {
|
||||
const { t } = useTranslation(['sidebar', 'common']);
|
||||
const { isPWA } = useDeviceSettings({ trackMobile: false });
|
||||
const { updateAvailable, latestVersion, currentVersion, releaseInfo } = useVersionCheck(
|
||||
'siteboon',
|
||||
'claudecodeui',
|
||||
);
|
||||
const { preferences, setPreference } = useUiPreferences();
|
||||
const { sidebarVisible } = preferences;
|
||||
const { setCurrentProject, mcpServerStatus } = useTaskMaster() as TaskMasterSidebarContext;
|
||||
const { tasksEnabled } = useTasksSettings();
|
||||
|
||||
const {
|
||||
isSidebarCollapsed,
|
||||
expandedProjects,
|
||||
editingProject,
|
||||
showNewProject,
|
||||
editingName,
|
||||
loadingSessions,
|
||||
initialSessionsLoaded,
|
||||
currentTime,
|
||||
isRefreshing,
|
||||
editingSession,
|
||||
editingSessionName,
|
||||
searchFilter,
|
||||
deletingProjects,
|
||||
deleteConfirmation,
|
||||
sessionDeleteConfirmation,
|
||||
showVersionModal,
|
||||
filteredProjects,
|
||||
handleTouchClick,
|
||||
toggleProject,
|
||||
handleSessionClick,
|
||||
toggleStarProject,
|
||||
isProjectStarred,
|
||||
getProjectSessions,
|
||||
startEditing,
|
||||
cancelEditing,
|
||||
saveProjectName,
|
||||
showDeleteSessionConfirmation,
|
||||
confirmDeleteSession,
|
||||
requestProjectDelete,
|
||||
confirmDeleteProject,
|
||||
loadMoreSessions,
|
||||
handleProjectSelect,
|
||||
refreshProjects,
|
||||
updateSessionSummary,
|
||||
collapseSidebar: handleCollapseSidebar,
|
||||
expandSidebar: handleExpandSidebar,
|
||||
setShowNewProject,
|
||||
setEditingName,
|
||||
setEditingSession,
|
||||
setEditingSessionName,
|
||||
setSearchFilter,
|
||||
setDeleteConfirmation,
|
||||
setSessionDeleteConfirmation,
|
||||
setShowVersionModal,
|
||||
} = useSidebarController({
|
||||
projects,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
isLoading,
|
||||
isMobile,
|
||||
t,
|
||||
onRefresh,
|
||||
onProjectSelect,
|
||||
onSessionSelect,
|
||||
onSessionDelete,
|
||||
onProjectDelete,
|
||||
setCurrentProject,
|
||||
setSidebarVisible: (visible) => setPreference('sidebarVisible', visible),
|
||||
sidebarVisible,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof document === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
document.documentElement.classList.toggle('pwa-mode', isPWA);
|
||||
document.body.classList.toggle('pwa-mode', isPWA);
|
||||
}, [isPWA]);
|
||||
|
||||
const handleProjectCreated = () => {
|
||||
if (window.refreshProjects) {
|
||||
void window.refreshProjects();
|
||||
return;
|
||||
}
|
||||
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
const projectListProps: SidebarProjectListProps = {
|
||||
projects,
|
||||
filteredProjects,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
isLoading,
|
||||
loadingProgress,
|
||||
expandedProjects,
|
||||
editingProject,
|
||||
editingName,
|
||||
loadingSessions,
|
||||
initialSessionsLoaded,
|
||||
currentTime,
|
||||
editingSession,
|
||||
editingSessionName,
|
||||
deletingProjects,
|
||||
tasksEnabled,
|
||||
mcpServerStatus,
|
||||
getProjectSessions,
|
||||
isProjectStarred,
|
||||
onEditingNameChange: setEditingName,
|
||||
onToggleProject: toggleProject,
|
||||
onProjectSelect: handleProjectSelect,
|
||||
onToggleStarProject: toggleStarProject,
|
||||
onStartEditingProject: startEditing,
|
||||
onCancelEditingProject: cancelEditing,
|
||||
onSaveProjectName: (projectName) => {
|
||||
void saveProjectName(projectName);
|
||||
},
|
||||
onDeleteProject: requestProjectDelete,
|
||||
onSessionSelect: handleSessionClick,
|
||||
onDeleteSession: showDeleteSessionConfirmation,
|
||||
onLoadMoreSessions: (project) => {
|
||||
void loadMoreSessions(project);
|
||||
},
|
||||
onNewSession,
|
||||
onEditingSessionNameChange: setEditingSessionName,
|
||||
onStartEditingSession: (sessionId, initialName) => {
|
||||
setEditingSession(sessionId);
|
||||
setEditingSessionName(initialName);
|
||||
},
|
||||
onCancelEditingSession: () => {
|
||||
setEditingSession(null);
|
||||
setEditingSessionName('');
|
||||
},
|
||||
onSaveEditingSession: (projectName, sessionId, summary) => {
|
||||
void updateSessionSummary(projectName, sessionId, summary);
|
||||
},
|
||||
touchHandlerFactory: handleTouchClick,
|
||||
t,
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<SidebarModals
|
||||
projects={projects}
|
||||
showSettings={showSettings}
|
||||
settingsInitialTab={settingsInitialTab}
|
||||
onCloseSettings={onCloseSettings}
|
||||
showNewProject={showNewProject}
|
||||
onCloseNewProject={() => setShowNewProject(false)}
|
||||
onProjectCreated={handleProjectCreated}
|
||||
deleteConfirmation={deleteConfirmation}
|
||||
onCancelDeleteProject={() => setDeleteConfirmation(null)}
|
||||
onConfirmDeleteProject={confirmDeleteProject}
|
||||
sessionDeleteConfirmation={sessionDeleteConfirmation}
|
||||
onCancelDeleteSession={() => setSessionDeleteConfirmation(null)}
|
||||
onConfirmDeleteSession={confirmDeleteSession}
|
||||
showVersionModal={showVersionModal}
|
||||
onCloseVersionModal={() => setShowVersionModal(false)}
|
||||
releaseInfo={releaseInfo}
|
||||
currentVersion={currentVersion}
|
||||
latestVersion={latestVersion}
|
||||
t={t}
|
||||
/>
|
||||
|
||||
{isSidebarCollapsed ? (
|
||||
<SidebarCollapsed
|
||||
onExpand={handleExpandSidebar}
|
||||
onShowSettings={onShowSettings}
|
||||
updateAvailable={updateAvailable}
|
||||
onShowVersionModal={() => setShowVersionModal(true)}
|
||||
t={t}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<SidebarContent
|
||||
isPWA={isPWA}
|
||||
isMobile={isMobile}
|
||||
isLoading={isLoading}
|
||||
projects={projects}
|
||||
searchFilter={searchFilter}
|
||||
onSearchFilterChange={setSearchFilter}
|
||||
onClearSearchFilter={() => setSearchFilter('')}
|
||||
onRefresh={() => {
|
||||
void refreshProjects();
|
||||
}}
|
||||
isRefreshing={isRefreshing}
|
||||
onCreateProject={() => setShowNewProject(true)}
|
||||
onCollapseSidebar={handleCollapseSidebar}
|
||||
updateAvailable={updateAvailable}
|
||||
releaseInfo={releaseInfo}
|
||||
latestVersion={latestVersion}
|
||||
onShowVersionModal={() => setShowVersionModal(true)}
|
||||
onShowSettings={onShowSettings}
|
||||
projectListProps={projectListProps}
|
||||
t={t}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default Sidebar;
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Settings, Sparkles } from 'lucide-react';
|
||||
import type { TFunction } from 'i18next';
|
||||
|
||||
type SidebarCollapsedProps = {
|
||||
onExpand: () => void;
|
||||
onShowSettings: () => void;
|
||||
updateAvailable: boolean;
|
||||
onShowVersionModal: () => void;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
export default function SidebarCollapsed({
|
||||
onExpand,
|
||||
onShowSettings,
|
||||
updateAvailable,
|
||||
onShowVersionModal,
|
||||
t,
|
||||
}: SidebarCollapsedProps) {
|
||||
return (
|
||||
<div className="h-full flex flex-col items-center py-4 gap-4 bg-card">
|
||||
<button
|
||||
onClick={onExpand}
|
||||
className="p-2 hover:bg-accent rounded-md transition-colors duration-200 group"
|
||||
aria-label={t('common:versionUpdate.ariaLabels.showSidebar')}
|
||||
title={t('common:versionUpdate.ariaLabels.showSidebar')}
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5 text-foreground group-hover:scale-110 transition-transform"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 5l7 7-7 7M5 5l7 7-7 7" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={onShowSettings}
|
||||
className="p-2 hover:bg-accent rounded-md transition-colors duration-200"
|
||||
aria-label={t('actions.settings')}
|
||||
title={t('actions.settings')}
|
||||
>
|
||||
<Settings className="w-5 h-5 text-muted-foreground hover:text-foreground transition-colors" />
|
||||
</button>
|
||||
|
||||
{updateAvailable && (
|
||||
<button
|
||||
onClick={onShowVersionModal}
|
||||
className="relative p-2 hover:bg-accent rounded-md transition-colors duration-200"
|
||||
aria-label={t('common:versionUpdate.ariaLabels.updateAvailable')}
|
||||
title={t('common:versionUpdate.ariaLabels.updateAvailable')}
|
||||
>
|
||||
<Sparkles className="w-5 h-5 text-blue-500" />
|
||||
<span className="absolute top-1 right-1 w-2 h-2 bg-blue-500 rounded-full animate-pulse" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
84
src/components/sidebar/view/subcomponents/SidebarContent.tsx
Normal file
84
src/components/sidebar/view/subcomponents/SidebarContent.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
import { ScrollArea } from '../../../ui/scroll-area';
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { Project } from '../../../../types/app';
|
||||
import type { ReleaseInfo } from '../../../../types/sharedTypes';
|
||||
import SidebarFooter from './SidebarFooter';
|
||||
import SidebarHeader from './SidebarHeader';
|
||||
import SidebarProjectList, { type SidebarProjectListProps } from './SidebarProjectList';
|
||||
|
||||
type SidebarContentProps = {
|
||||
isPWA: boolean;
|
||||
isMobile: boolean;
|
||||
isLoading: boolean;
|
||||
projects: Project[];
|
||||
searchFilter: string;
|
||||
onSearchFilterChange: (value: string) => void;
|
||||
onClearSearchFilter: () => void;
|
||||
onRefresh: () => void;
|
||||
isRefreshing: boolean;
|
||||
onCreateProject: () => void;
|
||||
onCollapseSidebar: () => void;
|
||||
updateAvailable: boolean;
|
||||
releaseInfo: ReleaseInfo | null;
|
||||
latestVersion: string | null;
|
||||
onShowVersionModal: () => void;
|
||||
onShowSettings: () => void;
|
||||
projectListProps: SidebarProjectListProps;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
export default function SidebarContent({
|
||||
isPWA,
|
||||
isMobile,
|
||||
isLoading,
|
||||
projects,
|
||||
searchFilter,
|
||||
onSearchFilterChange,
|
||||
onClearSearchFilter,
|
||||
onRefresh,
|
||||
isRefreshing,
|
||||
onCreateProject,
|
||||
onCollapseSidebar,
|
||||
updateAvailable,
|
||||
releaseInfo,
|
||||
latestVersion,
|
||||
onShowVersionModal,
|
||||
onShowSettings,
|
||||
projectListProps,
|
||||
t,
|
||||
}: SidebarContentProps) {
|
||||
return (
|
||||
<div
|
||||
className="h-full flex flex-col bg-card md:select-none md:w-80"
|
||||
style={isPWA && isMobile ? { paddingTop: '44px' } : {}}
|
||||
>
|
||||
<SidebarHeader
|
||||
isPWA={isPWA}
|
||||
isMobile={isMobile}
|
||||
isLoading={isLoading}
|
||||
projectsCount={projects.length}
|
||||
searchFilter={searchFilter}
|
||||
onSearchFilterChange={onSearchFilterChange}
|
||||
onClearSearchFilter={onClearSearchFilter}
|
||||
onRefresh={onRefresh}
|
||||
isRefreshing={isRefreshing}
|
||||
onCreateProject={onCreateProject}
|
||||
onCollapseSidebar={onCollapseSidebar}
|
||||
t={t}
|
||||
/>
|
||||
|
||||
<ScrollArea className="flex-1 md:px-2 md:py-3 overflow-y-auto overscroll-contain">
|
||||
<SidebarProjectList {...projectListProps} />
|
||||
</ScrollArea>
|
||||
|
||||
<SidebarFooter
|
||||
updateAvailable={updateAvailable}
|
||||
releaseInfo={releaseInfo}
|
||||
latestVersion={latestVersion}
|
||||
onShowVersionModal={onShowVersionModal}
|
||||
onShowSettings={onShowSettings}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
94
src/components/sidebar/view/subcomponents/SidebarFooter.tsx
Normal file
94
src/components/sidebar/view/subcomponents/SidebarFooter.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
import { Settings } from 'lucide-react';
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { ReleaseInfo } from '../../../../types/sharedTypes';
|
||||
import { Button } from '../../../ui/button';
|
||||
|
||||
type SidebarFooterProps = {
|
||||
updateAvailable: boolean;
|
||||
releaseInfo: ReleaseInfo | null;
|
||||
latestVersion: string | null;
|
||||
onShowVersionModal: () => void;
|
||||
onShowSettings: () => void;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
export default function SidebarFooter({
|
||||
updateAvailable,
|
||||
releaseInfo,
|
||||
latestVersion,
|
||||
onShowVersionModal,
|
||||
onShowSettings,
|
||||
t,
|
||||
}: SidebarFooterProps) {
|
||||
return (
|
||||
<>
|
||||
{updateAvailable && (
|
||||
<div className="md:p-2 border-t border-border/50 flex-shrink-0">
|
||||
<div className="hidden md:block">
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full justify-start gap-3 p-3 h-auto font-normal text-left hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors duration-200 border border-blue-200 dark:border-blue-700 rounded-lg mb-2"
|
||||
onClick={onShowVersionModal}
|
||||
>
|
||||
<div className="relative">
|
||||
<svg className="w-4 h-4 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M9 19l3 3m0 0l3-3m-3 3V10" />
|
||||
</svg>
|
||||
<div className="absolute -top-1 -right-1 w-2 h-2 bg-blue-500 rounded-full animate-pulse" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm font-medium text-blue-700 dark:text-blue-300">
|
||||
{releaseInfo?.title || `Version ${latestVersion}`}
|
||||
</div>
|
||||
<div className="text-xs text-blue-600 dark:text-blue-400">{t('version.updateAvailable')}</div>
|
||||
</div>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="md:hidden p-3 pb-2">
|
||||
<button
|
||||
className="w-full h-12 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-xl flex items-center justify-start gap-3 px-4 active:scale-[0.98] transition-all duration-150"
|
||||
onClick={onShowVersionModal}
|
||||
>
|
||||
<div className="relative">
|
||||
<svg className="w-5 h-5 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M9 19l3 3m0 0l3-3m-3 3V10" />
|
||||
</svg>
|
||||
<div className="absolute -top-1 -right-1 w-2 h-2 bg-blue-500 rounded-full animate-pulse" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 text-left">
|
||||
<div className="text-sm font-medium text-blue-700 dark:text-blue-300">
|
||||
{releaseInfo?.title || `Version ${latestVersion}`}
|
||||
</div>
|
||||
<div className="text-xs text-blue-600 dark:text-blue-400">{t('version.updateAvailable')}</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="md:p-2 md:border-t md:border-border flex-shrink-0">
|
||||
<div className="md:hidden p-4 pb-20 border-t border-border/50">
|
||||
<button
|
||||
className="w-full h-14 bg-muted/50 hover:bg-muted/70 rounded-2xl flex items-center justify-start gap-4 px-4 active:scale-[0.98] transition-all duration-150"
|
||||
onClick={onShowSettings}
|
||||
>
|
||||
<div className="w-10 h-10 rounded-2xl bg-background/80 flex items-center justify-center">
|
||||
<Settings className="w-5 h-5 text-muted-foreground" />
|
||||
</div>
|
||||
<span className="text-lg font-medium text-foreground">{t('actions.settings')}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="hidden md:flex w-full justify-start gap-2 p-2 h-auto font-normal text-muted-foreground hover:text-foreground hover:bg-accent transition-colors duration-200"
|
||||
onClick={onShowSettings}
|
||||
>
|
||||
<Settings className="w-3 h-3" />
|
||||
<span className="text-xs">{t('actions.settings')}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
187
src/components/sidebar/view/subcomponents/SidebarHeader.tsx
Normal file
187
src/components/sidebar/view/subcomponents/SidebarHeader.tsx
Normal file
@@ -0,0 +1,187 @@
|
||||
import { FolderPlus, MessageSquare, RefreshCw, Search, X } from 'lucide-react';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { Button } from '../../../ui/button';
|
||||
import { Input } from '../../../ui/input';
|
||||
import { IS_PLATFORM } from '../../../../constants/config';
|
||||
|
||||
type SidebarHeaderProps = {
|
||||
isPWA: boolean;
|
||||
isMobile: boolean;
|
||||
isLoading: boolean;
|
||||
projectsCount: number;
|
||||
searchFilter: string;
|
||||
onSearchFilterChange: (value: string) => void;
|
||||
onClearSearchFilter: () => void;
|
||||
onRefresh: () => void;
|
||||
isRefreshing: boolean;
|
||||
onCreateProject: () => void;
|
||||
onCollapseSidebar: () => void;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
export default function SidebarHeader({
|
||||
isPWA,
|
||||
isMobile,
|
||||
isLoading,
|
||||
projectsCount,
|
||||
searchFilter,
|
||||
onSearchFilterChange,
|
||||
onClearSearchFilter,
|
||||
onRefresh,
|
||||
isRefreshing,
|
||||
onCreateProject,
|
||||
onCollapseSidebar,
|
||||
t,
|
||||
}: SidebarHeaderProps) {
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className="md:p-4 md:border-b md:border-border"
|
||||
style={isPWA && isMobile ? { paddingTop: '44px' } : {}}
|
||||
>
|
||||
<div className="hidden md:flex items-center justify-between">
|
||||
{IS_PLATFORM ? (
|
||||
<a
|
||||
href="https://cloudcli.ai/dashboard"
|
||||
className="flex items-center gap-3 hover:opacity-80 transition-opacity group"
|
||||
title={t('tooltips.viewEnvironments')}
|
||||
>
|
||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center shadow-sm group-hover:shadow-md transition-shadow">
|
||||
<MessageSquare className="w-4 h-4 text-primary-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-lg font-bold text-foreground">{t('app.title')}</h1>
|
||||
<p className="text-sm text-muted-foreground">{t('app.subtitle')}</p>
|
||||
</div>
|
||||
</a>
|
||||
) : (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center shadow-sm">
|
||||
<MessageSquare className="w-4 h-4 text-primary-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-lg font-bold text-foreground">{t('app.title')}</h1>
|
||||
<p className="text-sm text-muted-foreground">{t('app.subtitle')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 px-0 hover:bg-accent transition-colors duration-200"
|
||||
onClick={onCollapseSidebar}
|
||||
title={t('tooltips.hideSidebar')}
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
|
||||
</svg>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="md:hidden p-3 border-b border-border"
|
||||
style={isPWA && isMobile ? { paddingTop: '16px' } : {}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
{IS_PLATFORM ? (
|
||||
<a
|
||||
href="https://cloudcli.ai/dashboard"
|
||||
className="flex items-center gap-3 active:opacity-70 transition-opacity"
|
||||
title={t('tooltips.viewEnvironments')}
|
||||
>
|
||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
|
||||
<MessageSquare className="w-4 h-4 text-primary-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-lg font-semibold text-foreground">{t('app.title')}</h1>
|
||||
<p className="text-sm text-muted-foreground">{t('projects.title')}</p>
|
||||
</div>
|
||||
</a>
|
||||
) : (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
|
||||
<MessageSquare className="w-4 h-4 text-primary-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-lg font-semibold text-foreground">{t('app.title')}</h1>
|
||||
<p className="text-sm text-muted-foreground">{t('projects.title')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
className="w-8 h-8 rounded-md bg-background border border-border flex items-center justify-center active:scale-95 transition-all duration-150"
|
||||
onClick={onRefresh}
|
||||
disabled={isRefreshing}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 text-foreground ${isRefreshing ? 'animate-spin' : ''}`} />
|
||||
</button>
|
||||
<button
|
||||
className="w-8 h-8 rounded-md bg-primary text-primary-foreground flex items-center justify-center active:scale-95 transition-all duration-150"
|
||||
onClick={onCreateProject}
|
||||
>
|
||||
<FolderPlus className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!isLoading && !isMobile && (
|
||||
<div className="px-3 md:px-4 py-2 border-b border-border">
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
className="flex-1 h-8 text-xs bg-primary hover:bg-primary/90 transition-all duration-200"
|
||||
onClick={onCreateProject}
|
||||
title={t('tooltips.createProject')}
|
||||
>
|
||||
<FolderPlus className="w-3.5 h-3.5 mr-1.5" />
|
||||
{t('projects.newProject')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 w-8 px-0 hover:bg-accent transition-colors duration-200 group"
|
||||
onClick={onRefresh}
|
||||
disabled={isRefreshing}
|
||||
title={t('tooltips.refresh')}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`w-3.5 h-3.5 ${
|
||||
isRefreshing ? 'animate-spin' : 'group-hover:rotate-180 transition-transform duration-300'
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{projectsCount > 0 && !isLoading && (
|
||||
<div className="px-3 md:px-4 py-2 border-b border-border">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={t('projects.searchPlaceholder')}
|
||||
value={searchFilter}
|
||||
onChange={(event) => onSearchFilterChange(event.target.value)}
|
||||
className="pl-9 h-9 text-sm bg-muted/50 border-0 focus:bg-background focus:ring-1 focus:ring-primary/20"
|
||||
/>
|
||||
{searchFilter && (
|
||||
<button
|
||||
onClick={onClearSearchFilter}
|
||||
className="absolute right-2 top-1/2 transform -translate-y-1/2 p-1 hover:bg-accent rounded"
|
||||
>
|
||||
<X className="w-3 h-3 text-muted-foreground" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
201
src/components/sidebar/view/subcomponents/SidebarModals.tsx
Normal file
201
src/components/sidebar/view/subcomponents/SidebarModals.tsx
Normal file
@@ -0,0 +1,201 @@
|
||||
import { useMemo } from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { AlertTriangle, Trash2 } from 'lucide-react';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { Button } from '../../../ui/button';
|
||||
import ProjectCreationWizard from '../../../ProjectCreationWizard';
|
||||
import Settings from '../../../Settings';
|
||||
import VersionUpgradeModal from '../../../modals/VersionUpgradeModal';
|
||||
import type { Project } from '../../../../types/app';
|
||||
import type { ReleaseInfo } from '../../../../types/sharedTypes';
|
||||
import { normalizeProjectForSettings } from '../../utils/utils';
|
||||
import type { DeleteProjectConfirmation, SessionDeleteConfirmation, SettingsProject } from '../../types/types';
|
||||
|
||||
type SidebarModalsProps = {
|
||||
projects: Project[];
|
||||
showSettings: boolean;
|
||||
settingsInitialTab: string;
|
||||
onCloseSettings: () => void;
|
||||
showNewProject: boolean;
|
||||
onCloseNewProject: () => void;
|
||||
onProjectCreated: () => void;
|
||||
deleteConfirmation: DeleteProjectConfirmation | null;
|
||||
onCancelDeleteProject: () => void;
|
||||
onConfirmDeleteProject: () => void;
|
||||
sessionDeleteConfirmation: SessionDeleteConfirmation | null;
|
||||
onCancelDeleteSession: () => void;
|
||||
onConfirmDeleteSession: () => void;
|
||||
showVersionModal: boolean;
|
||||
onCloseVersionModal: () => void;
|
||||
releaseInfo: ReleaseInfo | null;
|
||||
currentVersion: string;
|
||||
latestVersion: string | null;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
type TypedSettingsProps = {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
projects: SettingsProject[];
|
||||
initialTab: string;
|
||||
};
|
||||
|
||||
const SettingsComponent = Settings as (props: TypedSettingsProps) => JSX.Element;
|
||||
|
||||
function TypedSettings(props: TypedSettingsProps) {
|
||||
return <SettingsComponent {...props} />;
|
||||
}
|
||||
|
||||
export default function SidebarModals({
|
||||
projects,
|
||||
showSettings,
|
||||
settingsInitialTab,
|
||||
onCloseSettings,
|
||||
showNewProject,
|
||||
onCloseNewProject,
|
||||
onProjectCreated,
|
||||
deleteConfirmation,
|
||||
onCancelDeleteProject,
|
||||
onConfirmDeleteProject,
|
||||
sessionDeleteConfirmation,
|
||||
onCancelDeleteSession,
|
||||
onConfirmDeleteSession,
|
||||
showVersionModal,
|
||||
onCloseVersionModal,
|
||||
releaseInfo,
|
||||
currentVersion,
|
||||
latestVersion,
|
||||
t,
|
||||
}: SidebarModalsProps) {
|
||||
// Settings expects project identity/path fields to be present for dropdown labels and local-scope MCP config.
|
||||
const settingsProjects = useMemo(
|
||||
() => projects.map(normalizeProjectForSettings),
|
||||
[projects],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{showNewProject &&
|
||||
ReactDOM.createPortal(
|
||||
<ProjectCreationWizard
|
||||
onClose={onCloseNewProject}
|
||||
onProjectCreated={onProjectCreated}
|
||||
/>,
|
||||
document.body,
|
||||
)}
|
||||
|
||||
<TypedSettings
|
||||
isOpen={showSettings}
|
||||
onClose={onCloseSettings}
|
||||
projects={settingsProjects}
|
||||
initialTab={settingsInitialTab}
|
||||
/>
|
||||
|
||||
{deleteConfirmation &&
|
||||
ReactDOM.createPortal(
|
||||
<div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-card border border-border rounded-xl shadow-2xl max-w-md w-full overflow-hidden">
|
||||
<div className="p-6">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-12 h-12 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center flex-shrink-0">
|
||||
<AlertTriangle className="w-6 h-6 text-red-600 dark:text-red-400" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-lg font-semibold text-foreground mb-2">
|
||||
{t('deleteConfirmation.deleteProject')}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground mb-1">
|
||||
{t('deleteConfirmation.confirmDelete')}{' '}
|
||||
<span className="font-medium text-foreground">
|
||||
{deleteConfirmation.project.displayName || deleteConfirmation.project.name}
|
||||
</span>
|
||||
?
|
||||
</p>
|
||||
{deleteConfirmation.sessionCount > 0 && (
|
||||
<div className="mt-3 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
|
||||
<p className="text-sm text-red-700 dark:text-red-300 font-medium">
|
||||
{t('deleteConfirmation.sessionCount', { count: deleteConfirmation.sessionCount })}
|
||||
</p>
|
||||
<p className="text-xs text-red-600 dark:text-red-400 mt-1">
|
||||
{t('deleteConfirmation.allConversationsDeleted')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground mt-3">
|
||||
{t('deleteConfirmation.cannotUndo')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3 p-4 bg-muted/30 border-t border-border">
|
||||
<Button variant="outline" className="flex-1" onClick={onCancelDeleteProject}>
|
||||
{t('actions.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
className="flex-1 bg-red-600 hover:bg-red-700 text-white"
|
||||
onClick={onConfirmDeleteProject}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
{t('actions.delete')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
|
||||
{sessionDeleteConfirmation &&
|
||||
ReactDOM.createPortal(
|
||||
<div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-card border border-border rounded-xl shadow-2xl max-w-md w-full overflow-hidden">
|
||||
<div className="p-6">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-12 h-12 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center flex-shrink-0">
|
||||
<AlertTriangle className="w-6 h-6 text-red-600 dark:text-red-400" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-lg font-semibold text-foreground mb-2">
|
||||
{t('deleteConfirmation.deleteSession')}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground mb-1">
|
||||
{t('deleteConfirmation.confirmDelete')}{' '}
|
||||
<span className="font-medium text-foreground">
|
||||
{sessionDeleteConfirmation.sessionTitle || t('sessions.unnamed')}
|
||||
</span>
|
||||
?
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-3">
|
||||
{t('deleteConfirmation.cannotUndo')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3 p-4 bg-muted/30 border-t border-border">
|
||||
<Button variant="outline" className="flex-1" onClick={onCancelDeleteSession}>
|
||||
{t('actions.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
className="flex-1 bg-red-600 hover:bg-red-700 text-white"
|
||||
onClick={onConfirmDeleteSession}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
{t('actions.delete')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
|
||||
<VersionUpgradeModal
|
||||
isOpen={showVersionModal}
|
||||
onClose={onCloseVersionModal}
|
||||
releaseInfo={releaseInfo}
|
||||
currentVersion={currentVersion}
|
||||
latestVersion={latestVersion}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
432
src/components/sidebar/view/subcomponents/SidebarProjectItem.tsx
Normal file
432
src/components/sidebar/view/subcomponents/SidebarProjectItem.tsx
Normal file
@@ -0,0 +1,432 @@
|
||||
import { Button } from '../../../ui/button';
|
||||
import { Check, ChevronDown, ChevronRight, Edit3, Folder, FolderOpen, Star, Trash2, X } from 'lucide-react';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { cn } from '../../../../lib/utils';
|
||||
import TaskIndicator from '../../../TaskIndicator';
|
||||
import type { Project, ProjectSession, SessionProvider } from '../../../../types/app';
|
||||
import type { MCPServerStatus, SessionWithProvider, TouchHandlerFactory } from '../../types/types';
|
||||
import { getTaskIndicatorStatus } from '../../utils/utils';
|
||||
import SidebarProjectSessions from './SidebarProjectSessions';
|
||||
|
||||
type SidebarProjectItemProps = {
|
||||
project: Project;
|
||||
selectedProject: Project | null;
|
||||
selectedSession: ProjectSession | null;
|
||||
isExpanded: boolean;
|
||||
isDeleting: boolean;
|
||||
isStarred: boolean;
|
||||
editingProject: string | null;
|
||||
editingName: string;
|
||||
sessions: SessionWithProvider[];
|
||||
initialSessionsLoaded: boolean;
|
||||
isLoadingSessions: boolean;
|
||||
currentTime: Date;
|
||||
editingSession: string | null;
|
||||
editingSessionName: string;
|
||||
tasksEnabled: boolean;
|
||||
mcpServerStatus: MCPServerStatus;
|
||||
onEditingNameChange: (name: string) => void;
|
||||
onToggleProject: (projectName: string) => void;
|
||||
onProjectSelect: (project: Project) => void;
|
||||
onToggleStarProject: (projectName: string) => void;
|
||||
onStartEditingProject: (project: Project) => void;
|
||||
onCancelEditingProject: () => void;
|
||||
onSaveProjectName: (projectName: string) => void;
|
||||
onDeleteProject: (project: Project) => void;
|
||||
onSessionSelect: (session: SessionWithProvider, projectName: string) => void;
|
||||
onDeleteSession: (
|
||||
projectName: string,
|
||||
sessionId: string,
|
||||
sessionTitle: string,
|
||||
provider: SessionProvider,
|
||||
) => void;
|
||||
onLoadMoreSessions: (project: Project) => void;
|
||||
onNewSession: (project: Project) => void;
|
||||
onEditingSessionNameChange: (value: string) => void;
|
||||
onStartEditingSession: (sessionId: string, initialName: string) => void;
|
||||
onCancelEditingSession: () => void;
|
||||
onSaveEditingSession: (projectName: string, sessionId: string, summary: string) => void;
|
||||
touchHandlerFactory: TouchHandlerFactory;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
const getSessionCountDisplay = (sessions: SessionWithProvider[], hasMoreSessions: boolean): string => {
|
||||
const sessionCount = sessions.length;
|
||||
if (hasMoreSessions && sessionCount >= 5) {
|
||||
return `${sessionCount}+`;
|
||||
}
|
||||
|
||||
return `${sessionCount}`;
|
||||
};
|
||||
|
||||
export default function SidebarProjectItem({
|
||||
project,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
isExpanded,
|
||||
isDeleting,
|
||||
isStarred,
|
||||
editingProject,
|
||||
editingName,
|
||||
sessions,
|
||||
initialSessionsLoaded,
|
||||
isLoadingSessions,
|
||||
currentTime,
|
||||
editingSession,
|
||||
editingSessionName,
|
||||
tasksEnabled,
|
||||
mcpServerStatus,
|
||||
onEditingNameChange,
|
||||
onToggleProject,
|
||||
onProjectSelect,
|
||||
onToggleStarProject,
|
||||
onStartEditingProject,
|
||||
onCancelEditingProject,
|
||||
onSaveProjectName,
|
||||
onDeleteProject,
|
||||
onSessionSelect,
|
||||
onDeleteSession,
|
||||
onLoadMoreSessions,
|
||||
onNewSession,
|
||||
onEditingSessionNameChange,
|
||||
onStartEditingSession,
|
||||
onCancelEditingSession,
|
||||
onSaveEditingSession,
|
||||
touchHandlerFactory,
|
||||
t,
|
||||
}: SidebarProjectItemProps) {
|
||||
const isSelected = selectedProject?.name === project.name;
|
||||
const isEditing = editingProject === project.name;
|
||||
const hasMoreSessions = project.sessionMeta?.hasMore === true;
|
||||
const sessionCountDisplay = getSessionCountDisplay(sessions, hasMoreSessions);
|
||||
const sessionCountLabel = `${sessionCountDisplay} session${sessions.length === 1 ? '' : 's'}`;
|
||||
const taskStatus = getTaskIndicatorStatus(project, mcpServerStatus);
|
||||
|
||||
const toggleProject = () => onToggleProject(project.name);
|
||||
const toggleStarProject = () => onToggleStarProject(project.name);
|
||||
|
||||
const saveProjectName = () => {
|
||||
onSaveProjectName(project.name);
|
||||
};
|
||||
|
||||
const selectAndToggleProject = () => {
|
||||
if (selectedProject?.name !== project.name) {
|
||||
onProjectSelect(project);
|
||||
}
|
||||
|
||||
toggleProject();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn('md:space-y-1', isDeleting && 'opacity-50 pointer-events-none')}>
|
||||
<div className="group md:group">
|
||||
<div className="md:hidden">
|
||||
<div
|
||||
className={cn(
|
||||
'p-3 mx-3 my-1 rounded-lg bg-card border border-border/50 active:scale-[0.98] transition-all duration-150',
|
||||
isSelected && 'bg-primary/5 border-primary/20',
|
||||
isStarred &&
|
||||
!isSelected &&
|
||||
'bg-yellow-50/50 dark:bg-yellow-900/5 border-yellow-200/30 dark:border-yellow-800/30',
|
||||
)}
|
||||
onClick={toggleProject}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3 min-w-0 flex-1">
|
||||
<div
|
||||
className={cn(
|
||||
'w-8 h-8 rounded-lg flex items-center justify-center transition-colors',
|
||||
isExpanded ? 'bg-primary/10' : 'bg-muted',
|
||||
)}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<FolderOpen className="w-4 h-4 text-primary" />
|
||||
) : (
|
||||
<Folder className="w-4 h-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
{isEditing ? (
|
||||
<input
|
||||
type="text"
|
||||
value={editingName}
|
||||
onChange={(event) => onEditingNameChange(event.target.value)}
|
||||
className="w-full px-3 py-2 text-sm border-2 border-primary/40 focus:border-primary rounded-lg bg-background text-foreground shadow-sm focus:shadow-md transition-all duration-200 focus:outline-none"
|
||||
placeholder={t('projects.projectNamePlaceholder')}
|
||||
autoFocus
|
||||
autoComplete="off"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
saveProjectName();
|
||||
}
|
||||
|
||||
if (event.key === 'Escape') {
|
||||
onCancelEditingProject();
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
fontSize: '16px',
|
||||
WebkitAppearance: 'none',
|
||||
borderRadius: '8px',
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center justify-between min-w-0 flex-1">
|
||||
<h3 className="text-sm font-medium text-foreground truncate">{project.displayName}</h3>
|
||||
{tasksEnabled && (
|
||||
<TaskIndicator
|
||||
status={taskStatus}
|
||||
size="xs"
|
||||
className="hidden md:inline-flex flex-shrink-0 ml-2"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{sessionCountLabel}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
{isEditing ? (
|
||||
<>
|
||||
<button
|
||||
className="w-8 h-8 rounded-lg bg-green-500 dark:bg-green-600 flex items-center justify-center active:scale-90 transition-all duration-150 shadow-sm active:shadow-none"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
saveProjectName();
|
||||
}}
|
||||
>
|
||||
<Check className="w-4 h-4 text-white" />
|
||||
</button>
|
||||
<button
|
||||
className="w-8 h-8 rounded-lg bg-gray-500 dark:bg-gray-600 flex items-center justify-center active:scale-90 transition-all duration-150 shadow-sm active:shadow-none"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onCancelEditingProject();
|
||||
}}
|
||||
>
|
||||
<X className="w-4 h-4 text-white" />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
className={cn(
|
||||
'w-8 h-8 rounded-lg flex items-center justify-center active:scale-90 transition-all duration-150 border',
|
||||
isStarred
|
||||
? 'bg-yellow-500/10 dark:bg-yellow-900/30 border-yellow-200 dark:border-yellow-800'
|
||||
: 'bg-gray-500/10 dark:bg-gray-900/30 border-gray-200 dark:border-gray-800',
|
||||
)}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
toggleStarProject();
|
||||
}}
|
||||
title={isStarred ? t('tooltips.removeFromFavorites') : t('tooltips.addToFavorites')}
|
||||
>
|
||||
<Star
|
||||
className={cn(
|
||||
'w-4 h-4 transition-colors',
|
||||
isStarred
|
||||
? 'text-yellow-600 dark:text-yellow-400 fill-current'
|
||||
: 'text-gray-600 dark:text-gray-400',
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
|
||||
<button
|
||||
className="w-8 h-8 rounded-lg bg-red-500/10 dark:bg-red-900/30 flex items-center justify-center active:scale-90 border border-red-200 dark:border-red-800"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onDeleteProject(project);
|
||||
}}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 text-red-600 dark:text-red-400" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
className="w-8 h-8 rounded-lg bg-primary/10 dark:bg-primary/20 flex items-center justify-center active:scale-90 border border-primary/20 dark:border-primary/30"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onStartEditingProject(project);
|
||||
}}
|
||||
>
|
||||
<Edit3 className="w-4 h-4 text-primary" />
|
||||
</button>
|
||||
|
||||
<div className="w-6 h-6 rounded-md bg-muted/30 flex items-center justify-center">
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="w-3 h-3 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="w-3 h-3 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
'hidden md:flex w-full justify-between p-2 h-auto font-normal hover:bg-accent/50',
|
||||
isSelected && 'bg-accent text-accent-foreground',
|
||||
isStarred &&
|
||||
!isSelected &&
|
||||
'bg-yellow-50/50 dark:bg-yellow-900/10 hover:bg-yellow-100/50 dark:hover:bg-yellow-900/20',
|
||||
)}
|
||||
onClick={selectAndToggleProject}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0 flex-1">
|
||||
{isExpanded ? (
|
||||
<FolderOpen className="w-4 h-4 text-primary flex-shrink-0" />
|
||||
) : (
|
||||
<Folder className="w-4 h-4 text-muted-foreground flex-shrink-0" />
|
||||
)}
|
||||
<div className="min-w-0 flex-1 text-left">
|
||||
{isEditing ? (
|
||||
<div className="space-y-1">
|
||||
<input
|
||||
type="text"
|
||||
value={editingName}
|
||||
onChange={(event) => onEditingNameChange(event.target.value)}
|
||||
className="w-full px-2 py-1 text-sm border border-border rounded bg-background text-foreground focus:ring-2 focus:ring-primary/20"
|
||||
placeholder={t('projects.projectNamePlaceholder')}
|
||||
autoFocus
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
saveProjectName();
|
||||
}
|
||||
if (event.key === 'Escape') {
|
||||
onCancelEditingProject();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="text-xs text-muted-foreground truncate" title={project.fullPath}>
|
||||
{project.fullPath}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div className="text-sm font-semibold truncate text-foreground" title={project.displayName}>
|
||||
{project.displayName}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{sessionCountDisplay}
|
||||
{project.fullPath !== project.displayName && (
|
||||
<span className="ml-1 opacity-60" title={project.fullPath}>
|
||||
{' - '}
|
||||
{project.fullPath.length > 25 ? `...${project.fullPath.slice(-22)}` : project.fullPath}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 flex-shrink-0">
|
||||
{isEditing ? (
|
||||
<>
|
||||
<div
|
||||
className="w-6 h-6 text-green-600 hover:text-green-700 hover:bg-green-50 dark:hover:bg-green-900/20 flex items-center justify-center rounded cursor-pointer transition-colors"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
saveProjectName();
|
||||
}}
|
||||
>
|
||||
<Check className="w-3 h-3" />
|
||||
</div>
|
||||
<div
|
||||
className="w-6 h-6 text-gray-500 hover:text-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 flex items-center justify-center rounded cursor-pointer transition-colors"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onCancelEditingProject();
|
||||
}}
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div
|
||||
className={cn(
|
||||
'w-6 h-6 opacity-0 group-hover:opacity-100 transition-all duration-200 flex items-center justify-center rounded cursor-pointer touch:opacity-100',
|
||||
isStarred ? 'hover:bg-yellow-50 dark:hover:bg-yellow-900/20 opacity-100' : 'hover:bg-accent',
|
||||
)}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
toggleStarProject();
|
||||
}}
|
||||
title={isStarred ? t('tooltips.removeFromFavorites') : t('tooltips.addToFavorites')}
|
||||
>
|
||||
<Star
|
||||
className={cn(
|
||||
'w-3 h-3 transition-colors',
|
||||
isStarred
|
||||
? 'text-yellow-600 dark:text-yellow-400 fill-current'
|
||||
: 'text-muted-foreground',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className="w-6 h-6 opacity-0 group-hover:opacity-100 transition-all duration-200 hover:bg-accent flex items-center justify-center rounded cursor-pointer touch:opacity-100"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onStartEditingProject(project);
|
||||
}}
|
||||
title={t('tooltips.renameProject')}
|
||||
>
|
||||
<Edit3 className="w-3 h-3" />
|
||||
</div>
|
||||
<div
|
||||
className="w-6 h-6 opacity-0 group-hover:opacity-100 transition-all duration-200 hover:bg-red-50 dark:hover:bg-red-900/20 flex items-center justify-center rounded cursor-pointer touch:opacity-100"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onDeleteProject(project);
|
||||
}}
|
||||
title={t('tooltips.deleteProject')}
|
||||
>
|
||||
<Trash2 className="w-3 h-3 text-red-600 dark:text-red-400" />
|
||||
</div>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="w-4 h-4 text-muted-foreground group-hover:text-foreground transition-colors" />
|
||||
) : (
|
||||
<ChevronRight className="w-4 h-4 text-muted-foreground group-hover:text-foreground transition-colors" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<SidebarProjectSessions
|
||||
project={project}
|
||||
isExpanded={isExpanded}
|
||||
sessions={sessions}
|
||||
selectedSession={selectedSession}
|
||||
initialSessionsLoaded={initialSessionsLoaded}
|
||||
isLoadingSessions={isLoadingSessions}
|
||||
currentTime={currentTime}
|
||||
editingSession={editingSession}
|
||||
editingSessionName={editingSessionName}
|
||||
onEditingSessionNameChange={onEditingSessionNameChange}
|
||||
onStartEditingSession={onStartEditingSession}
|
||||
onCancelEditingSession={onCancelEditingSession}
|
||||
onSaveEditingSession={onSaveEditingSession}
|
||||
onProjectSelect={onProjectSelect}
|
||||
onSessionSelect={onSessionSelect}
|
||||
onDeleteSession={onDeleteSession}
|
||||
onLoadMoreSessions={onLoadMoreSessions}
|
||||
onNewSession={onNewSession}
|
||||
touchHandlerFactory={touchHandlerFactory}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
153
src/components/sidebar/view/subcomponents/SidebarProjectList.tsx
Normal file
153
src/components/sidebar/view/subcomponents/SidebarProjectList.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { LoadingProgress, Project, ProjectSession, SessionProvider } from '../../../../types/app';
|
||||
import type {
|
||||
LoadingSessionsByProject,
|
||||
MCPServerStatus,
|
||||
SessionWithProvider,
|
||||
TouchHandlerFactory,
|
||||
} from '../../types/types';
|
||||
import SidebarProjectItem from './SidebarProjectItem';
|
||||
import SidebarProjectsState from './SidebarProjectsState';
|
||||
|
||||
export type SidebarProjectListProps = {
|
||||
projects: Project[];
|
||||
filteredProjects: Project[];
|
||||
selectedProject: Project | null;
|
||||
selectedSession: ProjectSession | null;
|
||||
isLoading: boolean;
|
||||
loadingProgress: LoadingProgress | null;
|
||||
expandedProjects: Set<string>;
|
||||
editingProject: string | null;
|
||||
editingName: string;
|
||||
loadingSessions: LoadingSessionsByProject;
|
||||
initialSessionsLoaded: Set<string>;
|
||||
currentTime: Date;
|
||||
editingSession: string | null;
|
||||
editingSessionName: string;
|
||||
deletingProjects: Set<string>;
|
||||
tasksEnabled: boolean;
|
||||
mcpServerStatus: MCPServerStatus;
|
||||
getProjectSessions: (project: Project) => SessionWithProvider[];
|
||||
isProjectStarred: (projectName: string) => boolean;
|
||||
onEditingNameChange: (value: string) => void;
|
||||
onToggleProject: (projectName: string) => void;
|
||||
onProjectSelect: (project: Project) => void;
|
||||
onToggleStarProject: (projectName: string) => void;
|
||||
onStartEditingProject: (project: Project) => void;
|
||||
onCancelEditingProject: () => void;
|
||||
onSaveProjectName: (projectName: string) => void;
|
||||
onDeleteProject: (project: Project) => void;
|
||||
onSessionSelect: (session: SessionWithProvider, projectName: string) => void;
|
||||
onDeleteSession: (
|
||||
projectName: string,
|
||||
sessionId: string,
|
||||
sessionTitle: string,
|
||||
provider: SessionProvider,
|
||||
) => void;
|
||||
onLoadMoreSessions: (project: Project) => void;
|
||||
onNewSession: (project: Project) => void;
|
||||
onEditingSessionNameChange: (value: string) => void;
|
||||
onStartEditingSession: (sessionId: string, initialName: string) => void;
|
||||
onCancelEditingSession: () => void;
|
||||
onSaveEditingSession: (projectName: string, sessionId: string, summary: string) => void;
|
||||
touchHandlerFactory: TouchHandlerFactory;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
export default function SidebarProjectList({
|
||||
projects,
|
||||
filteredProjects,
|
||||
selectedProject,
|
||||
selectedSession,
|
||||
isLoading,
|
||||
loadingProgress,
|
||||
expandedProjects,
|
||||
editingProject,
|
||||
editingName,
|
||||
loadingSessions,
|
||||
initialSessionsLoaded,
|
||||
currentTime,
|
||||
editingSession,
|
||||
editingSessionName,
|
||||
deletingProjects,
|
||||
tasksEnabled,
|
||||
mcpServerStatus,
|
||||
getProjectSessions,
|
||||
isProjectStarred,
|
||||
onEditingNameChange,
|
||||
onToggleProject,
|
||||
onProjectSelect,
|
||||
onToggleStarProject,
|
||||
onStartEditingProject,
|
||||
onCancelEditingProject,
|
||||
onSaveProjectName,
|
||||
onDeleteProject,
|
||||
onSessionSelect,
|
||||
onDeleteSession,
|
||||
onLoadMoreSessions,
|
||||
onNewSession,
|
||||
onEditingSessionNameChange,
|
||||
onStartEditingSession,
|
||||
onCancelEditingSession,
|
||||
onSaveEditingSession,
|
||||
touchHandlerFactory,
|
||||
t,
|
||||
}: SidebarProjectListProps) {
|
||||
const state = (
|
||||
<SidebarProjectsState
|
||||
isLoading={isLoading}
|
||||
loadingProgress={loadingProgress}
|
||||
projectsCount={projects.length}
|
||||
filteredProjectsCount={filteredProjects.length}
|
||||
t={t}
|
||||
/>
|
||||
);
|
||||
|
||||
const showProjects = !isLoading && projects.length > 0 && filteredProjects.length > 0;
|
||||
|
||||
return (
|
||||
<div className="md:space-y-1 pb-safe-area-inset-bottom">
|
||||
{!showProjects
|
||||
? state
|
||||
: filteredProjects.map((project) => (
|
||||
<SidebarProjectItem
|
||||
key={project.name}
|
||||
project={project}
|
||||
selectedProject={selectedProject}
|
||||
selectedSession={selectedSession}
|
||||
isExpanded={expandedProjects.has(project.name)}
|
||||
isDeleting={deletingProjects.has(project.name)}
|
||||
isStarred={isProjectStarred(project.name)}
|
||||
editingProject={editingProject}
|
||||
editingName={editingName}
|
||||
sessions={getProjectSessions(project)}
|
||||
initialSessionsLoaded={initialSessionsLoaded.has(project.name)}
|
||||
isLoadingSessions={Boolean(loadingSessions[project.name])}
|
||||
currentTime={currentTime}
|
||||
editingSession={editingSession}
|
||||
editingSessionName={editingSessionName}
|
||||
tasksEnabled={tasksEnabled}
|
||||
mcpServerStatus={mcpServerStatus}
|
||||
onEditingNameChange={onEditingNameChange}
|
||||
onToggleProject={onToggleProject}
|
||||
onProjectSelect={onProjectSelect}
|
||||
onToggleStarProject={onToggleStarProject}
|
||||
onStartEditingProject={onStartEditingProject}
|
||||
onCancelEditingProject={onCancelEditingProject}
|
||||
onSaveProjectName={onSaveProjectName}
|
||||
onDeleteProject={onDeleteProject}
|
||||
onSessionSelect={onSessionSelect}
|
||||
onDeleteSession={onDeleteSession}
|
||||
onLoadMoreSessions={onLoadMoreSessions}
|
||||
onNewSession={onNewSession}
|
||||
onEditingSessionNameChange={onEditingSessionNameChange}
|
||||
onStartEditingSession={onStartEditingSession}
|
||||
onCancelEditingSession={onCancelEditingSession}
|
||||
onSaveEditingSession={onSaveEditingSession}
|
||||
touchHandlerFactory={touchHandlerFactory}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { ChevronDown, Plus } from 'lucide-react';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { Button } from '../../../ui/button';
|
||||
import type { Project, ProjectSession, SessionProvider } from '../../../../types/app';
|
||||
import type { SessionWithProvider, TouchHandlerFactory } from '../../types/types';
|
||||
import SidebarSessionItem from './SidebarSessionItem';
|
||||
|
||||
type SidebarProjectSessionsProps = {
|
||||
project: Project;
|
||||
isExpanded: boolean;
|
||||
sessions: SessionWithProvider[];
|
||||
selectedSession: ProjectSession | null;
|
||||
initialSessionsLoaded: boolean;
|
||||
isLoadingSessions: boolean;
|
||||
currentTime: Date;
|
||||
editingSession: string | null;
|
||||
editingSessionName: string;
|
||||
onEditingSessionNameChange: (value: string) => void;
|
||||
onStartEditingSession: (sessionId: string, initialName: string) => void;
|
||||
onCancelEditingSession: () => void;
|
||||
onSaveEditingSession: (projectName: string, sessionId: string, summary: string) => void;
|
||||
onProjectSelect: (project: Project) => void;
|
||||
onSessionSelect: (session: SessionWithProvider, projectName: string) => void;
|
||||
onDeleteSession: (
|
||||
projectName: string,
|
||||
sessionId: string,
|
||||
sessionTitle: string,
|
||||
provider: SessionProvider,
|
||||
) => void;
|
||||
onLoadMoreSessions: (project: Project) => void;
|
||||
onNewSession: (project: Project) => void;
|
||||
touchHandlerFactory: TouchHandlerFactory;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
function SessionListSkeleton() {
|
||||
return (
|
||||
<>
|
||||
{Array.from({ length: 3 }).map((_, index) => (
|
||||
<div key={index} className="p-2 rounded-md">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="w-3 h-3 bg-muted rounded-full animate-pulse mt-0.5" />
|
||||
<div className="flex-1 space-y-1">
|
||||
<div className="h-3 bg-muted rounded animate-pulse" style={{ width: `${60 + index * 15}%` }} />
|
||||
<div className="h-2 bg-muted rounded animate-pulse w-1/2" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SidebarProjectSessions({
|
||||
project,
|
||||
isExpanded,
|
||||
sessions,
|
||||
selectedSession,
|
||||
initialSessionsLoaded,
|
||||
isLoadingSessions,
|
||||
currentTime,
|
||||
editingSession,
|
||||
editingSessionName,
|
||||
onEditingSessionNameChange,
|
||||
onStartEditingSession,
|
||||
onCancelEditingSession,
|
||||
onSaveEditingSession,
|
||||
onProjectSelect,
|
||||
onSessionSelect,
|
||||
onDeleteSession,
|
||||
onLoadMoreSessions,
|
||||
onNewSession,
|
||||
touchHandlerFactory,
|
||||
t,
|
||||
}: SidebarProjectSessionsProps) {
|
||||
if (!isExpanded) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasSessions = sessions.length > 0;
|
||||
const hasMoreSessions = project.sessionMeta?.hasMore === true;
|
||||
|
||||
return (
|
||||
<div className="ml-3 space-y-1 border-l border-border pl-3">
|
||||
{!initialSessionsLoaded ? (
|
||||
<SessionListSkeleton />
|
||||
) : !hasSessions && !isLoadingSessions ? (
|
||||
<div className="py-2 px-3 text-left">
|
||||
<p className="text-xs text-muted-foreground">{t('sessions.noSessions')}</p>
|
||||
</div>
|
||||
) : (
|
||||
sessions.map((session) => (
|
||||
<SidebarSessionItem
|
||||
key={session.id}
|
||||
project={project}
|
||||
session={session}
|
||||
selectedSession={selectedSession}
|
||||
currentTime={currentTime}
|
||||
editingSession={editingSession}
|
||||
editingSessionName={editingSessionName}
|
||||
onEditingSessionNameChange={onEditingSessionNameChange}
|
||||
onStartEditingSession={onStartEditingSession}
|
||||
onCancelEditingSession={onCancelEditingSession}
|
||||
onSaveEditingSession={onSaveEditingSession}
|
||||
onProjectSelect={onProjectSelect}
|
||||
onSessionSelect={onSessionSelect}
|
||||
onDeleteSession={onDeleteSession}
|
||||
touchHandlerFactory={touchHandlerFactory}
|
||||
t={t}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
|
||||
{hasSessions && hasMoreSessions && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full justify-center gap-2 mt-2 text-muted-foreground"
|
||||
onClick={() => onLoadMoreSessions(project)}
|
||||
disabled={isLoadingSessions}
|
||||
>
|
||||
{isLoadingSessions ? (
|
||||
<>
|
||||
<div className="w-3 h-3 animate-spin rounded-full border border-muted-foreground border-t-transparent" />
|
||||
{t('sessions.loading')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ChevronDown className="w-3 h-3" />
|
||||
{t('sessions.showMore')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="md:hidden px-3 pb-2">
|
||||
<button
|
||||
className="w-full h-8 bg-primary hover:bg-primary/90 text-primary-foreground rounded-md flex items-center justify-center gap-2 font-medium text-xs active:scale-[0.98] transition-all duration-150"
|
||||
onClick={() => {
|
||||
onProjectSelect(project);
|
||||
onNewSession(project);
|
||||
}}
|
||||
>
|
||||
<Plus className="w-3 h-3" />
|
||||
{t('sessions.newSession')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
className="hidden md:flex w-full justify-start gap-2 mt-1 h-8 text-xs font-medium bg-primary hover:bg-primary/90 text-primary-foreground transition-colors"
|
||||
onClick={() => onNewSession(project)}
|
||||
>
|
||||
<Plus className="w-3 h-3" />
|
||||
{t('sessions.newSession')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Folder, Search } from 'lucide-react';
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { LoadingProgress } from '../../../../types/app';
|
||||
|
||||
type SidebarProjectsStateProps = {
|
||||
isLoading: boolean;
|
||||
loadingProgress: LoadingProgress | null;
|
||||
projectsCount: number;
|
||||
filteredProjectsCount: number;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
export default function SidebarProjectsState({
|
||||
isLoading,
|
||||
loadingProgress,
|
||||
projectsCount,
|
||||
filteredProjectsCount,
|
||||
t,
|
||||
}: SidebarProjectsStateProps) {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="text-center py-12 md:py-8 px-4">
|
||||
<div className="w-12 h-12 bg-muted rounded-lg flex items-center justify-center mx-auto mb-4 md:mb-3">
|
||||
<div className="w-6 h-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
|
||||
</div>
|
||||
<h3 className="text-base font-medium text-foreground mb-2 md:mb-1">{t('projects.loadingProjects')}</h3>
|
||||
{loadingProgress && loadingProgress.total > 0 ? (
|
||||
<div className="space-y-2">
|
||||
<div className="w-full bg-muted rounded-full h-2 overflow-hidden">
|
||||
<div
|
||||
className="bg-primary h-full transition-all duration-300 ease-out"
|
||||
style={{ width: `${(loadingProgress.current / loadingProgress.total) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{loadingProgress.current}/{loadingProgress.total} {t('projects.projects')}
|
||||
</p>
|
||||
{loadingProgress.currentProject && (
|
||||
<p
|
||||
className="text-xs text-muted-foreground/70 truncate max-w-[200px] mx-auto"
|
||||
title={loadingProgress.currentProject}
|
||||
>
|
||||
{loadingProgress.currentProject.split('-').slice(-2).join('/')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">{t('projects.fetchingProjects')}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (projectsCount === 0) {
|
||||
return (
|
||||
<div className="text-center py-12 md:py-8 px-4">
|
||||
<div className="w-12 h-12 bg-muted rounded-lg flex items-center justify-center mx-auto mb-4 md:mb-3">
|
||||
<Folder className="w-6 h-6 text-muted-foreground" />
|
||||
</div>
|
||||
<h3 className="text-base font-medium text-foreground mb-2 md:mb-1">{t('projects.noProjects')}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t('projects.runClaudeCli')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (filteredProjectsCount === 0) {
|
||||
return (
|
||||
<div className="text-center py-12 md:py-8 px-4">
|
||||
<div className="w-12 h-12 bg-muted rounded-lg flex items-center justify-center mx-auto mb-4 md:mb-3">
|
||||
<Search className="w-6 h-6 text-muted-foreground" />
|
||||
</div>
|
||||
<h3 className="text-base font-medium text-foreground mb-2 md:mb-1">{t('projects.noMatchingProjects')}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t('projects.tryDifferentSearch')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
236
src/components/sidebar/view/subcomponents/SidebarSessionItem.tsx
Normal file
236
src/components/sidebar/view/subcomponents/SidebarSessionItem.tsx
Normal file
@@ -0,0 +1,236 @@
|
||||
import { Badge } from '../../../ui/badge';
|
||||
import { Button } from '../../../ui/button';
|
||||
import { Check, Clock, Edit2, Trash2, X } from 'lucide-react';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { cn } from '../../../../lib/utils';
|
||||
import { formatTimeAgo } from '../../../../utils/dateUtils';
|
||||
import type { Project, ProjectSession, SessionProvider } from '../../../../types/app';
|
||||
import type { SessionWithProvider, TouchHandlerFactory } from '../../types/types';
|
||||
import { createSessionViewModel } from '../../utils/utils';
|
||||
import SessionProviderLogo from '../../../SessionProviderLogo';
|
||||
|
||||
type SidebarSessionItemProps = {
|
||||
project: Project;
|
||||
session: SessionWithProvider;
|
||||
selectedSession: ProjectSession | null;
|
||||
currentTime: Date;
|
||||
editingSession: string | null;
|
||||
editingSessionName: string;
|
||||
onEditingSessionNameChange: (value: string) => void;
|
||||
onStartEditingSession: (sessionId: string, initialName: string) => void;
|
||||
onCancelEditingSession: () => void;
|
||||
onSaveEditingSession: (projectName: string, sessionId: string, summary: string) => void;
|
||||
onProjectSelect: (project: Project) => void;
|
||||
onSessionSelect: (session: SessionWithProvider, projectName: string) => void;
|
||||
onDeleteSession: (
|
||||
projectName: string,
|
||||
sessionId: string,
|
||||
sessionTitle: string,
|
||||
provider: SessionProvider,
|
||||
) => void;
|
||||
touchHandlerFactory: TouchHandlerFactory;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
export default function SidebarSessionItem({
|
||||
project,
|
||||
session,
|
||||
selectedSession,
|
||||
currentTime,
|
||||
editingSession,
|
||||
editingSessionName,
|
||||
onEditingSessionNameChange,
|
||||
onStartEditingSession,
|
||||
onCancelEditingSession,
|
||||
onSaveEditingSession,
|
||||
onProjectSelect,
|
||||
onSessionSelect,
|
||||
onDeleteSession,
|
||||
touchHandlerFactory,
|
||||
t,
|
||||
}: SidebarSessionItemProps) {
|
||||
const sessionView = createSessionViewModel(session, currentTime, t);
|
||||
const isSelected = selectedSession?.id === session.id;
|
||||
|
||||
const selectMobileSession = () => {
|
||||
onProjectSelect(project);
|
||||
onSessionSelect(session, project.name);
|
||||
};
|
||||
|
||||
const saveEditedSession = () => {
|
||||
onSaveEditingSession(project.name, session.id, editingSessionName);
|
||||
};
|
||||
|
||||
const requestDeleteSession = () => {
|
||||
onDeleteSession(project.name, session.id, sessionView.sessionName, session.__provider);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="group relative">
|
||||
{sessionView.isActive && (
|
||||
<div className="absolute left-0 top-1/2 transform -translate-y-1/2 -translate-x-1">
|
||||
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="md:hidden">
|
||||
<div
|
||||
className={cn(
|
||||
'p-2 mx-3 my-0.5 rounded-md bg-card border active:scale-[0.98] transition-all duration-150 relative',
|
||||
isSelected ? 'bg-primary/5 border-primary/20' : '',
|
||||
!isSelected && sessionView.isActive
|
||||
? 'border-green-500/30 bg-green-50/5 dark:bg-green-900/5'
|
||||
: 'border-border/30',
|
||||
)}
|
||||
onClick={selectMobileSession}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={cn(
|
||||
'w-5 h-5 rounded-md flex items-center justify-center flex-shrink-0',
|
||||
isSelected ? 'bg-primary/10' : 'bg-muted/50',
|
||||
)}
|
||||
>
|
||||
<SessionProviderLogo provider={session.__provider} className="w-3 h-3" />
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-xs font-medium truncate text-foreground">{sessionView.sessionName}</div>
|
||||
<div className="flex items-center gap-1 mt-0.5">
|
||||
<Clock className="w-2.5 h-2.5 text-muted-foreground" />
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{formatTimeAgo(sessionView.sessionTime, currentTime, t)}
|
||||
</span>
|
||||
{sessionView.messageCount > 0 && (
|
||||
<Badge variant="secondary" className="text-xs px-1 py-0 ml-auto">
|
||||
{sessionView.messageCount}
|
||||
</Badge>
|
||||
)}
|
||||
<span className="ml-1 opacity-70">
|
||||
<SessionProviderLogo provider={session.__provider} className="w-3 h-3" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!sessionView.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={(event) => {
|
||||
event.stopPropagation();
|
||||
requestDeleteSession();
|
||||
}}
|
||||
>
|
||||
<Trash2 className="w-2.5 h-2.5 text-red-600 dark:text-red-400" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="hidden md:block">
|
||||
<Button
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
'w-full justify-start p-2 h-auto font-normal text-left hover:bg-accent/50 transition-colors duration-200',
|
||||
isSelected && 'bg-accent text-accent-foreground',
|
||||
)}
|
||||
onClick={() => onSessionSelect(session, project.name)}
|
||||
>
|
||||
<div className="flex items-start gap-2 min-w-0 w-full">
|
||||
<SessionProviderLogo provider={session.__provider} className="w-3 h-3 mt-0.5 flex-shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-xs font-medium truncate text-foreground">{sessionView.sessionName}</div>
|
||||
<div className="flex items-center gap-1 mt-0.5">
|
||||
<Clock className="w-2.5 h-2.5 text-muted-foreground" />
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{formatTimeAgo(sessionView.sessionTime, currentTime, t)}
|
||||
</span>
|
||||
{sessionView.messageCount > 0 && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="text-xs px-1 py-0 ml-auto group-hover:opacity-0 transition-opacity"
|
||||
>
|
||||
{sessionView.messageCount}
|
||||
</Badge>
|
||||
)}
|
||||
<span className="ml-1 opacity-70 group-hover:opacity-0 transition-opacity">
|
||||
<SessionProviderLogo provider={session.__provider} className="w-3 h-3" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
|
||||
{!sessionView.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 && !sessionView.isCodexSession ? (
|
||||
<>
|
||||
<input
|
||||
type="text"
|
||||
value={editingSessionName}
|
||||
onChange={(event) => onEditingSessionNameChange(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
event.stopPropagation();
|
||||
if (event.key === 'Enter') {
|
||||
saveEditedSession();
|
||||
} else if (event.key === 'Escape') {
|
||||
onCancelEditingSession();
|
||||
}
|
||||
}}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
className="w-32 px-2 py-1 text-xs border border-border rounded bg-background focus:outline-none focus:ring-1 focus:ring-primary"
|
||||
autoFocus
|
||||
/>
|
||||
<button
|
||||
className="w-6 h-6 bg-green-50 hover:bg-green-100 dark:bg-green-900/20 dark:hover:bg-green-900/40 rounded flex items-center justify-center"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
saveEditedSession();
|
||||
}}
|
||||
title={t('tooltips.save')}
|
||||
>
|
||||
<Check className="w-3 h-3 text-green-600 dark:text-green-400" />
|
||||
</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={(event) => {
|
||||
event.stopPropagation();
|
||||
onCancelEditingSession();
|
||||
}}
|
||||
title={t('tooltips.cancel')}
|
||||
>
|
||||
<X className="w-3 h-3 text-gray-600 dark:text-gray-400" />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{!sessionView.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={(event) => {
|
||||
event.stopPropagation();
|
||||
onStartEditingSession(session.id, session.summary || t('projects.newSession'));
|
||||
}}
|
||||
title={t('tooltips.editSessionName')}
|
||||
>
|
||||
<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={(event) => {
|
||||
event.stopPropagation();
|
||||
requestDeleteSession();
|
||||
}}
|
||||
title={t('tooltips.deleteSession')}
|
||||
>
|
||||
<Trash2 className="w-3 h-3 text-red-600 dark:text-red-400" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import * as React from "react"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
|
||||
outline: "text-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({ className, variant, ...props }) {
|
||||
return (
|
||||
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
31
src/components/ui/badge.tsx
Normal file
31
src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
const badgeVariants = cva(
|
||||
'inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80',
|
||||
secondary: 'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
|
||||
destructive:
|
||||
'border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80',
|
||||
outline: 'text-foreground',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
@@ -1,46 +0,0 @@
|
||||
import * as React from "react"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2",
|
||||
sm: "h-8 rounded-md px-3 text-xs",
|
||||
lg: "h-10 rounded-md px-8",
|
||||
icon: "h-9 w-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
const Button = React.forwardRef(({ className, variant, size, ...props }, ref) => {
|
||||
return (
|
||||
<button
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
Button.displayName = "Button"
|
||||
|
||||
export { Button, buttonVariants }
|
||||
50
src/components/ui/button.tsx
Normal file
50
src/components/ui/button.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
const buttonVariants = cva(
|
||||
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-primary text-primary-foreground shadow hover:bg-primary/90',
|
||||
destructive:
|
||||
'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
|
||||
outline:
|
||||
'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
|
||||
secondary: 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
|
||||
ghost: 'hover:bg-accent hover:text-accent-foreground',
|
||||
link: 'text-primary underline-offset-4 hover:underline',
|
||||
},
|
||||
size: {
|
||||
default: 'h-9 px-4 py-2',
|
||||
sm: 'h-8 rounded-md px-3 text-xs',
|
||||
lg: 'h-10 rounded-md px-8',
|
||||
icon: 'h-9 w-9',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
size: 'default',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, ...props }, ref) => {
|
||||
return (
|
||||
<button
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
Button.displayName = 'Button';
|
||||
|
||||
export { Button, buttonVariants };
|
||||
@@ -1,19 +0,0 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
const Input = React.forwardRef(({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
Input.displayName = "Input"
|
||||
|
||||
export { Input }
|
||||
24
src/components/ui/input.tsx
Normal file
24
src/components/ui/input.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
export interface InputProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className,
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
Input.displayName = 'Input';
|
||||
|
||||
export { Input };
|
||||
@@ -1,23 +0,0 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
const ScrollArea = React.forwardRef(({ className, children, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("relative overflow-hidden", className)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
className="h-full w-full rounded-[inherit] overflow-auto"
|
||||
style={{
|
||||
WebkitOverflowScrolling: 'touch',
|
||||
touchAction: 'pan-y'
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
ScrollArea.displayName = "ScrollArea"
|
||||
|
||||
export { ScrollArea }
|
||||
27
src/components/ui/scroll-area.tsx
Normal file
27
src/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
export interface ScrollAreaProps extends React.HTMLAttributes<HTMLDivElement> {}
|
||||
|
||||
const ScrollArea = React.forwardRef<HTMLDivElement, ScrollAreaProps>(
|
||||
({ className, children, ...props }, ref) => (
|
||||
<div
|
||||
className={cn(className, 'relative overflow-hidden')}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
ref={ref}
|
||||
className="h-full w-full rounded-[inherit] overflow-auto"
|
||||
style={{
|
||||
WebkitOverflowScrolling: 'touch',
|
||||
touchAction: 'pan-y',
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
);
|
||||
ScrollArea.displayName = 'ScrollArea';
|
||||
|
||||
export { ScrollArea };
|
||||
@@ -94,12 +94,12 @@ const useWebSocketProviderState = (): WebSocketContextType => {
|
||||
|
||||
const sendMessage = useCallback((message: any) => {
|
||||
const socket = wsRef.current;
|
||||
if (socket && isConnected) {
|
||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify(message));
|
||||
} else {
|
||||
console.warn('WebSocket not connected');
|
||||
}
|
||||
}, [isConnected]);
|
||||
}, []);
|
||||
|
||||
const value: WebSocketContextType = useMemo(() =>
|
||||
({
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user