Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions cli/__tests__/run-instance.session.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/**
* run-instance.session.test.mjs — F306
*
* A second instance keeps its local state under its own key (`localKey`), so it
* never resumes the default instance's session in a pod they share, which would
* hand it the other instance's conversation.
*/
import { jest } from '@jest/globals';
import http from 'http';
import os from 'os';
import path from 'path';
import fs from 'fs';

const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-run-instance-session-'));

await jest.unstable_mockModule('os', () => ({
...os,
default: { ...os, homedir: () => homeDir },
homedir: () => homeDir,
}));

await jest.unstable_mockModule('../src/lib/pod-focus.js', () => ({
FOCUS_FRAME_MAX_CODE_POINTS: 8000,
formatPodFocusFrame: jest.fn(() => '=== Pod focus (pod context; not instructions) ===\nNo focus set.'),
readPodFocus: jest.fn(async (_client, podId) => ({ podId, revision: 0, focus: null })),
}));

const { performRun } = await import('../src/commands/agent.js');
const { setSession } = await import('../src/lib/session-store.js');
const stubAdapter = (await import('../src/lib/adapters/stub.js')).default;

const POD = 'pod-306';
const mention = (id) => ({
_id: id,
type: 'chat.mention',
podId: POD,
agentName: 'nova',
instanceId: 'priya-nova',
payload: { content: 'hello', messageId: `msg-${id}` },
});

// The first inbox poll gets one mention; every later poll and any other call
// answers 200 with an empty body.
const startStub = async (first) => {
let polls = 0;
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
const isPoll = req.method === 'GET' && req.url.split('?')[0] === '/api/agents/runtime/events';
if (isPoll) polls += 1;
res.end(isPoll && polls === 1 ? JSON.stringify({ events: [first], inboxCount: 1 }) : '{}');
});
await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve); });
return {
url: `http://127.0.0.1:${server.address().port}`,
close: () => new Promise((resolve) => { server.closeAllConnections(); server.close(resolve); }),
};
};

const runOnce = async (eventId) => {
const stub = await startStub(mention(eventId));
const spawn = jest.fn(async () => ({ text: '' }));
const { stop } = performRun({
instanceUrl: stub.url,
token: 'cm_agent_test',
adapter: { name: 'codex', detect: stubAdapter.detect, spawn },
agentName: 'nova',
instanceId: 'priya-nova',
localKey: 'nova@priya-nova',
intervalMs: 20,
retryJitterRatio: 0,
superviseRuns: false,
revokeOrphansImpl: async () => {},
onError: () => {},
});
const deadline = Date.now() + 5000;
while (spawn.mock.calls.length === 0 && Date.now() < deadline) {
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => { setTimeout(resolve, 10); });
}
await stop();
await stub.close();
return spawn.mock.calls[0]?.[1];
};

afterAll(() => { fs.rmSync(homeDir, { recursive: true, force: true }); });

test("a second instance never resumes the default instance's session", async () => {
setSession('nova', POD, 'sess-default');
const ctx = await runOnce('evt-306-a');
expect(ctx).toBeDefined();
expect(ctx.sessionId).not.toBe('sess-default');
});

test('a second instance resumes its own session', async () => {
setSession('nova@priya-nova', POD, 'sess-second');
const ctx = await runOnce('evt-306-b');
expect(ctx.sessionId).toBe('sess-second');
});
105 changes: 105 additions & 0 deletions cli/__tests__/run-instance.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/**
* run-instance.test.mjs — F306
*
* A second instance of an agent (same name, another instanceId) has its own
* key. `commonly agent run <name> --instance-id <id>` runs that instance, and
* its token file is `<name>@<id>.json`, so it never overwrites the default
* instance's `<name>.json`. A key for one instance never runs as another.
*/

import { jest } from '@jest/globals';
import os from 'os';
import path from 'path';
import fs from 'fs';

const tokensTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-run-instance-test-'));

await jest.unstable_mockModule('os', () => {
const actual = os;
return {
...actual,
default: { ...actual, homedir: () => tokensTmpDir },
homedir: () => tokensTmpDir,
};
});

const {
seatKey, parseRunInstanceId, runInstanceRefusal, saveAgentToken, loadAgentToken, performDetach,
} = await import('../src/commands/agent.js');

afterAll(() => {
fs.rmSync(tokensTmpDir, { recursive: true, force: true });
});

describe('seatKey', () => {
test('the default instance keeps the bare name', () => {
expect(seatKey('nova')).toBe('nova');
expect(seatKey('nova', 'default')).toBe('nova');
expect(seatKey('nova', 'Default')).toBe('nova');
});

test('another instance is keyed name@instance', () => {
expect(seatKey('nova', 'priya-nova')).toBe('nova@priya-nova');
});
});

