Files
OmniRoute/tests/unit/conductor-create-route.test.ts
Diego Rodrigues de Sa e Souza a628d28898 feat(dashboard): orchestration canvas fase 2 — repeat action + A2A memory hits (2.6/2.7) (#12508)
* feat(api): conductor task creation route (repeat support)

* feat(a2a): record memoryHits consulted per task (observability, 2.7)

* feat(dashboard): repeat action in orchestration drawer (2.6 — repeat only)

* fix(dashboard): require every field each repeat contract needs before enabling the action

* feat(dashboard): memory-used drawer section + fase2 i18n/changelog (2.7)

* fix(dashboard): validate memoryHits shape before rendering + locale wording fixes

* fix(dashboard,a2a): stop memoryHits leaking into repeats, harden drawer guard + status clamp

Final whole-branch review fix wave for the Orchestration Canvas Fase 2 PR-C.

- a2a: `createTask` stores a COPY of `input.metadata` instead of aliasing it, so the
  observability `memoryHits` written by `executeA2ATaskWithState` no longer leak into
  `task.input.metadata`, into the persisted `a2a_tasks.input_json`, or into the drawer's
  "Repeat" body (a repeated task was born carrying the previous run's memory snippets,
  even with the `OMNIROUTE_A2A_MEMORY_HITS=0` kill-switch on).
- dashboard: `repeatReqFor` strips `memoryHits` from the a2a repeat metadata, so tasks
  persisted before the copy-fix do not propagate them either.
- dashboard: the "Memory used" section now requires all four rendered fields (id, key,
  type, snippet) to be strings — `{ id: "x", key: { a: 1 } }` used to throw "Objects are
  not valid as a React child" and take the whole drawer down.
- dashboard: an `/a2a` action answered with a JSON-RPC error under HTTP 200 is reported as
  a failure (`RPC <code>`, code only — never the upstream message) instead of a success
  toast; the secured-deployment rejection keeps surfacing the sanitized `HTTP 400`.
- api: the conductor task-creation route clamps a hub status outside 400-599 to 502, so an
  out-of-range status can no longer turn a hub refusal into a `RangeError`.
- dashboard: the History tab's `onActionDone` keeps the drawer mounted (and refreshes the
  range) instead of closing it, so the repeat/cancel confirmation is actually visible.
- a2a: documented the recall owner-id limitation — `task.owner` is a SHA-256 key prefix
  while memory rows are keyed by the DB api-key id, and no hash-to-id lookup exists today,
  so recall only resolves under the keyless posture.

* refactor(dashboard): split drawer repeat helpers and test file under the size/complexity gates

---------

Co-authored-by: Markus Hartung <diegosouzapw@users.noreply.github.com>
2026-09-02 20:37:02 -03:00

