Skip to content

Commit c1fc17e

Browse files
igorcostaAutohand Evolve
andcommitted
Close out final-review findings for the /ps and /stop background-process controls
Adds the spec-mandated interactive-only regression test for /ps and /stop to the parametrized gating suite, then works through the remaining polish items from the whole-branch review: killProcessGroup's four near-identical platform-fallback blocks collapse into a single attemptKill helper (with the already-dead fast-path preserved so shutdown timing is unchanged); a shared formatBackgroundProcessEntry formatter replaces the duplicated per-command rendering in ps.ts and stop.ts so the ambiguous-target listing in /stop now matches /ps exactly, as the design spec requires; the killProcessGroup fallback test no longer leaks a live child process on assertion failure; and BackgroundProcessRegistry.stop() carries a comment documenting the narrow, inherent pid-reuse race, which is accepted rather than fixed since it can't be closed portably. Rounds out coverage with an empty-registry killAll() test, a /ps uptime-format assertion, and /stop boundary tests for "0", "-1", "1.5", and an empty-string argument. Co-authored-by: Autohand Evolve <code-noreply@autohand.ai>
1 parent 5bb5225 commit c1fc17e

9 files changed

Lines changed: 91 additions & 54 deletions

File tree

‎src/actions/command.ts‎

Lines changed: 27 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,28 @@ export function runCommand(
363363
});
364364
}
365365

366+
/**
367+
* Send a signal to a detached process group, falling back to a direct pid
368+
* kill on Windows or if the group no longer exists. Returns whether the
369+
* signal was delivered to something — false means the pid is already gone.
370+
*/
371+
function attemptKill(pid: number, signal: NodeJS.Signals): boolean {
372+
if (process.platform !== 'win32') {
373+
try {
374+
process.kill(-pid, signal);
375+
return true;
376+
} catch {
377+
// Process group doesn't exist or already gone; fall back to direct kill.
378+
}
379+
}
380+
try {
381+
process.kill(pid, signal);
382+
return true;
383+
} catch {
384+
return false;
385+
}
386+
}
387+
366388
/**
367389
* Send SIGTERM to a detached process group, then SIGKILL after a grace
368390
* period if it hasn't exited. Used to stop background processes tracked
@@ -373,48 +395,15 @@ export async function killProcessGroup(
373395
pid: number,
374396
gracePeriodMs: number = DEFAULT_KILL_GRACE_PERIOD_MS,
375397
): Promise<void> {
376-
// Try process-group kill on POSIX; fall back to direct kill on Windows or if it fails.
377-
if (process.platform !== 'win32') {
378-
try {
379-
process.kill(-pid, 'SIGTERM');
380-
} catch {
381-
// Process group doesn't exist or already gone; fall back to direct kill.
382-
try {
383-
process.kill(pid, 'SIGTERM');
384-
} catch {
385-
// Already dead.
386-
return;
387-
}
388-
}
389-
} else {
390-
// Windows doesn't support process groups; try direct kill.
391-
try {
392-
process.kill(pid, 'SIGTERM');
393-
} catch {
394-
return;
395-
}
398+
if (!attemptKill(pid, 'SIGTERM')) {
399+
// Already dead — no point waiting out the grace period.
400+
return;
396401
}
397402

398403
await new Promise<void>((resolve) => {
399404
const timer = setTimeout(() => {
400-
// Grace period elapsed; escalate to SIGKILL with same fallback pattern.
401-
if (process.platform !== 'win32') {
402-
try {
403-
process.kill(-pid, 'SIGKILL');
404-
} catch {
405-
try {
406-
process.kill(pid, 'SIGKILL');
407-
} catch {
408-
// Already dead.
409-
}
410-
}
411-
} else {
412-
try {
413-
process.kill(pid, 'SIGKILL');
414-
} catch {
415-
// Already dead.
416-
}
417-
}
405+
// Grace period elapsed; escalate to SIGKILL regardless of outcome.
406+
attemptKill(pid, 'SIGKILL');
418407
resolve();
419408
}, gracePeriodMs);
420409
timer.unref?.();

‎src/commands/ps.ts‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,13 @@
44
* SPDX-License-Identifier: Apache-2.0
55
*/
66
import chalk from 'chalk';
7+
import { formatBackgroundProcessEntry } from '../core/agent/BackgroundProcessRegistry.js';
78
import type { BackgroundProcessRegistry } from '../core/agent/BackgroundProcessRegistry.js';
89

