Долгоживущий агент чата (только для managerIds, тестовый менеджер) и тайминг чата (chat_timing, миграция 016); тесты; docs
All checks were successful
ci / test (push) Successful in 23s
ci / deploy (push) Successful in 1m46s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 12:55:18 +03:00
parent 81634fbfa9
commit 65ab75d378
17 changed files with 733 additions and 29 deletions

View File

@@ -167,6 +167,56 @@ d("консольные агенты (временная БД, фейковый
}
});
it("новая версия агента: только для менеджеров из agent.live.managerIds; в диалоге промт короткий (без инструкций, списка и памяти)", async () => {
calls = [];
const liveCalls: ClaudeCall[] = [];
let active = false;
const liveRunner = {
run: async (c: ClaudeCall) => { liveCalls.push(c); active = true; return { text: "## Ответ менеджеру\n(без ответа)\n## Память\nлайв-память", sessionId: c.sessionId }; },
isActive: () => active, close: () => { active = false; }, closeAll: () => undefined, activeCount: () => (active ? 1 : 0),
};
const base = ctx();
const liveCtx = { ...base, liveRunner, settings: { ...base.settings, live: { managerIds: [MGR], idleMinutes: 10, warmupSeconds: 0 } } };
const slack = { postMessage: async () => true, fileInfo: async () => null, download: async () => 0 };
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
const msg = (text: string, ts: string) => [{ channel: "CLLMTEST", ts, text, fileIds: [] }];
await handleManagerMessages({ ctx: liveCtx, timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("первое сообщение", "1791741300.000001"));
await handleManagerMessages({ ctx: liveCtx, timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("второе сообщение", "1791741310.000001"));
expect(calls).toHaveLength(0); // прежний раннер не использовался
expect(liveCalls).toHaveLength(2);
expect(liveCalls[0]!.prompt).toContain("# Память");
expect(liveCalls[0]!.prompt).toContain("ToolSearch с запросом select:mcp__claude_ai_JobTread__query");
expect(liveCalls[1]!.prompt).toContain("# Продолжение диалога");
expect(liveCalls[1]!.prompt).toContain("второе сообщение");
expect(liveCalls[1]!.prompt).not.toContain("\n# Память\n");
expect(liveCalls[1]!.prompt).not.toContain("# Список задач на сегодня");
// менеджер не из списка: прежняя версия, полный промт каждый раз
script = [ok("## Ответ менеджеру\n(без ответа)\n## Память\nм")];
const other = { ...liveCtx, settings: { ...liveCtx.settings, live: { managerIds: ["other"], idleMinutes: 10, warmupSeconds: 0 } } };
await handleManagerMessages({ ctx: other, timezone: "America/New_York", slack, dryPublish: true }, mgr, msg("третье", "1791741320.000001"));
expect(liveCalls).toHaveLength(2);
expect(calls).toHaveLength(1);
expect(calls[0]!.prompt).toContain("# Память");
});
it("тайминг чата: строка chat_timing с этапами от сообщения в Slack до ответа в Slack", async () => {
calls = [];
const reply = ["## Ответ менеджеру", "тайминг", "## Память", "м"].join(String.fromCharCode(10));
script = [async (c) => ({ text: reply, sessionId: c.sessionId, costUsd: 0.05, timing: { startMs: 50, turnMs: 1234, apiMs: 1000, numTurns: 3, toolCalls: 2 } })];
await db.pool.query("delete from chat_timing");
await db.pool.query("insert into slack_message_log (channel_id, message_ts, manager_person_id, status, received_at) values ('CLLMTEST','1791741990.000001',$1,'received', to_timestamp(1791741991.5))", [MGR]);
const slack = { postMessage: async () => true, postMessageTs: async () => "1791741999.000100", fileInfo: async () => null, download: async () => 0 };
const mgr = { personId: MGR, name: "llmtest-Manager", slackUserId: "ULLMTEST", slackChannelId: "CLLMTEST" };
await handleManagerMessages({ ctx: ctx(), timezone: "America/New_York", slack }, mgr, [{ channel: "CLLMTEST", ts: "1791741990.000001", text: "замер", fileIds: [] }]);
const r = (await db.pool.query("select * from chat_timing")).rows;
expect(r).toHaveLength(1);
expect(r[0]).toMatchObject({ kind: "message", agent_version: "classic", status: "ok", reply_slack_ts: "1791741999.000100", slack_in_ms: 1500, total_ms: 9000, model_ms: 1234, start_ms: 50, api_ms: 1000, num_turns: 3, tool_calls: 2, attempts: 1 });
expect(Number(r[0].cost_usd)).toBeCloseTo(0.05);
for (const k of ["inputs_ms", "drive_ms", "prompt_ms", "queue_ms", "post_ms", "publish_ms", "final_ms", "processing_ms"]) expect(r[0][k], k).not.toBeNull();
expect(r[0].prompt_chars).toBeGreaterThan(100);
expect(r[0].steps.runs).toHaveLength(1);
});
it("событие ассистента: напоминание пишется в историю, ответ менеджера закрывает его; через followup агент спрашивает `что-то ещё`", async () => {
calls = [];
const posted: string[] = [];