@mrpatronz/nexusflow 0.2.7 → 0.2.8

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.
Files changed (99) hide show
  1. package/.github/workflows/release.yml +7 -0
  2. package/dist/commands/create.d.ts.map +1 -1
  3. package/dist/commands/create.js +6 -1
  4. package/dist/commands/create.js.map +1 -1
  5. package/dist/commands/doctor.d.ts.map +1 -1
  6. package/dist/commands/doctor.js +58 -0
  7. package/dist/commands/doctor.js.map +1 -1
  8. package/dist/commands/init.d.ts.map +1 -1
  9. package/dist/commands/init.js +73 -1
  10. package/dist/commands/init.js.map +1 -1
  11. package/dist/core/config.d.ts.map +1 -1
  12. package/dist/core/config.js +11 -1
  13. package/dist/core/config.js.map +1 -1
  14. package/dist/core/config.test.d.ts +2 -0
  15. package/dist/core/config.test.d.ts.map +1 -0
  16. package/dist/core/config.test.js +75 -0
  17. package/dist/core/config.test.js.map +1 -0
  18. package/dist/core/scanner.test.d.ts +2 -0
  19. package/dist/core/scanner.test.d.ts.map +1 -0
  20. package/dist/core/scanner.test.js +53 -0
  21. package/dist/core/scanner.test.js.map +1 -0
  22. package/dist/generators/base.d.ts.map +1 -1
  23. package/dist/generators/base.js +8 -2
  24. package/dist/generators/base.js.map +1 -1
  25. package/dist/generators/skills-generator.js +1 -1
  26. package/dist/generators/skills-generator.js.map +1 -1
  27. package/dist/gui/assets/index-Ca2VRMrQ.js +22 -0
  28. package/dist/gui/assets/index-fj0RJiOb.css +2 -0
  29. package/dist/gui/index.html +2 -2
  30. package/dist/mcp/server.d.ts.map +1 -1
  31. package/dist/mcp/server.js +132 -93
  32. package/dist/mcp/server.js.map +1 -1
  33. package/dist/server.d.ts.map +1 -1
  34. package/dist/server.js +132 -11
  35. package/dist/server.js.map +1 -1
  36. package/dist/server.test.d.ts +2 -0
  37. package/dist/server.test.d.ts.map +1 -0
  38. package/dist/server.test.js +318 -0
  39. package/dist/server.test.js.map +1 -0
  40. package/dist/types.d.ts +12 -0
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/utils/detect-ai.test.d.ts +2 -0
  43. package/dist/utils/detect-ai.test.d.ts.map +1 -0
  44. package/dist/utils/detect-ai.test.js +37 -0
  45. package/dist/utils/detect-ai.test.js.map +1 -0
  46. package/dist/utils/detect-editors.test.d.ts +2 -0
  47. package/dist/utils/detect-editors.test.d.ts.map +1 -0
  48. package/dist/utils/detect-editors.test.js +39 -0
  49. package/dist/utils/detect-editors.test.js.map +1 -0
  50. package/dist/utils/git.test.d.ts +2 -0
  51. package/dist/utils/git.test.d.ts.map +1 -0
  52. package/dist/utils/git.test.js +55 -0
  53. package/dist/utils/git.test.js.map +1 -0
  54. package/dist/utils/local-ai.d.ts +27 -0
  55. package/dist/utils/local-ai.d.ts.map +1 -0
  56. package/dist/utils/local-ai.js +96 -0
  57. package/dist/utils/local-ai.js.map +1 -0
  58. package/dist/utils/local-ai.test.d.ts +2 -0
  59. package/dist/utils/local-ai.test.d.ts.map +1 -0
  60. package/dist/utils/local-ai.test.js +108 -0
  61. package/dist/utils/local-ai.test.js.map +1 -0
  62. package/dist/utils/system-scanner.d.ts +16 -0
  63. package/dist/utils/system-scanner.d.ts.map +1 -0
  64. package/dist/utils/system-scanner.js +85 -0
  65. package/dist/utils/system-scanner.js.map +1 -0
  66. package/dist/utils/system-scanner.test.d.ts +2 -0
  67. package/dist/utils/system-scanner.test.d.ts.map +1 -0
  68. package/dist/utils/system-scanner.test.js +73 -0
  69. package/dist/utils/system-scanner.test.js.map +1 -0
  70. package/gui/e2e/wizard.spec.ts +327 -0
  71. package/gui/package-lock.json +64 -0
  72. package/gui/package.json +4 -1
  73. package/gui/playwright.config.ts +41 -0
  74. package/gui/src/App.tsx +376 -786
  75. package/gui/src/index.css +16 -0
  76. package/package.json +3 -1
  77. package/scripts/simulate-workspaces.ts +55 -0
  78. package/src/commands/create.ts +7 -1
  79. package/src/commands/doctor.ts +56 -0
  80. package/src/commands/init.ts +77 -1
  81. package/src/core/config.test.ts +96 -0
  82. package/src/core/config.ts +11 -1
  83. package/src/core/scanner.test.ts +61 -0
  84. package/src/generators/base.ts +13 -2
  85. package/src/generators/skills-generator.ts +1 -1
  86. package/src/mcp/server.ts +144 -95
  87. package/src/server.test.ts +367 -0
  88. package/src/server.ts +139 -10
  89. package/src/types.ts +16 -0
  90. package/src/utils/detect-ai.test.ts +44 -0
  91. package/src/utils/detect-editors.test.ts +47 -0
  92. package/src/utils/git.test.ts +74 -0
  93. package/src/utils/local-ai.test.ts +130 -0
  94. package/src/utils/local-ai.ts +111 -0
  95. package/src/utils/system-scanner.test.ts +89 -0
  96. package/src/utils/system-scanner.ts +96 -0
  97. package/vitest.config.ts +2 -1
  98. package/dist/gui/assets/index-BgEo5w2Q.js +0 -22
  99. package/dist/gui/assets/index-D-VigurY.css +0 -2