910
export interface PsCommandContext {
1011
backgroundProcessRegistry?: BackgroundProcessRegistry;
1112
}
1213

13-
function formatElapsed(startedAt: number): string {
14-
const totalSeconds = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
15-
const minutes = Math.floor(totalSeconds / 60);
16-
const seconds = totalSeconds % 60;
17-
return `${minutes}m${seconds.toString().padStart(2, '0')}s`;
18-
}
19-
2014
/**
2115
* List background shell processes the agent currently has running.
2216
*/
@@ -26,9 +20,7 @@ export async function ps(ctx: PsCommandContext): Promise<string> {
2620
return 'No background processes running.';
2721
}
2822

29-
const lines = entries.map((entry) => (
30-
`${entry.id} ${entry.command} (pid ${entry.pid}, running ${formatElapsed(entry.startedAt)})`
31-
));
23+
const lines = entries.map(formatBackgroundProcessEntry);
3224
return `${chalk.bold('Background processes:')}\n${lines.join('\n')}`;
3325
}
3426

‎src/commands/stop.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@
33
* Copyright 2025 Autohand AI LLC
44
* SPDX-License-Identifier: Apache-2.0
55
*/
6+
import { formatBackgroundProcessEntry } from '../core/agent/BackgroundProcessRegistry.js';
67
import type { BackgroundProcessEntry, BackgroundProcessRegistry } from '../core/agent/BackgroundProcessRegistry.js';
78

89
export interface StopCommandContext {
910
backgroundProcessRegistry?: BackgroundProcessRegistry;
1011
}
1112

1213
function formatEntryList(entries: BackgroundProcessEntry[]): string {
13-
return entries.map((entry) => `${entry.id} ${entry.command} (pid ${entry.pid})`).join('\n');
14+
return entries.map(formatBackgroundProcessEntry).join('\n');
1415
}
1516

