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
131 changes: 131 additions & 0 deletions src/lib/executor-registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import {
findExecutorBySession,
getCurrentExecutor,
getExecutor,
getLiveExecutorState,
isExecutorAlive,
listExecutors,
terminateActiveExecutor,
terminateExecutor,
Expand Down Expand Up @@ -999,4 +1001,133 @@ describe.skipIf(!DB_AVAILABLE)('executor-registry', () => {
expect(agent!.currentExecutorId).toBe(active[0].id);
});
});

// ==========================================================================
// getLiveExecutorState / isExecutorAlive — liveness + display state for
// non-tmux transports (SDK, omni, process).
//
// Regression for `genie ls` showing SDK/omni-bridge agents as 'offline' while
// actively running. Tmux liveness (isPaneAlive) stays authoritative for tmux
// agents; `executors.state` is the authoritative source for everything else,
// and is returned directly so the display doesn't fall back to the stale
// `agents.state` column.
// ==========================================================================

describe('getLiveExecutorState', () => {
test('returns the executor state for each live state', async () => {
const liveStates: ExecutorState[] = ['spawning', 'running', 'working', 'idle', 'permission', 'question'];
for (const state of liveStates) {
const agentId = await seedAgent(`state-${state}`, 'live-team');
await createAndLinkExecutor(agentId, 'claude-sdk', 'process', { state });
expect(await getLiveExecutorState(agentId)).toBe(state);
}
});

test('returns null for terminal states (done / error / terminated)', async () => {
const terminalStates: ExecutorState[] = ['done', 'error', 'terminated'];
for (const terminal of terminalStates) {
const agentId = await seedAgent(`terminal-${terminal}`, 'terminal-team');
const exec = await createAndLinkExecutor(agentId, 'claude-sdk', 'process', { state: 'running' });
await updateExecutorState(exec.id, terminal);
expect(await getLiveExecutorState(agentId)).toBeNull();
}
});

test('returns null when agent has no current executor', async () => {
const agentId = await seedAgent();
expect(await getLiveExecutorState(agentId)).toBeNull();
});

test('returns null for nonexistent agent', async () => {
expect(await getLiveExecutorState('ghost-agent')).toBeNull();
});

test('tracks live → terminated transition', async () => {
const agentId = await seedAgent();
const exec = await createAndLinkExecutor(agentId, 'claude-sdk', 'process', { state: 'working' });
expect(await getLiveExecutorState(agentId)).toBe('working');

await updateExecutorState(exec.id, 'done');
expect(await getLiveExecutorState(agentId)).toBeNull();
});

test('works for process transport (SDK) with null pane id', async () => {
// Simulates the real bug: SDK agents register with paneId='sdk',
// omni auto-spawn with paneId=''. Neither matches /^%\d+$/ so
// isPaneAlive falsely reports offline. getLiveExecutorState bypasses that
// and returns the authoritative executor state.
const agentId = await seedAgent();
await createAndLinkExecutor(agentId, 'claude-sdk', 'process', {
state: 'working',
tmuxPaneId: null,
});
expect(await getLiveExecutorState(agentId)).toBe('working');
});
});

describe('isExecutorAlive', () => {
test('returns true when current executor is running', async () => {
const agentId = await seedAgent();
await createAndLinkExecutor(agentId, 'claude-sdk', 'process', { state: 'running' });
expect(await isExecutorAlive(agentId)).toBe(true);
});

test('returns true for each live state (working/idle/permission/question/spawning)', async () => {
const liveStates: ExecutorState[] = ['spawning', 'running', 'working', 'idle', 'permission', 'question'];
for (const state of liveStates) {
const agentId = await seedAgent(`agent-${state}`, 'live-team');
await createAndLinkExecutor(agentId, 'claude-sdk', 'process', { state });
expect(await isExecutorAlive(agentId)).toBe(true);
}
});

test('returns false when current executor is terminated', async () => {
const agentId = await seedAgent();
const exec = await createAndLinkExecutor(agentId, 'claude-sdk', 'process', { state: 'running' });
await updateExecutorState(exec.id, 'terminated');
expect(await isExecutorAlive(agentId)).toBe(false);
});

test('returns false for done / error terminal states', async () => {
const agent1 = await seedAgent('done-agent', 'terminal-team');
const e1 = await createAndLinkExecutor(agent1, 'claude-sdk', 'process', { state: 'running' });
await updateExecutorState(e1.id, 'done');
expect(await isExecutorAlive(agent1)).toBe(false);

const agent2 = await seedAgent('error-agent', 'terminal-team');
const e2 = await createAndLinkExecutor(agent2, 'claude-sdk', 'process', { state: 'running' });
await updateExecutorState(e2.id, 'error');
expect(await isExecutorAlive(agent2)).toBe(false);
});

test('returns false when agent has no current executor', async () => {
const agentId = await seedAgent();
expect(await isExecutorAlive(agentId)).toBe(false);
});

test('returns false for nonexistent agent', async () => {
expect(await isExecutorAlive('ghost-agent')).toBe(false);
});

test('tracks live → terminated transition', async () => {
const agentId = await seedAgent();
const exec = await createAndLinkExecutor(agentId, 'claude-sdk', 'process', { state: 'working' });
expect(await isExecutorAlive(agentId)).toBe(true);

await updateExecutorState(exec.id, 'done');
expect(await isExecutorAlive(agentId)).toBe(false);
});

test('works for process transport (SDK) with empty/synthetic pane ids', async () => {
// Simulates the real bug: SDK agents register with paneId='sdk',
// omni auto-spawn with paneId=''. Neither matches /^%\d+$/ so
// isPaneAlive falsely reports offline. isExecutorAlive bypasses that.
const agentId = await seedAgent();
await createAndLinkExecutor(agentId, 'claude-sdk', 'process', {
state: 'working',
tmuxPaneId: null,
});
expect(await isExecutorAlive(agentId)).toBe(true);
});
});
});
31 changes: 31 additions & 0 deletions src/lib/executor-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,34 @@ export async function updateClaudeSessionId(executorId: string, sessionId: strin
const sql = await getConnection();
await sql`UPDATE executors SET claude_session_id = ${sessionId} WHERE id = ${executorId}`;
}

