Skip to content

Commit 2311d8e

Browse files
committed
fix(server): list agent servers outside workspaces, never stop an exec'd shell
The scan gate now skips `ps` only when attribution would provably come out empty (no agent CLI, no terminal process, no listener in a workspace), and attributes every listener once it reads the table. A server an agent or a terminal job starts outside every workspace is listed, and what is listed no longer depends on unrelated listeners. Stop refuses a root that exec'd an interactive shell since the scan: it keeps its pid, start time and parent but now hosts the user's own jobs.
1 parent 1914778 commit 2311d8e

3 files changed

Lines changed: 101 additions & 32 deletions

File tree

‎apps/server/src/threadServices/ThreadServices.test.ts‎

Lines changed: 78 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,11 @@ interface World {
9898
readonly cwds: Map<number, string>;
9999
/** Like an lsof timeout: the cwd lookup as a whole fails. */
100100
cwdsUnreadable: boolean;
101+
/** Terminal shells and the descendants the terminal manager has reported so far. */
102+
readonly terminalOwners: Map<
103+
number,
104+
{ readonly threadId: ThreadId; readonly terminalId: string }
105+
>;
101106
readonly projects: Array<OrchestrationProjectShell>;
102107
readonly threads: Array<{
103108
readonly threadId: ThreadId;
@@ -168,6 +173,10 @@ const makeWorld = (options: { readonly cpuTimes?: Map<number, number> } = {}): W
168173
[SERVER, "/opt/t3"],
169174
]),
170175
cwdsUnreadable: false,
176+
terminalOwners: new Map([
177+
[SHELL, { threadId: THREAD_APP, terminalId: "term-1" }],
178+
[VITE, { threadId: THREAD_APP, terminalId: "term-1" }],
179+
]),
171180
projects: [project(PROJECT_APP, "/work/app"), project(PROJECT_API, "/work/api/")],
172181
threads: [
173182
{ threadId: THREAD_APP, projectId: PROJECT_APP, worktreePath: null },
@@ -210,13 +219,7 @@ const layerFor = (
210219
world.probes.push(port);
211220
return world.webPorts.get(port) ?? null;
212221
}),
213-
terminalProcessOwners: Effect.sync(
214-
() =>
215-
new Map([
216-
[SHELL, { threadId: THREAD_APP, terminalId: "term-1" }],
217-
[VITE, { threadId: THREAD_APP, terminalId: "term-1" }],
218-
]),
219-
),
222+
terminalProcessOwners: Effect.sync(() => new Map(world.terminalOwners)),
220223
}),
221224
Layer.succeed(
222225
ProcessInspector.ProcessInspector,
@@ -409,37 +412,69 @@ describe("ThreadServices", () => {
409412
}).pipe(Effect.provide(layerFor(world)));
410413
});
411414

