Skip to content
Closed
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
3 changes: 2 additions & 1 deletion apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1566,7 +1566,8 @@ export const layerQueryRunner: Layer.Layer<
const child = spawnProcess(spawnOptions);
spawnedProcess = child;
// A spawn that fails emits only "error".
const releaseAgent = portDiscovery.trackAgent();
// The CLI carries the thread itself, so a port it holds would read as its server.
const releaseAgent = portDiscovery.trackAgent("pid" in child ? child.pid : undefined);
child.once("exit", releaseAgent);
child.on("error", releaseAgent);
processExited = child.exitCode !== null || child.signalCode != null;
Expand Down
57 changes: 57 additions & 0 deletions apps/server/src/preview/PortScanner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,63 @@ effectIt.effect.each(["linux", "darwin"] as const)(
},
);

effectIt.effect.each(["linux", "darwin"] as const)(
"does not list the agent CLI's own listener on %s, only the servers it started",
(platform) => {
const cliPort = 43_126;
const jobPort = 43_127;
const thread = `${PortScanner.AGENT_THREAD_ENV}=thread-agent`;
const missing = FileSystem.makeNoop({});
const procEnviron: Record<string, string> = {
"/proc/7000/environ": `PATH=/usr/bin\0${thread}\0`,
"/proc/7100/environ": `PATH=/usr/bin\0${thread}\0`,
};
const layer = PortScanner.layer.pipe(
Layer.provide(
Layer.mergeAll(
FileSystem.layerNoop({
readFileString: (path) => {
const content = procEnviron[path];
return content === undefined ? missing.readFileString(path) : Effect.succeed(content);
},
}),
Layer.succeed(ProcessRunner.ProcessRunner, {
run: (input) =>
Effect.succeed(
processOutput(
input.command === "lsof"
? `p7000\ncclaude\nn127.0.0.1:${cliPort}\np7100\ncnode\nn127.0.0.1:${jobPort}\n`
: ` 7000 claude --output-format stream-json PATH=/usr/bin ${thread}\n` +
` 7100 node server.js PATH=/usr/bin ${thread}\n`,
),
),
}),
Layer.succeed(HostProcess.Platform, platform),
FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, globalThis.fetch)),
),
),
),
);

return Effect.gen(function* () {
const scanner = yield* PortScanner.PortDiscovery;
scanner.trackAgent(7000);
expect(yield* scanner.scan()).toEqual([
{
host: "localhost",
port: jobPort,
url: `http://localhost:${jobPort}`,
processName: "node",
pid: 7100,
terminal: null,
agent: { threadId: "thread-agent" },
},
]);
}).pipe(Effect.provide(layer));
},
);

effectIt.effect("stops only a job's own process group", () =>
Effect.sync(() => {
const serverPid = 100;
Expand Down
16 changes: 11 additions & 5 deletions apps/server/src/preview/PortScanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,11 @@ export class PortDiscovery extends Context.Service<
}) => Effect.Effect<void>;
/**
* Counts a running agent until the returned function is called. While one runs, any
* listener may be a server it started. Synchronous because provider spawn callbacks run
* outside Effect.
* listener may be a server it started. `cliPid` is the agent CLI's own process when it carries
* the thread itself: a port it holds is not a server. Synchronous because provider spawn
* callbacks run outside Effect.
*/
readonly trackAgent: () => () => void;
readonly trackAgent: (cliPid?: number) => () => void;
/**
* Tells an agent CLI's adapter which of its commands a user stop is about to signal, so the
* exit is not reported to the agent as the command finishing by itself.
Expand Down Expand Up @@ -531,6 +532,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
const agentThreadsRef = yield* Ref.make<ReadonlyMap<number, ThreadId | null>>(new Map());
const agentCommandStopWatchers = new Set<AgentCommandStopWatcher>();
let runningAgents = 0;
const agentCliPids = new Set<number>();
// An agent that exited, or a cache cleared with a marked listener, owes one listener read: the
// servers it left may still run. So does startup, for agents that ran before a restart.
let agentScanPending = true;
Expand Down Expand Up @@ -588,7 +590,9 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
const threads = yield* readAgentThreads(pids.filter((pid) => !terminalOwners.has(pid)));
const owners = new Map(terminalOwners);
for (const [pid, threadId] of threads) {
if (threadId !== null) owners.set(pid, { terminal: null, agent: { threadId } });
if (threadId !== null && !agentCliPids.has(pid)) {
owners.set(pid, { terminal: null, agent: { threadId } });
}
}
return owners;
});
Expand Down Expand Up @@ -1062,13 +1066,15 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
});
});

const trackAgent: PortDiscovery["Service"]["trackAgent"] = () => {
const trackAgent: PortDiscovery["Service"]["trackAgent"] = (cliPid) => {
runningAgents += 1;
if (cliPid !== undefined) agentCliPids.add(cliPid);
let released = false;
return () => {
if (released) return;
released = true;
runningAgents -= 1;
if (cliPid !== undefined) agentCliPids.delete(cliPid);
agentScanPending = true;
};
};
Expand Down
Loading