Files
loki/scripts/test/notify-close.ts
CatoandClaude Opus 5.5 a1b9d212b2 fix: no silent standing approvals for Loki's own ideas, and no dead-end stalls (#1168)
* fix(approvals): standing approvals cover what you ask for, never Loki's own ideas

The owner saw "✅ Done — Check in with Rajif Rao" on Telegram and feared Loki
had contacted someone without permission. Nothing was sent: a commitment is a
row in the operator's own list. But the path was still wrong. The check-in
producer writes its suggestions as create_commitment rows, so the "Record
commitments I mention" standing approval silently approved one nobody
mentioned, and the confirmation read as if the check-in had happened.

- standing-approval: RAIL 0. Every proposal now carries a required origin
  ("operator" | "loki"); only operator proposals may ride a standing rule.
- enqueueAction takes the origin from every caller and stamps it on the
  payload so the calendar drain's confirmation can say the same thing.
- Check-ins, the night plan and propose calls marked "not asked for" are
  origin "loki"; chat, the agent's propose tool and MCP are "operator".
- A commitment's confirmation now reads "📌 Added to your commitments —
  “Reach out to …”. A reminder for you. Nothing was sent to anyone."
- The Approvals setting says Loki's own suggestions still wait for a yes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XXM7KBHBym6au4L6sxShwz

* fix(control): a stalled queue always has a button, and names who holds it

On a phone the owner tapped "Run it in the cloud" under "Waiting for this
computer". The next refresh said "Stalled — 2 dispatches queued for 118m, the
builder is connected but not executing them. Restart the desktop app or check
the cloud builder if this persists", with no button, under a foot line that
read "This computer offline". Three things were wrong:

- The stall clock ran from created_at, so work the cloud had held for seconds
  was reported as 118 minutes stuck. A reroute now stamps reroutedAt and the
  detector measures from it.
- The sentence blamed a desktop app for work the cloud was holding. The stall
  query now counts cloud-held rows too, and the headline names the builder
  that actually has the work and whether it is connected.
- A genuine stall had no way forward. It now offers "Stop waiting"
  (POST /api/control/stop-waiting): the stuck rows close as failed dispatches,
  where Retry sends them again verbatim and Dismiss clears them, and their
  runs close so the project's lane is free. The consequence is stated in the
  headline before the tap.

Both hero queue buttons now report what they did ("Handed 2 dispatches to the
cloud builder.", or why a project stayed put) instead of firing and forgetting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XXM7KBHBym6au4L6sxShwz

* fix(loki): a screenshot sent with "fix this" finds the project it shows

On a phone the owner opened a new chat, attached a screenshot of Loki's own
Control page and wrote "Fix this so it works properly". The thread read
"No project — answers only": the text named no project, so the screenshot
fast path could not dispatch, and the picture was only ever described,
never used to decide where the fix should go.

- The vision preflight now opens with one line, "Shown: <app or site, and
  any URL visible>".
- projectShownInScreenshot picks a project only when the evidence points at
  exactly one: a project's live host visible in the analysis (compared whole,
  so loki.orangecat.ch is Loki and not OrangeCat), else a single project
  named on the Shown line. Projects merely listed on the screen do not count,
  and two candidates stay a question for the person.
- When Loki chose the project this way the reply says so and how to pick a
  different one, so a guess never reads as the person's own choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XXM7KBHBym6au4L6sxShwz

* fix(notify): a failed run's Telegram message links to where Retry is

"❌ loki: run error … choose another AI provider and Retry" arrived with
nothing to tap. Failed, partial and timed-out runs now carry one button,
"Open <project> in Control", which lands on the project card where Retry and
the provider switch live. Successes stay buttonless.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XXM7KBHBym6au4L6sxShwz

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-12 06:40:51 -07:00

167 lines
6.4 KiB
TypeScript

