Skip to content

Commit 3c2c88d

Browse files
committed
Read ReplBench reopen locations from CLI exit hints
1 parent 79c7f39 commit 3c2c88d

4 files changed

Lines changed: 147 additions & 83 deletions

File tree

‎examples/repl-bench/lib/driver-bun.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,15 @@ const ACTION_TIMEOUT = 5_000;
5555
const SCRIPTED_STOP_GRACE = 10_000;
5656

5757
function reopenLocation(raw: string): string | null {
58-
// A terminal wraps at display time. If a host inserts line breaks in the
59-
// printed command, the closing quote still delimits the complete location.
60-
const quoted = [...raw.matchAll(/xmd repl '(xmd:\/\/repl\/[^']+)'/g)].at(-1)?.[1];
61-
if (quoted === undefined) {
62-
return null;
63-
}
64-
const location = quoted.replace(/\r?\n[ \t]*/g, "");
65-
return decodeLocation(location).ok ? location : null;
58+
// The restore screen previews the command in the alternate buffer. The
59+
// CLI prints the labelled reopen hint after releasing that buffer.
60+
const restoreBuffer = "\u001b[?1049l";
61+
const restoredAt = raw.lastIndexOf(restoreBuffer);
62+
const output = restoredAt === -1 ? raw : raw.slice(restoredAt + restoreBuffer.length);
63+
const hint =
64+
/(?:^|\n)Reopen this view with:\r?\n xmd repl '(xmd:\/\/repl\/[^'\r\n]+)'(?:\r?\n)?$/u;
65+
const location = hint.exec(output)?.[1];
66+
return location !== undefined && decodeLocation(location).ok ? location : null;
6667
}
6768