1617
/**

‎src/core/agent/BackgroundProcessRegistry.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,14 @@ export interface StopResult {
1818
message: string;
1919
}
2020

21+
/** Shared one-line rendering of a background process entry, used by both /ps and /stop. */
22+
export function formatBackgroundProcessEntry(entry: BackgroundProcessEntry): string {
23+
const totalSeconds = Math.max(0, Math.floor((Date.now() - entry.startedAt) / 1000));
24+
const minutes = Math.floor(totalSeconds / 60);
25+
const seconds = totalSeconds % 60;
26+
return `${entry.id} ${entry.command} (pid ${entry.pid}, running ${minutes}m${seconds.toString().padStart(2, '0')}s)`;
27+
}
28+
2129
/**
2230
* Session-scoped registry of currently-running background shell processes,
2331
* backing the /ps and /stop slash commands. `id` is a monotonically
@@ -47,6 +55,11 @@ export class BackgroundProcessRegistry {
4755
return this.entries.get(id);
4856
}
4957

58+
// Kills by pid, not a live handle, so there's a narrow inherent race: if the OS
59+
// reuses this pid as a new process-group leader in the brief window between the
60+
// original process exiting and this entry being removed, that unrelated process
61+
// could be signaled. Same limitation every pid-based process manager has; not
62+
// portably fixable, and accepted here.
5063
async stop(id: number, gracePeriodMs?: number): Promise<StopResult> {
5164
const entry = this.entries.get(id);
5265
if (!entry) {

‎tests/actions/killProcessGroup.spec.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,15 @@ describe('killProcessGroup', () => {
7777
});
7878
const pid = child.pid!;
7979

80-
expect(() => process.kill(pid, 0)).not.toThrow();
80+
try {
81+
expect(() => process.kill(pid, 0)).not.toThrow();
8182

82-
await killProcessGroup(pid, 50);
83-
await waitForProcessExit(pid);
83+
await killProcessGroup(pid, 50);
84+
await waitForProcessExit(pid);
8485

85-
expect(() => process.kill(pid, 0)).toThrow();
86+
expect(() => process.kill(pid, 0)).toThrow();
87+
} finally {
88+
try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ }
89+
}
8690
});
8791
});

‎tests/commands/ps.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,5 +32,6 @@ describe('/ps', () => {
3232
expect(output).toContain('pid 4242');
3333
expect(output).toContain('2 npm run watch:css');
3434
expect(output).toContain('pid 4343');
35+
expect(output).toMatch(/running \d+m\d{2}s/);
3536
});
3637
});

‎tests/commands/stop.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,34 @@ describe('/stop', () => {
6464
expect(output).toContain('not a valid process index');
6565
});
6666

67+
it('reports an error for "0" as an out-of-range index', async () => {
68+
const registry = new BackgroundProcessRegistry();
69+
const output = await stop({ backgroundProcessRegistry: registry }, ['0']);
70+
71+
expect(output).toContain('not a valid process index');
72+
});
73+
74+
it('reports an error for a negative index', async () => {
75+
const registry = new BackgroundProcessRegistry();
76+
const output = await stop({ backgroundProcessRegistry: registry }, ['-1']);
77+
78+
expect(output).toContain('not a valid process index');
79+
});
80+
81+
it('reports an error for a non-integer index', async () => {
82+
const registry = new BackgroundProcessRegistry();
83+
const output = await stop({ backgroundProcessRegistry: registry }, ['1.5']);
84+
85+
expect(output).toContain('not a valid process index');
86+
});
87+
88+
it('treats an empty-string arg the same as no argument at all', async () => {
89+
const registry = new BackgroundProcessRegistry();
90+
const output = await stop({ backgroundProcessRegistry: registry }, ['']);
91+
92+
expect(output).toBe('No background processes running.');
93+
});
94+
6795
it('reports an error for an unknown index', async () => {
6896
const registry = new BackgroundProcessRegistry();
6997
registry.register(4242, 'bun run dev', undefined);

‎tests/core/agent/BackgroundProcessRegistry.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,13 @@ describe('BackgroundProcessRegistry', () => {
8080
expect(killProcessGroupSpy).toHaveBeenCalledWith(2, undefined);
8181
expect(registry.list()).toEqual([]);
8282
});
83+
84+
it('killAll() on an empty registry resolves without calling killProcessGroup', async () => {
85+
const killProcessGroupSpy = vi.spyOn(commandActions, 'killProcessGroup').mockResolvedValue(undefined);
86+
const registry = new BackgroundProcessRegistry();
87+
88+
await expect(registry.killAll()).resolves.toBeUndefined();
89+
90+
expect(killProcessGroupSpy).not.toHaveBeenCalled();
91+
});
8392
});

‎tests/slashCommandDispatch.spec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ describe('slash command dispatch – output vs instruction', () => {
367367
const ctx = { ...createMinimalContext(), isNonInteractive: true };
368368
const handler = new SlashCommandHandler(ctx, SLASH_COMMANDS);
369369

370-
const interactiveCommands = ['/model', '/cc', '/search', '/theme', '/language', '/feedback'];
370+
const interactiveCommands = ['/model', '/cc', '/search', '/theme', '/language', '/feedback', '/ps', '/stop'];
371371
for (const cmd of interactiveCommands) {
372372
const result = await handler.handle(cmd);
373373
expect(result).toContain('requires an interactive terminal');

0 commit comments

Comments
 (0)