Skip to content

Commit 7511e77

Browse files
committed
✨ Route a pane's native launch through its own composite (#732)
Implements architecture commit 802b07d. `TerminalComposite.launch(ordinal, request, spawned)` is required of every composite. Core closes the pane-scoped launcher over it and the pane's authored ordinal, so after claim admission and the pane flush a `<Session.Launch>` written in a paired pane reaches *that pane's* terminal. The ordinal lives in core's closure and enters no native request, Agent request, session key, construction route, durable phase, result or diagnostic. The pane launcher is now the end of the chain. Middleware written nearer the authored launch still composes in front and may observe, wrap, refuse or short-circuit; what it can no longer do is reach past, because past it is the root foreground launcher and the root terminal is the one thing a pane exists to avoid. A composite that cannot run a pane's launch refuses — there is no fallback, because the only thing to fall back to is the wrong terminal. Root `<Session.Launch>` is untouched. The tmux composite sends the exact command vector, working directory and environment over the pane's authenticated channel; tmux's parser sees a directory and an ordinal. `shell()` stays separate and keeps deriving the executable from live host policy. `spawned` is invoked only for the worker-observed runtime spawn event. Also fails closed on settlement: `requireQuiescent()` is the rule everything downstream is conditional on, and a settlement that could not prove the pane free no longer clears the pane, reports success, or admits another launch. TG20 proves the endpoint against real workers on real sockets with a fake tmux that now starts the pane commands it is given, and with no `<TestAgent>` or nearer launcher in front: exact argv, cwd and environment arrive at the pane's authenticated worker; a root-foreground-launcher sentinel is never entered while a root launch still reaches it; distinct panes launch concurrently; and a pane the composite cannot serve refuses. Tier GN is rewired through the endpoint, which is what exposed the gap: before this, its pane launches reached `<TestAgent>`'s launcher and nothing could tell that from reaching the pane. GN now separates the two — `launches` at the pane endpoint, `agentLaunches` at the root route — and GN3 and GN8 assert both.
1 parent 802b07d commit 7511e77

10 files changed

Lines changed: 544 additions & 73 deletions

File tree

