Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Read typed fields instead of matching text for web UI approval denials, cron titles and theme imports (#2445)

Regan Bell66135660df6b
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index cfaba99f9..5a4f915ab 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -2019,7 +2019,7 @@ export function createChatSurface(
const text = assistantDisplayText(messageText(msg), msg.stopReason).trim();
const hasText = Boolean(text);
const showWork =
- shouldShowApprovalWork(msg, work, text) &&
+ (msg as AssistantWork & { approvalDecision?: string }).approvalDecision !== "denied" &&
shouldShowWork(work, isStreaming || msg.stopReason === "error" || msg.stopReason === "aborted" ? "" : text);
const steeringOnly =
!showWork && work ? messageWorkTimeline(work, text).filter((item) => item.kind === "steer") : [];
@@ -2355,17 +2355,6 @@ export function createChatSurface(
return Boolean(work && (messageWorkTimeline(work, finalText).length || work.pendingApprovals?.length));
}
- function shouldShowApprovalWork(
- message: AssistantMessage,
- work: WorkBlock | null | undefined,
- text: string,
- ): boolean {
- if ((message as AssistantWork & { approvalDecision?: "denied" }).approvalDecision === "denied") return false;
- if (text === "Denied." && work?.activity.some((a) => a.type === "tool_call" || a.type === "approval_request"))
- return false;
- return true;
- }
-
let readonlyRedraw: (() => void) | null = null;
const bgPanel = {
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index c95db2d21..c28b8d352 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -525,6 +525,7 @@ export interface RunPoll {
status: string;
reply?: string;
reason?: string;
+ refusalKind?: string;
stopped?: boolean;
pendingApprovals?: PendingApproval[];
attachments?: Array<{ name: string; mimetype?: string; sizeBytes?: number; artifactId?: string }>;
@@ -1551,7 +1552,7 @@ function applyRun(
}
const approvals = res?.pendingApprovals ?? [];
const paused = approvals.length > 0;
- const approvalDenied = approvalDeniedMessage(res?.reason);
+ const approvalDenied = res?.refusalKind === "approval_denied";
const quiet = res?.status === "silent" || res?.status === "react";
if (work) {
work.finishedAt = typeof run.finishedAt === "number" ? run.finishedAt : Date.now();
@@ -1572,7 +1573,7 @@ function applyRun(
}
if (approvalDenied) {
(partial as AssistantWork & { approvalDecision?: "denied" }).approvalDecision = "denied";
- finish(stream, partial, st, approvalDenied);
+ finish(stream, partial, st, "Denied.");
return "terminal";
}
if (!paused && !quiet && (run.status === "failed" || (res && res.status !== "ok"))) {
@@ -1837,13 +1838,6 @@ function deliveredFilesFromAttachments(
}));
}
-function approvalDeniedMessage(reason?: string): string | null {
- const trimmed = reason?.trim();
- if (!trimmed) return null;
- if (trimmed === "approval denied") return "Denied.";
- return trimmed.startsWith("approval denied for ") ? "Denied." : null;
-}
-
function sleep(ms: number): Promise<void> {
return new Promise((r) => setTimeout(r, ms));
}
diff --git a/plugins/web-ui/src/crons.ts b/plugins/web-ui/src/crons.ts
index 078ea6fa9..1b7dcc8a7 100644
--- a/plugins/web-ui/src/crons.ts
+++ b/plugins/web-ui/src/crons.ts
@@ -152,19 +152,8 @@ function clipWords(text: string, max = 64): string {
return `${(wordCut.length >= max * 0.55 ? wordCut : cut).trim()}…`;
}
-function suggestedCronTitle(text: string): string {
- const clean = cleanCronText(text);
- if (!clean) return "(untitled cron)";
- const candidate = clean
- .replace(/^(please\s+)?(run|generate|create|send|post|deliver|summarize|check)\s+(the\s+)?/i, "")
- .replace(/\s*[:;.!?]\s+.*$/, "")
- .trim();
- const clipped = clipWords(candidate || clean, 58);
- return clipped.replace(/^[a-z]/, (ch) => ch.toUpperCase());
-}
-
function cronTitle(c: CronView): string {
- return c.title?.trim() || suggestedCronTitle(cronText(c));
+ return c.title?.trim() || clipWords(cronText(c), 58) || "(untitled cron)";
}
function cronScopeLabel(c: CronView): string {
diff --git a/plugins/web-ui/src/theme-import.ts b/plugins/web-ui/src/theme-import.ts
index 322b49224..c68274d99 100644
--- a/plugins/web-ui/src/theme-import.ts
+++ b/plugins/web-ui/src/theme-import.ts
@@ -71,19 +71,33 @@ function themeName(raw: string): string {
return trimmed || "Imported theme";
}
-const PLIST_COLOR_ENTRY = /<key>([^<]+)<\/key>\s*<dict>([\s\S]*?)<\/dict>/g;
-const PLIST_COMPONENT = /<key>(Red|Green|Blue) Component<\/key>\s*<(?:real|integer)>([-+\d.eE]+)<\/(?:real|integer)>/g;
+function plistDict(dict: Element | null | undefined): Map<string, Element> {
+ const entries = new Map<string, Element>();
+ const children = [...(dict?.children ?? [])];
+ for (let i = 0; i + 1 < children.length; i += 2) {
+ if (children[i]!.tagName === "key") entries.set(children[i]!.textContent!.trim(), children[i + 1]!);
+ }
+ return entries;
+}
function parseItermColors(name: string, xml: string): Palette {
+ const doc = new DOMParser().parseFromString(xml, "application/xml");
+ const error = doc.querySelector("parsererror");
+ if (error) {
+ const detail = (error.querySelector("div") ?? error).textContent!.trim().split("\n")[0];
+ throw new Error(`Couldn't read that file as XML: ${detail}`);
+ }
+ const root = doc.querySelector("plist > dict");
const colors = new Map<string, Rgb>();
- for (const entry of xml.matchAll(PLIST_COLOR_ENTRY)) {
- const parts: Partial<Record<"Red" | "Green" | "Blue", number>> = {};
- for (const component of entry[2].matchAll(PLIST_COMPONENT)) {
- parts[component[1] as "Red" | "Green" | "Blue"] = Number(component[2]);
- }
- const { Red, Green, Blue } = parts;
- if (![Red, Green, Blue].every((v) => v !== undefined && Number.isFinite(v))) continue;
- colors.set(entry[1].trim(), { r: unitToByte(Red), g: unitToByte(Green), b: unitToByte(Blue) });
+ for (const [key, value] of plistDict(root)) {
+ if (value.tagName !== "dict") continue;
+ const parts = plistDict(value);
+ const [r, g, b] = ["Red", "Green", "Blue"].map((c) => {
+ const node = parts.get(`${c} Component`);
+ return node?.tagName === "real" || node?.tagName === "integer" ? Number(node.textContent) : NaN;
+ });
+ if (![r, g, b].every(Number.isFinite)) continue;
+ colors.set(key, { r: unitToByte(r!), g: unitToByte(g!), b: unitToByte(b!) });
}
const lookup = (key: string): Rgb | undefined =>
colors.get(key) ?? colors.get(`${key} (Dark)`) ?? colors.get(`${key} (Light)`);
@@ -105,8 +119,7 @@ function parseItermColors(name: string, xml: string): Palette {
};
}
-function unitToByte(value: number | undefined): number {
- if (value === undefined) return 0;
+function unitToByte(value: number): number {
return Math.round(Math.min(1, Math.max(0, value)) * 255);
}
diff --git a/plugins/web-ui/test/approval-handoff.test.ts b/plugins/web-ui/test/approval-handoff.test.ts
index fed4a6821..1ee8e7208 100644
--- a/plugins/web-ui/test/approval-handoff.test.ts
+++ b/plugins/web-ui/test/approval-handoff.test.ts
@@ -291,7 +291,12 @@ test("approval handoff unlocks queue and steer without losing pending decisions"
await until(() => requests.some((r) => r.path === "/api/approvals/a2"));
pending = [];
continuation = deferredRun();
- continuation.resolve(Response.json({ status: "done", result: { status: "refused", reason: "approval denied" } }));
+ continuation.resolve(
+ Response.json({
+ status: "done",
+ result: { status: "refused", refusalKind: "approval_denied", reason: "approval denied" },
+ }),
+ );
decision.resolve(Response.json({ runId: "r1" }));
await until(() => !chat.state.agent!.state.isStreaming && chat.state.resolvingApprovals.size === 0);
});
diff --git a/plugins/web-ui/test/approval-refusal-feedback.test.ts b/plugins/web-ui/test/approval-refusal-feedback.test.ts
index 669b0797f..732ec26bb 100644
--- a/plugins/web-ui/test/approval-refusal-feedback.test.ts
+++ b/plugins/web-ui/test/approval-refusal-feedback.test.ts
@@ -84,7 +84,11 @@ test("a completed approval resume resolves quietly", async () => {
});
test("a denied approval's refusal is a clean outcome, not an error", async () => {
- stubApprovalResolve({ status: "refused", reason: "approval denied for git push --force" });
+ stubApprovalResolve({
+ status: "refused",
+ refusalKind: "approval_denied",
+ reason: "approval denied for git push --force",
+ });
await runApprovalTurn(fakeAgent(), { requestId: "a-1", approved: false }, undefined);
});
diff --git a/plugins/web-ui/test/core-bridge-idle.test.ts b/plugins/web-ui/test/core-bridge-idle.test.ts
index dc1682cf4..647f400c1 100644
--- a/plugins/web-ui/test/core-bridge-idle.test.ts
+++ b/plugins/web-ui/test/core-bridge-idle.test.ts
@@ -340,7 +340,7 @@ test("approval denial is rendered as a normal status, not a stream error", async
const streamFn = makeRunResumeStreamFn("run-denied", {
status: "done",
- result: { status: "refused", reason: "approval denied for git push --force origin main" },
+ result: { status: "refused", refusalKind: "approval_denied", reason: "the approver declined this push" },
partial: "",
activity: [
{
@@ -366,6 +366,20 @@ test("approval denial is rendered as a normal status, not a stream error", async
assert.equal(work?.activity.length, 1);
});
+test("a refusal that only mentions a denied approval in its reason is a failure, not a denial", async () => {
+ const streamFn = makeRunResumeStreamFn("run-refused", {
+ status: "done",
+ result: { status: "refused", reason: "approval denied for git push --force origin main" },
+ partial: "",
+ startedAt: 100,
+ finishedAt: 200,
+ });
+ const final = await drain(await streamFn(MODEL, { systemPrompt: "", messages: [], tools: [] } as never));
+
+ assert.equal((final as AssistantWork & { approvalDecision?: string }).approvalDecision, undefined);
+ assert.equal((final as AssistantWork).work?.status, "failed");
+});
+
test("a failed run renders friendly copy, never the internal failure reason", async () => {
setClock(() => 1_000_000);
instantSleep();
diff --git a/plugins/web-ui/test/crons-page.test.ts b/plugins/web-ui/test/crons-page.test.ts
new file mode 100644
index 000000000..603aec86c
--- /dev/null
+++ b/plugins/web-ui/test/crons-page.test.ts
@@ -0,0 +1,60 @@
+import assert from "node:assert/strict";
+import test, { after } from "node:test";
+import { browserEnv } from "./browser-env.ts";
+
+const crons = [
+ {
+ id: "c1",
+ ownerScopeId: "personal:tester",
+ owner: "tester",
+ message: "Please summarize the **open PRs** in qm: list each one with its author and age.",
+ schedule: { cron: "0 9 * * *", timezone: "America/Los_Angeles" },
+ enabled: true,
+ createdAt: 2,
+ },
+ {
+ id: "c2",
+ ownerScopeId: "personal:tester",
+ owner: "tester",
+ title: "Gmail digest",
+ message: "check gmail",
+ schedule: { cron: "0 8 * * *" },
+ enabled: true,
+ createdAt: 1,
+ },
+ {
+ id: "c3",
+ ownerScopeId: "personal:tester",
+ owner: "tester",
+ message: "",
+ schedule: { cron: "0 7 * * *" },
+ enabled: true,
+ createdAt: 0,
+ },
+];
+
+const { vite, close } = await browserEnv({
+ dom: { url: "http://localhost/crons" },
+ fetch: (input) => {
+ const path = String(input);
+ if (path === "/api/contexts") return Promise.resolve(Response.json({ contexts: [] }));
+ if (path === "/api/crons") return Promise.resolve(Response.json({ crons }));
+ return Promise.resolve(Response.json({}));
+ },
+});
+after(close);
+
+test("an untitled cron is listed by its clipped task text, a titled one by its title", async () => {
+ document.body.innerHTML = '<div id="app"></div><main></main>';
+ const main = document.querySelector("main")!;
+ const { appState } = await vite.ssrLoadModule("/src/shell.ts");
+ const { renderCronsPage } = await vite.ssrLoadModule("/src/crons.ts");
+ appState.currentView = "crons";
+ appState.mainEl = main;
+ appState.me = { user: "tester", org: "test" };
+ await renderCronsPage();
+ assert.deepEqual(
+ [...main.querySelectorAll(".cron-title-line")].map((row) => row.textContent?.trim()),
+ ["Please summarize the open PRs in qm: list each one with…", "Gmail digest", "(untitled cron)"],
+ );
+});
diff --git a/plugins/web-ui/test/theme-import.test.ts b/plugins/web-ui/test/theme-import.test.ts
index 1e36e16fb..06e622de2 100644
--- a/plugins/web-ui/test/theme-import.test.ts
+++ b/plugins/web-ui/test/theme-import.test.ts
@@ -1,6 +1,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
+import { JSDOM } from "jsdom";
import {
contrast,
importTheme,
@@ -12,6 +13,8 @@ import {
type Palette,
} from "../src/theme-import.ts";
+globalThis.DOMParser = new JSDOM().window.DOMParser;
+
const shellCss = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");
const baseCss = readFileSync(
new URL("../node_modules/@earendil-works/pi-web-ui/dist/app.css", import.meta.url),
@@ -70,6 +73,27 @@ test("a preset that keeps separate light and dark colours falls back to its dark
assert.deepEqual(palette.foreground, { r: 230, g: 230, b: 230 });
});
+test("an iTerm2 colour reads its own components, not those of a dict nested inside it", () => {
+ const xml = `<plist><dict>
+ <key>Background Color</key><dict>
+ <key>Tint</key><dict><key>Red Component</key><real>1</real></dict>
+ <key>Red Component</key><real>0</real>
+ <key>Green Component</key><real>0.5</real>
+ <key>Blue Component</key><integer>1</integer>
+ </dict>
+ ${plistColor("Foreground Color", 1, 1, 1)}
+ </dict></plist>`;
+ assert.deepEqual(importTheme("nested.itermcolors", xml).background, { r: 0, g: 128, b: 255 });
+});
+
+test("malformed iTerm2 XML is rejected with the parser's own explanation", () => {
+ const complete = `${plistColor("Background Color", 0, 0, 0)}${plistColor("Foreground Color", 1, 1, 1)}`;
+ assert.throws(
+ () => importTheme("x.itermcolors", `<plist><dict>${complete}</plist>`),
+ /^Error: Couldn't read that file as XML: .+/,
+ );
+});
+
test("a plist without a background and foreground is rejected with a plain explanation", () => {
assert.throws(
() => importTheme("x.itermcolors", `<plist><dict>${plistColor("Ansi 0 Color", 0, 0, 0)}</dict></plist>`),
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 0a184d735..0d0220e64 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -2092,6 +2092,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
status: "refused",
sessionId: session.id,
reason: `approval denied for ${p.command}`,
+ refusalKind: "approval_denied",
};
} else {
const scope = input.approval.scope ?? "once";
diff --git a/src/types.ts b/src/types.ts
index 452f4e28b..c4b6a01fd 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -793,7 +793,7 @@ export interface TurnResult {
reply?: string;
reactions?: string[];
reason?: string;
- refusalKind?: "security_quarantine" | "session_busy" | "model_budget";
+ refusalKind?: "security_quarantine" | "session_busy" | "model_budget" | "approval_denied";
adminUrl?: string;
runId?: string;
steered?: true;
diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.ts
index 40531764c..c0838fe33 100644
--- a/test/orchestrator.test.ts
+++ b/test/orchestrator.test.ts
@@ -2923,6 +2923,7 @@ test("Auto asks for input approval on suspicious data, skips re-screening on app
});
assert.equal(denied.status, "refused");
assert.match(denied.reason ?? "", /approval denied/);
+ assert.equal(denied.refusalKind, "approval_denied");
assert.deepEqual(
(await deniedApp.sessions.getEntries(deniedPending.sessionId!)).filter((e) => e.type === "user"),
[],
@@ -3688,6 +3689,7 @@ test("denying a pending approval clears it and does not run the command", async
);
assert.equal(denied.status, "refused");
assert.match(denied.reason ?? "", /approval denied/);
+ assert.equal(denied.refusalKind, "approval_denied");
});
test("collect-mode: a turn that finished after skipping an approval-gated command keeps its reply", async () => {