6869
export function useDriver(options: Launch) {
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { exec } from "@effectionx/process";
2+
import { ensure, race, spawn, withResolvers } from "effection";
3+
import type { Operation } from "effection";
4+
import { fileURLToPath } from "node:url";
5+
import type { z } from "zod";
6+
import { response } from "./protocol.ts";
7+
import type { Command, Launch } from "./protocol.ts";
8+
import { root } from "./run.ts";
9+
10+
export function* connectDriver(options: Launch) {
11+
const script = fileURLToPath(new URL("../driver.ts", import.meta.url));
12+
const child = yield* exec("bun", {
13+
cwd: root,
14+
arguments: ["--no-install", script, JSON.stringify(options)],
15+
});
16+
const decoder = new TextDecoder();
17+
let pending = "";
18+
let pendingReply = withResolvers<z.infer<typeof response>>();
19+
let busy = false;
20+
let driverEnded = false;
21+
yield* spawn(function* () {
22+
const stream = yield* child.stdout;
23+
while (true) {
24+
const part = yield* stream.next();
25+
if (part.done) {
26+
return;
27+
}
28+
pending += decoder.decode(part.value, { stream: true });
29+
const lines = pending.split("\n");
30+
pending = lines.pop() ?? "";
31+
for (const line of lines) {
32+
pendingReply.resolve(response.parse(JSON.parse(line)));
33+
}
34+
}
35+
});
36+
const ended = yield* spawn(function* () {
37+
const { code, signal } = yield* child.join();
38+
driverEnded = true;
39+
return { error: `Driver exited (${code ?? signal}). Evidence: ${options.directory}` };
40+
});
41+
let stopRequested = false;
42+
function* close() {
43+
if (!driverEnded && !stopRequested) {
44+
stopRequested = true;
45+
child.stdin.send(`${JSON.stringify({ action: "stop" })}\n`);
46+
}
47+
return yield* child.join();
48+
}
49+
yield* ensure(function* () {
50+
yield* close();
51+
});
52+
function* dispatch(command: Command): Operation<unknown> {
53+
if (busy) {
54+
throw new Error("ReplBench actions run one at a time");
55+
}
56+
busy = true;
57+
try {
58+
pendingReply = withResolvers<z.infer<typeof response>>();
59+
child.stdin.send(`${JSON.stringify(command)}\n`);
60+
const result = yield* race([pendingReply.operation, ended]);
61+
if ("error" in result) {
62+
throw new Error(result.error);
63+
}
64+
return result.value;
65+
} finally {
66+
busy = false;
67+
}
68+
}
69+
return { dispatch, close };
70+
}

‎examples/repl-bench/plugin.ts‎

Lines changed: 4 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { ensureDir } from "@effectionx/fs";
2-
import { exec, Stdio } from "@effectionx/process";
2+
import { Stdio } from "@effectionx/process";
33
import {
44
capture,
55
content,
@@ -13,15 +13,7 @@ import {
1313
import { Plugin } from "@executablemd/core/api";
1414
import { command as xmdCommand, cwd, parseDuration, realpath } from "@executablemd/runtime";
1515
import { Test } from "@executablemd/testing";
16-
import {
17-
createContext,
18-
ensure,
19-
type Operation,
20-
race,
21-
spawn,
22-
withResolvers,
23-
type Yielded,
24-
} from "effection";
16+
import { createContext, ensure, type Operation, type Yielded } from "effection";
2517
import { randomUUID } from "node:crypto";
2618
import { extname, join, resolve, sep } from "node:path";
2719
import { fileURLToPath } from "node:url";
@@ -32,16 +24,15 @@ import {
3224
exitResult,
3325
point,
3426
region,
35-
response,
3627
screenshotName,
3728
size,
3829
type Command,
39-
type Launch,
4030
type Region,
4131
type Size,
4232
} from "./lib/protocol.ts";
4333
import { assertPinnedWorktree, prepareRun, root, type PreparedBuild } from "./lib/run.ts";
4434
import { attachSidekick } from "./lib/sidekick.ts";
35+
import { connectDriver } from "./lib/driver-client.ts";
4536

4637
type Execute = (command: Command) => Operation<unknown>;
4738

@@ -131,68 +122,6 @@ const bench = size.partial().extend({
131122
allowAbsolute: z.boolean().default(false),
132123
});
133124

134-
function* connect(options: Launch) {
135-
const script = fileURLToPath(new URL("./driver.ts", import.meta.url));
136-
const child = yield* exec("bun", {
137-
cwd: root,
138-
arguments: ["--no-install", script, JSON.stringify(options)],
139-
});
140-
const decoder = new TextDecoder();
141-
let pending = "";
142-
let pendingReply = withResolvers<z.infer<typeof response>>();
143-
let busy = false;
144-
let driverEnded = false;
145-
yield* spawn(function* () {
146-
const stream = yield* child.stdout;
147-
while (true) {
148-
const part = yield* stream.next();
149-
if (part.done) {
150-
return;
151-
}
152-
pending += decoder.decode(part.value, { stream: true });
153-
const lines = pending.split("\n");
154-
pending = lines.pop() ?? "";
155-
for (const line of lines) {
156-
pendingReply.resolve(response.parse(JSON.parse(line)));
157-
}
158-
}
159-
});
160-
const ended = yield* spawn(function* () {
161-
const { code, signal } = yield* child.join();
162-
driverEnded = true;
163-
return { error: `Driver exited (${code ?? signal}). Evidence: ${options.directory}` };
164-
});
165-
let stopRequested = false;
166-
function* close() {
167-
if (!driverEnded && !stopRequested) {
168-
stopRequested = true;
169-
child.stdin.send(`${JSON.stringify({ action: "stop" })}\n`);
170-
}
171-
return yield* child.join();
172-
}
173-
yield* ensure(function* () {
174-
yield* close();
175-
});
176-
const dispatch: Execute = function* (command) {
177-
if (busy) {
178-
throw new Error("ReplBench actions run one at a time");
179-
}
180-
busy = true;
181-
try {
182-
pendingReply = withResolvers<z.infer<typeof response>>();
183-
child.stdin.send(`${JSON.stringify(command)}\n`);
184-
const result = yield* race([pendingReply.operation, ended]);
185-
if ("error" in result) {
186-
throw new Error(result.error);
187-
}
188-
return result.value;
189-
} finally {
190-
busy = false;
191-
}
192-
};
193-
return { dispatch, close };
194-
}
195-
196125
const Terminal: FunctionComponent = function* (props, invocation) {
197126
if (!invocation.hasContent()) {
198127
throw new Error("Use a paired <Terminal>");
@@ -357,7 +286,7 @@ const XmdRepl: FunctionComponent = function* (props, invocation) {
357286
},
358287
{ at: "min" },
359288
);
360-
const { dispatch, close } = yield* connect(launch);
289+
const { dispatch, close } = yield* connectDriver(launch);
361290
yield* dispatch({ action: "ready" });
362291
let sidekick: Yielded<ReturnType<typeof attachSidekick>> | undefined;
363292
if (attachment !== undefined) {
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { writeTextFile } from "@effectionx/fs";
2+
import { Stdio } from "@effectionx/process";
3+
import { run, scoped } from "effection";
4+
import assert from "node:assert/strict";
5+
import { join, sep } from "node:path";
6+
import process from "node:process";
7+
import { platformDataRoot } from "../../../packages/cli/src/repl-assembly.ts";
8+
import { useMountedHost } from "../../../packages/cli/tests/support/mounted-repl.ts";
9+
import {
10+
invalidRestoreEntries,
11+
savedRestoreFixture,
12+
} from "../../../packages/cli/tests/support/restore-progress.ts";
13+
import { useTempDirectory } from "../../../scripts/lib/temp-directory.ts";
14+
import { connectDriver } from "../lib/driver-client.ts";
15+
import { exitResult } from "../lib/protocol.ts";
16+
import { prepareRun, root } from "../lib/run.ts";
17+
18+
Deno.test("driver reports the final CLI hint and ignores the cold restore command on refusal", () =>
19+
run(function* () {
20+
const cwd = yield* useTempDirectory("xmd-bench-driver-project-");
21+
const home = yield* useTempDirectory("xmd-bench-driver-home-");
22+
const dataRoot = platformDataRoot(
23+
process.platform,
24+
home,
25+
{ XDG_DATA_HOME: join(home, ".local", "share") },
26+
sep,
27+
);
28+
const fixture = yield* savedRestoreFixture(yield* useMountedHost({ dataRoot }), 155);
29+
const location = `xmd://repl/${fixture.id}/entries/entry-2`;
30+
const viewport = { columns: 72, rows: 20 };
31+
for (const refused of [false, true]) {
32+
if (refused) {
33+
yield* writeTextFile(fixture.files.entries, invalidRestoreEntries(fixture));
34+
}
35+
yield* scoped(function* () {
36+
const { launch } = yield* prepareRun(cwd, viewport, [location], {
37+
build: { checkout: root },
38+
home,
39+
});
40+
yield* Stdio.around(
41+
{
42+
// deno-lint-ignore require-yield
43+
*stdout() {},
44+
},
45+
{ at: "min" },
46+
);
47+
const { dispatch, close } = yield* connectDriver(launch);
48+
if (refused) {
49+
yield* dispatch({ action: "wait", text: `xmd repl '${location}'` });
50+
yield* dispatch({ action: "wait", text: "Restoring rounds · 118 / 155 · stopped" });
51+
yield* dispatch({ action: "key", key: "Escape" });
52+
} else {
53+
yield* dispatch({ action: "wait", text: "Saved round 2 witness." });
54+
yield* dispatch({ action: "key", key: "Ctrl+C" });
55+
}
56+
const result = exitResult.parse(yield* dispatch({ action: "exit" }));
57+
assert.equal((yield* close()).code, 0);
58+
assert.deepEqual(
59+
result,
60+
refused ? { exitCode: 1, location: null } : { exitCode: 0, location },
61+
);
62+
});
63+
}
64+
}));

0 commit comments

Comments
 (0)