Skip to content
23 changes: 23 additions & 0 deletions packages/cli/test/client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { JulesClient } from '../src/client';
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Your PR description mentions using node --experimental-strip-types, which requires explicit file extensions in import paths. To ensure the tests can run in that environment, you should add the .ts extension to this import.

Suggested change
import { JulesClient } from '../src/client';
import { JulesClient } from '../src/client.ts';

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We cannot add .ts extensions here — this was already tried and reverted in commits 77197d0 and 18b1090 because tsc errors with TS5097 ('An import path can only end with a .ts extension when allowImportingTsExtensions is enabled'). The project compiles with tsc without allowImportingTsExtensions, so .ts extensions in imports are not valid. The test runner used is node:test via tsc-compiled output, not --experimental-strip-types directly.

import assert from 'node:assert';
import { test } from 'node:test';

test('JulesClient constructor uses provided API key', () => {
const apiKey = 'test-api-key';
const client = new JulesClient(apiKey);
assert.strictEqual((client as any).apiKey, apiKey);
});

test('JulesClient constructor uses API key from environment if not provided', (t) => {
const originalEnvKey = process.env.JULES_API_KEY;
// We use direct mutation here because process.env is a special object
// and node:test mocks are not yet compatible with it for simple property replacement.
// Using t.after ensures the environment is restored regardless of test outcome.
process.env.JULES_API_KEY = 'env-api-key';
t.after(() => {
process.env.JULES_API_KEY = originalEnvKey;
});

const client = new JulesClient();
assert.strictEqual((client as any).apiKey, 'env-api-key');
});
Comment thread
GreyC marked this conversation as resolved.
Comment on lines +1 to +22
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current tests cover providing the API key directly and via an environment variable, which is great. However, to ensure full coverage of the JulesClient constructor's behavior, I recommend adding tests for two other important scenarios:

  • When the API key is sourced from the configuration file.
  • When no API key is available from any source, which should result in an error being thrown.

This will make the test suite more robust and prevent future regressions related to API key handling.

import { JulesClient } from '../src/client';
import assert from 'node:assert';
import { test } from 'node:test';
import * as fs from 'fs';

test('JulesClient constructor uses provided API key', () => {
  const apiKey = 'test-api-key';
  const client = new JulesClient(apiKey);
  assert.strictEqual((client as any).apiKey, apiKey);
});

test('JulesClient constructor uses API key from environment if not provided', (t) => {
  const originalEnvKey = process.env.JULES_API_KEY;
  process.env.JULES_API_KEY = 'env-api-key';
  t.after(() => {
    process.env.JULES_API_KEY = originalEnvKey;
  });

  const client = new JulesClient();
  assert.strictEqual((client as any).apiKey, 'env-api-key');
});

test('JulesClient constructor uses API key from config file', (t) => {
  const originalEnvKey = process.env.JULES_API_KEY;
  delete process.env.JULES_API_KEY;
  t.after(() => {
    process.env.JULES_API_KEY = originalEnvKey;
  });

  t.mock.method(fs, 'existsSync', () => true);
  t.mock.method(fs, 'readFileSync', () => JSON.stringify({ apiKey: 'config-api-key' }));

  const client = new JulesClient();
  assert.strictEqual((client as any).apiKey, 'config-api-key');
});

test('JulesClient constructor throws when no API key is found', (t) => {
  const originalEnvKey = process.env.JULES_API_KEY;
  delete process.env.JULES_API_KEY;
  t.after(() => {
    process.env.JULES_API_KEY = originalEnvKey;
  });

  t.mock.method(fs, 'existsSync', () => false);

  assert.throws(
    () => {
      new JulesClient();
    },
    {
      message: 'No API key found. Set JULES_API_KEY or run: jules_cli setup',
    }
  );
});

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jules Please add the two missing test cases suggested here:

  1. API key sourced from the config file (~/.config/jules/config.json) — mock the fs.readFileSync or the config reading logic to return a known key, and assert the constructor picks it up.
  2. Error thrown when no API key is available from any source — ensure no env var, no config file, no explicit arg, and assert that constructing JulesClient throws an error.

Do not add any temp directories. Only modify packages/cli/test/client.test.ts.

29 changes: 29 additions & 0 deletions temp_verify/src/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';

