Отключение агента менеджера: на время и до команды владельца (миграция 017, API pause/resume, события, шаг 2 и приём сообщений); тесты; docs
Some checks failed
ci / deploy (push) Has been cancelled
ci / test (push) Has been cancelled

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-19 19:56:51 +03:00
parent 3e696bb53f
commit f3e0b0618e
13 changed files with 273 additions and 22 deletions

View File

@@ -8,7 +8,10 @@ import { KeyedMutex, Semaphore } from "./agents/pool.js";
import { parseSections } from "./agents/sections.js";
import { AgentFailure, closeOrphanRuns, runManagerAgent, type AgentContext } from "./agents/session.js";
import { runStep2, saveProblems } from "./agents/step2.js";
import Fastify from "fastify";
import { registerAgentRoutes } from "./agents-api.js";
import { buildApi } from "./http-api.js";
import { listManagers } from "./managers.js";
import { handleManagerMessages } from "./slack/chat.js";
import { DriveInbox } from "./slack/drive-inbox.js";
import { SlackIntake } from "./slack/intake.js";
@@ -221,6 +224,72 @@ d("консольные агенты (временная БД, фейковый
expect(r[0].steps.runs).toHaveLength(1);
});
it("отключение агента: на время и до команды; события и сообщения менеджера не идут, после включения всё работает", async () => {
calls = [];
const app = Fastify();
registerAgentRoutes(app, db.pool);
await db.pool.query("insert into assistant_project (jt_job_id, manager_person_id, mode, is_enabled) values ('llmtest-pause',$1,'test',true)", [MGR]);
const ids = async (includePaused = false) => (await listManagers(db.pool, ["test"], { includePaused })).map((m) => m.personId);
const post = (url: string, payload?: object) => app.inject({ method: "POST", url, payload: payload ?? {} });
const nl = String.fromCharCode(10);
const intakeSend = async (ts: string, text: string) => {
const posted: string[] = [];
const deps = { ctx: ctx(), timezone: "America/New_York", slack: { postMessage: async (_c: string, x: string) => { posted.push(x); return true; }, fileInfo: async () => null, download: async () => 0 } };
const intake = new SlackIntake(deps, { channelIds: [], debounceMs: 600_000 });
await intake.onEvent({ type: "message", channel: "CLLMTEST", user: "ULLMTEST", ts, text });
await intake.flush(MGR);
await intake.idle();
intake.stop();
return posted;
};
try {
expect(await ids()).toContain(MGR);
// до команды владельца (срок не задан)
let r = await post("/agents/" + MGR + "/pause", { reason: "тест" });
expect(r.json()).toMatchObject({ ok: true, paused: true, indefinite: true, until: null, reason: "тест" });
expect(await ids()).not.toContain(MGR); // системные события ему не идут
expect(await ids(true)).toContain(MGR); // ручные запуски владельца - идут
expect(await intakeSend("7.1", "сообщение отключённому")).toEqual([]);
expect(calls).toHaveLength(0); // агент не запускался
const ignored = await db.pool.query("select status from slack_message_log where message_ts = '7.1'");
expect(ignored.rows).toEqual([{ status: "ignored" }]);
const listed = ((await app.inject("/agents")).json() as Array<Record<string, unknown>>).find((a) => a.id === MGR);
expect(listed).toMatchObject({ paused: true, paused_indefinitely: true });
// включить обратно
r = await post("/agents/" + MGR + "/resume");
expect(r.json()).toMatchObject({ ok: true, paused: false });
expect(await ids()).toContain(MGR);
script = [ok(["## Ответ менеджеру", "после включения", "## Память", "м"].join(nl))];
expect(await intakeSend("7.2", "сообщение после включения")).toEqual(["после включения"]);
// на время
r = await post("/agents/" + MGR + "/pause", { hours: 2 });
const j = r.json() as { paused: boolean; indefinite: boolean; until: string };
expect(j).toMatchObject({ paused: true, indefinite: false });
expect(new Date(j.until).getTime() - Date.now()).toBeGreaterThan(1.9 * 3600_000);
expect(await ids()).not.toContain(MGR);
await db.pool.query("update construction_manager set paused_until = now() - interval '1 minute' where person_id = $1", [MGR]); // срок истёк
expect(await ids()).toContain(MGR);
expect((await post("/agents/" + MGR + "/pause", { until: "2020-01-01T00:00:00Z" })).statusCode).toBe(400);
expect((await post("/agents/" + MGR + "/pause", { until: "не дата" })).statusCode).toBe(400);
expect((await post("/agents/" + MGR + "/pause", { days: 4000 })).statusCode).toBe(400);
expect((await post("/agents/00000000-0000-4000-8000-000000000000/pause")).statusCode).toBe(404);
// все менеджеры
const all = (await post("/agents/pause-all", { reason: "общая остановка" })).json() as { managers: number };
expect(all.managers).toBeGreaterThanOrEqual(1);
expect(await ids()).not.toContain(MGR);
expect(((await post("/agents/resume-all")).json() as { managers: number }).managers).toBeGreaterThanOrEqual(1);
expect(await ids()).toContain(MGR);
} finally {
await db.pool.query("update construction_manager set agent_paused = false, paused_until = null where person_id = $1", [MGR]);
await db.pool.query("delete from assistant_project where jt_job_id = 'llmtest-pause'");
await app.close();
}
});
it("событие ассистента: напоминание пишется в историю, ответ менеджера закрывает его; через followup агент спрашивает `что-то ещё`", async () => {
calls = [];
const posted: string[] = [];