package/src/server.ts CHANGED
@@ -19,9 +19,11 @@ import { createWorkspace, listWorkspaces, loadFeatureConfig, deleteWorkspace, ad
19
19
  import { analyzeAllRepos } from './analyzers/index.js';
20
20
  import { generateContextFiles } from './generators/index.js';
21
21
  import { packWorkspace } from './core/packer.js';
22
+ import { isOllamaModelAvailable, getOpenAiCompatibleUrl, callLocalLlm } from './utils/local-ai.js';
22
23
  import { detectAIAssistants } from './utils/detect-ai.js';
23
24
  import { detectEditors } from './utils/detect-editors.js';
24
25
  import { findSessions, getSessionTranscript } from './utils/session-finder.js';
26
+ import { scanSystemSpecs } from './utils/system-scanner.js';
25
27
  import { getWorkspaceRepos, rebaseRepo, commitAndPush, getRepoStatus } from './utils/multi-git.js';
26
28
  import {
27
29
  detectAllServices,
@@ -43,6 +45,9 @@ const guiPath = path.join(__dirname, 'gui');
43
45
 
44
46
  export const app = new Hono();
45
47
 
48
+ // Allowed editor binaries/scripts to prevent command injection
49
+ const ALLOWED_EDITORS = new Set(['code', 'code-insiders', 'cursor', 'agy', 'idea', 'charm', 'webstorm', 'subl', 'nano', 'vim', 'nvim', 'emacs']);
50
+
46
51
  // Enable CORS for frontend dev server
47
52
  app.use('/api/*', cors());
48
53
 
@@ -66,10 +71,32 @@ app.get('/api/config', async (c) => {
66
71
  }
67
72
  });
68
73
 
74
+ function isSafeLocalEndpoint(urlStr: string): boolean {
75
+ try {
76
+ const url = new URL(urlStr);
77
+ const hostname = url.hostname.toLowerCase();
78
+ if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]') {
79
+ return true;
80
+ }
81
+ const ipv4Pattern = /^(?:10|127|192\.168|172\.(?:1[6-9]|2[0-9]|3[01]))\.\d+\.\d+\.\d+$/;
82
+ if (ipv4Pattern.test(hostname)) {
83
+ return true;
84
+ }
85
+ return false;
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
90
+
69
91
  // 2. Save configuration
70
92
  app.post('/api/config', async (c) => {
71
93
  try {
72
94
  const newConfig = await c.req.json();
95
+ if (newConfig?.localLlm?.enabled && newConfig.localLlm.endpoint) {
96
+ if (!isSafeLocalEndpoint(newConfig.localLlm.endpoint)) {
97
+ return c.json({ error: 'Local AI endpoint must be localhost, 127.0.0.1, or a private LAN IP.' }, 400);
98
+ }
99
+ }
73
100
  await saveConfig(newConfig);
74
101
  return c.json({ success: true, config: newConfig });
75
102
  } catch (error) {
@@ -124,6 +151,66 @@ app.get('/api/editor-detect', async (c) => {
124
151
  }
125
152
  });
126
153
 
154
+ // 6.5. Local LLM test & recommendation
155
+ app.post('/api/local-llm/test', async (c) => {
156
+ try {
157
+ const { provider, endpoint, model, shoot } = await c.req.json();
158
+ if (!endpoint || !isSafeLocalEndpoint(endpoint)) {
159
+ return c.json({ success: false, error: 'Local AI endpoint must be localhost, 127.0.0.1, or a private LAN IP.' }, 400);
160
+ }
161
+ const cleanEndpoint = endpoint.replace(/\/$/, '');
162
+
163
+ if (shoot) {
164
+ const responseText = await callLocalLlm(
165
+ { enabled: true, provider, endpoint, model },
166
+ [{ role: 'user', content: 'Respond with the exact word "OK" and nothing else.' }]
167
+ );
168
+ const cleanResponse = responseText.trim();
169
+ return c.json({
170
+ success: true,
171
+ modelReady: true,
172
+ message: `Inference test succeeded! Response from model: "${cleanResponse}"`
173
+ });
174
+ }
175
+
176
+ if (provider === 'ollama') {
177
+ const res = await fetch(`${cleanEndpoint}/api/tags`);
178
+ if (!res.ok) throw new Error(`Ollama responded with status ${res.status}`);
179
+ const data: any = await res.json();
180
+ const models = data?.models || [];
181
+ const isModelLoaded = isOllamaModelAvailable(models, model);
182
+ return c.json({
183
+ success: true,
184
+ modelReady: isModelLoaded,
185
+ message: isModelLoaded ? 'Connected successfully! Model is ready.' : `Connected successfully, but model "${model}" is not pulled. Run "ollama pull ${model}" to install it.`
186
+ });
187
+ } else {
188
+ const testUrl = getOpenAiCompatibleUrl(cleanEndpoint, '/v1/models');
189
+ const res = await fetch(testUrl);
190
+ if (!res.ok) throw new Error(`OpenAI-compatible server responded with status ${res.status}`);
191
+ return c.json({ success: true, modelReady: true, message: 'Connected successfully to OpenAI-compatible server!' });
192
+ }
193
+ } catch (error) {
194
+ const msg = error instanceof Error ? error.message : String(error);
195
+ return c.json({ success: false, error: msg }, 400);
196
+ }
197
+ });
198
+
199
+ app.get('/api/local-llm/recommend', async (c) => {
200
+ try {
201
+ const specs = await scanSystemSpecs();
202
+ return c.json(specs);
203
+ } catch (error) {
204
+ return c.json({
205
+ totalRamGb: 8,
206
+ gpuName: 'Unknown/Integrated',
207
+ hasHardwareAcceleration: false,
208
+ recommendedModel: 'qwen2.5-coder:1.5b',
209
+ });
210
+ }
211
+ });
212
+
213
+
127
214
  interface JobStep {
128
215
  id: string;
129
216
  name: string;
@@ -203,11 +290,13 @@ async function runCreationJob(jobId: string, body: any, config: any) {
203
290
  id: body.branchName,
204
291
  branchName: body.branchName,
205
292
  description: body.description,
206
- repos: body.repos.map((r: any) => r.path),
293
+ repos: body.repos.map((r: any) => path.join(workspacePath, r.name)),
294
+ originalRepos: body.repos.map((r: any) => r.path),
207
295
  assistants: body.assistants,
208
296
  workspacePath,
209
297
  createdAt: new Date().toISOString(),
210
298
  resumption: body.resumption,
299
+ localLlmEnabled: body.localLlmEnabled,
211
300
  };
212
301
  if (job) {
213
302
  job.feature = feature;
@@ -233,14 +322,17 @@ async function runCreationJob(jobId: string, body: any, config: any) {
233
322
  feature,
234
323
  repos: workspaceRepos,
235
324
  analysis,
325
+ localLlm: config.localLlm,
236
326
  };
237
327
  await generateContextFiles(ctx, body.assistants, workspacePath);
238
328
  updateJobStep(jobId, 'context', 'completed', 'AI context files generated.');
239
329
 
240
330
  // Step 4: Pack codebase context
241
- updateJobStep(jobId, 'pack', 'running', 'Packing codebase context with Repomix...');
242
- const packResult = await packWorkspace(workspacePath);
243
- updateJobStep(jobId, 'pack', 'completed', `Packed codebase context (${packResult.totalFiles} files, ${(packResult.fileSize / 1024).toFixed(2)} KB).`);
331
+ if (config.packContextXml) {
332
+ updateJobStep(jobId, 'pack', 'running', 'Packing codebase context with Repomix...');
333
+ const packResult = await packWorkspace(workspacePath);
334
+ updateJobStep(jobId, 'pack', 'completed', `Packed codebase context (${packResult.totalFiles} files, ${(packResult.fileSize / 1024).toFixed(2)} KB).`);
335
+ }
244
336
 
245
337
  } catch (error) {
246
338
  const msg = error instanceof Error ? error.message : String(error);
@@ -261,6 +353,7 @@ app.post('/api/workspace', async (c) => {
261
353
  description: string;
262
354
  repos: RepoInfo[];
263
355
  assistants: any[];
356
+ localLlmEnabled?: boolean;
264
357
  resumption?: {
265
358
  testCommand?: string;
266
359
  mockCommand?: string;
@@ -282,8 +375,10 @@ app.post('/api/workspace', async (c) => {
282
375
  { id: 'worktrees', name: 'Create Git Worktrees', status: 'pending', message: 'Waiting...' },
283
376
  { id: 'analysis', name: 'Analyze Repositories', status: 'pending', message: 'Waiting...' },
284
377
  { id: 'context', name: 'Generate AI Context Files', status: 'pending', message: 'Waiting...' },
285
- { id: 'pack', name: 'Pack Codebase Context', status: 'pending', message: 'Waiting...' },
286
378
  ];
379
+ if (config.packContextXml) {
380
+ steps.push({ id: 'pack', name: 'Pack Codebase Context', status: 'pending', message: 'Waiting...' });
381
+ }
287
382
 
288
383
  const job: CreationJob = {
289
384
  id: jobId,
@@ -396,8 +491,33 @@ app.post('/api/open-editor', async (c) => {
396
491
  command: string;
397
492
  };
398
493
 
494
+ if (!ALLOWED_EDITORS.has(command)) {
495
+ return c.json({ error: 'Forbidden editor command' }, 400);
496
+ }
497
+
498
+ // Validate path exists and is a directory
499
+ try {
500
+ const stats = await fs.stat(workspacePath);
501
+ if (!stats.isDirectory()) {
502
+ return c.json({ error: 'Workspace path is not a directory' }, 400);
503
+ }
504
+ } catch {
505
+ return c.json({ error: 'Workspace path does not exist' }, 400);
506
+ }
507
+
399
508
  // Spawn editor process
400
- execa(command, [workspacePath], { detached: true, stdio: 'ignore' }).unref();
509
+ const isWin = process.platform === 'win32';
510
+ const child = execa(command, [workspacePath], {
511
+ detached: true,
512
+ stdio: 'ignore',
513
+ shell: isWin,
514
+ cleanup: false,
515
+ });
516
+ child.unref();
517
+ child.catch((err) => {
518
+ console.error(`Failed to launch editor ${command} for path ${workspacePath}:`, err);
519
+ });
520
+
401
521
  return c.json({ success: true });
402
522
  } catch (error) {
403
523
  const msg = error instanceof Error ? error.message : String(error);
@@ -758,11 +878,20 @@ app.post('/api/workspace/:id/resume', async (c) => {
758
878
 
759
879
  // Open in editor if command is provided
760
880
  if (body.command) {
761
- try {
762
- execa(body.command, [workspacePath], { detached: true, stdio: 'ignore' }).unref();
763
- } catch (e) {
764
- console.error('Failed to launch editor:', e);
881
+ if (!ALLOWED_EDITORS.has(body.command)) {
882
+ return c.json({ error: 'Forbidden editor command' }, 400);
765
883
  }
884
+ const isWin = process.platform === 'win32';
885
+ const child = execa(body.command, [workspacePath], {
886
+ detached: true,
887
+ stdio: 'ignore',
888
+ shell: isWin,
889
+ cleanup: false,
890
+ });
891
+ child.unref();
892
+ child.catch((err) => {
893
+ console.error(`Failed to launch editor ${body.command} for path ${workspacePath}:`, err);
894
+ });
766
895
  }
767
896
 
768
897
  return c.json({ success: true, resumeCommand, workspacePath });
package/src/types.ts CHANGED
@@ -6,6 +6,13 @@
6
6
  /** Supported AI assistant identifiers. */
7
7
  export type AIAssistant = 'claude' | 'antigravity' | 'codex' | 'copilot' | 'cursor';
8
8
 
9
+ export interface LocalLlmConfig {
10
+ enabled: boolean;
11
+ provider: 'ollama' | 'openai-compatible';
12
+ endpoint: string;
13
+ model: string;
14
+ }
15
+
9
16
  /** Top-level NexusFlow configuration stored in ~/.nexusflow/config.json. */
10
17
  export interface NexusFlowConfig {
11
18
  /** Semantic version of the NexusFlow config schema. */
@@ -37,6 +44,9 @@ export interface NexusFlowConfig {
37
44
 
38
45
  /** The last checked latest version from NPM. */
39
46
  latestVersion?: string;
47
+
48
+ /** Local LLM settings for delegating simple tasks. */
49
+ localLlm?: LocalLlmConfig;
40
50
  }
41
51
 
42
52
  /** Result of probing for an AI assistant on the system. */
@@ -135,6 +145,9 @@ export interface Feature {
135
145
 
136
146
  /** Resumption configuration. */
137
147
  resumption?: ResumptionConfig;
148
+
149
+ /** Whether the Local LLM Co-processor is active for this workspace. */
150
+ localLlmEnabled?: boolean;
138
151
  }
139
152
 
140
153
  /** Runtime context for an active workspace — now includes analysis data. */
@@ -147,6 +160,9 @@ export interface WorkspaceContext {
147
160
 
148
161
  /** Analysis results for each repo (keyed by repo path). */
149
162
  analysis?: Map<string, ProjectAnalysis>;
163
+
164
+ /** The global local LLM config, to provide model context. */
165
+ localLlm?: LocalLlmConfig;
150
166
  }
151
167
 
152
168
  // ─── Phase 2: Project Analysis Types ──────────────────────────────────────
@@ -0,0 +1,44 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { execa } from 'execa';
3
+ import { detectAIAssistants } from './detect-ai.js';
4
+
5
+ vi.mock('execa');
6
+
7
+ describe('detectAIAssistants', () => {
8
+ beforeEach(() => {
9
+ vi.clearAllMocks();
10
+ });
11
+
12
+ it('should detect claude and antigravity when commands exit with 0', async () => {
13
+ vi.mocked(execa).mockImplementation((command: any, args?: any, options?: any): any => {
14
+ if (command === 'claude' || command === 'agy') {
15
+ return Promise.resolve({ exitCode: 0 } as any);
16
+ }
17
+ return Promise.resolve({ exitCode: 1 } as any);
18
+ });
19
+
20
+ const result = await detectAIAssistants();
21
+
22
+ expect(result).toEqual([
23
+ { name: 'claude', displayName: 'Claude Code', detected: true, command: 'claude' },
24
+ { name: 'antigravity', displayName: 'Antigravity', detected: true, command: 'agy' },
25
+ { name: 'codex', displayName: 'OpenAI Codex', detected: false },
26
+ { name: 'copilot', displayName: 'GitHub Copilot', detected: true },
27
+ { name: 'cursor', displayName: 'Cursor', detected: false },
28
+ ]);
29
+ });
30
+
31
+ it('should handle failures gracefully and set detected to false', async () => {
32
+ vi.mocked(execa).mockRejectedValue(new Error('Spawn error'));
33
+
34
+ const result = await detectAIAssistants();
35
+
36
+ expect(result).toEqual([
37
+ { name: 'claude', displayName: 'Claude Code', detected: false },
38
+ { name: 'antigravity', displayName: 'Antigravity', detected: false },
39
+ { name: 'codex', displayName: 'OpenAI Codex', detected: false },
40
+ { name: 'copilot', displayName: 'GitHub Copilot', detected: true },
41
+ { name: 'cursor', displayName: 'Cursor', detected: false },
42
+ ]);
43
+ });
44
+ });
@@ -0,0 +1,47 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { execa } from 'execa';
3
+ import { detectEditors } from './detect-editors.js';
4
+
5
+ vi.mock('execa');
6
+
7
+ describe('detectEditors', () => {
8
+ beforeEach(() => {
9
+ vi.clearAllMocks();
10
+ });
11
+
12
+ it('should return detected = true for editors whose commands exit with 0', async () => {
13
+ vi.mocked(execa).mockImplementation((command: any, args?: any, options?: any): any => {
14
+ if (command === 'code' || command === 'cursor') {
15
+ return Promise.resolve({ exitCode: 0 } as any);
16
+ }
17
+ return Promise.resolve({ exitCode: 1 } as any);
18
+ });
19
+
20
+ const result = await detectEditors();
21
+
22
+ expect(result).toEqual([
23
+ { name: 'VS Code', command: 'code', detected: true },
24
+ { name: 'VS Code Insiders', command: 'code-insiders', detected: false },
25
+ { name: 'Cursor', command: 'cursor', detected: true },
26
+ { name: 'Antigravity', command: 'agy', detected: false },
27
+ ]);
28
+
29
+ expect(execa).toHaveBeenCalledWith('code', ['--version'], { reject: false });
30
+ expect(execa).toHaveBeenCalledWith('code-insiders', ['--version'], { reject: false });
31
+ expect(execa).toHaveBeenCalledWith('cursor', ['--version'], { reject: false });
32
+ expect(execa).toHaveBeenCalledWith('agy', ['--version'], { reject: false });
33
+ });
34
+
35
+ it('should return detected = false for all editors if execa throws an error', async () => {
36
+ vi.mocked(execa).mockRejectedValue(new Error('Spawn error'));
37
+
38
+ const result = await detectEditors();
39
+
40
+ expect(result).toEqual([
41
+ { name: 'VS Code', command: 'code', detected: false },
42
+ { name: 'VS Code Insiders', command: 'code-insiders', detected: false },
43
+ { name: 'Cursor', command: 'cursor', detected: false },
44
+ { name: 'Antigravity', command: 'agy', detected: false },
45
+ ]);
46
+ });
47
+ });
@@ -0,0 +1,74 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import * as fs from 'node:fs/promises';
3
+ import * as path from 'node:path';
4
+ import { execa } from 'execa';
5
+ import { isGitRepo, gitFetch, detectDefaultBranch } from './git.js';
6
+
7
+ vi.mock('node:fs/promises');
8
+ vi.mock('execa');
9
+
10
+ describe('git utilities', () => {
11
+ beforeEach(() => {
12
+ vi.clearAllMocks();
13
+ });
14
+
15
+ describe('isGitRepo', () => {
16
+ it('should return true if .git directory exists and is accessible', async () => {
17
+ vi.mocked(fs.access).mockResolvedValue(undefined);
18
+
19
+ const result = await isGitRepo('/mock/repo');
20
+
21
+ expect(result).toBe(true);
22
+ expect(fs.access).toHaveBeenCalledWith(path.join('/mock/repo', '.git'));
23
+ });
24
+
25
+ it('should return false if .git directory is not accessible', async () => {
26
+ vi.mocked(fs.access).mockRejectedValue(new Error('ENOENT'));
27
+
28
+ const result = await isGitRepo('/mock/repo');
29
+
30
+ expect(result).toBe(false);
31
+ });
32
+ });
33
+
34
+ describe('gitFetch', () => {
35
+ it('should run git fetch origin', async () => {
36
+ vi.mocked(execa).mockResolvedValue({} as any);
37
+
38
+ await gitFetch('/mock/repo');
39
+
40
+ expect(execa).toHaveBeenCalledWith('git', ['fetch', 'origin'], { cwd: '/mock/repo' });
41
+ });
42
+ });
43
+
44
+ describe('detectDefaultBranch', () => {
45
+ it('should prefer main over master', async () => {
46
+ vi.mocked(execa).mockResolvedValue({
47
+ stdout: ' origin/master\n origin/main\n'
48
+ } as any);
49
+
50
+ const branch = await detectDefaultBranch('/mock/repo');
51
+
52
+ expect(branch).toBe('main');
53
+ expect(execa).toHaveBeenCalledWith('git', ['branch', '-r'], { cwd: '/mock/repo' });
54
+ });
55
+
56
+ it('should match master if main is not present', async () => {
57
+ vi.mocked(execa).mockResolvedValue({
58
+ stdout: ' origin/master\n origin/feature-branch\n'
59
+ } as any);
60
+
61
+ const branch = await detectDefaultBranch('/mock/repo');
62
+
63
+ expect(branch).toBe('master');
64
+ });
65
+
66
+ it('should fallback to main if neither is present or command fails', async () => {
67
+ vi.mocked(execa).mockRejectedValue(new Error('git command failed'));
68
+
69
+ const branch = await detectDefaultBranch('/mock/repo');
70
+
71
+ expect(branch).toBe('main');
72
+ });
73
+ });
74
+ });
@@ -0,0 +1,130 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { callLocalLlm, isOllamaModelAvailable, getOpenAiCompatibleUrl } from './local-ai.js';
3
+
4
+ describe('local-ai utilities', () => {
5
+ beforeEach(() => {
6
+ vi.stubGlobal('fetch', vi.fn());
7
+ });
8
+
9
+ afterEach(() => {
10
+ vi.restoreAllMocks();
11
+ });
12
+
13
+ describe('isOllamaModelAvailable', () => {
14
+ it('should match exact model names and tag variations', () => {
15
+ const models = [{ name: 'qwen2.5-coder:1.5b' }, { name: 'llama3:latest' }];
16
+ expect(isOllamaModelAvailable(models, 'qwen2.5-coder:1.5b')).toBe(true);
17
+ expect(isOllamaModelAvailable(models, 'llama3')).toBe(true);
18
+ expect(isOllamaModelAvailable(models, 'llama3:latest')).toBe(true);
19
+ expect(isOllamaModelAvailable(models, 'non-existent')).toBe(false);
20
+ });
21
+ });
22
+
23
+ describe('getOpenAiCompatibleUrl', () => {
24
+ it('should properly format endpoint URLs', () => {
25
+ expect(getOpenAiCompatibleUrl('http://localhost:11434', '/v1/chat/completions')).toBe('http://localhost:11434/v1/chat/completions');
26
+ expect(getOpenAiCompatibleUrl('http://localhost:11434/', '/v1/chat/completions')).toBe('http://localhost:11434/v1/chat/completions');
27
+ expect(getOpenAiCompatibleUrl('http://localhost:1234/v1', '/v1/chat/completions')).toBe('http://localhost:1234/v1/chat/completions');
28
+ expect(getOpenAiCompatibleUrl('http://localhost:1234/v1/', '/v1/chat/completions')).toBe('http://localhost:1234/v1/chat/completions');
29
+ });
30
+ });
31
+
32
+ describe('callLocalLlm', () => {
33
+ const configOllama = {
34
+ enabled: true,
35
+ provider: 'ollama' as const,
36
+ endpoint: 'http://localhost:11434',
37
+ model: 'qwen2.5-coder:1.5b',
38
+ };
39
+
40
+ const configOpenAi = {
41
+ enabled: true,
42
+ provider: 'openai-compatible' as const,
43
+ endpoint: 'http://localhost:1234/v1',
44
+ model: 'custom-model',
45
+ };
46
+
47
+ const messages = [{ role: 'user' as const, content: 'Hello' }];
48
+
49
+ it('should request and return message content for Ollama provider', async () => {
50
+ const mockResponse = {
51
+ message: {
52
+ content: 'Hello from Ollama!',
53
+ },
54
+ };
55
+
56
+ vi.mocked(fetch).mockResolvedValue({
57
+ ok: true,
58
+ json: () => Promise.resolve(mockResponse),
59
+ } as any);
60
+
61
+ const response = await callLocalLlm(configOllama, messages);
62
+
63
+ expect(response).toBe('Hello from Ollama!');
64
+ expect(fetch).toHaveBeenCalledWith('http://localhost:11434/api/chat', {
65
+ method: 'POST',
66
+ headers: { 'Content-Type': 'application/json' },
67
+ body: JSON.stringify({
68
+ model: 'qwen2.5-coder:1.5b',
69
+ messages,
70
+ stream: false,
71
+ }),
72
+ signal: expect.any(AbortSignal),
73
+ });
74
+ });
75
+
76
+ it('should throw an error if Ollama response is not ok', async () => {
77
+ vi.mocked(fetch).mockResolvedValue({
78
+ ok: false,
79
+ status: 500,
80
+ text: () => Promise.resolve('Internal server error'),
81
+ } as any);
82
+
83
+ await expect(callLocalLlm(configOllama, messages)).rejects.toThrow(
84
+ 'Ollama request failed with status 500: Internal server error'
85
+ );
86
+ });
87
+
88
+ it('should request and return message content for OpenAI provider', async () => {
89
+ const mockResponse = {
90
+ choices: [
91
+ {
92
+ message: {
93
+ content: 'Hello from OpenAI!',
94
+ },
95
+ },
96
+ ],
97
+ };
98
+
99
+ vi.mocked(fetch).mockResolvedValue({
100
+ ok: true,
101
+ json: () => Promise.resolve(mockResponse),
102
+ } as any);
103
+
104
+ const response = await callLocalLlm(configOpenAi, messages);
105
+
106
+ expect(response).toBe('Hello from OpenAI!');
107
+ expect(fetch).toHaveBeenCalledWith('http://localhost:1234/v1/chat/completions', {
108
+ method: 'POST',
109
+ headers: { 'Content-Type': 'application/json' },
110
+ body: JSON.stringify({
111
+ model: 'custom-model',
112
+ messages,
113
+ stream: false,
114
+ }),
115
+ signal: expect.any(AbortSignal),
116
+ });
117
+ });
118
+
119
+ it('should throw an error if OpenAI response has invalid format', async () => {
120
+ vi.mocked(fetch).mockResolvedValue({
121
+ ok: true,
122
+ json: () => Promise.resolve({}),
123
+ } as any);
124
+
125
+ await expect(callLocalLlm(configOpenAi, messages)).rejects.toThrow(
126
+ 'Invalid response format received from OpenAI-compatible endpoint'
127
+ );
128
+ });
129
+ });
130
+ });
@@ -0,0 +1,111 @@
1
+ /**
2
+ * @module utils/local-ai
3
+ * Handles requests to local LLM servers (Ollama or OpenAI-compatible like LM Studio).
4
+ */
5
+
6
+ import type { LocalLlmConfig } from '../types.js';
7
+
8
+ export interface LocalLlmMessage {
9
+ role: 'system' | 'user' | 'assistant';
10
+ content: string;
11
+ }
12
+
13
+ /**
14
+ * Sends a chat completion request to the configured local LLM provider.
15
+ * Supports Ollama-specific API and standard OpenAI-compatible endpoints.
16
+ */
17
+ export async function callLocalLlm(
18
+ config: LocalLlmConfig,
19
+ messages: LocalLlmMessage[],
20
+ ): Promise<string> {
21
+ const { provider, endpoint, model } = config;
22
+ const cleanEndpoint = endpoint.replace(/\/$/, '');
23
+ const controller = new AbortController();
24
+ const timeout = setTimeout(() => controller.abort(), 60_000);
25
+
26
+ try {
27
+ if (provider === 'ollama') {
28
+ const url = `${cleanEndpoint}/api/chat`;
29
+ const response = await fetch(url, {
30
+ method: 'POST',
31
+ headers: {
32
+ 'Content-Type': 'application/json',
33
+ },
34
+ body: JSON.stringify({
35
+ model,
36
+ messages,
37
+ stream: false,
38
+ }),
39
+ signal: controller.signal,
40
+ });
41
+
42
+ if (!response.ok) {
43
+ const text = await response.text();
44
+ throw new Error(`Ollama request failed with status ${response.status}: ${text}`);
45
+ }
46
+
47
+ const data: any = await response.json();
48
+ if (data?.message?.content) {
49
+ return data.message.content;
50
+ }
51
+ throw new Error('Invalid response format received from Ollama');
52
+ } else {
53
+ // OpenAI-compatible provider
54
+ const url = getOpenAiCompatibleUrl(cleanEndpoint, '/v1/chat/completions');
55
+
56
+ const response = await fetch(url, {
57
+ method: 'POST',
58
+ headers: {
59
+ 'Content-Type': 'application/json',
60
+ },
61
+ body: JSON.stringify({
62
+ model,
63
+ messages,
64
+ stream: false,
65
+ }),
66
+ signal: controller.signal,
67
+ });
68
+
69
+ if (!response.ok) {
70
+ const text = await response.text();
71
+ throw new Error(`OpenAI-compatible request failed with status ${response.status}: ${text}`);
72
+ }
73
+
74
+ const data: any = await response.json();
75
+ if (data?.choices?.[0]?.message?.content) {
76
+ return data.choices[0].message.content;
77
+ }
78
+ throw new Error('Invalid response format received from OpenAI-compatible endpoint');
79
+ }
80
+ } catch (error: any) {
81
+ if (error.name === 'AbortError') {
82
+ throw new Error('Local LLM request timed out after 60 seconds');
83
+ }
84
+ throw error;
85
+ } finally {
86
+ clearTimeout(timeout);
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Checks whether a target model name matches any model in an Ollama model list.
92
+ * Handles tag variations like 'model' vs 'model:latest' vs 'model:7b'.
93
+ */
94
+ export function isOllamaModelAvailable(models: { name: string }[], targetModel: string): boolean {
95
+ const normalize = (name: string) => name.includes(':') ? name : `${name}:latest`;
96
+ const targetNorm = normalize(targetModel);
97
+ return models.some((m) => normalize(m.name) === targetNorm);
98
+ }
99
+
100
+ /**
101
+ * Helper to build standard OpenAI compatible URLs.
102
+ * Handles cases where the configured endpoint already has or does not have `/v1`.
103
+ */
104
+ export function getOpenAiCompatibleUrl(endpoint: string, suffix: string): string {
105
+ const cleanEndpoint = endpoint.replace(/\/$/, '');
106
+ const hasV1 = /\/v1\/?$/.test(cleanEndpoint);
107
+ if (hasV1) {
108
+ return `${cleanEndpoint.replace(/\/v1\/?$/, '')}${suffix}`;
109
+ }
110
+ return `${cleanEndpoint}${suffix}`;
111
+ }