‎packages/cli/src/terminal/pane-worker.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,42 @@ export function runPaneWorkerProcess(invocation: {
8989
return run(() => runPaneWorker(invocation.ordinal, invocation.directory));
9090
}
9191

92+
/**
93+
* A pane that could not be proved free.
94+
*
95+
* Provider-neutral: it names no socket, session, pane, client, argv or
96+
* environment, because a settlement that failed is read in exactly the places a
97+
* private identifier must not appear.
98+
*/
99+
export class PaneNotQuiescent extends Error {
100+
override name = "PaneNotQuiescent";
101+
constructor(what: string) {
102+
super(`this terminal pane could not be proved free: ${what}`);
103+
}
104+
}
105+
106+
/**
107+
* What a settlement means for the pane it settled.
108+
*
109+
* Exported because it is the rule, not an implementation detail: everything
110+
* downstream — clearing the pane, reporting a launch settled, admitting the
111+
* next one, letting teardown succeed — is conditional on it, and a rule that
112+
* several callers depend on is one worth being able to state and test on its
113+
* own.
114+
*/
115+
export function requireQuiescent(settlement: Settlement): void {
116+
if (settlement.quiet) {
117+
return;
118+
}
119+
// Everything the worker can do has been done and something is still there: a
120+
// survivor of the escalation, or a holder of the pane's terminal.
121+
throw new PaneNotQuiescent(
122+
settlement.holders.some((holder) => !holder.gone)
123+
? "something still holds its terminal"
124+
: "something it started is still running",
125+
);
126+
}
127+
92128
/** A settlement for a pane that never started anything. */
93129
const NOTHING_TO_SETTLE: Settlement = {
94130
method: "exited",
@@ -176,6 +212,9 @@ export function* runPaneWorker(ordinal: number, directory: string): Operation<vo
176212
try {
177213
const settlement =
178214
entry.child === undefined ? NOTHING_TO_SETTLE : yield* entry.child.settle();
215+
// Fails closed: a settlement that could not prove the pane free leaves it
216+
// uncleared, reports no success, and refuses the next launch.
217+
requireQuiescent(settlement);
179218
// Cleared only after the settlement, so a launch arriving now is refused
180219
// rather than started beside a sweep that would reach it.
181220
if (live === entry) {
@@ -231,7 +270,9 @@ export function* runPaneWorker(ordinal: number, directory: string): Operation<vo
231270
yield* say({ type: "started", id: message.id, pid: started.value });
232271
const outcome = yield* child.exited;
233272
// The exit is not the end of it. `exited` is what frees the pane for
234-
// the next launch, so it follows the whole settlement.
273+
// the next launch, so it follows the whole settlement — and is sent
274+
// only when that settlement proved the pane free. A settlement that
275+
// did not throws out of here instead, and no success is reported.
235276
const settlement = yield* settle(entry);
236277
yield* say({ type: "exited", id: message.id, ...outcome, settlement });
237278
});

‎packages/cli/src/terminal/provider.ts‎

Lines changed: 46 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ import process from "node:process";
2525
import type { Operation } from "effection";
2626
import { TerminalGrids } from "@executablemd/runtime";
2727
import type {
28+
NativeLaunchOutcome,
29+
NativeLaunchRequest,
2830
TerminalComposite,
2931
TerminalGridRequest,
3032
TerminalPaneState,
@@ -175,7 +177,19 @@ function usePresentedGrid(
175177
yield* link.send({ type: "display", seq: ++shown, text });
176178
},
177179
*shell(ordinal, spawned) {
178-
return yield* runShell(links[ordinal], deps, spawned);
180+
// The host's default shell, derived from live policy — never from the
181+
// document, and never from a request.
182+
return yield* runInPane(
183+
links[ordinal],
184+
{ command: [deps.env.SHELL ?? "/bin/sh"], cwd: process.cwd(), env: deps.env },
185+
spawned,
186+
);
187+
},
188+
*launch(ordinal, request, spawned) {
189+
// The exact command vector, working directory and environment the Agent
190+
// provider supplied, over this pane's authenticated channel. tmux's
191+
// parser sees none of it.
192+
return yield* runInPane(links[ordinal], request, spawned);
179193
},
180194
*closed() {
181195
yield* race([left.operation, grid.detached()]);
@@ -201,39 +215,52 @@ function* label(
201215
yield* grid.title(ordinal, `${pane.title} — ${state}`);
202216
}
203217

204-
/** Start the host's default shell in one pane, through its worker. */
205-
function* runShell(
218+
/**
219+
* Run one request in one pane, through that pane's authenticated worker.
220+
*
221+
* The same path for both callers, because they are the same act: a shell whose
222+
* executable came from host policy and a native UI whose argv came from the
223+
* Agent provider are both "start this, on that pane's terminal". What differs
224+
* is who decided the vector, and that is decided before this is called.
225+
*/
226+
export function* runInPane(
206227
link: PaneLink | undefined,
207-
deps: TmuxProviderDependencies,
228+
request: NativeLaunchRequest,
208229
spawned: () => void,
209-
): Operation<TerminalShellOutcome> {
230+
): Operation<NativeLaunchOutcome> {
210231
if (link === undefined) {
211-
throw new Error("this grid has no such pane");
232+
// No fallback. A composite that cannot run this in the pane it was asked
233+
// for refuses, rather than putting a native UI on the root terminal.
234+
throw new Error("this terminal grid cannot run that pane's launch");
212235
}
213-
const shell = deps.env.SHELL ?? "/bin/sh";
214236
yield* link.send({
215237
type: "launch",
216-
id: `shell-${link.ordinal}`,
217-
argv: [shell],
218-
cwd: process.cwd(),
219-
env: deps.env,
238+
id: `launch-${link.ordinal}-${++started}`,
239+
argv: [...request.command],
240+
cwd: request.cwd,
241+
env: request.env ?? {},
220242
});
221243
while (true) {
222244
const frame = yield* link.next();
223245
if (frame === undefined) {
224-
return {};
246+
// The worker's channel ended mid-launch. Nothing about that says the
247+
// child stopped, so it is a failure rather than an empty outcome.
248+
throw new Error("the terminal pane stopped answering before its launch settled");
225249
}
226250
if (frame.type === "started") {
227-
// The runtime's own start event, and the only thing that makes this pane
228-
// ready.
251+
// The worker-observed runtime spawn event, and the only thing that makes
252+
// this pane ready.
229253
spawned();
230254
continue;
231255
}
256+
if (frame.type === "busy") {
257+
throw new Error("that terminal pane already has a live child");
258+
}
232259
if (frame.type === "start-failed") {
233-
throw new Error("the pane's shell could not be started");
260+
throw new Error("the terminal pane's child could not be started");
234261
}
235262
if (frame.type === "exited") {
236-
const outcome: TerminalShellOutcome = {};
263+
const outcome: NativeLaunchOutcome = {};
237264
if (frame.exitCode !== undefined) {
238265
outcome.exitCode = frame.exitCode;
239266
}
@@ -245,6 +272,9 @@ function* runShell(
245272
}
246273
}
247274

275+
/** Distinguishes one pane's launches from the next in this invocation. */
276+
let started = 0;
277+
248278
/** Install the tmux provider for this host, when this host can present one. */
249279
export function* installTmuxGridProvider(deps: TmuxProviderDependencies): Operation<void> {
250280
yield* registerTerminalProvider(TMUX_PROVIDER, tmuxGridProvider(deps));

‎packages/cli/tests/fixtures/fake-tmux.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
*/
2020

2121
import { appendFile } from "node:fs/promises";
22+
import { spawn as spawnChild } from "node:child_process";
23+
import type { ChildProcess } from "node:child_process";
2224
import { until } from "effection";
2325
import type { Operation } from "effection";
2426
import { TmuxCommandFailed } from "../../src/terminal/tmux.ts";
@@ -56,6 +58,15 @@ export interface FakeTmuxOptions {
5658
* is the only way to reach the escalation that follows the ask.
5759
*/
5860
readonly stubbornClient?: boolean;
61+
/**
62+
* Actually start the pane commands, the way a server would.
63+
*
64+
* With this on, `new-session` and `split-window` spawn the exact worker
65+
* command they were given, each in a session of its own — which is what tmux
66+
* gives a pane's initial process. That yields real workers on real sockets
67+
* with no real tmux anywhere.
68+
*/
69+
readonly spawnPanes?: boolean;
5970
}
6071

6172
export interface FakeTmux extends Tmux {
@@ -66,6 +77,10 @@ export interface FakeTmux extends Tmux {
6677
readonly serverPid: number;
6778
readonly alive: () => boolean;
6879
readonly clients: readonly string[];
80+
/** Every pane process this server actually started. */
81+
readonly started: readonly ChildProcess[];
82+
/** End every started pane process. */
83+
stopPanes(): void;
6984
/** Say something on the control channel, as the server would. */
7085
say(line: string): Operation<void>;
7186
}
@@ -97,6 +112,7 @@ export function createFakeTmux(options: FakeTmuxOptions): FakeTmux {
97112
/** Window-list order — the order panes were created, which tmux fills by. */
98113
const panes: FakePane[] = [];
99114
const clients: string[] = [];
115+
const started: ChildProcess[] = [];
100116
let alive = false;
101117
let nextPane = 0;
102118
let nextPid = 4000;
@@ -127,6 +143,20 @@ export function createFakeTmux(options: FakeTmuxOptions): FakeTmux {
127143
title: "",
128144
command,
129145
};
146+
if (options.spawnPanes === true && command.length > 0) {
147+
const [program, ...argv] = command;
148+
if (program !== undefined) {
149+
started.push(
150+
spawnChild(program, argv, {
151+
stdio: ["ignore", "pipe", "pipe"],
152+
// A pane's initial process is tmux's session leader, so it is its
153+
// own process group — which is also what keeps a worker's own
154+
// settlement from sweeping this test runner.
155+
detached: true,
156+
}),
157+
);
158+
}
159+
}
130160
const at = after === undefined ? -1 : panes.findIndex((entry) => entry.id === after);
131161
if (at < 0) {
132162
panes.push(created);
@@ -274,6 +304,12 @@ export function createFakeTmux(options: FakeTmuxOptions): FakeTmux {
274304
serverPid,
275305
alive: () => alive,
276306
clients,
307+
started,
308+
stopPanes() {
309+
for (const child of started) {
310+
child.kill("SIGKILL");
311+
}
312+
},
277313
argv(args) {
278314
const mode = args.includes("-C") ? "control" : "attach";
279315
if (mode === "attach") {

0 commit comments

Comments
 (0)