Skip to content

Commit 10a3df4

Browse files
authored
feat(mantis): let proof agents extend desktop control (#127271)
* feat(mantis): let proof agents extend desktop control * fix(mantis): constrain desktop extensions * docs(mantis): document desktop action authority * fix(mantis): bind actions to recorded window
1 parent 0c2b224 commit 10a3df4

7 files changed

Lines changed: 348 additions & 29 deletions

File tree

‎.github/codex/prompts/mantis-telegram-desktop-proof.md‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,15 +63,22 @@ Use `$OPENCLAW_TELEGRAM_MANTIS_LANE_CMD` with `--lane baseline|candidate`:
6363
- `requests` (redacted provider requests; zero is a valid recorded fact)
6464
- `press --message-id ID --button INDEX`
6565
- `delete --message-id ID` (only user messages sent in this session)
66+
- `desktop --actions-file <public-json> [--timeout-seconds N]` (run an
67+
agent-authored click/key/type/sleep action sequence in the recorded desktop)
6668
- `view --message-id ID` (scroll Desktop to the exact Telegram server message)
6769
- `screenshot` (returns a public inspection PNG)
6870
- `finish [--focus-message-id ID]` (focus the named message or the latest sent message, stop, capture, publish facts)
6971
- `block --reason TEXT [--missing-primitive NAME]` (clean stop-report)
7072
- `abort` (cleanup after scenario failure)
7173

72-
`start` returns the exact command/budget list. No generic exec/eval or raw
73-
Telegram API exists. If the comparison cannot prove the PR's visible behavior,
74-
use `block` and say why.
74+
`start` returns the exact command/budget list. When the listed primitives cannot
75+
exercise the behavior, extend the harness: write a focused JSON action sequence
76+
under `MANTIS_OUTPUT_DIR` and run it with `desktop`. Actions use Telegram-window
77+
coordinates: `{"command":"click","x":N,"y":N,"button":1}`,
78+
`{"command":"key","keys":["ctrl+a"]}`, `{"command":"type","text":"..."}`,
79+
or `{"command":"sleep","milliseconds":N}`. Inspect a screenshot, adjust the
80+
sequence, and continue the proof. Use `block` only when the ephemeral desktop
81+
itself cannot exercise the behavior.
7582
Raw response events must form a complete provider response; deltas alone do not
7683
produce a final answer. Copy the terminal item and completed-response structure
7784
from `responseEvents` in `scripts/e2e/mock-openai-server.mjs`, and use

‎docs/concepts/mantis.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -202,10 +202,13 @@ in.
202202
### Telegram Desktop recorder
203203

204204
The Telegram Desktop recorder is a standalone operator utility, invoked
205-
directly through `pnpm qa:telegram-desktop-recorder`. It records native
206-
Telegram Desktop and nothing else: it never drives OpenClaw or sends Telegram
207-
messages. Whoever runs it owns the turn — start the SUT, send through a real
208-
Telegram user, then tell the recorder which message to show — and supplies
205+
directly through `pnpm qa:telegram-desktop-recorder`. It never drives OpenClaw.
206+
Its normal recording commands do not send Telegram messages. The optional
207+
`actions` command drives only the measured Telegram window through bounded
208+
`click`, `key`, `type`, and `sleep` actions; those actions can send as the
209+
signed-in Telegram user. Whoever runs it owns the turn and those side effects —
210+
start the SUT, send through a real Telegram user, then tell the recorder which
211+
message to show — and supplies
209212
`--user-driver`, the command the recorder shells out to for the TDLib calls it
210213
cannot make itself (`confirm-qr`, `terminate-session`). Any driver exposing
211214
those two verbs works, including this repo's

‎scripts/e2e/telegram-desktop-recorder-contract.ts‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const recorderSessionBaseSchema = z.object({
2727
/** Telegram Desktop window as placed on the recorded desktop; the crop uses it. */
2828
window: z.object({
2929
height: z.number().int().positive(),
30+
id: z.string().regex(/^0x[0-9a-f]+$/iu),
3031
width: z.number().int().positive(),
3132
x: z.number().int().nonnegative(),
3233
y: z.number().int().nonnegative(),
@@ -70,6 +71,13 @@ export type ViewOptions = {
7071
sessionPath: string;
7172
};
7273

74+
export type ActionsOptions = {
75+
actionsFile: string;
76+
command: "actions";
77+
sessionPath: string;
78+
timeoutSeconds: number;
79+
};
80+
7381
export type ScreenshotOptions = {
7482
command: "screenshot";
7583
output?: string;
@@ -100,6 +108,7 @@ export type ArtifactsOptions = {
100108

101109
type RecorderOptions =
102110
| ArtifactsOptions
111+
| ActionsOptions
103112
| RecoverOptions
104113
| ScreenshotOptions
105114
| StartOptions
@@ -113,6 +122,7 @@ export function recorderUsageText(): string {
113122
" pnpm qa:telegram-desktop-recorder artifacts --session <recorder.json>",
114123
' pnpm qa:telegram-desktop-recorder start --output-dir <dir> --chat <-100groupId> --user-driver "<space-separated cmd prefix>" [options]',
115124
" pnpm qa:telegram-desktop-recorder view --session <recorder.json> --message-id <id>",
125+
" pnpm qa:telegram-desktop-recorder actions --session <recorder.json> --actions-file <json> [--timeout-seconds <seconds>]",
116126
" pnpm qa:telegram-desktop-recorder screenshot --session <recorder.json> [--output <png>]",
117127
" pnpm qa:telegram-desktop-recorder recover --session <recorder.json>",
118128
" pnpm qa:telegram-desktop-recorder stop --session <recorder.json> [--crop telegram-window] [--keep-box]",
@@ -163,7 +173,7 @@ export function parseRecorderArgs(argv: string[]): RecorderOptions {
163173
throw new Error(recorderUsageText());
164174
}
165175
const parsedCommand = z
166-
.enum(["artifacts", "recover", "screenshot", "start", "status", "stop", "view"])
176+
.enum(["actions", "artifacts", "recover", "screenshot", "start", "status", "stop", "view"])
167177
.safeParse(rawCommand);
168178
if (!parsedCommand.success) {
169179
throw new Error(`Unknown command: ${rawCommand}\n\n${recorderUsageText()}`);
@@ -205,11 +215,13 @@ export function parseRecorderArgs(argv: string[]): RecorderOptions {
205215
])
206216
: command === "view"
207217
? new Set(["--message-id", "--session"])
208-
: command === "screenshot"
209-
? new Set(["--output", "--session"])
210-
: command === "stop"
211-
? new Set(["--crop", "--session"])
212-
: new Set(["--session"]);
218+
: command === "actions"
219+
? new Set(["--actions-file", "--session", "--timeout-seconds"])
220+
: command === "screenshot"
221+
? new Set(["--output", "--session"])
222+
: command === "stop"
223+
? new Set(["--crop", "--session"])
224+
: new Set(["--session"]);
213225
for (const flag of values.keys()) {
214226
if (!allowed.has(flag)) {
215227
throw new Error(`${flag} is not available for ${command}.`);
@@ -266,6 +278,14 @@ export function parseRecorderArgs(argv: string[]): RecorderOptions {
266278
positiveInteger(messageId, "--message-id");
267279
return { command, messageId, sessionPath };
268280
}
281+
if (command === "actions") {
282+
return {
283+
actionsFile: requiredString(values, "--actions-file"),
284+
command,
285+
sessionPath,
286+
timeoutSeconds: positiveInteger(values.get("--timeout-seconds") ?? "60", "--timeout-seconds"),
287+
};
288+
}
269289
if (command === "screenshot") {
270290
return { command, output: values.get("--output"), sessionPath };
271291
}

‎scripts/e2e/telegram-desktop-recorder.ts‎

Lines changed: 106 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
import {
2727
parseRecorderArgs,
2828
readRecorderSession,
29+
type ActionsOptions,
2930
type ArtifactsOptions,
3031
type RecoverOptions,
3132
recorderUsageText,
@@ -174,14 +175,13 @@ export DISPLAY=:99
174175
win="$(wmctrl -lx | awk 'tolower($0) ~ /telegramdesktop/ {print $1; exit}')"
175176
test -n "$win"
176177
eval "$(xdotool getwindowgeometry --shell "$win")"
177-
printf '%s %s %s %s\n' "$X" "$Y" "$WIDTH" "$HEIGHT"`;
178+
printf '%s %s %s %s %s\n' "$win" "$X" "$Y" "$WIDTH" "$HEIGHT"`;
178179
}
179180

180-
function renderHideTelegramWindow(): string {
181+
function renderHideTelegramWindow(windowId: string): string {
181182
return `set -euo pipefail
182183
export DISPLAY=:99
183-
win="$(wmctrl -lx | awk 'tolower($0) ~ /telegramdesktop/ {print $1; exit}')"
184-
test -n "$win"
184+
win=${shellQuote(windowId)}
185185
xdotool windowminimize "$win"
186186
sleep 0.2`;
187187
}
@@ -236,19 +236,26 @@ exit 1`;
236236

237237
export function parseWindowGeometry(raw: string): {
238238
height: number;
239+
id: string;
239240
width: number;
240241
x: number;
241242
y: number;
242243
} {
243-
const parts = raw.trim().split(/\s+/u).map(Number);
244-
if (parts.length !== 4 || parts.some((value) => !Number.isFinite(value) || value < 0)) {
244+
const [id, ...rawGeometry] = raw.trim().split(/\s+/u);
245+
const parts = rawGeometry.map(Number);
246+
if (
247+
!id ||
248+
!/^0x[0-9a-f]+$/iu.test(id) ||
249+
parts.length !== 4 ||
250+
parts.some((value) => !Number.isFinite(value) || value < 0)
251+
) {
245252
throw new Error(`Telegram Desktop window geometry was not readable: ${raw.trim()}`);
246253
}
247254
const [x, y, width, height] = parts as [number, number, number, number];
248255
if (width < 200 || height < 200) {
249256
throw new Error(`Telegram Desktop window is too small to crop: ${width}x${height}`);
250257
}
251-
return { height, width, x, y };
258+
return { height, id, width, x, y };
252259
}
253260

254261
function driverCommand(userDriver: string[], args: string[]) {
@@ -611,7 +618,7 @@ async function startRecorderAttempt(
611618
// The lane clears prior history before recorder start. Keep the empty chat hidden until
612619
// the first session-owned send is ready, so setup frames reveal neither account UI nor chat.
613620
await operations.sshRun({
614-
command: renderHideTelegramWindow(),
621+
command: renderHideTelegramWindow(windowGeometry.id),
615622
cwd,
616623
inspect,
617624
run: operations.runCommand,
@@ -815,6 +822,93 @@ export async function viewRecorder(
815822
});
816823
}
817824

825+
const desktopActionsSchema = z
826+
.array(
827+
z.discriminatedUnion("command", [
828+
z.object({
829+
button: z.number().int().min(1).max(5).default(1),
830+
command: z.literal("click"),
831+
x: z.number().int().nonnegative(),
832+
y: z.number().int().nonnegative(),
833+
}),
834+
z.object({
835+
command: z.literal("key"),
836+
keys: z
837+
.array(z.string().regex(/^[A-Za-z0-9_+:-]+$/u))
838+
.min(1)
839+
.max(20),
840+
}),
841+
z.object({ command: z.literal("sleep"), milliseconds: z.number().int().min(1).max(30_000) }),
842+
z.object({
843+
command: z.literal("type"),
844+
delayMs: z.number().int().min(0).max(1_000).default(5),
845+
text: z.string().min(1).max(10_000),
846+
}),
847+
]),
848+
)
849+
.min(1)
850+
.max(100);
851+
852+
export async function runRecorderActions(
853+
cwd: string,
854+
opts: ActionsOptions,
855+
operations: RecorderOperations = defaultOperations,
856+
): Promise<{ results: Array<{ command: string; stderr: string; stdout: string }> }> {
857+
const sessionPath = resolveRecorderPath(cwd, opts.sessionPath, "--session");
858+
const actionsPath = resolveRecorderPath(cwd, opts.actionsFile, "--actions-file");
859+
const actionsStat = fs.lstatSync(actionsPath);
860+
if (!actionsStat.isFile() || actionsStat.isSymbolicLink() || actionsStat.size > 64 * 1024) {
861+
throw new Error("--actions-file must be a regular file no larger than 64 KiB.");
862+
}
863+
const actions = desktopActionsSchema.parse(JSON.parse(fs.readFileSync(actionsPath, "utf8")));
864+
const session = readRecorderSession(sessionPath);
865+
for (const action of actions) {
866+
if (
867+
action.command === "click" &&
868+
(action.x >= session.window.width || action.y >= session.window.height)
869+
) {
870+
throw new Error("click coordinates must stay inside the Telegram window.");
871+
}
872+
}
873+
const crabboxBin = process.env.OPENCLAW_TELEGRAM_USER_CRABBOX_BIN?.trim() || "crabbox";
874+
const inspect = await sessionInspect({ crabboxBin, cwd, operations, session });
875+
const results: Array<{ command: string; stderr: string; stdout: string }> = [];
876+
for (const action of actions) {
877+
if (action.command === "sleep") {
878+
await sleep(action.milliseconds);
879+
results.push({ command: "sleep", stderr: "", stdout: "" });
880+
continue;
881+
}
882+
const telegramWindow = `win=${shellQuote(session.window.id)}
883+
if ! wmctrl -lx | awk -v win="$win" 'tolower($1) == tolower(win) && tolower($0) ~ /telegramdesktop/ {found=1} END {exit !found}'; then
884+
echo "Recorded Telegram window $win no longer exists." >&2
885+
exit 1
886+
fi
887+
eval "$(xdotool getwindowgeometry --shell "$win")"
888+
if [ "$X" -ne ${session.window.x} ] || [ "$Y" -ne ${session.window.y} ] || [ "$WIDTH" -ne ${session.window.width} ] || [ "$HEIGHT" -ne ${session.window.height} ]; then
889+
echo "Recorded Telegram window $win moved or resized." >&2
890+
exit 1
891+
fi
892+
`;
893+
const actionCommand =
894+
action.command === "click"
895+
? `xdotool windowactivate --sync "$win" mousemove --window "$win" ${action.x} ${action.y} click ${action.button}`
896+
: action.command === "key"
897+
? `xdotool key --window "$win" ${action.keys.map(shellQuote).join(" ")}`
898+
: `xdotool type --window "$win" --delay ${action.delayMs} -- ${shellQuote(action.text)}`;
899+
const result = await operations.sshRun({
900+
command: `export DISPLAY=:99\n${telegramWindow}${actionCommand}`,
901+
cwd,
902+
inspect,
903+
run: operations.runCommand,
904+
stdio: "pipe",
905+
timeoutMs: opts.timeoutSeconds * 1000,
906+
});
907+
results.push({ command: action.command, ...result });
908+
}
909+
return { results };
910+
}
911+
818912
async function captureScreenshot(params: {
819913
crop: ReturnType<typeof proofViewport>;
820914
cwd: string;
@@ -1067,6 +1161,10 @@ async function main(): Promise<void> {
10671161
console.log(`Telegram Desktop opened message ${opts.messageId}.`);
10681162
return;
10691163
}
1164+
if (opts.command === "actions") {
1165+
console.log(JSON.stringify(await runRecorderActions(cwd, opts), null, 2));
1166+
return;
1167+
}
10701168
if (opts.command === "screenshot") {
10711169
console.log(await screenshotRecorder(cwd, opts));
10721170
return;

‎scripts/e2e/telegram-mantis-lane.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ const commandOptions: Record<string, readonly string[]> = {
112112
abort: ["--lane"],
113113
block: ["--lane", "--missing-primitive", "--reason"],
114114
delete: ["--lane", "--message-id"],
115+
desktop: ["--lane", "--actions-file", "--timeout-seconds"],
115116
finish: ["--lane", "--focus-message-id"],
116117
mock: ["--lane", "--response-file", "--response-events-file", "--chunk-delay-ms"],
117118
observe: ["--lane", "--seconds", "--since"],
@@ -1033,6 +1034,56 @@ async function observerAction(
10331034
return response;
10341035
}
10351036

1037+
async function runDesktopActions(
1038+
state: ActiveSession,
1039+
values: Map<string, string>,
1040+
roots: Roots,
1041+
): Promise<Record<string, unknown>> {
1042+
const actions = readPublicFile(
1043+
roots.outputRoot,
1044+
required(values, "--actions-file"),
1045+
"--actions-file",
1046+
64 * 1024,
1047+
);
1048+
if (!actions.text.trim()) {
1049+
throw new Error("--actions-file must not be empty.");
1050+
}
1051+
const timeoutSeconds = values.has("--timeout-seconds")
1052+
? numberOption(values, "--timeout-seconds", 300, 1)
1053+
: 60;
1054+
const privateActions = path.join(
1055+
state.privateDir,
1056+
`desktop-actions-${state.invocations.length + 1}.json`,
1057+
);
1058+
fs.mkdirSync(state.privateDir, { recursive: true });
1059+
fs.writeFileSync(privateActions, actions.text, { mode: 0o640 });
1060+
const actionsSha256 = createHash("sha256").update(actions.text).digest("hex");
1061+
appendInvocation(state, "desktop", {
1062+
actionsFile: actions.relative,
1063+
actionsSha256,
1064+
timeoutSeconds,
1065+
});
1066+
saveActive(roots.sessionRoot, state);
1067+
const result = z
1068+
.object({
1069+
results: z.array(z.object({ command: z.string(), stderr: z.string(), stdout: z.string() })),
1070+
})
1071+
.parse(
1072+
JSON.parse(
1073+
await runCommandOutput(requiredEnv("OPENCLAW_TELEGRAM_DESKTOP_RECORDER_CMD"), [
1074+
"actions",
1075+
"--session",
1076+
recorderRelativePath(state.recorderSession),
1077+
"--actions-file",
1078+
recorderRelativePath(privateActions),
1079+
"--timeout-seconds",
1080+
String(timeoutSeconds),
1081+
]),
1082+
),
1083+
);
1084+
return { ...result, actionsSha256 };
1085+
}
1086+
10361087
async function focusMessage(state: ActiveSession, messageId: string): Promise<void> {
10371088
if (!/^\d+$/u.test(messageId) || BigInt(messageId) < 1n) {
10381089
throw new Error("--message-id must be a positive Telegram server message id.");
@@ -1445,6 +1496,8 @@ async function main(): Promise<void> {
14451496
const credential = credentialSchema.parse(readJson(roots.credentialFile));
14461497
if (cli.command === "mock") {
14471498
outputJson(updateMockResponse(state, cli.values, roots.outputRoot));
1499+
} else if (cli.command === "desktop") {
1500+
outputJson(await runDesktopActions(state, cli.values, roots));
14481501
} else if (cli.command === "send") {
14491502
const sent = await sendVisibleMessage(state, cli.values, roots, credential.sutToken);
14501503
outputJson({ ...sent.response, revealedMessageId: sent.revealedMessageId });

0 commit comments

Comments
 (0)