@myrialabs/clopen 0.3.20 → 0.3.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/engine/adapters/claude/environment.ts +0 -17
- package/backend/engine/adapters/claude/error-handler.ts +0 -4
- package/backend/engine/adapters/claude/models.ts +43 -0
- package/backend/engine/install-recipes.ts +69 -117
- package/backend/engine/version-check.ts +145 -0
- package/backend/files/file-operations.test.ts +75 -0
- package/backend/files/file-operations.ts +10 -56
- package/backend/files/image-processing.test.ts +52 -0
- package/backend/files/image-processing.ts +11 -1
- package/backend/files/path-browsing.ts +141 -139
- package/backend/git/git-parser.ts +11 -0
- package/backend/git/git-service.ts +65 -9
- package/backend/http/files-upload.test.ts +174 -0
- package/backend/http/files-upload.ts +27 -7
- package/backend/http/upload-temp-cleanup.ts +53 -0
- package/backend/index.ts +31 -12
- package/backend/mcp/remote-server.test.ts +150 -0
- package/backend/mcp/remote-server.ts +68 -0
- package/backend/terminal/pty-session-manager.ts +18 -11
- package/backend/ws/chat/stream.ts +17 -6
- package/backend/ws/files/index.ts +5 -0
- package/backend/ws/files/reveal.ts +61 -0
- package/backend/ws/files/search.test.ts +115 -0
- package/backend/ws/files/search.ts +77 -26
- package/backend/ws/files/write.ts +3 -1
- package/backend/ws/git/branch-name.ts +170 -0
- package/backend/ws/git/branch.ts +15 -2
- package/backend/ws/git/commit-message.ts +8 -2
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/system-tools/status.ts +14 -0
- package/backend/ws/user/crud.ts +8 -4
- package/dist/assets/main-Ba19ADkk.js +377 -0
- package/dist/assets/main-CwCZzMVm.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +3 -1
- package/shared/constants/git.ts +5 -0
- package/shared/types/git.ts +13 -0
- package/shared/types/stores/settings.ts +17 -0
- package/dist/assets/main-72Z_L-nD.js +0 -362
- package/dist/assets/main-ClADBkFf.css +0 -1
|
@@ -86,17 +86,7 @@ class PtySessionManager {
|
|
|
86
86
|
});
|
|
87
87
|
|
|
88
88
|
debug.log('terminal', `✅ PTY spawned with PID: ${pty.pid}`);
|
|
89
|
-
|
|
90
|
-
// CRITICAL: Send initial newline to trigger shell prompt display
|
|
91
|
-
// Without this, shell won't show prompt on first connection
|
|
92
|
-
setTimeout(() => {
|
|
93
|
-
try {
|
|
94
|
-
pty.write('\r');
|
|
95
|
-
debug.log('terminal', '📝 Sent initial newline to trigger prompt');
|
|
96
|
-
} catch (error) {
|
|
97
|
-
debug.error('terminal', 'Failed to send initial newline:', error);
|
|
98
|
-
}
|
|
99
|
-
}, 100);
|
|
89
|
+
let receivedInitialOutput = false;
|
|
100
90
|
|
|
101
91
|
// Create session
|
|
102
92
|
const session: PtySession = {
|
|
@@ -117,6 +107,7 @@ class PtySessionManager {
|
|
|
117
107
|
|
|
118
108
|
// Setup PTY event handlers with micro-task batching
|
|
119
109
|
pty.onData((data: string) => {
|
|
110
|
+
receivedInitialOutput = true;
|
|
120
111
|
session.lastActivityAt = new Date();
|
|
121
112
|
|
|
122
113
|
// IMPORTANT: Always persist output to stream manager FIRST
|
|
@@ -158,6 +149,22 @@ class PtySessionManager {
|
|
|
158
149
|
}
|
|
159
150
|
});
|
|
160
151
|
|
|
152
|
+
// Some shells do not paint the first prompt until they receive input.
|
|
153
|
+
// Only send a fallback newline if the PTY stayed completely silent after
|
|
154
|
+
// spawn; otherwise it duplicates the initial prompt on normal shells.
|
|
155
|
+
setTimeout(() => {
|
|
156
|
+
if (receivedInitialOutput) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
try {
|
|
161
|
+
pty.write('\r');
|
|
162
|
+
debug.log('terminal', '📝 Sent fallback newline to trigger prompt');
|
|
163
|
+
} catch (error) {
|
|
164
|
+
debug.error('terminal', 'Failed to send fallback newline:', error);
|
|
165
|
+
}
|
|
166
|
+
}, 350);
|
|
167
|
+
|
|
161
168
|
pty.onExit((event: { exitCode: number; signal?: number | string }) => {
|
|
162
169
|
debug.log('terminal', `🏁 PTY session ${sessionId} exited with code: ${event.exitCode}`);
|
|
163
170
|
// Broadcast to all listeners
|
|
@@ -132,14 +132,25 @@ export const streamHandler = createRouter()
|
|
|
132
132
|
debug.warn('chat', 'Presence broadcast error after chat join-session:', err);
|
|
133
133
|
});
|
|
134
134
|
|
|
135
|
-
// Rehydrate rate-limit banners: replay
|
|
136
|
-
//
|
|
137
|
-
//
|
|
138
|
-
//
|
|
139
|
-
// the user is currently viewing.
|
|
135
|
+
// Rehydrate rate-limit banners: replay only snapshots matching the
|
|
136
|
+
// session's engine+account so banners are scoped to the active context.
|
|
137
|
+
// In-memory state takes priority (most current); DB is the fallback for
|
|
138
|
+
// sessions joined after a server restart.
|
|
140
139
|
try {
|
|
141
140
|
const userId = ws.getUserId(conn);
|
|
142
|
-
const
|
|
141
|
+
const inMemoryModel = chatSessionModelState.get(data.chatSessionId);
|
|
142
|
+
const inMemoryAccount = chatSessionAccountState.get(data.chatSessionId);
|
|
143
|
+
const sessionEngine: string | undefined =
|
|
144
|
+
inMemoryModel?.engine ?? sessionQueries.getById(data.chatSessionId)?.engine;
|
|
145
|
+
const sessionAccountId: number | null =
|
|
146
|
+
inMemoryAccount?.accountId ?? sessionQueries.getById(data.chatSessionId)?.account_id ?? null;
|
|
147
|
+
|
|
148
|
+
const snapshots = streamManager.getAllActiveRateLimits().filter(snap => {
|
|
149
|
+
if (sessionEngine && snap.engine !== sessionEngine) return false;
|
|
150
|
+
if (sessionAccountId != null && snap.accountId !== sessionAccountId) return false;
|
|
151
|
+
return true;
|
|
152
|
+
});
|
|
153
|
+
|
|
143
154
|
for (const snap of snapshots) {
|
|
144
155
|
ws.emit.user(userId, 'chat:rate_limit', {
|
|
145
156
|
chatSessionId: data.chatSessionId,
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* Structure:
|
|
7
7
|
* - read.ts: HTTP endpoints for reading (list-tree, browse, read-file, read-content)
|
|
8
8
|
* - write.ts: HTTP endpoints for writing (write, create, rename, duplicate, upload, delete)
|
|
9
|
+
* - reveal.ts: HTTP endpoint for revealing files in the OS file manager
|
|
9
10
|
* - search.ts: HTTP endpoints for searching (search-files, search-code)
|
|
10
11
|
* - watch.ts: Event handlers for real-time file watching
|
|
11
12
|
*/
|
|
@@ -13,6 +14,7 @@
|
|
|
13
14
|
import { createRouter } from '$shared/utils/ws-server';
|
|
14
15
|
import { readHandler } from './read';
|
|
15
16
|
import { writeHandler } from './write';
|
|
17
|
+
import { revealHandler } from './reveal';
|
|
16
18
|
import { imageEditHandler } from './image-edit';
|
|
17
19
|
import { fileSearchHandler } from './search';
|
|
18
20
|
import { watchHandler } from './watch';
|
|
@@ -25,6 +27,9 @@ export const filesRouter = createRouter()
|
|
|
25
27
|
// Write Operations (HTTP)
|
|
26
28
|
.merge(writeHandler)
|
|
27
29
|
|
|
30
|
+
// Reveal in File Manager (HTTP)
|
|
31
|
+
.merge(revealHandler)
|
|
32
|
+
|
|
28
33
|
// Image Edit Operation (HTTP)
|
|
29
34
|
.merge(imageEditHandler)
|
|
30
35
|
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files Reveal in File Manager Operation
|
|
3
|
+
*
|
|
4
|
+
* Opens the default file manager to reveal a file or directory, using the
|
|
5
|
+
* platform-native command: `open -R` (macOS), `cmd /c start /max explorer /select,`
|
|
6
|
+
* (Windows, via cmd to avoid minimized window), or `xdg-open` on the parent
|
|
7
|
+
* directory (Linux).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { sep } from 'node:path';
|
|
11
|
+
import { t } from 'elysia';
|
|
12
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
13
|
+
import { requireFilePathAccess } from './path-access';
|
|
14
|
+
|
|
15
|
+
export const revealHandler = createRouter()
|
|
16
|
+
|
|
17
|
+
.http('files:reveal-in-file-manager', {
|
|
18
|
+
data: t.Object({
|
|
19
|
+
path: t.String()
|
|
20
|
+
}),
|
|
21
|
+
response: t.Object({
|
|
22
|
+
ok: t.Boolean()
|
|
23
|
+
})
|
|
24
|
+
}, async ({ data, conn }) => {
|
|
25
|
+
const targetPath = await requireFilePathAccess(conn, data.path);
|
|
26
|
+
|
|
27
|
+
if (process.platform === 'darwin') {
|
|
28
|
+
const proc = Bun.spawn(['open', '-R', targetPath], {
|
|
29
|
+
stdout: 'ignore',
|
|
30
|
+
stderr: 'pipe'
|
|
31
|
+
});
|
|
32
|
+
const exitCode = await proc.exited;
|
|
33
|
+
if (exitCode !== 0) {
|
|
34
|
+
const stderr = proc.stderr ? (await new Response(proc.stderr).text()).trim() : '';
|
|
35
|
+
throw new Error(stderr || 'Failed to reveal item in Finder');
|
|
36
|
+
}
|
|
37
|
+
} else if (process.platform === 'win32') {
|
|
38
|
+
const winPath = targetPath.split('/').join(sep);
|
|
39
|
+
Bun.spawn(['cmd', '/c', 'start', '', '/max', 'explorer', '/select,' + winPath], {
|
|
40
|
+
stdout: 'ignore',
|
|
41
|
+
stderr: 'ignore'
|
|
42
|
+
});
|
|
43
|
+
} else if (process.platform === 'linux') {
|
|
44
|
+
const parentDir = targetPath.lastIndexOf('/') > 0
|
|
45
|
+
? targetPath.slice(0, targetPath.lastIndexOf('/'))
|
|
46
|
+
: '/';
|
|
47
|
+
const proc = Bun.spawn(['xdg-open', parentDir], {
|
|
48
|
+
stdout: 'ignore',
|
|
49
|
+
stderr: 'pipe'
|
|
50
|
+
});
|
|
51
|
+
const exitCode = await proc.exited;
|
|
52
|
+
if (exitCode !== 0) {
|
|
53
|
+
const stderr = proc.stderr ? (await new Response(proc.stderr).text()).trim() : '';
|
|
54
|
+
throw new Error(stderr || 'Failed to open file manager');
|
|
55
|
+
}
|
|
56
|
+
} else {
|
|
57
|
+
throw new Error('Reveal in file manager is not supported on this platform');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return { ok: true };
|
|
61
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { describe, it, expect } from 'bun:test';
|
|
2
|
+
import { createSafeRegex } from './search';
|
|
3
|
+
|
|
4
|
+
describe('ReDoS Protection', () => {
|
|
5
|
+
describe('Alternation-based ReDoS patterns', () => {
|
|
6
|
+
it('should reject (a|aa)+ pattern', () => {
|
|
7
|
+
const result = createSafeRegex('(a|aa)+', 'gi');
|
|
8
|
+
expect(result).toBeNull();
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it('should reject (foo|foobar)+ pattern', () => {
|
|
12
|
+
const result = createSafeRegex('(foo|foobar)+', 'gi');
|
|
13
|
+
expect(result).toBeNull();
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('should reject (a|b|c)+ pattern', () => {
|
|
17
|
+
const result = createSafeRegex('(a|b|c)+', 'gi');
|
|
18
|
+
expect(result).toBeNull();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('should reject (hello|helloworld)* pattern', () => {
|
|
22
|
+
const result = createSafeRegex('(hello|helloworld)*', 'gi');
|
|
23
|
+
expect(result).toBeNull();
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe('Nested quantifier patterns', () => {
|
|
28
|
+
it('should reject (a+)+ pattern', () => {
|
|
29
|
+
const result = createSafeRegex('(a+)+', 'gi');
|
|
30
|
+
expect(result).toBeNull();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('should reject (.*)+b pattern', () => {
|
|
34
|
+
const result = createSafeRegex('(.*)+b', 'gi');
|
|
35
|
+
expect(result).toBeNull();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('should reject (a*)* pattern', () => {
|
|
39
|
+
const result = createSafeRegex('(a*)*', 'gi');
|
|
40
|
+
expect(result).toBeNull();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('should reject (x{1,5})+ pattern', () => {
|
|
44
|
+
const result = createSafeRegex('(x{1,5})+', 'gi');
|
|
45
|
+
expect(result).toBeNull();
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('Adjacent character class quantifiers', () => {
|
|
50
|
+
it('should reject [a-z]*[a-z]+ pattern', () => {
|
|
51
|
+
const result = createSafeRegex('[a-z]*[a-z]+', 'gi');
|
|
52
|
+
expect(result).toBeNull();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('should reject [0-9]+[0-9]* pattern', () => {
|
|
56
|
+
const result = createSafeRegex('[0-9]+[0-9]*', 'gi');
|
|
57
|
+
expect(result).toBeNull();
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe('Safe patterns', () => {
|
|
62
|
+
it('should accept simple string pattern', () => {
|
|
63
|
+
const result = createSafeRegex('hello', 'gi');
|
|
64
|
+
expect(result).not.toBeNull();
|
|
65
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('should accept simple alternation without quantifier', () => {
|
|
69
|
+
const result = createSafeRegex('(foo|bar)', 'gi');
|
|
70
|
+
expect(result).not.toBeNull();
|
|
71
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('should accept single quantifier pattern', () => {
|
|
75
|
+
const result = createSafeRegex('a+', 'gi');
|
|
76
|
+
expect(result).not.toBeNull();
|
|
77
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('should accept word boundary pattern', () => {
|
|
81
|
+
const result = createSafeRegex('\\btest\\b', 'gi');
|
|
82
|
+
expect(result).not.toBeNull();
|
|
83
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('should accept character class pattern', () => {
|
|
87
|
+
const result = createSafeRegex('[a-z]+', 'gi');
|
|
88
|
+
expect(result).not.toBeNull();
|
|
89
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
describe('Invalid regex patterns', () => {
|
|
94
|
+
it('should reject invalid regex with unclosed group', () => {
|
|
95
|
+
const result = createSafeRegex('(abc', 'gi');
|
|
96
|
+
expect(result).toBeNull();
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('should reject invalid regex with unclosed bracket', () => {
|
|
100
|
+
const result = createSafeRegex('[a-z', 'gi');
|
|
101
|
+
expect(result).toBeNull();
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
describe('Execution timeout protection', () => {
|
|
106
|
+
it('should complete quickly for safe patterns', () => {
|
|
107
|
+
const startTime = Date.now();
|
|
108
|
+
const result = createSafeRegex('test.*pattern', 'gi');
|
|
109
|
+
const elapsed = Date.now() - startTime;
|
|
110
|
+
|
|
111
|
+
expect(result).not.toBeNull();
|
|
112
|
+
expect(elapsed).toBeLessThan(100);
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
});
|
|
@@ -6,6 +6,54 @@ import { readdir } from 'fs/promises';
|
|
|
6
6
|
import { requireProjectPathAccess } from './path-access';
|
|
7
7
|
import { validateFileSize } from '../../files/file-size-limit';
|
|
8
8
|
|
|
9
|
+
// Heuristic patterns that indicate potential ReDoS risk:
|
|
10
|
+
// 1. Nested quantifiers: (a+)+, (.*)+, (a*)*, (x{1,5})+
|
|
11
|
+
// 2. Alternation (with OR without quantifiers inside) under quantifier: (a|aa)+, (foo|foobar)+, (.*)+
|
|
12
|
+
// 3. Character classes with adjacent quantifiers: [a-z]*[a-z]+
|
|
13
|
+
const REDOS_PATTERNS = [
|
|
14
|
+
/\(.*[+*?{].*\)[+*?{]/, // nested quantifiers like (a+)+, (.*)+, or (x{1,5})+
|
|
15
|
+
/\([^)]*\|[^)]*\)[+*?{]/, // ANY alternation under quantifier: (a|aa)+, (foo|bar)+
|
|
16
|
+
/\[[^\]]+\]\s*[+*?]\s*\[[^\]]+\]\s*[+*?]/, // adjacent char-class quantifiers
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
// Maximum execution time for regex test (milliseconds)
|
|
20
|
+
const REGEX_TIMEOUT_MS = 100;
|
|
21
|
+
|
|
22
|
+
export function createSafeRegex(pattern: string, flags: string): RegExp | null {
|
|
23
|
+
// Check against ReDoS heuristics
|
|
24
|
+
for (const heuristic of REDOS_PATTERNS) {
|
|
25
|
+
if (heuristic.test(pattern)) {
|
|
26
|
+
debug.warn('file', 'ReDoS-risk pattern rejected:', pattern);
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let regex: RegExp;
|
|
32
|
+
try {
|
|
33
|
+
regex = new RegExp(pattern, flags);
|
|
34
|
+
} catch (error) {
|
|
35
|
+
debug.warn('file', 'Invalid regex pattern:', pattern);
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Test execution time with a worst-case string to detect catastrophic backtracking
|
|
40
|
+
const testString = 'a'.repeat(50); // 50-char string of 'a'
|
|
41
|
+
const startTime = Date.now();
|
|
42
|
+
try {
|
|
43
|
+
regex.test(testString);
|
|
44
|
+
const elapsed = Date.now() - startTime;
|
|
45
|
+
if (elapsed > REGEX_TIMEOUT_MS) {
|
|
46
|
+
debug.warn('file', `ReDoS-risk pattern rejected (execution timeout: ${elapsed}ms):`, pattern);
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
} catch (error) {
|
|
50
|
+
debug.warn('file', 'Regex execution error:', pattern, error);
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return regex;
|
|
55
|
+
}
|
|
56
|
+
|
|
9
57
|
// Directories to skip during search
|
|
10
58
|
const SKIP_DIRS = new Set([
|
|
11
59
|
'node_modules', '.git', '.svelte-kit', 'build', 'dist', 'coverage',
|
|
@@ -180,22 +228,23 @@ async function searchCodeContent(
|
|
|
180
228
|
|
|
181
229
|
const results: CodeSearchResult[] = [];
|
|
182
230
|
|
|
183
|
-
// Build the search regex
|
|
184
|
-
let searchPattern: RegExp;
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
231
|
+
// Build the search regex with ReDoS protection
|
|
232
|
+
let searchPattern: RegExp | null;
|
|
233
|
+
if (useRegex) {
|
|
234
|
+
let regexStr = query;
|
|
235
|
+
if (wholeWord) regexStr = `\\b${regexStr}\\b`;
|
|
236
|
+
searchPattern = createSafeRegex(regexStr, caseSensitive ? 'g' : 'gi');
|
|
237
|
+
} else {
|
|
238
|
+
let escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
239
|
+
if (wholeWord) escaped = `\\b${escaped}\\b`;
|
|
240
|
+
try {
|
|
193
241
|
searchPattern = new RegExp(escaped, caseSensitive ? 'g' : 'gi');
|
|
242
|
+
} catch (error) {
|
|
243
|
+
debug.error('file', 'Invalid escaped search pattern:', error);
|
|
244
|
+
return [];
|
|
194
245
|
}
|
|
195
|
-
} catch (error) {
|
|
196
|
-
debug.error('file', 'Invalid search pattern:', error);
|
|
197
|
-
return [];
|
|
198
246
|
}
|
|
247
|
+
if (!searchPattern) return [];
|
|
199
248
|
|
|
200
249
|
// Parse include/exclude filters
|
|
201
250
|
const includes = parseFilterPattern(includePattern);
|
|
@@ -292,22 +341,24 @@ async function replaceInFiles(
|
|
|
292
341
|
|
|
293
342
|
const results: ReplaceResult[] = [];
|
|
294
343
|
|
|
295
|
-
// Build replace regex
|
|
296
|
-
let pattern: RegExp;
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
344
|
+
// Build replace regex with ReDoS protection
|
|
345
|
+
let pattern: RegExp | null;
|
|
346
|
+
const flags = caseSensitive ? 'g' : 'gi';
|
|
347
|
+
if (useRegex) {
|
|
348
|
+
let regexStr = searchQuery;
|
|
349
|
+
if (wholeWord) regexStr = `\\b${regexStr}\\b`;
|
|
350
|
+
pattern = createSafeRegex(regexStr, flags);
|
|
351
|
+
} else {
|
|
352
|
+
let escaped = searchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
353
|
+
if (wholeWord) escaped = `\\b${escaped}\\b`;
|
|
354
|
+
try {
|
|
306
355
|
pattern = new RegExp(escaped, flags);
|
|
356
|
+
} catch (error) {
|
|
357
|
+
debug.error('file', 'Invalid escaped replace pattern:', error);
|
|
358
|
+
return [];
|
|
307
359
|
}
|
|
308
|
-
} catch {
|
|
309
|
-
return [];
|
|
310
360
|
}
|
|
361
|
+
if (!pattern) return [];
|
|
311
362
|
|
|
312
363
|
for (const searchResult of searchResults) {
|
|
313
364
|
const fullPath = join(projectPath, searchResult.relativePath);
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git Branch Name Generator Handler
|
|
3
|
+
*
|
|
4
|
+
* Uses AI engines to generate a branch name from staged diffs before commit.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { t } from 'elysia';
|
|
8
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
9
|
+
import { execGit } from '../../git/git-executor';
|
|
10
|
+
import { initializeEngine } from '../../engine';
|
|
11
|
+
import type { EngineType } from '$shared/types/unified';
|
|
12
|
+
import type { GeneratedBranchName } from '$shared/types/git';
|
|
13
|
+
import {
|
|
14
|
+
DEFAULT_BRANCH_NAME_PREFIX,
|
|
15
|
+
DEFAULT_BRANCH_SEPARATOR,
|
|
16
|
+
MAX_BRANCH_SEPARATOR_LENGTH,
|
|
17
|
+
RELEASE_BRANCH_NAME_PREFIX,
|
|
18
|
+
TEST_BRANCH_NAME_PREFIX
|
|
19
|
+
} from '$shared/constants/git';
|
|
20
|
+
import { debug } from '$shared/utils/logger';
|
|
21
|
+
import { requireProjectAccess } from '../access';
|
|
22
|
+
|
|
23
|
+
const INVALID_BRANCH_SEPARATOR_CHARS = /[\s\0~^:?*[\]\\]+/g;
|
|
24
|
+
const GENERATED_BRANCH_PREFIXES = [
|
|
25
|
+
DEFAULT_BRANCH_NAME_PREFIX,
|
|
26
|
+
RELEASE_BRANCH_NAME_PREFIX,
|
|
27
|
+
TEST_BRANCH_NAME_PREFIX
|
|
28
|
+
];
|
|
29
|
+
const GENERIC_BRANCH_DESCRIPTION_WORDS = new Set([
|
|
30
|
+
'add',
|
|
31
|
+
'added',
|
|
32
|
+
'change',
|
|
33
|
+
'create',
|
|
34
|
+
'fix',
|
|
35
|
+
'implement',
|
|
36
|
+
'improve',
|
|
37
|
+
'make',
|
|
38
|
+
'remove',
|
|
39
|
+
'update'
|
|
40
|
+
]);
|
|
41
|
+
const MAX_BRANCH_DESCRIPTION_WORDS = 3;
|
|
42
|
+
|
|
43
|
+
function sanitizeBranchDescription(input: string, maxWords = MAX_BRANCH_DESCRIPTION_WORDS): string {
|
|
44
|
+
const withoutPrefix = GENERATED_BRANCH_PREFIXES.reduce((value, prefix) => {
|
|
45
|
+
return value.replace(new RegExp(`^${prefix}[/#._-]+`, 'i'), '');
|
|
46
|
+
}, input.trim());
|
|
47
|
+
|
|
48
|
+
const sanitized = withoutPrefix
|
|
49
|
+
.trim()
|
|
50
|
+
.toLowerCase()
|
|
51
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
52
|
+
.replace(/[._]+/g, '-')
|
|
53
|
+
.replace(/-+/g, '-')
|
|
54
|
+
.replace(/^[.-]+|[.-]+$/g, '')
|
|
55
|
+
.slice(0, 72)
|
|
56
|
+
.replace(/[.-]$/g, '');
|
|
57
|
+
const words = sanitized
|
|
58
|
+
.split('-')
|
|
59
|
+
.filter(word => word && !GENERIC_BRANCH_DESCRIPTION_WORDS.has(word))
|
|
60
|
+
.slice(0, maxWords);
|
|
61
|
+
|
|
62
|
+
return words.join('-');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function normalizeBranchSeparator(input: string | undefined): string {
|
|
66
|
+
const cleaned = (input ?? DEFAULT_BRANCH_SEPARATOR)
|
|
67
|
+
.trim()
|
|
68
|
+
.replace(INVALID_BRANCH_SEPARATOR_CHARS, '')
|
|
69
|
+
.slice(0, MAX_BRANCH_SEPARATOR_LENGTH);
|
|
70
|
+
|
|
71
|
+
if (!cleaned || cleaned.includes('..') || cleaned.includes('//') || cleaned.includes('@{')) {
|
|
72
|
+
return DEFAULT_BRANCH_SEPARATOR;
|
|
73
|
+
}
|
|
74
|
+
return cleaned;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function getBranchPrefix(currentBranch: string): string {
|
|
78
|
+
if (currentBranch === 'main' || currentBranch === 'master') return RELEASE_BRANCH_NAME_PREFIX;
|
|
79
|
+
if (currentBranch === 'test' || currentBranch === 'testing') return TEST_BRANCH_NAME_PREFIX;
|
|
80
|
+
return DEFAULT_BRANCH_NAME_PREFIX;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const BRANCH_NAME_SCHEMA = {
|
|
84
|
+
type: 'object',
|
|
85
|
+
additionalProperties: false,
|
|
86
|
+
properties: {
|
|
87
|
+
description: {
|
|
88
|
+
type: 'string',
|
|
89
|
+
description: 'Very short lowercase kebab-case branch topic, 1-3 words, no prefix'
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
required: ['description']
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
function formatCurrentBranchForPrompt(currentBranch: string): string {
|
|
96
|
+
return currentBranch || 'detached or unknown';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function createBranchNameInstructions(currentBranch: string, prefix: string, separator: string): string {
|
|
100
|
+
return `Analyze the following staged git diff and generate a git branch name description.
|
|
101
|
+
|
|
102
|
+
Current branch: ${formatCurrentBranchForPrompt(currentBranch)}
|
|
103
|
+
Resolved prefix: ${prefix}
|
|
104
|
+
|
|
105
|
+
Rules:
|
|
106
|
+
- Use this repository format: ${prefix}${separator}<description>
|
|
107
|
+
- Prefix is fixed by the current branch: main/master -> release, test/testing -> test, anything else -> dev
|
|
108
|
+
- Return only the description field; do not include "${prefix}", "${separator}", or any branch prefix in the description
|
|
109
|
+
- description: lowercase kebab-case, 1-3 words maximum, no trailing punctuation
|
|
110
|
+
- Prefer the shortest changed area/topic over action phrases: login page changes -> login, auth form changes -> auth-form
|
|
111
|
+
- Avoid generic action words like add, fix, update, change, implement, improve, create, remove
|
|
112
|
+
- Do not include ticket IDs unless they appear in the diff`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export const branchNameHandler = createRouter()
|
|
116
|
+
.http('git:generate-branch-name', {
|
|
117
|
+
data: t.Object({
|
|
118
|
+
projectId: t.String(),
|
|
119
|
+
engine: t.String(),
|
|
120
|
+
providerSlug: t.String(),
|
|
121
|
+
modelId: t.String(),
|
|
122
|
+
branchSeparator: t.Optional(t.String()),
|
|
123
|
+
maxWords: t.Optional(t.Number()),
|
|
124
|
+
customPrompt: t.Optional(t.String())
|
|
125
|
+
}),
|
|
126
|
+
response: t.Object({
|
|
127
|
+
branchName: t.String()
|
|
128
|
+
})
|
|
129
|
+
}, async ({ data, conn }) => {
|
|
130
|
+
const project = requireProjectAccess(conn, data.projectId);
|
|
131
|
+
|
|
132
|
+
const diffResult = await execGit(['diff', '--cached'], project.path);
|
|
133
|
+
const rawDiff = diffResult.stdout;
|
|
134
|
+
|
|
135
|
+
if (!rawDiff.trim()) {
|
|
136
|
+
throw new Error('No staged changes to generate a branch name for');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const engineType = data.engine as EngineType;
|
|
140
|
+
const engine = await initializeEngine(engineType);
|
|
141
|
+
|
|
142
|
+
if (!engine.generateStructured) {
|
|
143
|
+
throw new Error(`Engine "${engineType}" does not support structured generation`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const branchResult = await execGit(['branch', '--show-current'], project.path);
|
|
147
|
+
const currentBranch = branchResult.stdout.trim();
|
|
148
|
+
const prefix = getBranchPrefix(currentBranch);
|
|
149
|
+
const separator = normalizeBranchSeparator(data.branchSeparator);
|
|
150
|
+
const instructions = createBranchNameInstructions(currentBranch, prefix, separator);
|
|
151
|
+
const extra = data.customPrompt?.trim();
|
|
152
|
+
const prompt = `${instructions}${extra ? `\n\nAdditional constraints:\n${extra}` : ''}\n\nGit diff:\n${rawDiff}`;
|
|
153
|
+
|
|
154
|
+
debug.log('git', `Generating branch name via ${engineType}/${data.modelId}`);
|
|
155
|
+
|
|
156
|
+
const result = await engine.generateStructured<GeneratedBranchName>({
|
|
157
|
+
prompt,
|
|
158
|
+
providerSlug: data.providerSlug,
|
|
159
|
+
modelId: data.modelId,
|
|
160
|
+
schema: BRANCH_NAME_SCHEMA,
|
|
161
|
+
projectPath: project.path
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
const description = sanitizeBranchDescription(result.description, data.maxWords ?? MAX_BRANCH_DESCRIPTION_WORDS);
|
|
165
|
+
if (!description) {
|
|
166
|
+
throw new Error('Generated branch description was empty');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return { branchName: `${prefix}${separator}${description}` };
|
|
170
|
+
});
|
package/backend/ws/git/branch.ts
CHANGED
|
@@ -59,6 +59,18 @@ export const branchHandler = createRouter()
|
|
|
59
59
|
return { ok: true };
|
|
60
60
|
})
|
|
61
61
|
|
|
62
|
+
.http('git:checkout-commit', {
|
|
63
|
+
data: t.Object({
|
|
64
|
+
projectId: t.String(),
|
|
65
|
+
commitHash: t.String()
|
|
66
|
+
}),
|
|
67
|
+
response: t.Object({ ok: t.Boolean() })
|
|
68
|
+
}, async ({ data, conn }) => {
|
|
69
|
+
const project = requireProjectAccess(conn, data.projectId);
|
|
70
|
+
await gitService.checkoutCommit(project.path, data.commitHash);
|
|
71
|
+
return { ok: true };
|
|
72
|
+
})
|
|
73
|
+
|
|
62
74
|
.http('git:delete-branch', {
|
|
63
75
|
data: t.Object({
|
|
64
76
|
projectId: t.String(),
|
|
@@ -88,7 +100,8 @@ export const branchHandler = createRouter()
|
|
|
88
100
|
.http('git:merge-branch', {
|
|
89
101
|
data: t.Object({
|
|
90
102
|
projectId: t.String(),
|
|
91
|
-
branchName: t.String()
|
|
103
|
+
branchName: t.String(),
|
|
104
|
+
noFastForward: t.Optional(t.Boolean())
|
|
92
105
|
}),
|
|
93
106
|
response: t.Object({
|
|
94
107
|
success: t.Boolean(),
|
|
@@ -96,5 +109,5 @@ export const branchHandler = createRouter()
|
|
|
96
109
|
})
|
|
97
110
|
}, async ({ data, conn }) => {
|
|
98
111
|
const project = requireProjectAccess(conn, data.projectId);
|
|
99
|
-
return await gitService.mergeBranch(project.path, data.branchName);
|
|
112
|
+
return await gitService.mergeBranch(project.path, data.branchName, data.noFastForward ?? false);
|
|
100
113
|
});
|
|
@@ -51,7 +51,8 @@ export const commitMessageHandler = createRouter()
|
|
|
51
51
|
engine: t.String(),
|
|
52
52
|
providerSlug: t.String(),
|
|
53
53
|
modelId: t.String(),
|
|
54
|
-
format: t.Union([t.Literal('single-line'), t.Literal('multi-line')])
|
|
54
|
+
format: t.Union([t.Literal('single-line'), t.Literal('multi-line')]),
|
|
55
|
+
customPrompt: t.Optional(t.String())
|
|
55
56
|
}),
|
|
56
57
|
response: t.Object({
|
|
57
58
|
message: t.String()
|
|
@@ -78,7 +79,7 @@ export const commitMessageHandler = createRouter()
|
|
|
78
79
|
? 'Generate a multi-line conventional commit message with type, scope, subject, AND body fields. The body should explain WHY the change was made.'
|
|
79
80
|
: 'Generate a single-line conventional commit message with type, optional scope, and subject. Leave body empty.';
|
|
80
81
|
|
|
81
|
-
const
|
|
82
|
+
const defaultPrompt = `Analyze the following git diff and generate a conventional commit message.
|
|
82
83
|
|
|
83
84
|
Rules:
|
|
84
85
|
- type: one of feat, fix, refactor, docs, test, chore, style, perf, ci, build
|
|
@@ -89,6 +90,11 @@ Rules:
|
|
|
89
90
|
Git diff:
|
|
90
91
|
${rawDiff}`;
|
|
91
92
|
|
|
93
|
+
const extra = data.customPrompt?.trim();
|
|
94
|
+
const prompt = extra
|
|
95
|
+
? `${defaultPrompt}\n\nAdditional constraints:\n${extra}`
|
|
96
|
+
: defaultPrompt;
|
|
97
|
+
|
|
92
98
|
debug.log('git', `Generating commit message via ${engineType}/${data.modelId}`);
|
|
93
99
|
|
|
94
100
|
const result = await engine.generateStructured<GeneratedCommitMessage>({
|
package/backend/ws/git/index.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { logHandler } from './log';
|
|
|
13
13
|
import { remoteHandler } from './remote';
|
|
14
14
|
import { conflictHandler } from './conflict';
|
|
15
15
|
import { commitMessageHandler } from './commit-message';
|
|
16
|
+
import { branchNameHandler } from './branch-name';
|
|
16
17
|
|
|
17
18
|
export const gitRouter = createRouter()
|
|
18
19
|
.merge(statusHandler)
|
|
@@ -23,4 +24,5 @@ export const gitRouter = createRouter()
|
|
|
23
24
|
.merge(logHandler)
|
|
24
25
|
.merge(remoteHandler)
|
|
25
26
|
.merge(conflictHandler)
|
|
26
|
-
.merge(commitMessageHandler)
|
|
27
|
+
.merge(commitMessageHandler)
|
|
28
|
+
.merge(branchNameHandler);
|