mirror of
https://github.com/tiennm99/ccs.git
synced 2026-10-16 22:14:21 +00:00
fix(cursor): resolve review feedback and harden edge cases
This commit is contained in:
1 parent
c639cefa7b
commit
4798741a99
13 files changed
+746
-114
No files matched your search
@@ -431,11 +431,23 @@ describe('autoDetectTokens', () => {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = autoDetectTokens();
|
||||
const originalHome = process.env.HOME;
|
||||
const isolatedHome = path.join(tempDir, 'no-cursor-home');
|
||||
process.env.HOME = isolatedHome;
|
||||
|
||||
// Should fail because Cursor database doesn't exist in test environment
|
||||
expect(result.found).toBe(false);
|
||||
expect(result.error).toBeDefined();
|
||||
try {
|
||||
const result = autoDetectTokens();
|
||||
|
||||
// Should fail because isolated test home has no Cursor database
|
||||
expect(result.found).toBe(false);
|
||||
expect(result.error).toBeDefined();
|
||||
} finally {
|
||||
if (originalHome !== undefined) {
|
||||
process.env.HOME = originalHome;
|
||||
} else {
|
||||
delete process.env.HOME;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should have found property in return type', () => {
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
} from '../../../src/cursor/cursor-daemon';
|
||||
import { getCcsDir } from '../../../src/utils/config-manager';
|
||||
import { handleCursorCommand } from '../../../src/commands/cursor-command';
|
||||
import { loadCredentials } from '../../../src/cursor/cursor-auth';
|
||||
import { loadCredentials, saveCredentials } from '../../../src/cursor/cursor-auth';
|
||||
|
||||
// Test isolation
|
||||
let originalCcsHome: string | undefined;
|
||||
@@ -181,6 +181,93 @@ describe('startDaemon', () => {
|
||||
},
|
||||
35000
|
||||
);
|
||||
|
||||
it('returns 404 for unknown routes', async () => {
|
||||
const port = 10000 + Math.floor(Math.random() * 50000);
|
||||
const result = await startDaemon({ port, ghost_mode: true });
|
||||
expect(result.success).toBe(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${port}/unknown`);
|
||||
expect(response.status).toBe(404);
|
||||
} finally {
|
||||
await stopDaemon();
|
||||
}
|
||||
});
|
||||
|
||||
it('returns 401 when credentials are expired', async () => {
|
||||
const port = 10000 + Math.floor(Math.random() * 50000);
|
||||
const expiredAt = new Date(Date.now() - 26 * 60 * 60 * 1000).toISOString();
|
||||
|
||||
saveCredentials({
|
||||
accessToken: 'a'.repeat(60),
|
||||
machineId: '1234567890abcdef1234567890abcdef',
|
||||
authMethod: 'manual',
|
||||
importedAt: expiredAt,
|
||||
});
|
||||
|
||||
const result = await startDaemon({ port, ghost_mode: true });
|
||||
expect(result.success).toBe(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model: 'gpt-4.1',
|
||||
messages: [{ role: 'user', content: 'hello' }],
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
const body = (await response.json()) as { error?: { message?: string } };
|
||||
expect(body.error?.message).toContain('expired');
|
||||
} finally {
|
||||
await stopDaemon();
|
||||
}
|
||||
});
|
||||
|
||||
it('validates invalid JSON, invalid message schema, and oversized body', async () => {
|
||||
const port = 10000 + Math.floor(Math.random() * 50000);
|
||||
const result = await startDaemon({ port, ghost_mode: true });
|
||||
expect(result.success).toBe(true);
|
||||
|
||||
try {
|
||||
const invalidJson = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{invalid-json',
|
||||
});
|
||||
expect(invalidJson.status).toBe(400);
|
||||
|
||||
const invalidSchema = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model: 'gpt-4.1',
|
||||
messages: { role: 'user', content: 'hello' },
|
||||
}),
|
||||
});
|
||||
expect(invalidSchema.status).toBe(400);
|
||||
|
||||
const oversized = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model: 'gpt-4.1',
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: 'x'.repeat(10 * 1024 * 1024 + 1024),
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
expect(oversized.status).toBe(413);
|
||||
} finally {
|
||||
await stopDaemon();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('isDaemonRunning', () => {
|
||||
|
||||
@@ -99,12 +99,52 @@ describe('formatModelName', () => {
|
||||
|
||||
describe('fetchModelsFromDaemon', () => {
|
||||
it('falls back to DEFAULT_CURSOR_MODELS when daemon is unreachable', async () => {
|
||||
// Use a port that nothing is listening on
|
||||
const unreachablePort = 9999;
|
||||
const models = await fetchModelsFromDaemon(unreachablePort);
|
||||
|
||||
expect(models).toEqual(DEFAULT_CURSOR_MODELS);
|
||||
});
|
||||
|
||||
it('falls back to defaults when daemon returns invalid JSON', async () => {
|
||||
const server = http.createServer((_req, res) => {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end('{not-valid-json');
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') {
|
||||
throw new Error('Unable to resolve test server port');
|
||||
}
|
||||
|
||||
try {
|
||||
const models = await fetchModelsFromDaemon(address.port);
|
||||
expect(models).toEqual(DEFAULT_CURSOR_MODELS);
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it('falls back to defaults when daemon response exceeds max body size', async () => {
|
||||
const oversizedPayload = 'x'.repeat(1024 * 1024 + 1024);
|
||||
const server = http.createServer((_req, res) => {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(oversizedPayload);
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') {
|
||||
throw new Error('Unable to resolve test server port');
|
||||
}
|
||||
|
||||
try {
|
||||
const models = await fetchModelsFromDaemon(address.port);
|
||||
expect(models).toEqual(DEFAULT_CURSOR_MODELS);
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchModelsFromCursorApi', () => {
|
||||
@@ -176,6 +216,90 @@ describe('fetchModelsFromCursorApi', () => {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it('parses response.models and filters invalid records', async () => {
|
||||
const server = http.createServer((_req, res) => {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
models: [
|
||||
{ id: 'gpt-5.3-codex', name: 'GPT-5.3 Codex' },
|
||||
{ id: '', name: 'invalid-empty-id' },
|
||||
{ id: 123, name: 'invalid-type-id' },
|
||||
],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') {
|
||||
throw new Error('Unable to resolve test server port');
|
||||
}
|
||||
|
||||
try {
|
||||
const models = await fetchModelsFromCursorApi(
|
||||
{
|
||||
accessToken: 'test-token-123',
|
||||
machineId: '1234567890abcdef1234567890abcdef',
|
||||
},
|
||||
{
|
||||
endpoint: `http://127.0.0.1:${address.port}/v1/models`,
|
||||
timeoutMs: 2000,
|
||||
}
|
||||
);
|
||||
|
||||
expect(models).not.toBeNull();
|
||||
expect(models).toHaveLength(1);
|
||||
expect(models?.[0].id).toBe('gpt-5.3-codex');
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it('returns null when required credentials are missing', async () => {
|
||||
const models = await fetchModelsFromCursorApi(
|
||||
{
|
||||
accessToken: '',
|
||||
machineId: '1234567890abcdef1234567890abcdef',
|
||||
},
|
||||
{
|
||||
endpoint: 'http://127.0.0.1:9/v1/models',
|
||||
timeoutMs: 50,
|
||||
}
|
||||
);
|
||||
|
||||
expect(models).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null on timeout/abort', async () => {
|
||||
const server = http.createServer((_req, _res) => {
|
||||
// Intentionally no response within timeout.
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') {
|
||||
throw new Error('Unable to resolve test server port');
|
||||
}
|
||||
|
||||
try {
|
||||
const models = await fetchModelsFromCursorApi(
|
||||
{
|
||||
accessToken: 'test-token-123',
|
||||
machineId: '1234567890abcdef1234567890abcdef',
|
||||
},
|
||||
{
|
||||
endpoint: `http://127.0.0.1:${address.port}/v1/models`,
|
||||
timeoutMs: 25,
|
||||
}
|
||||
);
|
||||
|
||||
expect(models).toBeNull();
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('getModelsForDaemon', () => {
|
||||
@@ -229,4 +353,68 @@ describe('getModelsForDaemon', () => {
|
||||
|
||||
expect(second[0]?.id).toBe(liveModelId);
|
||||
});
|
||||
|
||||
it('clears cache after auth failures and falls back to defaults', async () => {
|
||||
const liveModelId = 'test-live-model-auth-cache';
|
||||
const okServer = http.createServer((_req, res) => {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
data: [{ id: liveModelId, name: 'Live Model', provider: 'openai' }],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => okServer.listen(0, '127.0.0.1', resolve));
|
||||
const okAddress = okServer.address();
|
||||
if (!okAddress || typeof okAddress === 'string') {
|
||||
throw new Error('Unable to resolve test server port');
|
||||
}
|
||||
|
||||
try {
|
||||
const first = await getModelsForDaemon({
|
||||
credentials: {
|
||||
accessToken: 'test-token-123',
|
||||
machineId: '1234567890abcdef1234567890abcdef',
|
||||
},
|
||||
endpoint: `http://127.0.0.1:${okAddress.port}/v1/models`,
|
||||
timeoutMs: 2000,
|
||||
});
|
||||
|
||||
expect(first[0]?.id).toBe(liveModelId);
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => okServer.close(() => resolve()));
|
||||
}
|
||||
|
||||
const forbiddenServer = http.createServer((_req, res) => {
|
||||
res.writeHead(403, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: 'forbidden' }));
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => forbiddenServer.listen(0, '127.0.0.1', resolve));
|
||||
const forbiddenAddress = forbiddenServer.address();
|
||||
if (!forbiddenAddress || typeof forbiddenAddress === 'string') {
|
||||
throw new Error('Unable to resolve test server port');
|
||||
}
|
||||
|
||||
try {
|
||||
const forbidden = await fetchModelsFromCursorApi(
|
||||
{
|
||||
accessToken: 'test-token-123',
|
||||
machineId: '1234567890abcdef1234567890abcdef',
|
||||
},
|
||||
{
|
||||
endpoint: `http://127.0.0.1:${forbiddenAddress.port}/v1/models`,
|
||||
timeoutMs: 2000,
|
||||
}
|
||||
);
|
||||
|
||||
expect(forbidden).toBeNull();
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => forbiddenServer.close(() => resolve()));
|
||||
}
|
||||
|
||||
const afterAuthFailure = await getModelsForDaemon();
|
||||
expect(afterAuthFailure).toEqual(DEFAULT_CURSOR_MODELS);
|
||||
});
|
||||
});
|
||||
@@ -371,18 +371,12 @@ describe('Request Encoding', () => {
|
||||
it('should handle multi-frame buffer', () => {
|
||||
const executor = new CursorExecutor();
|
||||
|
||||
// Create two simple frames
|
||||
const frame1 = wrapConnectRPCFrame(
|
||||
encodeField(FIELD.ChatResponse.TEXT, WIRE_TYPE.LEN, 'Frame 1'),
|
||||
false
|
||||
);
|
||||
const frame2 = wrapConnectRPCFrame(
|
||||
encodeField(FIELD.ChatResponse.TEXT, WIRE_TYPE.LEN, ' Frame 2'),
|
||||
false
|
||||
);
|
||||
// Build two valid response frames (top-level Response.RESPONSE wrapper).
|
||||
const frame1 = buildTextFrame('Frame 1');
|
||||
const frame2 = buildTextFrame(' Frame 2');
|
||||
|
||||
// Concatenate them
|
||||
const multiFrame = Buffer.concat([Buffer.from(frame1), Buffer.from(frame2)]);
|
||||
const multiFrame = Buffer.concat([frame1, frame2]);
|
||||
|
||||
const result = executor.transformProtobufToJSON(multiFrame, 'gpt-4', {
|
||||
messages: [],
|
||||
@@ -457,6 +451,29 @@ describe('CursorExecutor', () => {
|
||||
expect(headers.authorization).toBe('Bearer actual-token');
|
||||
});
|
||||
|
||||
it('should throw when token becomes empty after delimiter parsing', () => {
|
||||
const credentials = {
|
||||
accessToken: 'prefix::',
|
||||
machineId: 'test-machine-id',
|
||||
};
|
||||
|
||||
expect(() => executor.buildHeaders(credentials)).toThrow('Access token is empty');
|
||||
});
|
||||
|
||||
it('should include normalized platform and timezone headers', () => {
|
||||
const credentials = {
|
||||
accessToken: 'test-token',
|
||||
machineId: 'test-machine-id',
|
||||
};
|
||||
|
||||
const headers = executor.buildHeaders(credentials);
|
||||
|
||||
expect(['windows', 'macos', 'linux']).toContain(headers['x-cursor-client-os']);
|
||||
expect(['aarch64', 'x64']).toContain(headers['x-cursor-client-arch']);
|
||||
expect(typeof headers['x-cursor-timezone']).toBe('string');
|
||||
expect(headers['x-cursor-timezone'].length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should respect ghostMode flag', () => {
|
||||
const credentialsGhost = {
|
||||
accessToken: 'test-token',
|
||||
@@ -553,6 +570,33 @@ describe('CursorExecutor', () => {
|
||||
expect(body.choices[0].message.content).toBe(textContent);
|
||||
expect(body.choices[0].message.reasoning_content).toBe(thinkingContent);
|
||||
});
|
||||
|
||||
it('should merge fragmented tool call arguments and set tool_calls finish reason', async () => {
|
||||
const frame1 = buildToolCallFrame({
|
||||
id: 'call_123',
|
||||
name: 'search_docs',
|
||||
args: '{"q":"hel',
|
||||
isLast: false,
|
||||
});
|
||||
const frame2 = buildToolCallFrame({
|
||||
id: 'call_123',
|
||||
name: 'search_docs',
|
||||
args: 'lo"}',
|
||||
isLast: true,
|
||||
});
|
||||
const combined = Buffer.concat([frame1, frame2]);
|
||||
|
||||
const result = executor.transformProtobufToJSON(combined, 'gpt-4', {
|
||||
messages: [],
|
||||
});
|
||||
|
||||
expect(result.status).toBe(200);
|
||||
const body = JSON.parse(await result.text());
|
||||
expect(body.choices[0].finish_reason).toBe('tool_calls');
|
||||
expect(body.choices[0].message.tool_calls[0].id).toBe('call_123');
|
||||
expect(body.choices[0].message.tool_calls[0].function.name).toBe('search_docs');
|
||||
expect(body.choices[0].message.tool_calls[0].function.arguments).toBe('{"q":"hello"}');
|
||||
});
|
||||
});
|
||||
|
||||
describe('transformProtobufToSSE', () => {
|
||||
@@ -611,6 +655,32 @@ describe('CursorExecutor', () => {
|
||||
expect(bodyText).toContain('reasoning_content');
|
||||
expect(bodyText).toContain(thinkingContent);
|
||||
});
|
||||
|
||||
it('should emit tool call deltas and end with finish_reason tool_calls', async () => {
|
||||
const frame1 = buildToolCallFrame({
|
||||
id: 'call_abc',
|
||||
name: 'search_docs',
|
||||
args: '{"q":"foo',
|
||||
isLast: false,
|
||||
});
|
||||
const frame2 = buildToolCallFrame({
|
||||
id: 'call_abc',
|
||||
name: 'search_docs',
|
||||
args: '"}',
|
||||
isLast: true,
|
||||
});
|
||||
const combined = Buffer.concat([frame1, frame2]);
|
||||
|
||||
const result = executor.transformProtobufToSSE(combined, 'gpt-4', {
|
||||
messages: [],
|
||||
});
|
||||
|
||||
expect(result.status).toBe(200);
|
||||
const bodyText = await result.text();
|
||||
expect(bodyText).toContain('tool_calls');
|
||||
expect(bodyText).toContain('search_docs');
|
||||
expect(bodyText).toContain('"finish_reason":"tool_calls"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('decompressPayload error handling', () => {
|
||||
@@ -725,6 +795,25 @@ function buildThinkingFrame(thinking: string): Buffer {
|
||||
return buildFrame(responseMsg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: build a protobuf tool call response frame
|
||||
*/
|
||||
function buildToolCallFrame(options: {
|
||||
id: string;
|
||||
name: string;
|
||||
args: string;
|
||||
isLast: boolean;
|
||||
}): Buffer {
|
||||
const toolCallPayload = concatArrays(
|
||||
encodeField(FIELD.ToolCall.ID, WIRE_TYPE.LEN, options.id),
|
||||
encodeField(FIELD.ToolCall.NAME, WIRE_TYPE.LEN, options.name),
|
||||
encodeField(FIELD.ToolCall.RAW_ARGS, WIRE_TYPE.LEN, options.args),
|
||||
encodeField(FIELD.ToolCall.IS_LAST, WIRE_TYPE.VARINT, options.isLast ? 1 : 0)
|
||||
);
|
||||
const responseMsg = encodeField(FIELD.Response.TOOL_CALL, WIRE_TYPE.LEN, toolCallPayload);
|
||||
return buildFrame(responseMsg);
|
||||
}
|
||||
|
||||
describe('StreamingFrameParser', () => {
|
||||
it('should parse a complete single frame', () => {
|
||||
const parser = new StreamingFrameParser();
|
||||
@@ -845,6 +934,39 @@ describe('StreamingFrameParser', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('should parse tool call frames', () => {
|
||||
const parser = new StreamingFrameParser();
|
||||
const frame = buildToolCallFrame({
|
||||
id: 'call_parser',
|
||||
name: 'search_docs',
|
||||
args: '{"q":"docs"}',
|
||||
isLast: true,
|
||||
});
|
||||
const results = parser.push(frame);
|
||||
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0].type).toBe('toolCall');
|
||||
if (results[0].type === 'toolCall') {
|
||||
expect(results[0].toolCall.id).toBe('call_parser');
|
||||
expect(results[0].toolCall.function.name).toBe('search_docs');
|
||||
expect(results[0].toolCall.function.arguments).toBe('{"q":"docs"}');
|
||||
expect(results[0].toolCall.isLast).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should classify malformed protobuf payload as server error', () => {
|
||||
const parser = new StreamingFrameParser();
|
||||
const malformedFrame = buildFrame(new Uint8Array([0xff, 0xff, 0xff]));
|
||||
const results = parser.push(malformedFrame);
|
||||
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0].type).toBe('error');
|
||||
if (results[0].type === 'error') {
|
||||
expect(results[0].errorType).toBe('server_error');
|
||||
expect(results[0].message).toContain('Malformed protobuf response');
|
||||
}
|
||||
});
|
||||
|
||||
it('should report hasPartial() correctly', () => {
|
||||
const parser = new StreamingFrameParser();
|
||||
expect(parser.hasPartial()).toBe(false);
|
||||
|
||||
Reference in new issue
Block a user