Проектные каналы: тихий режим, recap для Daily Log; Huddle через message_changed; короткие напоминания
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,7 @@ import { isReplyMode } from "./tts.js";
|
||||
import { loadFragment } from "../agents/prompts.js";
|
||||
import { pauseState } from "../pause.js";
|
||||
import { promptSideFor } from "../agents/session.js";
|
||||
import { getRecapState, recapDelayMs } from "./recap.js";
|
||||
import { handleManagerMessages, type ChatDeps, type IncomingMessage, type ManagerInfo, type ProjectContext } from "./chat.js";
|
||||
|
||||
interface Pending {
|
||||
@@ -25,16 +26,32 @@ export function rowToManager(r: Record<string, unknown>): ManagerInfo {
|
||||
|
||||
const ACCEPTED_SUBTYPES = new Set([undefined, "file_share", "thread_broadcast"]);
|
||||
|
||||
type SlackFileRef = { id?: string; name?: string; mimetype?: string; filetype?: string };
|
||||
const huddleFilesOf = (ev: Record<string, unknown>): SlackFileRef[] =>
|
||||
((ev.files as SlackFileRef[] | undefined) ?? []).filter((f) => /huddle|vnd\.slack-docs/i.test(`${f.name ?? ""} ${f.mimetype ?? ""} ${f.filetype ?? ""}`));
|
||||
|
||||
/**
|
||||
* Заметки Huddle Slack прикрепляет к родительскому сообщению (subtype huddle_thread) правкой - приходит message_changed.
|
||||
* Правка с файлами заметок превращается в обычное сообщение того же ts (дубли отсекает журнал); прочие правки не обрабатываются.
|
||||
*/
|
||||
export function normalizeHuddleEvent(ev: Record<string, unknown>): Record<string, unknown> | null {
|
||||
if (ev.subtype !== "message_changed") return ev;
|
||||
const inner = ev.message as Record<string, unknown> | undefined;
|
||||
if (!inner || !huddleFilesOf(inner).length) return null;
|
||||
return { ...inner, type: "message", channel: ev.channel };
|
||||
}
|
||||
|
||||
/** Приём сообщений Slack: фильтр, журнал (защита от дублей), накопление сообщений менеджера (debounce) и запуск шага 4. */
|
||||
export class SlackIntake {
|
||||
private pending = new Map<string, Pending>();
|
||||
private inflight = new Set<Promise<void>>();
|
||||
|
||||
private followups = new Map<string, NodeJS.Timeout>();
|
||||
private recapTimers = new Map<string, NodeJS.Timeout>();
|
||||
|
||||
constructor(
|
||||
private deps: ChatDeps,
|
||||
private opts: { channelIds: string[]; debounceMs: number; followupMs?: number },
|
||||
private opts: { channelIds: string[]; debounceMs: number; followupMs?: number; recapSilenceMs?: number; recapFromHour?: number; recapToHour?: number },
|
||||
) {}
|
||||
|
||||
private get pool(): Pool {
|
||||
@@ -62,19 +79,26 @@ export class SlackIntake {
|
||||
|
||||
private async handle(ev: Record<string, unknown>): Promise<void> {
|
||||
if (ev.type !== "message") return;
|
||||
const norm = normalizeHuddleEvent(ev);
|
||||
if (!norm) return;
|
||||
ev = norm;
|
||||
const channel = String(ev.channel ?? "");
|
||||
const user = String(ev.user ?? "");
|
||||
const ts = String(ev.ts ?? "");
|
||||
if (!channel || !ts) return;
|
||||
const project = await this.findProjectByChannel(channel);
|
||||
if (project) return this.handleProjectEvent(ev, project);
|
||||
if (ev.bot_id || !user || !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
|
||||
const huddle = ev.subtype === "huddle_thread" || huddleFilesOf(ev).length > 0;
|
||||
if (huddle) {
|
||||
// заметки Huddle от Slackbot: принимаются только с вложениями; "AI huddle notes are ready" без файлов и прочие сообщения Slackbot - нет
|
||||
if (!((ev.files as unknown[] | undefined)?.length)) return;
|
||||
} else if (ev.bot_id || !user || user === "USLACKBOT" || !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
|
||||
// чат менеджера: пишет любой участник канала, обрабатывается как сообщение менеджера (отправитель сохраняется в журнале)
|
||||
let manager = await this.findManagerByChannel(channel);
|
||||
if (!manager && this.opts.channelIds.includes(channel)) manager = await this.findManagerBySlackUser(user);
|
||||
if (!manager && this.opts.channelIds.includes(channel) && user) manager = await this.findManagerBySlackUser(user);
|
||||
if (!manager) return;
|
||||
const files = ((ev.files as { id?: string }[] | undefined) ?? []).map((f) => String(f.id)).filter(Boolean);
|
||||
await this.accept(manager, { channel, ts, text: String(ev.text ?? ""), fileIds: files, senderUserId: user });
|
||||
await this.accept(manager, { channel, ts, text: (huddle ? "[Slack huddle: заметки и расшифровка во вложениях] " : "") + String(ev.text ?? ""), fileIds: files, senderUserId: user || undefined });
|
||||
}
|
||||
|
||||
/** Проектный канал: проект определяется каналом (таблица project_channel). */
|
||||
@@ -97,7 +121,7 @@ export class SlackIntake {
|
||||
const rawFiles = (ev.files as { id?: string; name?: string; mimetype?: string; filetype?: string }[] | undefined) ?? [];
|
||||
const huddleFiles = rawFiles.filter((f) => /huddle|vnd\.slack-docs/i.test(`${f.name ?? ""} ${f.mimetype ?? ""} ${f.filetype ?? ""}`));
|
||||
const isHuddle = ev.subtype === "huddle_thread" || huddleFiles.length > 0;
|
||||
if (ev.bot_id && !isHuddle) return; // собственные ответы и прочие боты
|
||||
if ((ev.bot_id || user === "USLACKBOT") && !isHuddle) return; // собственные ответы, прочие боты и служебные сообщения Slackbot ("AI huddle notes are ready")
|
||||
if (!isHuddle && !ACCEPTED_SUBTYPES.has(ev.subtype as string | undefined)) return;
|
||||
if (isHuddle && !rawFiles.length) return; // "A huddle started" без материалов
|
||||
const sender = user ? (await this.pool.query("select id, display_name from person where slack_user_id = $1 and is_active", [user])).rows[0] : undefined;
|
||||
@@ -115,7 +139,57 @@ export class SlackIntake {
|
||||
const manager = (await this.findManagerByPerson(String(owner.id))) ?? { personId: String(owner.id), name: String(owner.display_name), slackUserId: null, slackChannelId: channel };
|
||||
const ctx: ProjectContext = { jobId: project.jobId, jobName: project.jobName, channel, senderName: (sender?.display_name as string | undefined) ?? null, isHuddle };
|
||||
const text = (isHuddle ? "[Slack huddle: заметки и расшифровка во вложениях] " : "") + String(ev.text ?? "");
|
||||
await this.accept({ ...manager, slackChannelId: channel }, { channel, ts, text, fileIds: rawFiles.map((f) => String(f.id)).filter(Boolean), senderUserId: user || undefined, project: ctx });
|
||||
const accepted = await this.accept({ ...manager, slackChannelId: channel }, { channel, ts, text, fileIds: rawFiles.map((f) => String(f.id)).filter(Boolean), senderUserId: user || undefined, project: ctx });
|
||||
if (accepted) this.scheduleRecap(channel, { ...manager, slackChannelId: channel }, ctx);
|
||||
}
|
||||
|
||||
/** Проектный канал: через recapSilenceMinutes после последнего сообщения людей агент решает, спрашивать ли про Daily Log. */
|
||||
scheduleRecap(channel: string, manager: ManagerInfo, ctx: ProjectContext, delayMs?: number): void {
|
||||
const silence = this.opts.recapSilenceMs;
|
||||
if (!silence) return;
|
||||
clearTimeout(this.recapTimers.get(channel));
|
||||
const t = setTimeout(() => {
|
||||
this.recapTimers.delete(channel);
|
||||
this.track(this.runRecap(channel, manager, ctx).catch((e) => this.deps.ctx.log.error({ channel, err: String(e) }, "recap проектного канала не удался")));
|
||||
}, delayMs ?? silence);
|
||||
this.recapTimers.set(channel, t);
|
||||
}
|
||||
|
||||
private async runRecap(channel: string, manager: ManagerInfo, ctx: ProjectContext): Promise<void> {
|
||||
const now = (this.deps.now ?? (() => new Date()))();
|
||||
const st = await getRecapState(this.pool, channel);
|
||||
if (!st || st.status === "asked" || !st.notes.trim()) return;
|
||||
if (promptSideFor(this.deps.ctx, manager.personId) !== "proposed") return; // recap - только у новой версии агента
|
||||
if (now.getTime() - st.lastHumanAt.getTime() > 36 * 3600_000) {
|
||||
await this.pool.query("delete from channel_recap_state where channel_id = $1", [channel]); // устарело: молча сбрасываем, не тревожим людей
|
||||
return;
|
||||
}
|
||||
if ((await pauseState(this.pool, manager.personId)).paused) return;
|
||||
const wait = recapDelayMs(now, this.deps.timezone, this.opts.recapFromHour, this.opts.recapToHour);
|
||||
if (wait > 0) return this.scheduleRecap(channel, manager, ctx, wait + 1000);
|
||||
await handleManagerMessages(this.deps, manager, [], {
|
||||
systemEvent: loadFragment("p-chat-events.md", "Беседа в проектном канале затихла", {}, promptSideFor(this.deps.ctx, manager.personId)),
|
||||
project: ctx,
|
||||
channel,
|
||||
});
|
||||
const after = await getRecapState(this.pool, channel);
|
||||
if (after && after.status === "collecting") {
|
||||
// агент решил подождать (например, последняя реплика - вопрос к кому-то): ещё до трёх попыток через тот же интервал
|
||||
if (after.attempts >= 3) return;
|
||||
await this.pool.query("update channel_recap_state set attempts = attempts + 1 where channel_id = $1", [channel]);
|
||||
this.scheduleRecap(channel, manager, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/** После перезапуска сервиса: восстанавливает таймеры recap для каналов с накопленным. */
|
||||
async restoreRecapTimers(): Promise<void> {
|
||||
const { rows } = await this.pool.query("select channel_id, job_id, manager_person_id from channel_recap_state where status = 'collecting' and notes <> ''");
|
||||
for (const r of rows) {
|
||||
const proj = await this.findProjectByChannel(String(r.channel_id));
|
||||
const mgr = r.manager_person_id ? await this.findManagerByPerson(String(r.manager_person_id)) : null;
|
||||
if (!proj || !mgr) continue;
|
||||
this.scheduleRecap(String(r.channel_id), { ...mgr, slackChannelId: String(r.channel_id) }, { jobId: proj.jobId, jobName: proj.jobName, channel: String(r.channel_id), senderName: null, isHuddle: false });
|
||||
}
|
||||
}
|
||||
|
||||
async findManagerByPerson(personId: string): Promise<ManagerInfo | null> {
|
||||
@@ -238,5 +312,7 @@ export class SlackIntake {
|
||||
this.pending.clear();
|
||||
for (const t of this.followups.values()) clearTimeout(t);
|
||||
this.followups.clear();
|
||||
for (const t of this.recapTimers.values()) clearTimeout(t);
|
||||
this.recapTimers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user