156 lines
5.8 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createServer, type Server } from "node:http";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-conductor-create-route-"));
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const createRoute = await import("../../src/app/api/conductor/tasks/route.ts");
const servers: Server[] = [];
function fakeHub(routes: Record<string, { status: number; body: unknown }>): Promise<string> {
const server = createServer((req, res) => {
const hit = Object.entries(routes).find(([p]) => (req.url ?? "").startsWith(p));
res.writeHead(hit ? hit[1].status : 404, { "content-type": "application/json" });
res.end(
JSON.stringify(hit ? hit[1].body : { error: "hub: segredo interno que NÃO pode vazar" })
);
});
servers.push(server);
return new Promise((resolve) => {
server.listen(0, "127.0.0.1", () => {
const addr = server.address();
resolve(`http://127.0.0.1:${typeof addr === "object" && addr ? addr.port : 0}`);
});
});
}
function postJson(body: unknown): Request {
return new Request("http://localhost/api/conductor/tasks", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
test.beforeEach(() => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
delete process.env.CONDUCTOR_HUB_URL;
delete process.env.CONDUCTOR_HUB_TOKEN;
});
test.after(async () => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
delete process.env.CONDUCTOR_HUB_URL;
delete process.env.CONDUCTOR_HUB_TOKEN;
while (servers.length > 0) {
const s = servers.pop();
await new Promise((resolve) => s?.close(resolve));
}
});
test("route: requireManagementAuth antes de criar a task no hub", () => {
const src = fs.readFileSync(
path.join(process.cwd(), "src/app/api/conductor/tasks/route.ts"),
"utf8"
);
const authAt = src.indexOf("requireManagementAuth(");
assert.ok(authAt > 0, "handler chama requireManagementAuth");
assert.match(src, /if \(authError\) return authError;/, "curto-circuito no erro de auth");
const proxyAt = src.indexOf("createConductorTask(");
assert.ok(proxyAt > authAt, "proxy ao hub só depois do gate de auth");
assert.ok(
!src.includes("CONDUCTOR_HUB_TOKEN"),
"token nunca manuseado na rota (vive no hubProxy)"
);
});
test("POST /api/conductor/tasks: body válido + hub ok → 201 {task_id}", async () => {
process.env.CONDUCTOR_HUB_URL = await fakeHub({
"/v1/tasks": { status: 201, body: { id: "t_repeat_1" } },
});
process.env.CONDUCTOR_HUB_TOKEN = "tok";
const res = await createRoute.POST(
postJson({ repoUrl: "https://git.x/repo", prompt: "refaça isso" })
);
assert.equal(res.status, 201);
assert.deepEqual(await res.json(), { task_id: "t_repeat_1" });
});
test("POST /api/conductor/tasks: hub recusa (502) → status espelhado, sem corpo upstream", async () => {
process.env.CONDUCTOR_HUB_URL = await fakeHub({
"/v1/tasks": { status: 502, body: { error: "segredo interno que NÃO pode vazar" } },
});
process.env.CONDUCTOR_HUB_TOKEN = "tok";
const res = await createRoute.POST(
postJson({ repoUrl: "https://git.x/repo", prompt: "refaça isso" })
);
assert.equal(res.status, 502);
const text = await res.text();
assert.ok(!text.includes("segredo interno"), "corpo do hub NUNCA repassado (HR#12)");
});
test("POST /api/conductor/tasks: body inválido (sem prompt) → 400", async () => {
const res = await createRoute.POST(postJson({ repoUrl: "https://git.x/repo" }));
assert.equal(res.status, 400);
});
test("POST /api/conductor/tasks: body inválido (sem repoUrl) → 400", async () => {
const res = await createRoute.POST(postJson({ prompt: "refaça isso" }));
assert.equal(res.status, 400);
});
test("POST /api/conductor/tasks: JSON malformado → 400", async () => {
const res = await createRoute.POST(
new Request("http://localhost/api/conductor/tasks", {
method: "POST",
headers: { "content-type": "application/json" },
body: "{not json",
})
);
assert.equal(res.status, 400);
});
/**
* Review finding (Minor A): the hub's status was forwarded verbatim as OUR response status.
* `Response.json()` throws a `RangeError` for anything outside 200-599, and a 3xx/2xx is
* meaningless as an error status anyway — so anything outside 400-599 must become a 502
* instead of an unhandled throw. A 302 with no `Location` is returned as-is by fetch (there
* is nothing to follow), which reproduces the out-of-band status without a fake fetch impl.
*/
test("POST /api/conductor/tasks: status fora de 400-599 vindo do hub é clampado para 502", async () => {
process.env.CONDUCTOR_HUB_URL = await fakeHub({
"/v1/tasks": { status: 302, body: { error: "segredo interno que NÃO pode vazar" } },
});
process.env.CONDUCTOR_HUB_TOKEN = "tok";
const res = await createRoute.POST(
postJson({ repoUrl: "https://git.x/repo", prompt: "refaça isso" })
);
assert.equal(res.status, 502);
const text = await res.text();
assert.ok(!text.includes("segredo interno"), "corpo do hub NUNCA repassado (HR#12)");
});
test("POST /api/conductor/tasks: status 4xx/5xx legítimo do hub continua espelhado", async () => {
process.env.CONDUCTOR_HUB_URL = await fakeHub({
"/v1/tasks": { status: 429, body: { error: "rate limited" } },
});
process.env.CONDUCTOR_HUB_TOKEN = "tok";
const res = await createRoute.POST(
postJson({ repoUrl: "https://git.x/repo", prompt: "refaça isso" })
);
assert.equal(res.status, 429);
});