412-
it.effect("skips the process table when no listener is in a terminal or a workspace", () => {
415+
it.effect(
416+
"skips the process table when no agent, terminal, or workspace could own a listener",
417+
() => {
418+
const world = makeWorld();
419+
world.terminalOwners.clear();
420+
world.listeners.splice(
421+
0,
422+
world.listeners.length,
423+
{ pid: POSTGRES, port: 5432, processName: "postgres", exposed: false },
424+
{ pid: SERVER, port: 3773, processName: "node", exposed: false },
425+
);
426+
return Effect.gen(function* () {
427+
const { received } = yield* subscribe(THREAD_APP);
428+
expect((yield* Queue.take(received)).services).toEqual([]);
429+
yield* TestClock.adjust("9 seconds");
430+
431+
expect(world.listCalls).toBe(4);
432+
expect(world.tableCalls).toBe(0);
433+
}).pipe(Effect.provide(layerFor(world)));
434+
},
435+
);
436+
437+
it.effect("lists an agent's server outside every workspace, whatever else listens", () => {
413438
const world = makeWorld();
439+
// Started by thread-api's Claude, outside every workspace.
440+
world.cwds.set(AGENT_SERVER, "/tmp/demo");
441+
const everyListener = [...world.listeners];
414442
world.listeners.splice(
415443
0,
416444
world.listeners.length,
417-
{ pid: POSTGRES, port: 5432, processName: "postgres", exposed: false },
418-
{ pid: SERVER, port: 3773, processName: "node", exposed: false },
445+
...everyListener.filter(({ pid }) => pid !== VITE && pid !== DOCS_SERVER),
419446
);
420447
return Effect.gen(function* () {
421-
const { received } = yield* subscribe(THREAD_APP);
422-
expect((yield* Queue.take(received)).services).toEqual([]);
423-
yield* TestClock.adjust("9 seconds");
448+
yield* registerClaude;
449+
const alone = yield* subscribe(THREAD_API);
450+
expect((yield* Queue.take(alone.received)).services.map(({ pid }) => pid)).toEqual([
451+
AGENT_SHELL,
452+
]);
453+
yield* Fiber.interrupt(alone.fiber);
424454

425-
expect(world.listCalls).toBe(4);
426-
expect(world.tableCalls).toBe(0);
455+
world.listeners.splice(0, world.listeners.length, ...everyListener);
456+
const api = yield* subscribe(THREAD_API);
457+
expect((yield* Queue.take(api.received)).services.map(({ pid }) => pid)).toEqual([
458+
AGENT_SHELL,
459+
]);
427460
}).pipe(Effect.provide(layerFor(world)));
428461
});
429462

430-
it.effect("lists an agent's server only inside a workspace, whatever else listens", () => {
463+
it.effect("lists a terminal job outside every workspace before the terminal reports it", () => {
431464
const world = makeWorld();
432-
// Started by thread-api's Claude, while a terminal server of thread-app opens the gate.
433-
world.cwds.set(AGENT_SERVER, "/tmp/demo");
465+
const PYTHON = 5_000_102;
466+
// Only the shell is known: its jobs arrive with the terminal manager's next poll.
467+
world.terminalOwners.delete(VITE);
468+
world.processes.set(PYTHON, row(PYTHON, SHELL, "python3 -m http.server 8000", 40));
469+
world.cwds.set(PYTHON, "/tmp/scratch");
470+
world.listeners.push({ pid: PYTHON, port: 8000, processName: "python3", exposed: false });
434471
return Effect.gen(function* () {
435-
yield* registerClaude;
436472
const app = yield* subscribe(THREAD_APP);
437-
const api = yield* subscribe(THREAD_API);
438473
expect((yield* Queue.take(app.received)).services.map(({ pid }) => pid)).toEqual([
439474
VITE,
440475
DOCS,
476+
PYTHON,
441477
]);
442-
expect((yield* Queue.take(api.received)).services).toEqual([]);
443478
}).pipe(Effect.provide(layerFor(world)));
444479
});
445480

@@ -1219,6 +1254,28 @@ describe("ThreadServices", () => {
12191254
}).pipe(Effect.provide(layerFor(world)));
12201255
});
12211256

1257+
it.effect("never stops a root that turned into an interactive shell since the scan", () => {
1258+
const world = makeWorld();
1259+
return Effect.gen(function* () {
1260+
const threadServices = yield* ThreadServices.ThreadServices;
1261+
const { received } = yield* subscribe(THREAD_APP);
1262+
yield* Queue.take(received);
1263+
1264+
// `exec "$SHELL" -i` at the end of a dev script keeps its pid, start time, and parent.
1265+
world.processes.set(DOCS, row(DOCS, LOGIN_SHELL, "/bin/zsh -i", 30));
1266+
const stopping = yield* threadServices
1267+
.stop({ serviceId: serviceIdOf(DOCS, 30) })
1268+
.pipe(Effect.forkChild);
1269+
yield* TestClock.adjust("4 seconds");
1270+
1271+
expect(yield* Fiber.join(stopping)).toEqual({
1272+
stopped: false,
1273+
message: "The service is no longer listed. Refresh and try again.",
1274+
});
1275+
expect(world.signals).toEqual([]);
1276+
}).pipe(Effect.provide(layerFor(world)));
1277+
});
1278+
12221279
it.effect("tells a pid reused in the same second by another command and parent", () => {
12231280
const world = makeWorld();
12241281
return Effect.gen(function* () {

‎apps/server/src/threadServices/ThreadServices.ts‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import * as ServerSettings from "../serverSettings.ts";
3232
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
3333
import {
3434
attributeServices,
35+
isInteractiveShell,
3536
stopTargets,
3637
workspaceThreadsOf,
3738
type AttributedService,
@@ -94,6 +95,10 @@ const CPU_MIN_WINDOW_MS = 1_000;
9495
const MIB = 1024 * 1024;
9596

9697
const STOPPED: ThreadServiceStopResult = { stopped: true, message: null };
98+
const NO_LONGER_LISTED: ThreadServiceStopResult = {
99+
stopped: false,
100+
message: "The service is no longer listed. Refresh and try again.",
101+
};
97102
const UNCONFIRMED: ThreadServiceStopResult = {
98103
stopped: false,
99104
message: "Could not confirm the service stopped",
@@ -469,25 +474,29 @@ const make = Effect.gen(function* () {
469474
// An unread cwd would drop every workspace and agent service until the next scan.
470475
if (cwds === null) return null;
471476
const threads = yield* threadWorkspaces;
477+
const agentRoots = processRoots.snapshot();
472478
// `ps` lists every process on the machine with its full argv, while most listeners (browsers,
473-
// system daemons, other apps) belong to no thread; the cwds and terminal pids are cheap. Only
474-
// listeners past this gate are attributed, so whether a service is listed never depends on
475-
// unrelated ones: a server an agent starts outside every workspace is not listed.
476-
const candidates = listeners.filter(
477-
({ pid }) => terminalPids.has(pid) || workspaceThreadsOf(cwds.get(pid), threads).length > 0,
478-
);
479-
if (candidates.length === 0) return NOTHING_ATTRIBUTED;
479+
// system daemons, other apps) belong to no thread. With no agent CLI or terminal process to
480+
// descend from, only a listener whose cwd is in a workspace can, so `ps` is skipped exactly
481+
// when attribution would come out empty and never changes what is listed.
482+
if (
483+
agentRoots.size === 0 &&
484+
terminalPids.size === 0 &&
485+
!listeners.some(({ pid }) => workspaceThreadsOf(cwds.get(pid), threads).length > 0)
486+
) {
487+
return NOTHING_ATTRIBUTED;
488+
}
480489
const processes = yield* processInspector.table;
481490
if (!(yield* processInspector.supported)) {
482491
return { ...NOTHING_ATTRIBUTED, supported: false } satisfies Attribution;
483492
}
484493
const services = attributeServices({
485494
serverPid,
486-
listeners: candidates,
495+
listeners,
487496
processes,
488497
cwds,
489498
terminalPids,
490-
agentRoots: processRoots.snapshot(),
499+
agentRoots,
491500
threads,
492501
});
493502
return { services, processes, supported: true } satisfies Attribution;
@@ -747,7 +756,7 @@ const make = Effect.gen(function* () {
747756
) {
748757
return STOPPED;
749758
}
750-
return { stopped: false, message: "The service is no longer listed. Refresh and try again." };
759+
return NO_LONGER_LISTED;
751760
});
752761

753762
const stop: ThreadServices["Service"]["stop"] = Effect.fn("ThreadServices.stop")(
@@ -765,6 +774,9 @@ const make = Effect.gen(function* () {
765774
const root = processes.value.get(service.rootPid);
766775
// A different start time or command line means the pid now belongs to another process.
767776
if (root === undefined || !isSameProcess(root, listed.root)) return STOPPED;
777+
// The root is never an interactive shell when listed, so it exec'd one since and now hosts
778+
// the user's own jobs: same pid, start time, and parent, but no longer the service.
779+
if (isInteractiveShell(root)) return NO_LONGER_LISTED;
768780
const targets = stopTargets({
769781
serverPid,
770782
processes: processes.value,

‎apps/server/src/threadServices/attribution.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ const runsCommandOrScript = (args: ReadonlyArray<string>): boolean => {
200200
return false;
201201
};
202202

203-
const isInteractiveShell = (row: ProcessRow): boolean =>
203+
export const isInteractiveShell = (row: ProcessRow): boolean =>
204204
SHELL_NAMES.has(row.name) && !runsCommandOrScript(argsOf(row));
205205

206206
/** The script a JS runtime runs (null for `-e` and the REPL), and whether it reruns it on changes. */

0 commit comments

Comments
 (0)