rob-revisited/ide/tests/SessionArbiterTest.php

429 lines
20 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\Async\Processes;
use JumPHP\Ide\Claude\ClaudeCode;
use JumPHP\Ide\Claude\LeaseRefused;
use JumPHP\Ide\Claude\SessionArbiter;
use PHPUnit\Framework\TestCase;
/** docs/claude-session-arbiter.md: one claude at a time per session, whoever asks. */
final class SessionArbiterTest extends TestCase
{
private const SESS = 'sess-12345678';
private string $dir;
private string $path;
private string $cfg;
/** @var list<array{0: string, 1: array<string, mixed>}> */
private array $events = [];
private Processes $processes;
private ClaudeCode $cc;
/** @var list<int> */
private array $strays = [];
protected function setUp(): void
{
$this->dir = sys_get_temp_dir() . '/jph-arb-' . bin2hex(random_bytes(4));
mkdir("$this->dir/proj", 0775, true);
mkdir("$this->dir/fake", 0775, true);
mkdir("$this->dir/proc", 0775, true);
$this->cfg = "$this->dir/cfg";
mkdir($this->cfg . '/projects/' . preg_replace('/[^A-Za-z0-9]/', '-', "$this->dir/proj"), 0775, true);
$this->path = (string)getenv('PATH');
putenv("PATH=$this->dir/fake:$this->path");
putenv("CLAUDE_CONFIG_DIR=$this->cfg");
$this->processes = new Processes();
}
protected function tearDown(): void
{
putenv("PATH=$this->path");
putenv('CLAUDE_CONFIG_DIR');
foreach ($this->strays as $pid) {
@posix_kill($pid, 9);
}
foreach (glob('/proc/[0-9]*', GLOB_ONLYDIR) ?: [] as $d) {
if (str_contains((string)@file_get_contents("$d/cmdline"), $this->dir)) {
@posix_kill((int)basename($d), 9);
}
}
$this->processes->poll();
usleep(30000);
exec('rm -rf ' . escapeshellarg($this->dir));
}
/** A stand-in claude: logs its start (pid) and each message, answers each with a result carrying the session. $ignoreTerm: it survives SIGTERM. */
private function fakeClaude(bool $ignoreTerm = false): void
{
file_put_contents("$this->dir/fake/claude", "#!/bin/sh\n[ \"\$1\" = --version ] && { echo '9.9'; exit 0; }\n"
. ($ignoreTerm ? "trap '' TERM\n" : '')
. "echo \"START \$\$\" >> $this->dir/log.txt\n"
. "while read -r line; do echo \"MSG \$line\" >> $this->dir/log.txt; printf '%s\\n' '{\"type\":\"result\",\"subtype\":\"success\",\"session_id\":\"" . self::SESS . "\"}'; done\n");
chmod("$this->dir/fake/claude", 0755);
}
private function code(string $procRoot = '/proc'): ClaudeCode
{
$this->events = [];
$this->cc = new ClaudeCode($this->processes, "$this->dir/proj", function (string $e, array $p): void {
$this->events[] = [$e, $p];
}, null, $procRoot);
return $this->cc;
}
private function pump(int $ms = 20): void
{
$until = microtime(true) + $ms / 1000;
do {
$this->processes->poll();
$this->cc->tick();
usleep(2000);
} while (microtime(true) < $until);
}
private function until(callable $done, int $ms = 4000): bool
{
$end = microtime(true) + $ms / 1000;
while (microtime(true) < $end) {
$this->pump(5);
if ($done()) {
return true;
}
}
return false;
}
private function send(string $text, string $conv = 'a', ?string $session = self::SESS): array
{
return $this->cc->send($text, $session, 'acceptEdits', null, null, true, $conv);
}
/** @return list<string> */
private function log(): array
{
return array_values(array_filter(explode("\n", (string)@file_get_contents("$this->dir/log.txt"))));
}
private function fakeProc(int $pid, string $cmdline, string $cwd, string $tty = '', string $state = 'S'): void
{
$d = "$this->dir/proc/$pid";
@mkdir("$d/fd", 0775, true);
file_put_contents("$d/cmdline", str_replace(' ', "\0", $cmdline) . "\0");
file_put_contents("$d/stat", "$pid (claude) $state 1 1 1 0");
@unlink("$d/cwd");
symlink($cwd, "$d/cwd");
@unlink("$d/fd/0");
if ($tty !== '') {
symlink($tty, "$d/fd/0");
}
}
private function dropProc(int $pid): void
{
exec('rm -rf ' . escapeshellarg("$this->dir/proc/$pid"));
}
public function testTheHandoffWaitsForTheConfirmedExitAndKillsAProcessThatIgnoresTheStop(): void
{
$this->fakeClaude(true);
$cc = $this->code();
$cc->arbiter()->termTimeout = 0.4;
$run = $this->send('hello');
$pid = $this->processes->pid($run['id']);
self::assertNotNull($pid);
self::assertTrue($this->until(fn () => $this->processesStarted() >= 1), 'the trap is set');
$lease = $cc->hold('a', self::SESS);
self::assertSame('handoff', $lease['state'], 'the panel process is still alive: not granted yet');
$this->pump(100);
self::assertSame('handoff', $cc->arbiter()->get('a', self::SESS)['state']);
self::assertTrue(posix_kill($pid, 0), 'it ignores SIGTERM: still there');
self::assertTrue($this->until(fn () => $cc->arbiter()->get('a', self::SESS)['state'] === 'terminal'), 'granted after the hard kill');
self::assertFalse(is_dir("/proc/$pid") && !str_contains((string)@file_get_contents("/proc/$pid/stat"), ' Z '), 'the process is gone when the Terminal is granted');
}
public function testInputsDuringAHandoffAreQueuedAndReachTheTerminalInOrder(): void
{
$this->fakeClaude();
$cc = $this->code();
$this->send('first');
$cc->hold('a', self::SESS);
$queued = [];
foreach (['one', 'two', 'three'] as $t) {
$queued[] = $this->send($t);
}
foreach ($queued as $q) {
self::assertTrue($q['queued']);
self::assertSame('terminal', $q['to']);
}
self::assertTrue($this->until(fn () => $cc->arbiter()->get('a', self::SESS)['state'] === 'terminal'));
self::assertSame([], $cc->arbiter()->drainTerminal('a', self::SESS), 'claude is not seen yet: nothing is typed');
$cc->arbiter()->terminalReady('a', self::SESS);
$out = $cc->arbiter()->drainTerminal('a', self::SESS);
self::assertSame(['one', 'two', 'three'], array_column($out, 'text'));
self::assertSame([], $cc->arbiter()->drainTerminal('a', self::SESS));
self::assertSame($cc->arbiter()->get('a', self::SESS)['epoch'], $out[0]['epoch']);
}
public function testWhatWaitsGoesToThePanelInOrderWhenTheTerminalLeaves(): void
{
$this->fakeClaude();
$cc = $this->code();
$cc->hold('a', self::SESS);
self::assertSame('terminal', $cc->arbiter()->get('a', self::SESS)['state']);
foreach (['x1', 'x2', 'x3'] as $t) {
self::assertTrue($this->send($t)['queued']);
}
$cc->release('a', self::SESS);
self::assertTrue($this->until(fn () => count(array_filter($this->log(), fn ($l) => str_starts_with($l, 'MSG'))) >= 3));
$msgs = array_values(array_filter($this->log(), fn ($l) => str_starts_with($l, 'MSG')));
self::assertStringContainsString('x1', $msgs[0]);
self::assertStringContainsString('x2', $msgs[1]);
self::assertStringContainsString('x3', $msgs[2]);
self::assertSame(1, count(array_filter($this->log(), fn ($l) => str_starts_with($l, 'START'))), 'one process took all three');
}
public function testAStaleEpochIsRefused(): void
{
$this->fakeClaude();
$cc = $this->code();
$first = $cc->arbiter()->acquirePanel('a', self::SESS, null);
$cc->arbiter()->assertPanel('a', self::SESS, $first['epoch']);
$cc->hold('a', self::SESS);
$cc->release('a', self::SESS);
$this->pump(10);
$second = $cc->arbiter()->acquirePanel('a', self::SESS, null);
self::assertGreaterThan($first['epoch'], $second['epoch']);
$this->expectException(LeaseRefused::class);
$cc->arbiter()->assertPanel('a', self::SESS, $first['epoch']);
}
public function testTheSameSessionThroughTwoConversationKeysIsOneLease(): void
{
$this->fakeClaude();
$cc = $this->code();
$this->send('from a', 'a');
$b = $this->send('from b', 'b');
self::assertSame(0, $b['id'], 'b waits for a to leave: never two claude on the session');
$this->until(fn () => $this->processesStarted() >= 2);
self::assertSame(self::SESS, $cc->arbiter()->get('b')['session'], 'b is aliased to the session');
$cc->hold('b', self::SESS);
self::assertTrue($this->until(fn () => $cc->arbiter()->get('a')['state'] === 'terminal'), 'the lease of a is the lease of b');
self::assertSame(0, $this->livePanel(), 'the Terminal owns it: no panel process');
self::assertTrue($this->send('late', 'a')['queued']);
}
private function livePanel(): int
{
$n = 0;
foreach (glob('/proc/[0-9]*', GLOB_ONLYDIR) as $d) {
$c = (string)@file_get_contents("$d/cmdline");
if (str_contains($c, "$this->dir/fake/claude") && !str_contains((string)@file_get_contents("$d/stat"), ' Z ')) {
$n++;
}
}
return $n;
}
public function testAForeignClaudeOnTheSessionIsDetectedAndTheHandoffRefusedUntilItIsStopped(): void
{
$this->fakeClaude();
mkdir("$this->dir/other");
file_put_contents("$this->dir/other/claude", "#!/bin/sh\nsleep 60\n");
$foreign = proc_open(['/bin/sh', "$this->dir/other/claude", '--resume', self::SESS], [['pipe', 'r'], ['file', '/dev/null', 'w'], ['file', '/dev/null', 'w']], $pipes, "$this->dir/proj");
$pid = (int)proc_get_status($foreign)['pid'];
$this->strays[] = $pid;
$cc = $this->code();
// the panel wants to send: refused (queued behind the conflict), the person is told which process
$r = $this->send('hi');
self::assertTrue($r['queued']);
$lease = $cc->arbiter()->get('a', self::SESS);
self::assertSame('conflict', $lease['state']);
self::assertSame($pid, $lease['conflict']['foreign'][0]['pid']);
self::assertStringContainsString("pid $pid", $lease['conflict']['message']);
self::assertSame(0, $this->processesStarted(), 'no claude was started over the foreign one');
$term = $cc->hold('a', self::SESS);
self::assertSame('conflict', $term['state'], 'the Terminal is not granted either');
// "stop it" (the person's click)
$cc->arbiter()->resolve('a', self::SESS, 'kill', $pid);
self::assertTrue($this->until(function () use ($cc, $foreign) {
proc_get_status($foreign);
return $cc->arbiter()->get('a', self::SESS)['state'] !== 'conflict';
}, 6000));
self::assertTrue($this->until(fn () => count(array_filter($this->log(), fn ($l) => str_starts_with($l, 'MSG'))) >= 1), 'the queued message went to the panel once it was free');
proc_close($foreign);
}
public function testTheConflictIsSolvedWhateverNameThePageGivesTheConversationOrSession(): void
{
$this->fakeClaude();
mkdir("$this->dir/other");
file_put_contents("$this->dir/other/claude", "#!/bin/sh\nsleep 60\n");
$foreign = proc_open(['/bin/sh', "$this->dir/other/claude", '--resume', self::SESS], [['pipe', 'r'], ['file', '/dev/null', 'w'], ['file', '/dev/null', 'w']], $pipes, "$this->dir/proj");
$pid = (int)proc_get_status($foreign)['pid'];
$this->strays[] = $pid;
$cc = $this->code();
$this->send('hi');
self::assertSame('conflict', $cc->arbiter()->get('a', self::SESS)['state']);
// the page knows the conversation but no session id (it was opened before claude named it): "Stop it" still reaches the right lease
$cc->arbiter()->resolve('a', null, 'kill', $pid);
self::assertTrue($this->until(function () use ($cc, $foreign) {
proc_get_status($foreign);
return $cc->arbiter()->get('a', self::SESS)['state'] !== 'conflict';
}, 6000));
proc_close($foreign);
}
private function processesStarted(): int
{
return count(array_filter($this->log(), fn ($l) => str_starts_with($l, 'START')));
}
public function testAClaudeOfTheProjectFolderOnlyCountsWhileTheSessionFileMoves(): void
{
$cc = $this->code("$this->dir/proc");
$arb = $cc->arbiter();
$this->fakeProc(900, 'claude', "$this->dir/proj"); // a bare claude in the project folder
$this->fakeProc(901, 'claude --resume other-session-1', "$this->dir/proj");
self::assertNotEmpty($arb->acquirePanel('a', self::SESS, null)['ok'], 'quiet session file: a claude that merely sits in the folder is no conflict');
$arb->panelExited('a', self::SESS);
// the file moves: now it may be the one writing
$file = $this->cfg . '/projects/' . preg_replace('/[^A-Za-z0-9]/', '-', "$this->dir/proj") . '/' . self::SESS . '.jsonl';
$b = new SessionArbiter("$this->dir/proj", function (): void {
}, $this->cfg, "$this->dir/proc");
file_put_contents($file, "{}\n");
$lease = $b->requestTerminal('z', self::SESS);
self::assertSame('conflict', $lease['state']);
self::assertSame([900], array_column($lease['conflict']['foreign'], 'pid'), 'a claude on another session (901) never counts');
self::assertSame('weak', $lease['conflict']['foreign'][0]['kind']);
}
public function testTheTerminalLeaseIsReleasedWhenItsClaudeLeavesAndTheShellStays(): void
{
$events = [];
$now = 1000.0;
$arb = new SessionArbiter("$this->dir/proj", function (string $e, array $p) use (&$events): void {
$events[] = [$e, $p];
}, $this->cfg, "$this->dir/proc", function () use (&$now): float {
return $now;
});
$arb->bind(fn () => [], fn () => null, fn (array $a, int $e): array => ['id' => 7], fn (int $id): string => '/dev/pts/77');
$arb->requestTerminal('a', self::SESS);
self::assertSame('terminal', $arb->get('a', self::SESS)['state']);
$arb->attach('a', self::SESS, 5);
$this->fakeProc(500, 'claude --resume ' . self::SESS, "$this->dir/proj", '/dev/pts/77');
$now += 1;
self::assertSame('terminal', $arb->get('a', self::SESS)['state']);
self::assertTrue($arb->get('a', self::SESS)['seen'], 'claude is seen on the terminal\'s device');
// a panel message typed meanwhile waits
self::assertTrue($arb->acquirePanel('a', self::SESS, ['prompt' => 'typed', 'conv' => 'a'])['queued']);
// /exit: the claude is gone, the shell stays
$this->dropProc(500);
$now += 1;
$state = $arb->get('a', self::SESS);
self::assertContains($state['state'], ['idle', 'panel'], 'released by itself: ' . json_encode($state));
self::assertContains('terminal-claude-exited', array_map(fn ($e) => $e[1]['reason'] ?? '', $events));
self::assertContains('claude.queue.sent', array_column($events, 0), 'and the typed message went to the panel');
}
public function testTheLeaseIsReleasedWhenClaudeNeverStartsInTheTerminal(): void
{
$now = 1000.0;
$arb = new SessionArbiter("$this->dir/proj", function (): void {
}, $this->cfg, "$this->dir/proc", function () use (&$now): float {
return $now;
});
$arb->bind(fn () => [], fn () => null, fn (array $a, int $e): array => ['id' => 7], fn (int $id): string => '/dev/pts/78');
$arb->requestTerminal('a', self::SESS);
$arb->attach('a', self::SESS, 5);
$now += 61;
self::assertSame('idle', $arb->get('a', self::SESS)['state']);
}
public function testAnOpenCodeConversationIsAnsweredByOpenCodeNotClaude(): void
{
// 0.1.105 to 0.1.109: the arbiter's refactor sent every message to claude, whatever the panel's assistant and model
$this->fakeClaude();
file_put_contents("$this->dir/fake/opencode", "#!/bin/sh\n[ \"\$1\" = --version ] && { echo '1.0'; exit 0; }\necho \"OPENCODE \$*\" >> $this->dir/log.txt\n");
chmod("$this->dir/fake/opencode", 0755);
$cc = $this->code();
$cc->send('hello', null, 'acceptEdits', 'llamacpp/qwen3-coder', null, true, 'oc', 'opencode');
self::assertTrue($this->until(fn () => $this->log() !== []), 'something was started');
$this->pump(200);
$log = implode("\n", $this->log());
self::assertStringContainsString('OPENCODE run', $log);
self::assertStringContainsString('llamacpp/qwen3-coder', $log);
self::assertStringNotContainsString('START', $log, 'no claude was started');
}
public function testAFileGrowingWithNoClaudeToBlameIsNotAConflict(): void
{
// the last lines of the IDE's own claude, written after it was stopped (Restart), made a conflict nobody could close (2026-11-11)
$this->fakeClaude();
$cc = $this->code();
$file = $this->cfg . '/projects/' . preg_replace('/[^A-Za-z0-9]/', '-', "$this->dir/proj") . '/' . self::SESS . '.jsonl';
file_put_contents($file, "{}\n");
$cc->arbiter()->quiet = 0.0;
$cc->arbiter()->every = 0.0;
$cc->arbiter()->acquirePanel('a', self::SESS, null);
$cc->arbiter()->panelExited('a', self::SESS); // idle: nobody works
$this->pump(30);
file_put_contents($file, "{\"x\":1}\n", FILE_APPEND); // a late write, and no claude of this session anywhere
$this->pump(30);
self::assertSame('idle', $cc->arbiter()->get('a', self::SESS)['state']);
self::assertFalse(!empty($this->send('now')['queued']), 'the next message goes to the panel at once');
}
public function testNoTwoProcessesOfOneSessionEverOverlap(): void
{
$this->fakeClaude();
$cc = $this->code("$this->dir/proc");
mt_srand(20261110);
$terminalPid = 0;
$maxPanel = 0;
for ($i = 0; $i < 220; $i++) {
$arb = $cc->arbiter();
$state = $arb->get('a', self::SESS)['state'];
switch (mt_rand(0, 6)) {
case 0:
case 1:
$this->send('m' . $i, mt_rand(0, 1) ? 'a' : 'b');
break;
case 2:
$cc->hold(mt_rand(0, 1) ? 'a' : 'b', self::SESS);
break;
case 3:
if ($terminalPid) { // the person quits claude, the shell stays
$this->dropProc($terminalPid);
$terminalPid = 0;
} else {
$cc->release('a', self::SESS);
}
break;
case 4:
$cc->stopConversation('a', self::SESS);
break;
case 5:
$arb->terminalReady('a', self::SESS);
break;
default:
$this->pump(mt_rand(1, 25));
}
// whenever the Terminal holds the lease, its claude starts in the terminal (after the grant, as the page does)
if ($arb->get('a', self::SESS)['state'] === 'terminal' && $terminalPid === 0 && mt_rand(0, 2) === 0) {
$terminalPid = 4000 + $i;
$this->fakeProc($terminalPid, 'claude --resume ' . self::SESS, "$this->dir/proj");
}
$this->pump(2);
$panel = $this->livePanel();
$maxPanel = max($maxPanel, $panel);
$now = $arb->get('a', self::SESS)['state'];
self::assertLessThanOrEqual(1, $panel, "two panel claude at once (step $i)");
self::assertFalse($panel > 0 && $terminalPid > 0, "the panel's claude and the Terminal's claude overlap (step $i, state $now)");
}
self::assertGreaterThanOrEqual(1, $maxPanel, 'the stress run really started processes');
$cc->stopConversation('a', self::SESS);
$cc->stopConversation('b', self::SESS);
}
}