/**
* Return an agent's current executor state iff it is live, else null.
*
* Used by `genie ls` to determine liveness for non-tmux transports (SDK, omni,
* process) where `isPaneAlive` cannot apply — these agents carry synthetic pane
* IDs like 'sdk' or '' that do not match tmux's `%N` format. The `executors.state`
* column is the authoritative signal, updated by each transport's own heartbeat
* (e.g., claude-sdk updates it on every message). Returning the state — not just
* a boolean — lets the caller display it directly without a second query; the
* cached `agents.state` column is stale for non-tmux transports.
*
* Treats `spawning|running|working|idle|permission|question` as live;
* `done|error|terminated` and missing rows return null.
*/
export async function getLiveExecutorState(agentId: string): Promise<ExecutorState | null> {
const sql = await getConnection();
const rows = await sql<{ state: ExecutorState }[]>`
SELECT e.state FROM executors e
JOIN agents a ON a.current_executor_id = e.id
WHERE a.id = ${agentId}
AND e.state IN ('spawning', 'running', 'working', 'idle', 'permission', 'question')
LIMIT 1
`;
return rows.length > 0 ? rows[0].state : null;
}
Comment on lines +271 to +281

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The getLiveExecutorState function returns null for terminal states (done, error, terminated). However, as noted in the function's documentation, the agents.state column is stale for non-tmux transports. By returning null for dead executors, you force the caller to fall back to this stale data, which can result in genie ls showing an incorrect status (e.g., offline instead of error) for crashed agents. Consider returning the authoritative executor state regardless of liveness and letting the caller determine how to handle terminal states.


/** Boolean convenience wrapper around {@link getLiveExecutorState}. */
export async function isExecutorAlive(agentId: string): Promise<boolean> {
return (await getLiveExecutorState(agentId)) !== null;
}
22 changes: 20 additions & 2 deletions src/term-commands/agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2134,14 +2134,32 @@ type WorkerStatus = {
autoResume?: boolean;
};

/**
* Resolve liveness + display state for a worker.
*
* - Tmux transport: `isPaneAlive(%N)` is authoritative and `agents.state` is
* kept in sync, so we preserve the legacy behavior exactly.
* - Non-tmux transports (SDK, omni, inline): pane IDs are synthetic ('sdk', '',
* 'inline') and fail tmux's regex, so we query `executors.state` directly.
* The cached `agents.state` is stale for these transports — we use the live
* executor state for display as well.
*/
async function resolveWorkerLiveness(w: registry.Agent): Promise<{ alive: boolean; state: string }> {
if (/^%\d+$/.test(w.paneId)) {
return { alive: await isPaneAlive(w.paneId), state: w.state };
}
const execState = await executorRegistry.getLiveExecutorState(w.id);
return { alive: execState !== null, state: execState ?? w.state };
Comment on lines +2148 to +2152

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Exclude identity rows when resolving worker liveness

registry.list() includes identity-only agent rows (from findOrCreateAgent) that have empty paneId but a live current_executor_id; with this new branch, those rows are treated as non-tmux and marked alive from executors.state. For tmux-backed workers this creates a duplicate entry keyed by the same role, and because buildWorkerStatusMap overwrites by name without stable ordering, genie ls can nondeterministically show the identity row’s stale executor state (often running) instead of the runtime row’s agents.state (idle/working).

Useful? React with 👍 / 👎.

}

/** Build a name → status map from registry workers, including resume info for dead agents. */
async function buildWorkerStatusMap(workers: registry.Agent[]): Promise<Map<string, WorkerStatus>> {
const statusMap = new Map<string, WorkerStatus>();
for (const w of workers) {
const name = w.role || w.id;
const alive = await isPaneAlive(w.paneId);
const { alive, state } = await resolveWorkerLiveness(w);
Comment on lines 2158 to +2160

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The loop performs sequential asynchronous calls to resolveWorkerLiveness, which involves external process executions (tmux) and database queries. This can lead to significant performance degradation when listing a large number of agents. Parallelizing these checks using Promise.all would improve responsiveness.

Suggested change
for (const w of workers) {
const name = w.role || w.id;
const alive = await isPaneAlive(w.paneId);
const { alive, state } = await resolveWorkerLiveness(w);
const results = await Promise.all(workers.map(async (w) => ({ w, ...(await resolveWorkerLiveness(w)) })));
for (const { w, alive, state } of results) {
const name = w.role || w.id;

if (alive) {
statusMap.set(name, { state: w.state, team: w.team || '-' });
statusMap.set(name, { state, team: w.team || '-' });
} else if (w.state === 'suspended' || w.state === 'error') {
const attempts = w.resumeAttempts ?? 0;
const max = w.maxResumeAttempts ?? 3;
Expand Down
Loading