mirror of
https://github.com/tiennm99/ccs.git
synced 2026-10-14 00:16:38 +00:00
Merge pull request #891 from kaitranntt/kai/fix/855-cursor-dual-mode-runtime-dev-refresh
fix(cursor): make Cursor a first-class runtime profile and harden integration
This commit is contained in:
24 files changed
+1712
-142
No files matched your search
@@ -195,5 +195,74 @@ describe('ProfileDetector', () => {
|
||||
existsSyncSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('should detect cursor as a first-class runtime profile when enabled', () => {
|
||||
const isUnifiedModeSpy = spyOn(unifiedConfigLoader, 'isUnifiedMode').mockReturnValue(true);
|
||||
const getCursorConfigSpy = spyOn(unifiedConfigLoader, 'getCursorConfig').mockReturnValue({
|
||||
enabled: true,
|
||||
port: 20129,
|
||||
auto_start: true,
|
||||
ghost_mode: true,
|
||||
model: 'gpt-5.3-codex',
|
||||
});
|
||||
|
||||
try {
|
||||
const result = detector.detectProfileType('cursor');
|
||||
expect(result.type).toBe('cursor');
|
||||
expect(result.name).toBe('cursor');
|
||||
expect(result.cursorConfig?.auto_start).toBe(true);
|
||||
} finally {
|
||||
isUnifiedModeSpy.mockRestore();
|
||||
getCursorConfigSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('should merge default cursor fields when enabled via partial unified config', () => {
|
||||
const originalCcsHome = process.env.CCS_HOME;
|
||||
process.env.CCS_HOME = tempDir;
|
||||
const ccsDir = path.join(tempDir, '.ccs');
|
||||
fs.mkdirSync(ccsDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(ccsDir, 'config.yaml'),
|
||||
['version: 12', 'cursor:', ' enabled: true'].join('\n')
|
||||
);
|
||||
|
||||
try {
|
||||
const localDetector = new ProfileDetector();
|
||||
const result = localDetector.detectProfileType('cursor');
|
||||
expect(result.type).toBe('cursor');
|
||||
expect(result.cursorConfig).toEqual({
|
||||
enabled: true,
|
||||
port: 20129,
|
||||
auto_start: false,
|
||||
ghost_mode: true,
|
||||
model: 'gpt-5.3-codex',
|
||||
});
|
||||
} finally {
|
||||
if (originalCcsHome !== undefined) {
|
||||
process.env.CCS_HOME = originalCcsHome;
|
||||
} else {
|
||||
delete process.env.CCS_HOME;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should throw a helpful error when cursor profile is disabled', () => {
|
||||
const isUnifiedModeSpy = spyOn(unifiedConfigLoader, 'isUnifiedMode').mockReturnValue(true);
|
||||
const getCursorConfigSpy = spyOn(unifiedConfigLoader, 'getCursorConfig').mockReturnValue({
|
||||
enabled: false,
|
||||
port: 20129,
|
||||
auto_start: false,
|
||||
ghost_mode: true,
|
||||
model: 'gpt-5.3-codex',
|
||||
});
|
||||
|
||||
try {
|
||||
expect(() => detector.detectProfileType('cursor')).toThrow(/Cursor profile is not enabled/);
|
||||
} finally {
|
||||
isUnifiedModeSpy.mockRestore();
|
||||
getCursorConfigSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -88,6 +88,15 @@ describe('help command parity', () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test('root help documents bare cursor as the runtime entrypoint', async () => {
|
||||
const lines: string[] = [];
|
||||
await handleHelpCommand((line) => lines.push(line));
|
||||
|
||||
const rendered = stripAnsi(lines.join('\n'));
|
||||
expect(rendered.includes('ccs cursor <cmd>')).toBe(false);
|
||||
expect(rendered.includes('Run Claude via Cursor local proxy')).toBe(true);
|
||||
});
|
||||
|
||||
test('root help explains Claude [1m] as an explicit CCS suffix with upstream limits', async () => {
|
||||
const lines: string[] = [];
|
||||
await handleHelpCommand((line) => lines.push(line));
|
||||
|
||||
@@ -74,6 +74,15 @@ describe('root-command-router', () => {
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not capture cursor so bare cursor can fall through to profile routing', async () => {
|
||||
const tryHandleRootCommand = await loadTryHandleRootCommand();
|
||||
|
||||
await expect(tryHandleRootCommand(['cursor'])).resolves.toBe(false);
|
||||
await expect(tryHandleRootCommand(['cursor', 'status'])).resolves.toBe(false);
|
||||
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
it('prints update help without invoking the updater', async () => {
|
||||
const tryHandleRootCommand = await loadTryHandleRootCommand();
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Unit tests for Cursor daemon module
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
|
||||
import { describe, it, expect, beforeEach, afterEach, spyOn } from 'bun:test';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
@@ -19,7 +19,12 @@ import {
|
||||
} from '../../../src/cursor/cursor-daemon';
|
||||
import { getCcsDir } from '../../../src/utils/config-manager';
|
||||
import { handleCursorCommand } from '../../../src/commands/cursor-command';
|
||||
import {
|
||||
renderCursorHelp,
|
||||
renderCursorStatus,
|
||||
} from '../../../src/commands/cursor-command-display';
|
||||
import { loadCredentials } from '../../../src/cursor/cursor-auth';
|
||||
import { DEFAULT_CURSOR_CONFIG } from '../../../src/config/unified-config-types';
|
||||
|
||||
// Test isolation
|
||||
let originalCcsHome: string | undefined;
|
||||
@@ -268,9 +273,62 @@ describe('stopDaemon', () => {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses to stop when daemon ownership cannot be verified', async () => {
|
||||
const killSpy = spyOn(process, 'kill').mockImplementation(
|
||||
((pid: number, signal?: NodeJS.Signals | number) => {
|
||||
if (pid === process.pid && signal === 0) {
|
||||
const err = new Error('EPERM') as NodeJS.ErrnoException;
|
||||
err.code = 'EPERM';
|
||||
throw err;
|
||||
}
|
||||
|
||||
return true;
|
||||
}) as typeof process.kill
|
||||
);
|
||||
|
||||
writePidToFile(process.pid);
|
||||
|
||||
try {
|
||||
const result = await stopDaemon();
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('unable to verify daemon ownership');
|
||||
expect(fs.existsSync(path.join(getTestCursorDir(), 'daemon.pid'))).toBe(true);
|
||||
} finally {
|
||||
killSpy.mockRestore();
|
||||
removePidFile();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('handleCursorCommand', () => {
|
||||
it('shows help when invoked without an admin subcommand', async () => {
|
||||
const originalLog = console.log;
|
||||
const originalError = console.error;
|
||||
const logs: string[] = [];
|
||||
const errors: string[] = [];
|
||||
|
||||
console.log = (...args: unknown[]) => {
|
||||
logs.push(args.map((arg) => String(arg)).join(' '));
|
||||
};
|
||||
console.error = (...args: unknown[]) => {
|
||||
errors.push(args.map((arg) => String(arg)).join(' '));
|
||||
};
|
||||
|
||||
try {
|
||||
const exitCode = await handleCursorCommand([]);
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(errors).toHaveLength(0);
|
||||
expect(logs.some((line) => line.includes('Cursor IDE Integration'))).toBe(true);
|
||||
expect(logs.some((line) => line.includes('Usage: ccs cursor <subcommand>'))).toBe(true);
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
console.error = originalError;
|
||||
}
|
||||
});
|
||||
|
||||
it('returns exit code 1 for unknown subcommand', async () => {
|
||||
const exitCode = await handleCursorCommand(['nonexistent']);
|
||||
expect(exitCode).toBe(1);
|
||||
@@ -297,3 +355,140 @@ describe('handleCursorCommand', () => {
|
||||
expect(credentials?.machineId).toBe(machineId);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderCursorStatus', () => {
|
||||
it('shows runtime endpoint guidance when Cursor is ready', () => {
|
||||
const originalLog = console.log;
|
||||
const logs: string[] = [];
|
||||
|
||||
console.log = (...args: unknown[]) => {
|
||||
logs.push(args.map((arg) => String(arg)).join(' '));
|
||||
};
|
||||
|
||||
try {
|
||||
renderCursorStatus(
|
||||
{ ...DEFAULT_CURSOR_CONFIG, enabled: true, port: 20129 },
|
||||
{
|
||||
authenticated: true,
|
||||
expired: false,
|
||||
tokenAge: 0,
|
||||
credentials: {
|
||||
accessToken: 'a'.repeat(60),
|
||||
machineId: '1234567890abcdef1234567890abcdef',
|
||||
authMethod: 'manual',
|
||||
importedAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
{ running: true, port: 20129, pid: 1234 }
|
||||
);
|
||||
|
||||
expect(logs.some((line) => line.includes('OpenAI base: http://127.0.0.1:20129/v1'))).toBe(
|
||||
true
|
||||
);
|
||||
expect(
|
||||
logs.some((line) => line.includes('Chat route: http://127.0.0.1:20129/v1/chat/completions'))
|
||||
).toBe(true);
|
||||
expect(
|
||||
logs.some((line) => line.includes('Anthropic base: http://127.0.0.1:20129'))
|
||||
).toBe(true);
|
||||
expect(
|
||||
logs.some((line) => line.includes(`Raw settings: ${getCcsDir()}/cursor.settings.json`))
|
||||
).toBe(true);
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
}
|
||||
});
|
||||
|
||||
it('shows runtime guidance even when setup is incomplete', () => {
|
||||
const originalLog = console.log;
|
||||
const logs: string[] = [];
|
||||
|
||||
console.log = (...args: unknown[]) => {
|
||||
logs.push(args.map((arg) => String(arg)).join(' '));
|
||||
};
|
||||
|
||||
try {
|
||||
renderCursorStatus(
|
||||
{ ...DEFAULT_CURSOR_CONFIG, enabled: false, port: 20129 },
|
||||
{
|
||||
authenticated: false,
|
||||
expired: false,
|
||||
tokenAge: undefined,
|
||||
credentials: undefined,
|
||||
},
|
||||
{ running: false, port: 20129, pid: undefined }
|
||||
);
|
||||
|
||||
expect(logs.some((line) => line.includes('OpenAI base: http://127.0.0.1:20129/v1'))).toBe(
|
||||
true
|
||||
);
|
||||
expect(logs.some((line) => line.includes('Next steps:'))).toBe(true);
|
||||
expect(logs.some((line) => line.includes(' - Help: ccs cursor help'))).toBe(true);
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
}
|
||||
});
|
||||
|
||||
it('falls back to ~/.ccs in status output when no CCS override is active', () => {
|
||||
const originalLog = console.log;
|
||||
const originalCcsHomeValue = process.env.CCS_HOME;
|
||||
const logs: string[] = [];
|
||||
|
||||
delete process.env.CCS_HOME;
|
||||
console.log = (...args: unknown[]) => {
|
||||
logs.push(args.map((arg) => String(arg)).join(' '));
|
||||
};
|
||||
|
||||
try {
|
||||
renderCursorStatus(
|
||||
{ ...DEFAULT_CURSOR_CONFIG, enabled: true, port: 20129 },
|
||||
{
|
||||
authenticated: true,
|
||||
expired: false,
|
||||
tokenAge: 0,
|
||||
credentials: {
|
||||
accessToken: 'a'.repeat(60),
|
||||
machineId: '1234567890abcdef1234567890abcdef',
|
||||
authMethod: 'manual',
|
||||
importedAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
{ running: true, port: 20129, pid: 1234 }
|
||||
);
|
||||
|
||||
expect(logs.some((line) => line.includes('Raw settings: ~/.ccs/cursor.settings.json'))).toBe(
|
||||
true
|
||||
);
|
||||
} finally {
|
||||
if (originalCcsHomeValue !== undefined) {
|
||||
process.env.CCS_HOME = originalCcsHomeValue;
|
||||
} else {
|
||||
delete process.env.CCS_HOME;
|
||||
}
|
||||
console.log = originalLog;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderCursorHelp', () => {
|
||||
it('shows bare ccs cursor as the runtime entrypoint', () => {
|
||||
const originalLog = console.log;
|
||||
const logs: string[] = [];
|
||||
|
||||
console.log = (...args: unknown[]) => {
|
||||
logs.push(args.map((arg) => String(arg)).join(' '));
|
||||
};
|
||||
|
||||
try {
|
||||
const exitCode = renderCursorHelp();
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(logs.some((line) => line.includes('Usage: ccs cursor <subcommand>'))).toBe(true);
|
||||
expect(
|
||||
logs.some((line) => line.includes('ccs cursor [claude args]'))
|
||||
).toBe(true);
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
|
||||
import {
|
||||
executeCursorProfile,
|
||||
generateCursorEnv,
|
||||
resolveCursorImageAnalysisEnv,
|
||||
} from '../../../src/cursor/cursor-profile-executor';
|
||||
import { saveCredentials } from '../../../src/cursor/cursor-auth';
|
||||
import type { CursorConfig } from '../../../src/config/unified-config-types';
|
||||
|
||||
const BASE_CONFIG: CursorConfig = {
|
||||
enabled: true,
|
||||
port: 20129,
|
||||
auto_start: false,
|
||||
ghost_mode: true,
|
||||
model: 'gpt-5.3-codex',
|
||||
};
|
||||
|
||||
describe('cursor-profile-executor', () => {
|
||||
let originalCcsHome: string | undefined;
|
||||
let tempDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
originalCcsHome = process.env.CCS_HOME;
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccs-cursor-profile-executor-'));
|
||||
process.env.CCS_HOME = tempDir;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalCcsHome !== undefined) {
|
||||
process.env.CCS_HOME = originalCcsHome;
|
||||
} else {
|
||||
delete process.env.CCS_HOME;
|
||||
}
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('builds Cursor env for Claude runtime', () => {
|
||||
const env = generateCursorEnv(
|
||||
{
|
||||
...BASE_CONFIG,
|
||||
opus_model: 'cursor-opus',
|
||||
sonnet_model: 'cursor-sonnet',
|
||||
haiku_model: 'cursor-haiku',
|
||||
},
|
||||
'/tmp/claude-config'
|
||||
);
|
||||
|
||||
expect(env.ANTHROPIC_BASE_URL).toBe('http://127.0.0.1:20129');
|
||||
expect(env.ANTHROPIC_AUTH_TOKEN).toBe('cursor-managed');
|
||||
expect(env.ANTHROPIC_MODEL).toBe('gpt-5.3-codex');
|
||||
expect(env.ANTHROPIC_DEFAULT_OPUS_MODEL).toBe('cursor-opus');
|
||||
expect(env.ANTHROPIC_DEFAULT_SONNET_MODEL).toBe('cursor-sonnet');
|
||||
expect(env.ANTHROPIC_DEFAULT_HAIKU_MODEL).toBe('cursor-haiku');
|
||||
expect(env.CLAUDE_CONFIG_DIR).toBe('/tmp/claude-config');
|
||||
});
|
||||
|
||||
it('skips image-analysis provider routing for cursor unless explicitly mapped', async () => {
|
||||
const { env, warning } = await resolveCursorImageAnalysisEnv();
|
||||
|
||||
expect(env.CCS_CURRENT_PROVIDER).toBe('');
|
||||
expect(env.CCS_IMAGE_ANALYSIS_SKIP).toBe('1');
|
||||
expect(warning).toBeNull();
|
||||
});
|
||||
|
||||
it('fails fast when Cursor integration is disabled', async () => {
|
||||
const exitCode = await executeCursorProfile({ ...BASE_CONFIG, enabled: false }, []);
|
||||
expect(exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it('fails when credentials are missing', async () => {
|
||||
const exitCode = await executeCursorProfile(BASE_CONFIG, []);
|
||||
expect(exitCode).toBe(1);
|
||||
});
|
||||
|
||||
it('fails with actionable guidance when daemon is down and auto_start is false', async () => {
|
||||
saveCredentials({
|
||||
accessToken: 'a'.repeat(60),
|
||||
machineId: '1234567890abcdef1234567890abcdef',
|
||||
authMethod: 'manual',
|
||||
importedAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const exitCode = await executeCursorProfile(
|
||||
{
|
||||
...BASE_CONFIG,
|
||||
port: 29991,
|
||||
auto_start: false,
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
expect(exitCode).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import {
|
||||
decodeVarint,
|
||||
decodeField,
|
||||
decodeMessage,
|
||||
parseConnectRPCFrame,
|
||||
} from '../../../src/cursor/cursor-protobuf-decoder';
|
||||
import { buildCursorRequest } from '../../../src/cursor/cursor-translator';
|
||||
@@ -21,6 +22,25 @@ import { CursorExecutor } from '../../../src/cursor/cursor-executor';
|
||||
import { WIRE_TYPE, FIELD } from '../../../src/cursor/cursor-protobuf-schema';
|
||||
import { StreamingFrameParser, decompressPayload } from '../../../src/cursor/cursor-stream-parser';
|
||||
|
||||
const MAX_TOOL_RESULT_CHARS = 12_000;
|
||||
|
||||
function computeExpectedToolResultOmittedChars(textLength: number): number {
|
||||
if (textLength <= MAX_TOOL_RESULT_CHARS) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let omittedChars = textLength - MAX_TOOL_RESULT_CHARS;
|
||||
while (true) {
|
||||
const suffix = `\n[truncated ${omittedChars} chars]`;
|
||||
const keepLength = Math.max(MAX_TOOL_RESULT_CHARS - suffix.length, 0);
|
||||
const nextOmittedChars = textLength - keepLength;
|
||||
if (nextOmittedChars === omittedChars) {
|
||||
return omittedChars;
|
||||
}
|
||||
omittedChars = nextOmittedChars;
|
||||
}
|
||||
}
|
||||
|
||||
describe('Protobuf Encoding/Decoding', () => {
|
||||
describe('encodeVarint / decodeVarint round-trip', () => {
|
||||
it('should encode and decode 0', () => {
|
||||
@@ -222,7 +242,7 @@ describe('Message Translation', () => {
|
||||
expect(result.messages[0].tool_calls![0].function.name).toBe('get_weather');
|
||||
});
|
||||
|
||||
it('should accumulate tool results', () => {
|
||||
it('should flatten tool results into user tool_result blocks', () => {
|
||||
const result = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
@@ -251,11 +271,424 @@ describe('Message Translation', () => {
|
||||
{}
|
||||
);
|
||||
|
||||
expect(result.messages).toHaveLength(3);
|
||||
expect(result.messages[1].role).toBe('user');
|
||||
expect(result.messages[1].content).toContain('<tool_result>');
|
||||
expect(result.messages[1].content).toContain('<tool_name>get_weather</tool_name>');
|
||||
expect(result.messages[1].content).toContain('<tool_call_id>call_123</tool_call_id>');
|
||||
expect(result.messages[2]).toEqual({ role: 'user', content: 'What is the weather?' });
|
||||
});
|
||||
|
||||
it('should preserve consecutive tool messages as separate user turns', () => {
|
||||
const result = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: [
|
||||
{
|
||||
id: 'call_one',
|
||||
type: 'function',
|
||||
function: { name: 'search_docs', arguments: '{"q":"cursor"}' },
|
||||
},
|
||||
{
|
||||
id: 'call_two',
|
||||
type: 'function',
|
||||
function: { name: 'read_file', arguments: '{"path":"README.md"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'tool',
|
||||
content: 'first result',
|
||||
tool_call_id: 'call_one',
|
||||
},
|
||||
{
|
||||
role: 'tool',
|
||||
content: 'second result',
|
||||
tool_call_id: 'call_two',
|
||||
},
|
||||
{ role: 'user', content: 'Summarize both results.' },
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
);
|
||||
|
||||
expect(result.messages).toHaveLength(4);
|
||||
expect(result.messages[1]).toEqual({
|
||||
role: 'user',
|
||||
content: expect.stringContaining('<tool_call_id>call_one</tool_call_id>'),
|
||||
});
|
||||
expect(result.messages[2]).toEqual({
|
||||
role: 'user',
|
||||
content: expect.stringContaining('<tool_call_id>call_two</tool_call_id>'),
|
||||
});
|
||||
expect(result.messages[3]).toEqual({ role: 'user', content: 'Summarize both results.' });
|
||||
});
|
||||
|
||||
it('should recover tool names for tool results without a name field', () => {
|
||||
const result = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: [
|
||||
{
|
||||
id: 'call_456',
|
||||
type: 'function',
|
||||
function: { name: 'search_docs', arguments: '{"q":"cursor"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'tool',
|
||||
content: 'done',
|
||||
tool_call_id: 'call_456',
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
);
|
||||
|
||||
expect(result.messages).toHaveLength(2);
|
||||
// Tool result should be attached to next message
|
||||
expect(result.messages[1].tool_results).toBeDefined();
|
||||
expect(result.messages[1].tool_results).toHaveLength(1);
|
||||
expect(result.messages[1].tool_results![0].tool_call_id).toBe('call_123');
|
||||
expect(result.messages[1].content).toContain('<tool_name>search_docs</tool_name>');
|
||||
expect(result.messages[1].tool_results).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should flatten user content arrays that include tool_result blocks', () => {
|
||||
const result = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: [
|
||||
{
|
||||
id: 'call_789',
|
||||
type: 'function',
|
||||
function: { name: 'search_docs', arguments: '{"q":"cursor"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: 'Tool finished.' },
|
||||
{
|
||||
type: 'tool_result',
|
||||
tool_use_id: 'call_789',
|
||||
content: { answer: 'Cursor integration ready' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
);
|
||||
|
||||
expect(result.messages).toHaveLength(2);
|
||||
expect(result.messages[1].role).toBe('user');
|
||||
expect(result.messages[1].content).toContain('Tool finished.');
|
||||
expect(result.messages[1].content).toContain('<tool_name>search_docs</tool_name>');
|
||||
expect(result.messages[1].content).toContain('{"answer":"Cursor integration ready"}');
|
||||
});
|
||||
|
||||
it('should preserve line breaks for multipart tool_result text content', () => {
|
||||
const result = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: [
|
||||
{
|
||||
id: 'call_lines',
|
||||
type: 'function',
|
||||
function: { name: 'read_file', arguments: '{"path":"notes.txt"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'tool_result',
|
||||
tool_use_id: 'call_lines',
|
||||
content: [
|
||||
{ type: 'text', text: 'first line' },
|
||||
{ type: 'text', text: 'second line' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
);
|
||||
|
||||
expect(result.messages).toHaveLength(2);
|
||||
expect(result.messages[1].content).toContain('<result>first line\nsecond line</result>');
|
||||
});
|
||||
|
||||
it('should convert assistant tool_use content blocks into tool_calls', () => {
|
||||
const result = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{ type: 'text', text: 'Inspecting the workspace.' },
|
||||
{
|
||||
type: 'tool_use',
|
||||
id: 'call_999',
|
||||
name: 'list_files',
|
||||
input: { path: '/tmp' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
);
|
||||
|
||||
expect(result.messages).toHaveLength(1);
|
||||
expect(result.messages[0].role).toBe('assistant');
|
||||
expect(result.messages[0].content).toBe('Inspecting the workspace.');
|
||||
expect(result.messages[0].tool_calls).toEqual([
|
||||
{
|
||||
id: 'call_999',
|
||||
type: 'function',
|
||||
function: { name: 'list_files', arguments: '{"path":"/tmp"}' },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should synthesize fallback ids for tool_use blocks that omit them', () => {
|
||||
const result = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{
|
||||
type: 'tool_use',
|
||||
name: 'search_docs',
|
||||
input: { q: 'cursor' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
);
|
||||
|
||||
expect(result.messages).toHaveLength(1);
|
||||
expect(result.messages[0].tool_calls).toHaveLength(1);
|
||||
expect(result.messages[0].tool_calls![0].id).toBe('toolu_cursor_fallback_0_0');
|
||||
});
|
||||
|
||||
it('should normalize invalid assistant tool call ids before emitting tool results', () => {
|
||||
const result = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: [
|
||||
{
|
||||
id: 'call_bad\nline two',
|
||||
type: 'function',
|
||||
function: { name: 'search_docs', arguments: '{"q":"cursor"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'tool',
|
||||
content: 'done',
|
||||
tool_call_id: 'call_bad\nline two',
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
);
|
||||
|
||||
expect(result.messages).toHaveLength(2);
|
||||
expect(result.messages[0].tool_calls![0].id).toBe('call_bad');
|
||||
expect(result.messages[1].content).toContain('<tool_call_id>call_bad</tool_call_id>');
|
||||
});
|
||||
|
||||
it('should dedupe tool calls when assistant messages contain both tool_calls and tool_use blocks', () => {
|
||||
const result = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{
|
||||
type: 'tool_use',
|
||||
id: 'call_dupe',
|
||||
name: 'search_docs',
|
||||
input: { q: 'cursor' },
|
||||
},
|
||||
],
|
||||
tool_calls: [
|
||||
{
|
||||
id: 'call_dupe',
|
||||
type: 'function',
|
||||
function: { name: 'search_docs', arguments: '{"q":"cursor"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
);
|
||||
|
||||
expect(result.messages).toHaveLength(1);
|
||||
expect(result.messages[0].tool_calls).toEqual([
|
||||
{
|
||||
id: 'call_dupe',
|
||||
type: 'function',
|
||||
function: { name: 'search_docs', arguments: '{"q":"cursor"}' },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should truncate oversized tool result payloads', () => {
|
||||
const oversizedResult = '&'.repeat(12_050);
|
||||
const omittedChars = computeExpectedToolResultOmittedChars(oversizedResult.length);
|
||||
const preservedChars = oversizedResult.length - omittedChars;
|
||||
const result = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: [
|
||||
{
|
||||
id: 'call_big',
|
||||
type: 'function',
|
||||
function: { name: 'read_file', arguments: '{"path":"big.txt"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'tool',
|
||||
content: oversizedResult,
|
||||
tool_call_id: 'call_big',
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
);
|
||||
|
||||
expect(result.messages).toHaveLength(2);
|
||||
expect(result.messages[1].content).toContain('[truncated ');
|
||||
expect(result.messages[1].content).toContain(`[truncated ${omittedChars} chars]`);
|
||||
|
||||
const resultMatch = result.messages[1].content.match(/<result>([\s\S]*)<\/result>/);
|
||||
expect(resultMatch).not.toBeNull();
|
||||
expect((resultMatch?.[1].match(/&/g) ?? []).length).toBe(preservedChars);
|
||||
});
|
||||
|
||||
it('should mark unserializable structured tool results explicitly', () => {
|
||||
const circular: Record<string, unknown> = {};
|
||||
circular.self = circular;
|
||||
|
||||
const result = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: [
|
||||
{
|
||||
id: 'call_bad',
|
||||
type: 'function',
|
||||
function: { name: 'read_json', arguments: '{"path":"bad.json"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'tool_result',
|
||||
tool_use_id: 'call_bad',
|
||||
content: circular,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
);
|
||||
|
||||
expect(result.messages).toHaveLength(2);
|
||||
expect(result.messages[1].content).toContain('[unserializable content]');
|
||||
});
|
||||
|
||||
it('should reject tool_result blocks without a valid tool_use_id', () => {
|
||||
expect(() =>
|
||||
buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'tool_result',
|
||||
content: 'done',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
)
|
||||
).toThrow('messages[0].content[0] must include a valid tool result id');
|
||||
});
|
||||
|
||||
it('should reject tool role messages without a valid tool_call_id', () => {
|
||||
expect(() =>
|
||||
buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'tool',
|
||||
content: 'done',
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
)
|
||||
).toThrow('messages[0].tool_call_id must include a valid tool result id');
|
||||
});
|
||||
|
||||
it('should handle array content format', () => {
|
||||
@@ -344,6 +777,57 @@ describe('Request Encoding', () => {
|
||||
expect(result).toBeInstanceOf(Uint8Array);
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should preserve flattened tool_result blocks through protobuf encoding', () => {
|
||||
const translated = buildCursorRequest(
|
||||
'gpt-4',
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: [
|
||||
{
|
||||
id: 'call_wire',
|
||||
type: 'function',
|
||||
function: { name: 'read_file', arguments: '{"path":"notes.txt"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'tool',
|
||||
content: 'workspace snapshot',
|
||||
tool_call_id: 'call_wire',
|
||||
},
|
||||
],
|
||||
},
|
||||
false,
|
||||
{}
|
||||
);
|
||||
|
||||
const body = generateCursorBody(translated.messages, 'gpt-4', [], null);
|
||||
const frame = parseConnectRPCFrame(Buffer.from(body));
|
||||
expect(frame).not.toBeNull();
|
||||
|
||||
const topLevel = decodeMessage(frame!.payload);
|
||||
const requestPayload = topLevel.get(FIELD.Request.REQUEST)?.[0]?.value as Uint8Array;
|
||||
const chatRequest = decodeMessage(requestPayload);
|
||||
const encodedMessages = (chatRequest.get(FIELD.Chat.MESSAGES) || []).map((entry) =>
|
||||
decodeMessage(entry.value as Uint8Array)
|
||||
);
|
||||
const decoder = new TextDecoder();
|
||||
const contents = encodedMessages.map((message) =>
|
||||
decoder.decode(message.get(FIELD.Message.CONTENT)?.[0]?.value as Uint8Array)
|
||||
);
|
||||
|
||||
expect(contents.some((content) => content.includes('<tool_result>'))).toBe(true);
|
||||
expect(contents.some((content) => content.includes('<tool_name>read_file</tool_name>'))).toBe(
|
||||
true
|
||||
);
|
||||
expect(
|
||||
contents.some((content) => content.includes('<tool_call_id>call_wire</tool_call_id>'))
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Edge cases', () => {
|
||||
|
||||
@@ -3,6 +3,27 @@ import { describe, expect, test } from 'bun:test';
|
||||
import { evaluateTargetRuntimeCompatibility } from '../../../src/targets/target-runtime-compatibility';
|
||||
|
||||
describe('evaluateTargetRuntimeCompatibility', () => {
|
||||
test('rejects account, copilot, and cursor profiles on Droid target', () => {
|
||||
expect(
|
||||
evaluateTargetRuntimeCompatibility({
|
||||
target: 'droid',
|
||||
profileType: 'account',
|
||||
}).supported
|
||||
).toBe(false);
|
||||
expect(
|
||||
evaluateTargetRuntimeCompatibility({
|
||||
target: 'droid',
|
||||
profileType: 'copilot',
|
||||
}).supported
|
||||
).toBe(false);
|
||||
expect(
|
||||
evaluateTargetRuntimeCompatibility({
|
||||
target: 'droid',
|
||||
profileType: 'cursor',
|
||||
}).supported
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test('supports native Codex default sessions', () => {
|
||||
expect(
|
||||
evaluateTargetRuntimeCompatibility({
|
||||
@@ -69,7 +90,7 @@ describe('evaluateTargetRuntimeCompatibility', () => {
|
||||
expect(genericSettingsCompatibility.reason).toMatch(/currently supports native default sessions/);
|
||||
});
|
||||
|
||||
test('rejects account and copilot profiles on Codex target', () => {
|
||||
test('rejects account, copilot, and cursor profiles on Codex target', () => {
|
||||
expect(
|
||||
evaluateTargetRuntimeCompatibility({
|
||||
target: 'codex',
|
||||
@@ -82,5 +103,11 @@ describe('evaluateTargetRuntimeCompatibility', () => {
|
||||
profileType: 'copilot',
|
||||
}).supported
|
||||
).toBe(false);
|
||||
expect(
|
||||
evaluateTargetRuntimeCompatibility({
|
||||
target: 'codex',
|
||||
profileType: 'cursor',
|
||||
}).supported
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -44,6 +44,44 @@ describe('image-analysis-backend-resolver', () => {
|
||||
expect(status.resolutionSource).toBe('copilot-alias');
|
||||
});
|
||||
|
||||
it('does not route cursor image analysis through the fallback backend by default', () => {
|
||||
const status = resolveImageAnalysisStatus(
|
||||
{
|
||||
profileName: 'cursor',
|
||||
profileType: 'cursor',
|
||||
},
|
||||
DEFAULT_IMAGE_ANALYSIS_CONFIG
|
||||
);
|
||||
|
||||
expect(status.supported).toBe(false);
|
||||
expect(status.backendId).toBeNull();
|
||||
expect(status.status).toBe('skipped');
|
||||
expect(status.resolutionSource).toBe('unresolved');
|
||||
expect(status.reason).toContain('profile_backends.cursor');
|
||||
});
|
||||
|
||||
it('allows cursor image analysis only when explicitly mapped to a backend', () => {
|
||||
const config: ImageAnalysisConfig = {
|
||||
...DEFAULT_IMAGE_ANALYSIS_CONFIG,
|
||||
profile_backends: {
|
||||
cursor: 'ghcp',
|
||||
},
|
||||
};
|
||||
|
||||
const status = resolveImageAnalysisStatus(
|
||||
{
|
||||
profileName: 'cursor',
|
||||
profileType: 'cursor',
|
||||
},
|
||||
config
|
||||
);
|
||||
|
||||
expect(status.supported).toBe(true);
|
||||
expect(status.backendId).toBe('ghcp');
|
||||
expect(status.status).toBe('mapped');
|
||||
expect(status.resolutionSource).toBe('profile-backend');
|
||||
});
|
||||
|
||||
it('uses the fallback backend for an unmapped third-party settings profile', () => {
|
||||
const status = resolveImageAnalysisStatus(
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user