@mrpatronz/nexusflow 0.2.7 → 0.2.11

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 +134 -12
  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 +401 -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 +464 -0
  88. package/src/server.ts +141 -11
  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;
@@ -160,7 +247,8 @@ function updateJobStep(
160
247
  step.message = message;
161
248
  }
162
249
 
163
- if (stepId === 'pack' && status === 'completed') {
250
+ const isLastStep = job.steps[job.steps.length - 1]?.id === stepId;
251
+ if (isLastStep && status === 'completed') {
164
252
  job.status = 'completed';
165
253
  job.progress = 100;
166
254
  } else if (status === 'failed') {
@@ -203,11 +291,13 @@ async function runCreationJob(jobId: string, body: any, config: any) {
203
291
  id: body.branchName,
204
292
  branchName: body.branchName,
205
293
  description: body.description,
206
- repos: body.repos.map((r: any) => r.path),
294
+ repos: body.repos.map((r: any) => path.join(workspacePath, r.name)),
295
+ originalRepos: body.repos.map((r: any) => r.path),
207
296
  assistants: body.assistants,
208
297
  workspacePath,
209
298
  createdAt: new Date().toISOString(),
210
299
  resumption: body.resumption,
300
+ localLlmEnabled: body.localLlmEnabled,
211
301
  };
212
302
  if (job) {
213
303
  job.feature = feature;
@@ -233,14 +323,17 @@ async function runCreationJob(jobId: string, body: any, config: any) {
233
323
  feature,
234
324
  repos: workspaceRepos,
235
325
  analysis,
326
+ localLlm: config.localLlm,
236
327
  };
237
328
  await generateContextFiles(ctx, body.assistants, workspacePath);
238
329
  updateJobStep(jobId, 'context', 'completed', 'AI context files generated.');
239
330
 
240
331
  // 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).`);
332
+ if (config.packContextXml) {
333
+ updateJobStep(jobId, 'pack', 'running', 'Packing codebase context with Repomix...');
334
+ const packResult = await packWorkspace(workspacePath);
335
+ updateJobStep(jobId, 'pack', 'completed', `Packed codebase context (${packResult.totalFiles} files, ${(packResult.fileSize / 1024).toFixed(2)} KB).`);
336
+ }
244
337
 
245
338
  } catch (error) {
246
339
  const msg = error instanceof Error ? error.message : String(error);
@@ -261,6 +354,7 @@ app.post('/api/workspace', async (c) => {
261
354
  description: string;
262
355
  repos: RepoInfo[];
263
356
  assistants: any[];
357
+ localLlmEnabled?: boolean;
264
358
  resumption?: {
265
359
  testCommand?: string;
266
360
  mockCommand?: string;
@@ -282,8 +376,10 @@ app.post('/api/workspace', async (c) => {
282
376
  { id: 'worktrees', name: 'Create Git Worktrees', status: 'pending', message: 'Waiting...' },
283
377
  { id: 'analysis', name: 'Analyze Repositories', status: 'pending', message: 'Waiting...' },
284
378
  { id: 'context', name: 'Generate AI Context Files', status: 'pending', message: 'Waiting...' },
285
- { id: 'pack', name: 'Pack Codebase Context', status: 'pending', message: 'Waiting...' },
286
379
  ];
380
+ if (config.packContextXml) {
381
+ steps.push({ id: 'pack', name: 'Pack Codebase Context', status: 'pending', message: 'Waiting...' });
382
+ }
287
383
 
288
384
  const job: CreationJob = {
289
385
  id: jobId,
@@ -396,8 +492,33 @@ app.post('/api/open-editor', async (c) => {
396
492
  command: string;
397
493
  };
398
494
 
495
+ if (!ALLOWED_EDITORS.has(command)) {
496
+ return c.json({ error: 'Forbidden editor command' }, 400);
497
+ }
498
+
499
+ // Validate path exists and is a directory
500
+ try {
501
+ const stats = await fs.stat(workspacePath);
502
+ if (!stats.isDirectory()) {
503
+ return c.json({ error: 'Workspace path is not a directory' }, 400);
504
+ }
505
+ } catch {
506
+ return c.json({ error: 'Workspace path does not exist' }, 400);
507
+ }
508
+
399
509
  // Spawn editor process
400
- execa(command, [workspacePath], { detached: true, stdio: 'ignore' }).unref();
510
+ const isWin = process.platform === 'win32';
511
+ const child = execa(command, [workspacePath], {
512
+ detached: true,
513
+ stdio: 'ignore',
514
+ shell: isWin,
515
+ cleanup: false,
516
+ });
517
+ child.unref();
518
+ child.catch((err) => {
519
+ console.error(`Failed to launch editor ${command} for path ${workspacePath}:`, err);
520
+ });
521
+
401
522
  return c.json({ success: true });
402
523
  } catch (error) {
403
524
  const msg = error instanceof Error ? error.message : String(error);
@@ -758,11 +879,20 @@ app.post('/api/workspace/:id/resume', async (c) => {
758
879
 
759
880
  // Open in editor if command is provided
760
881
  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);
882
+ if (!ALLOWED_EDITORS.has(body.command)) {
883
+ return c.json({ error: 'Forbidden editor command' }, 400);
765
884
  }
885
+ const isWin = process.platform === 'win32';
886
+ const child = execa(body.command, [workspacePath], {
887
+ detached: true,
888
+ stdio: 'ignore',
889
+ shell: isWin,
890
+ cleanup: false,
891
+ });
892
+ child.unref();
893
+ child.catch((err) => {
894
+ console.error(`Failed to launch editor ${body.command} for path ${workspacePath}:`, err);
895
+ });
766
896
  }
767
897
 
768
898
  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
+ });