export function getApiKey(): string {
// 1. Check environment variable
const envKey = process.env.JULES_API_KEY;
if (envKey) {
return envKey;
}

// 2. Check config file: ~/.config/jules/config.json
const configPath = path.join(os.homedir(), '.config', 'jules', 'config.json');
try {
if (fs.existsSync(configPath)) {
const configContent = fs.readFileSync(configPath, 'utf8');
const config = JSON.parse(configContent);
if (config.apiKey) {
return config.apiKey;
}
}
} catch (error) {
console.error('Warning: could not read config file:', configPath);
}

// 3. Neither found, exit with error message
console.error('No API key found. Set JULES_API_KEY or run: jules_cli setup');
process.exit(1);
Comment thread
GreyC marked this conversation as resolved.
Outdated
}
114 changes: 114 additions & 0 deletions temp_verify/src/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { getApiKey } from './auth.ts';

const BASE_URL = 'https://jules.googleapis.com/v1alpha';

export class JulesClient {
private apiKey: string;

constructor(apiKey?: string) {
this.apiKey = apiKey || getApiKey();
}

private getHeaders(): Record<string, string> {
return {
'x-goog-api-key': this.apiKey,
'Content-Type': 'application/json',
};
}

static async validateKey(apiKey: string): Promise<boolean> {
const response = await fetch(`${BASE_URL}/sessions`, {
method: 'GET',
headers: {
'x-goog-api-key': apiKey,
'Content-Type': 'application/json',
},
});

if (!response.ok) {
throw new Error(`Failed to validate key: ${response.status} ${response.statusText}`);
}

return true;
}

async getSessions(): Promise<any> {
Comment thread
GreyC marked this conversation as resolved.
Outdated
const response = await fetch(`${BASE_URL}/sessions`, {
method: 'GET',
headers: this.getHeaders(),
});

if (!response.ok) {
throw new Error(`Failed to fetch sessions: ${response.status} ${response.statusText}`);
}

return response.json();
}

async getSession(id: string): Promise<any> {
const response = await fetch(`${BASE_URL}/sessions/${id}`, {
method: 'GET',
headers: this.getHeaders(),
});

if (!response.ok) {
throw new Error(`Failed to fetch session: ${response.status} ${response.statusText}`);
}

return response.json();
}

async createSession(options: any): Promise<any> {
Comment thread
GreyC marked this conversation as resolved.
Outdated
const response = await fetch(`${BASE_URL}/sessions`, {
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify(options),
});

if (!response.ok) {
throw new Error(`Failed to create session: ${response.status} ${response.statusText}`);
}

return response.json();
}

async approvePlan(id: string): Promise<any> {
const response = await fetch(`${BASE_URL}/sessions/${id}:approvePlan`, {
method: 'POST',
headers: this.getHeaders(),
});

if (!response.ok) {
throw new Error(`Failed to approve plan: ${response.status} ${response.statusText}`);
}

return response.json();
}

async sendMessage(id: string, message: string): Promise<any> {
const response = await fetch(`${BASE_URL}/sessions/${id}:sendMessage`, {
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify({ prompt: message }),
});

if (!response.ok) {
throw new Error(`Failed to send message: ${response.status} ${response.statusText}`);
}

return response.json();
}

async getActivities(id: string): Promise<any> {
const response = await fetch(`${BASE_URL}/sessions/${id}/activities`, {
method: 'GET',
headers: this.getHeaders(),
});

if (!response.ok) {
throw new Error(`Failed to fetch activities: ${response.status} ${response.statusText}`);
}

return response.json();
}
}
18 changes: 18 additions & 0 deletions temp_verify/test/client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { JulesClient } from '../src/client.ts';
import assert from 'node:assert';
import { test } from 'node:test';
import * as auth from '../src/auth.ts';

test('JulesClient constructor uses provided API key', () => {
const apiKey = 'test-api-key';
const client = new JulesClient(apiKey);
assert.strictEqual((client as any).apiKey, apiKey);
});

test('JulesClient constructor uses API key from auth if not provided', (t) => {
// Use node:test mock.method to mock the getApiKey function from the auth module
t.mock.method(auth, 'getApiKey', () => 'mock-api-key');

const client = new JulesClient();
assert.strictEqual((client as any).apiKey, 'mock-api-key');
});
Loading