/**
* Inline tests for the chat close-notification decision
* (lib/orchestration/notify-close.ts, pure half). The contract under test:
* ONLY runs that opted in via payload.notifyOnClose ever produce a message —
* a formatting regression here either spams the phone with the fleet's whole
* churn or silently swallows chat-dispatch outcomes.
*
* Run: npm run test:notify-close
*/
import {
formatRunCloseMessage,
runCloseButtons,
shouldAnnounceOnClose,
} from "@/lib/orchestration/notify-close-format";
function assert(condition: boolean, message: string): void {
if (!condition) throw new Error(message);
}
function runTests(): void {
let passed = 0;
const check = (label: string, fn: () => void) => {
fn();
passed += 1;
console.log(` ✓ ${label}`);
};
const base = {
projectKey: "orangecat",
outcome: "success",
finishedAt: new Date("2026-08-13T12:00:00Z"),
payload: { projectKey: "orangecat", projectPath: "/x", notifyOnClose: true },
} as Parameters<typeof formatRunCloseMessage>[0];
check("no opt-in ⇒ null (UI dispatches stay silent)", () => {
assert(
formatRunCloseMessage({
...base,
payload: { projectKey: "orangecat", projectPath: "/x" },
}) === null,
"expected null without notifyOnClose",
);
});
check("opted-in but not finished ⇒ null", () => {
assert(
formatRunCloseMessage({ ...base, finishedAt: null }) === null,
"expected null for open run",
);
});
check("a run closed from a handoff says what the agent did", () => {
// The local PTY path sets no resultText — the agent's words live in the
// handoff summary. Reading only resultText sent "🟡 orangecat: run
// partial" and nothing else to the person's phone.
const msg = formatRunCloseMessage({
...base,
outcome: "partial",
summary: {
done: "e2e ok — no changes",
next: "Definition of done not yet met — include a committed change.",
tests: "",
todos: "",
health: "",
},
} as Parameters<typeof formatRunCloseMessage>[0]);
assert(!!msg && msg.includes("e2e ok — no changes"), `got: ${msg}`);
assert(!!msg && msg.includes("Next: Definition of done"), `got: ${msg}`);
});
check("success carries ✅ + project + outcome", () => {
const msg = formatRunCloseMessage(base);
assert(!!msg && msg.startsWith("✅ orangecat: run success"), `got: ${msg}`);
});
check("failure carries ❌ and the error text", () => {
const msg = formatRunCloseMessage({
...base,
outcome: "error",
payload: { ...base.payload!, error: "runner nack" },
});
assert(!!msg && msg.startsWith("❌") && msg.includes("runner nack"), `got: ${msg}`);
});
check("partial carries 🟡", () => {
const msg = formatRunCloseMessage({ ...base, outcome: "partial" });
assert(!!msg && msg.startsWith("🟡"), `got: ${msg}`);
});
// The reaper's verdicts must be announceable. The reaper closes runs with a
// raw UPDATE that bypasses updateOrchestrationRun, so it calls notifyRunClosed
// itself — if this formatter ever went success-only, a timed-out run would go
// silent again, which is exactly how visitor-feedback fixes sat "in progress"
// for weeks after their runs had died.
check("reaper timeout is announced, not swallowed", () => {
const msg = formatRunCloseMessage({
...base,
outcome: "timeout",
payload: {
...base.payload!,
error: "Timed out — run exceeded maximum duration and was cleaned up",
},
});
assert(!!msg && msg.startsWith("❌"), `timeout must produce a message, got: ${msg}`);
assert(msg!.includes("Timed out"), `timeout message must carry the reason, got: ${msg}`);
});
check("resultText wins over error and is truncated to 600 chars", () => {
const msg = formatRunCloseMessage({
...base,
payload: { ...base.payload!, resultText: "R".repeat(1000), error: "ignored" },
});
const body = msg?.split("\n")[1] ?? "";
assert(body.length === 600 && !msg?.includes("ignored"), `body len ${body.length}`);
});
// ── Who gets told ─────────────────────────────────────────────────────────
//
// This is the rule that shipped OFF. `notifyOnClose` was plumbed end to end,
// unit-tested, and set by nothing but a test fixture — so no dispatch ever
// announced itself, and clicking Send produced silence. The gate is now the
// auth path: a person gets told, a machine does not.
check("a browser session announces — a person clicked and may walk away", () => {
assert(shouldAnnounceOnClose({ via: "session" }) === true, "session must announce");
});
check("a bearer token stays silent — autopilot churn must not reach the phone", () => {
assert(shouldAnnounceOnClose({ via: "token" }) === false, "token must stay silent");
});
check("no actor stays silent", () => {
assert(shouldAnnounceOnClose(null) === false, "null actor must not announce");
assert(shouldAnnounceOnClose(undefined) === false, "undefined actor must not announce");
});
check("an explicit value wins in BOTH directions", () => {
// Chat opts in deliberately even though it authenticates with a token...
assert(shouldAnnounceOnClose({ via: "token" }, true) === true, "explicit true must win");
// ...and a noisy UI-initiated loop can opt out.
assert(shouldAnnounceOnClose({ via: "session" }, false) === false, "explicit false must win");
});
check("only an actual boolean counts as explicit", () => {
// A stray undefined must fall through to the actor rule rather than being
// read as "false" — that would silently restore the shipped-off behavior.
assert(
shouldAnnounceOnClose({ via: "session" }, undefined) === true,
"undefined is not an opt-out",
);
});
check("a failed run links to the project in Control; a success has no button", () => {
const failed = runCloseButtons({ projectKey: "loki", outcome: "error" });
assert(failed.length === 1 && failed[0].length === 1, "one button for a failure");
assert(failed[0][0].url.endsWith("/control?focus=loki"), `url: ${failed[0][0].url}`);
assert(
runCloseButtons({ projectKey: "loki", outcome: "success" }).length === 0,
"none on success",
);
});
console.log(`\n${passed} passed`);
}
runTests();