Агент чата: один автор - одно имя во входе (справочник person + пометка [менеджер] в диалоге канала); deviations п.68
All checks were successful
ci / test (push) Successful in 29s
ci / deploy (push) Successful in 2m20s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 13:47:12 +03:00
parent 2b3cd2ab82
commit 333106e518
5 changed files with 46 additions and 10 deletions

View File

@@ -184,10 +184,18 @@ export async function handleManagerMessages(
const disabled = aps.filter((r) => !r.is_enabled) as { jt_job_id: string; name: string | null }[];
const writableJobs = ctx.settings.allowedJobIds.filter((id) => !disabled.some((d) => d.jt_job_id === id));
// автор каждого сообщения: ответ адресуется тому, кто написал (в чате могут писать и другие, не только менеджер)
const senderNames = new Map<string, string>();
for (const id of new Set(messages.map((m) => m.senderUserId).filter((x): x is string => !!x))) {
// имя человека по Slack-id одно во всех блоках входа (новые сообщения, диалог канала): справочник person, затем Slack
const nameCache = new Map<string, string | null>();
const nameOfUser = async (id: string): Promise<string | null> => {
if (nameCache.has(id)) return nameCache.get(id)!;
const row = (await ctx.pool.query("select display_name from person where slack_user_id = $1 and is_active limit 1", [id])).rows[0];
const name = (row?.display_name as string | undefined) ?? (await deps.slack.userName?.(id).catch(() => null)) ?? null;
nameCache.set(id, name);
return name;
};
const senderNames = new Map<string, string>();
for (const id of new Set(messages.map((m) => m.senderUserId).filter((x): x is string => !!x))) {
const name = await nameOfUser(id);
if (name) senderNames.set(id, name);
}
const authorOf = (m: IncomingMessage): string => {
@@ -283,7 +291,7 @@ export async function handleManagerMessages(
const channelBlocks: string[] = [];
const recapOn = !!proj && !!channel; // тихий режим и recap проектных каналов - у всех менеджеров (промты согласованы, approved = proposed)
if (recapOn && proj && channel) {
const dialogText = await loadChannelDialog(deps.slack, channel, now, deps.timezone);
const dialogText = await loadChannelDialog(deps.slack, channel, now, deps.timezone, 24, { nameOf: nameOfUser, managerUserId: manager.slackUserId });
const st = await getRecapState(ctx.pool, channel);
channelBlocks.push("", `# Диалог канала за последние сутки (время по Тампе)
${dialogText}`, "", `# Накопленное для Daily Log

View File

@@ -25,10 +25,13 @@ export function stampLocal(d: Date, tz: string): string {
return `${g("weekday")} ${g("month")}/${g("day")} ${g("hour")}:${g("minute")}`;
}
/** Диалог канала для агента: время по Тампе, автор, текст; упоминания заменены именами; сообщения бота помечены. */
/**
* Диалог канала для агента: время по Тампе, автор, текст; упоминания заменены именами; сообщения бота помечены.
* Менеджер подписан так же, как в блоке «Новые сообщения менеджера»: `Имя (<@id>) [менеджер]` (иначе один автор выглядит как два разных человека).
*/
export function formatChannelDialog(
msgs: SlackHistoryMessage[],
opts: { tz: string; botUserId: string | null; names: Map<string, string> },
opts: { tz: string; botUserId: string | null; names: Map<string, string>; managerUserId?: string | null },
): string {
if (!msgs.length) return "(за последние сутки сообщений нет)";
const who = (id: string | null) => (id ? (opts.names.get(id) ?? id) : "?");
@@ -36,7 +39,8 @@ export function formatChannelDialog(
return msgs
.map((m) => {
const fromBot = (m.userId && m.userId === opts.botUserId) || (m.botId && !m.userId);
const author = fromBot ? "ASSISTANT (ты)" : m.botId && m.userId ? `${who(m.userId)} (бот)` : who(m.userId);
const mgr = !!m.userId && m.userId === opts.managerUserId ? ` (<@${m.userId}>) [менеджер]` : "";
const author = fromBot ? "ASSISTANT (ты)" : m.botId && m.userId ? `${who(m.userId)} (бот)` : `${who(m.userId)}${mgr}`;
const thread = m.threadTs && m.threadTs !== m.ts ? " (в треде)" : "";
const files = m.fileNames.length ? ` [файлы: ${m.fileNames.join(", ")}]` : "";
return `- [${stampLocal(new Date(Number(m.ts) * 1000), opts.tz)}] (ts ${m.ts}) ${author}${thread}: ${resolve(m.text).replace(/\n/g, " ⏎ ").trim() || "(без текста)"}${files}`;
@@ -44,30 +48,35 @@ export function formatChannelDialog(
.join("\n");
}
/** Загружает диалог канала за последние hours часов (по умолчанию сутки). Сбой Slack - пустая строка-заглушка, обработка не останавливается. */
/**
* Загружает диалог канала за последние hours часов (по умолчанию сутки). Сбой Slack - пустая строка-заглушка, обработка не останавливается.
* `nameOf` - единый для всех блоков входа способ узнать имя автора (справочник person, затем Slack); без него имя берётся из Slack.
*/
export async function loadChannelDialog(
slack: Pick<SlackApi, "history" | "userName" | "botUserId">,
channel: string,
now: Date,
tz: string,
hours = 24,
who: { nameOf?: (id: string) => Promise<string | null>; managerUserId?: string | null } = {},
): Promise<string> {
if (!slack.history) return "(история канала недоступна)";
try {
const msgs = await slack.history(channel, Math.floor(now.getTime() / 1000) - hours * 3600);
const names = new Map<string, string>();
if (slack.userName) {
const nameOf = who.nameOf ?? slack.userName;
if (nameOf) {
const ids = new Set<string>();
for (const m of msgs) {
if (m.userId) ids.add(m.userId);
for (const x of m.text.matchAll(/<@([UW][A-Z0-9]+)>/g)) ids.add(x[1]!);
}
for (const id of ids) {
const n = await slack.userName(id);
const n = await nameOf(id);
if (n) names.set(id, n);
}
}
return formatChannelDialog(msgs, { tz, botUserId: (await slack.botUserId?.()) ?? null, names });
return formatChannelDialog(msgs, { tz, botUserId: (await slack.botUserId?.()) ?? null, names, managerUserId: who.managerUserId });
} catch (e) {
return `(история канала не загрузилась: ${e instanceof Error ? e.message : String(e)})`;
}