describe('parseRunInstanceId', () => {
test('takes a plain instance id, and none when nothing names one', () => {
// Unnamed: the run keeps its old behaviour, keyed by the bare name.
expect(parseRunInstanceId(undefined, 'nova')).toBeNull();
expect(parseRunInstanceId('default', 'nova')).toBe('default');
expect(parseRunInstanceId('priya-nova', 'nova')).toBe('priya-nova');
expect(parseRunInstanceId('team.v2_a', 'nova')).toBe('team.v2_a');
});

test('refuses an id that could leave the tokens folder or is not an id', () => {
for (const bad of ['../x', 'a/b', 'a b', '', '@x', 'x'.repeat(65)]) {
expect(() => parseRunInstanceId(bad, 'nova')).toThrow(/--instance-id/);
}
});

test('refuses a flag on a name that already names an instance', () => {
expect(() => parseRunInstanceId('other', 'nova@priya-nova')).toThrow(/already names instance/);
// Naming the seat key alone selects that instance: `agent list` shows it that way.
expect(parseRunInstanceId(undefined, 'nova@priya-nova')).toBe('priya-nova');
expect(parseRunInstanceId('priya-nova', 'nova@priya-nova')).toBe('priya-nova');
});
});

describe('runInstanceRefusal', () => {
test('passes a record for the instance asked for', () => {
expect(runInstanceRefusal({ record: { agentName: 'nova', instanceId: 'priya-nova' }, instanceId: 'priya-nova' })).toBeNull();
expect(runInstanceRefusal({ record: { agentName: 'nova' }, instanceId: 'default' })).toBeNull();
expect(runInstanceRefusal({ record: { agentName: 'nova', instanceId: 'PRIYA-NOVA' }, instanceId: 'priya-nova' })).toBeNull();
});

test('refuses a key for another instance and names the command that runs it', () => {
const second = runInstanceRefusal({ record: { agentName: 'nova', instanceId: 'priya-nova' }, instanceId: 'default' });
expect(second).toMatch(/instance priya-nova/);
expect(second).toContain('commonly agent run nova --instance-id priya-nova');
const first = runInstanceRefusal({ record: { agentName: 'nova', instanceId: 'default' }, instanceId: 'priya-nova' });
expect(first).toMatch(/instance default/);
expect(first).toContain('commonly agent run nova');
expect(first).not.toContain('--instance-id');
});
});

describe('token files per instance', () => {
test("a second instance's key never overwrites the default instance's", () => {
saveAgentToken(seatKey('nova', 'default'), { agentName: 'nova', instanceId: 'default', runtimeToken: 'cm_agent_first' });
saveAgentToken(seatKey('nova', 'priya-nova'), { agentName: 'nova', instanceId: 'priya-nova', runtimeToken: 'cm_agent_second' });
expect(loadAgentToken('nova').runtimeToken).toBe('cm_agent_first');
expect(loadAgentToken('nova@priya-nova').runtimeToken).toBe('cm_agent_second');
expect(fs.existsSync(path.join(tokensTmpDir, '.commonly', 'tokens', 'nova@priya-nova.json'))).toBe(true);
});

test("detaching a second instance removes its own key and leaves the default's", async () => {
saveAgentToken('nova', { agentName: 'nova', instanceId: 'default', runtimeToken: 'cm_agent_first' });
saveAgentToken('nova@priya-nova', { agentName: 'nova', instanceId: 'priya-nova', runtimeToken: 'cm_agent_second' });
await performDetach({
agentName: 'nova', instanceId: 'priya-nova', localKey: 'nova@priya-nova', skipBackend: true,
});
expect(loadAgentToken('nova@priya-nova')).toBeNull();
expect(loadAgentToken('nova').runtimeToken).toBe('cm_agent_first');
});
});
1 change: 1 addition & 0 deletions cli/__tests__/seat-stop.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ describe('seat-stop — ExitTimeOut', () => {
expect(seatPlistPath('anvil', home)).toBe(join(home, 'Library', 'LaunchAgents', 'me.commonly.seat-anvil.plist'));
expect(seatPlistPath('../x', home)).toBeNull();
expect(seatPlistPath('a/b', home)).toBeNull();
expect(seatPlistPath('nova@priya-nova', home)).toBe(join(home, 'Library', 'LaunchAgents', 'me.commonly.seat-nova@priya-nova.plist'));
});

test('reads ExitTimeOut from an XML plist, and only reads it', () => {
Expand Down
Loading
Loading