Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fc224887c8 | |||
| 78fc7c4842 | |||
| be25b31a0e | |||
| d6411424c1 | |||
| 199a9a1750 | |||
| 6b825ad440 | |||
| 0cee2cc9dc | |||
| e4af672c2c | |||
| ec8dd7d110 | |||
| 4423b19850 | |||
| 688cb54f26 | |||
| ec5416068b |
@@ -0,0 +1,362 @@
|
||||
/**
|
||||
* PageHistoryModal — редизайн окна «Page history».
|
||||
* Mantine v7. Light/dark. Полноразмерное модальное окно.
|
||||
*
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* ЧТО ЭТО
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* Окно истории версий страницы. Слева — панель навигации: мини-календарь
|
||||
* (heatmap: яркость дня = число ревизий, обводка = выбранный день) + плотный
|
||||
* список ревизий (одна ревизия = одна строка). Справа — реально отрендеренная
|
||||
* версия страницы с подсветкой изменений. Все контролы — в одну строку шапки.
|
||||
*
|
||||
* Ключевые решения:
|
||||
* - Плотный список: одна ревизия на строку (аватар · время · автор · [SAVED]).
|
||||
* Бейдж показывается ТОЛЬКО у сохранённых версий; всё остальное — autosave.
|
||||
* - Агентские ревизии визуально отличаются: квадратный глиф роли (К/Ф) вместо
|
||||
* круглого аватара пользователя + «via <кто запустил>».
|
||||
* - Календарь объединён со списком в одной панели (мини-календарь = date jumper).
|
||||
* - Highlight changes + навигация по изменениям (N of M, ↑/↓) вынесены в шапку.
|
||||
* - Текущая версия помечена; Restore для неё недоступен.
|
||||
*
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* УСТАНОВКА / ИСПОЛЬЗОВАНИЕ
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* import { PageHistoryModal, Revision } from './PageHistoryModal';
|
||||
*
|
||||
* <PageHistoryModal
|
||||
* opened={open}
|
||||
* onClose={() => setOpen(false)}
|
||||
* revisions={revisions} // Revision[]
|
||||
* selectedId={selId}
|
||||
* onSelect={setSelId} // клик по ревизии → рендер справа
|
||||
* renderVersion={(rev) => <ArticleView versionId={rev.id} />} // ваш рендер страницы
|
||||
* highlightChanges={hl}
|
||||
* onToggleHighlight={setHl}
|
||||
* changeNav={{ index: 1, total: 3, onPrev, onNext }} // навигация по диффу
|
||||
* onlySaved={onlySaved}
|
||||
* onToggleOnlySaved={setOnlySaved}
|
||||
* onRestore={(rev) => api.restore(rev.id)} // async; текущая версия → disabled
|
||||
* />
|
||||
*
|
||||
* Требует MantineProvider на корне приложения (defaultColorScheme="auto" для тем).
|
||||
*
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* ФОРМАТ ДАННЫХ
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* interface Revision {
|
||||
* id: string;
|
||||
* at: Date | string; // время ревизии; форматируется вызывающим/util-ом
|
||||
* dayGroup: string; // 'Today' | 'Yesterday' | 'Mon 12 Jul' — заголовок группы
|
||||
* saved: boolean; // true → бейдж SAVED; false → autosave (без бейджа)
|
||||
* author: { name: string } & (
|
||||
* | { kind: 'human' }
|
||||
* | { kind: 'agent'; role: string; triggeredBy: string } // роль + кто запустил
|
||||
* );
|
||||
* isCurrent?: boolean; // текущая (последняя) версия — Restore недоступен
|
||||
* }
|
||||
*
|
||||
* Ревизии приходят плоским массивом; группировка по dayGroup — на клиенте.
|
||||
* Никаких изменений API не требуется: агентское авторство берётся из author.kind.
|
||||
*
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* СОСТОЯНИЯ (нарисованы/поддержаны)
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* - Ревизия: обычная / hover / выбранная / текущая / агентская / человеческая.
|
||||
* - Restore: default / disabled (выбрана текущая) / loading (спиннер после клика).
|
||||
* - Highlight changes: on/off; при off навигация по изменениям неактивна.
|
||||
* - Пустая история: одна версия / нет ревизий → EmptyState.
|
||||
* - Тёмная тема: через токены Mantine (useMantineColorScheme, var(--mantine-*)).
|
||||
*/
|
||||
import { useMemo, useState, useCallback } from 'react';
|
||||
import {
|
||||
Modal, Box, Group, Stack, Text, Switch, Avatar, Badge, Button, ActionIcon,
|
||||
ScrollArea, useMantineTheme, useMantineColorScheme,
|
||||
} from '@mantine/core';
|
||||
|
||||
/* ─────────────────────────── Типы ─────────────────────────── */
|
||||
|
||||
export type Author =
|
||||
| { name: string; kind: 'human' }
|
||||
| { name: string; kind: 'agent'; role: string; triggeredBy: string };
|
||||
|
||||
export interface Revision {
|
||||
id: string;
|
||||
at: Date | string;
|
||||
atLabel: string; // предформатированное «5:35AM»
|
||||
dayGroup: string; // «Today» | «Yesterday» | «Mon 12 Jul»
|
||||
saved: boolean;
|
||||
author: Author;
|
||||
isCurrent?: boolean;
|
||||
}
|
||||
|
||||
export interface CalendarDay {
|
||||
label: string; // «12»
|
||||
inMonth: boolean;
|
||||
count: number; // число ревизий за день (для heatmap)
|
||||
selected?: boolean;
|
||||
date: Date | string;
|
||||
}
|
||||
|
||||
export interface PageHistoryModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
revisions: Revision[];
|
||||
selectedId: string | null;
|
||||
onSelect: (id: string) => void;
|
||||
renderVersion: (rev: Revision | null) => React.ReactNode;
|
||||
highlightChanges: boolean;
|
||||
onToggleHighlight: (v: boolean) => void;
|
||||
changeNav?: { index: number; total: number; onPrev: () => void; onNext: () => void };
|
||||
onlySaved: boolean;
|
||||
onToggleOnlySaved: (v: boolean) => void;
|
||||
onRestore: (rev: Revision) => Promise<void>;
|
||||
/** Ячейки текущего месяца календаря + управление. Необязательно — без него панель = только список. */
|
||||
calendar?: {
|
||||
monthLabel: string; // «July 2025»
|
||||
weekdays: string[]; // ['Mon',…,'Sun']
|
||||
days: CalendarDay[]; // обычно 35/42 ячейки
|
||||
onPrevMonth: () => void;
|
||||
onNextMonth: () => void;
|
||||
onToday: () => void;
|
||||
onPickDay: (d: CalendarDay) => void;
|
||||
};
|
||||
}
|
||||
|
||||
/* ─────────────────────────── Утилиты представления ─────────────────────────── */
|
||||
|
||||
const USER_PALETTE = ['#495057', '#e8590c', '#1c7ed6', '#7048e8', '#0ca678'];
|
||||
function userColor(name: string) {
|
||||
let h = 0;
|
||||
for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;
|
||||
return USER_PALETTE[h % USER_PALETTE.length];
|
||||
}
|
||||
const AGENT_GRAD: Record<string, string> = {
|
||||
'Корректор': 'linear-gradient(135deg,#20c997,#12b886)',
|
||||
'Фактчекер': 'linear-gradient(135deg,#4c6ef5,#7048e8)',
|
||||
};
|
||||
function agentGrad(role: string) { return AGENT_GRAD[role] ?? 'linear-gradient(135deg,#868e96,#495057)'; }
|
||||
|
||||
/** heatmap: число ревизий → фон/текст ячейки календаря. */
|
||||
function heat(n: number, dark: boolean) {
|
||||
if (n === 0) return { bg: 'transparent', fg: dark ? '#5c5f66' : '#adb5bd' };
|
||||
if (n <= 2) return { bg: dark ? 'rgba(34,139,230,.20)' : '#e7f0ff', fg: dark ? '#74c0fc' : '#1971c2' };
|
||||
if (n <= 4) return { bg: dark ? 'rgba(34,139,230,.45)' : '#a5c8ff', fg: dark ? '#dbeafe' : '#0b3d91' };
|
||||
return { bg: '#4c8dff', fg: '#ffffff' };
|
||||
}
|
||||
|
||||
/* ─────────────────────────── Строка ревизии ─────────────────────────── */
|
||||
|
||||
function RevisionRow({ rev, selected, onSelect }: { rev: Revision; selected: boolean; onSelect: () => void }) {
|
||||
const theme = useMantineTheme();
|
||||
const { colorScheme } = useMantineColorScheme();
|
||||
const dark = colorScheme === 'dark';
|
||||
const a = rev.author;
|
||||
const isAgent = a.kind === 'agent';
|
||||
|
||||
return (
|
||||
<Group
|
||||
gap={8} wrap="nowrap" h={28} px="12px 14px" m="1px 6px"
|
||||
onClick={onSelect}
|
||||
style={{
|
||||
cursor: 'pointer', borderRadius: 7,
|
||||
background: selected ? (dark ? 'rgba(34,139,230,.14)' : '#eef4ff')
|
||||
: isAgent ? (dark ? 'rgba(112,72,232,.06)' : '#fbfaff') : undefined,
|
||||
}}
|
||||
>
|
||||
{/* аватар/глиф */}
|
||||
{isAgent ? (
|
||||
<Box style={{ flex: 'none', width: 16, height: 16, borderRadius: 4, background: agentGrad(a.role), display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', font: '700 8px system-ui' }}>
|
||||
{a.role[0]}
|
||||
</Box>
|
||||
) : (
|
||||
<Box style={{ flex: 'none', width: 16, height: 16, borderRadius: '50%', background: userColor(a.name), display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', font: '700 8px system-ui' }}>
|
||||
{a.name[0].toUpperCase()}
|
||||
</Box>
|
||||
)}
|
||||
{/* время */}
|
||||
<Text fz={12.5} fw={rev.isCurrent ? 600 : 500} c={rev.isCurrent ? undefined : 'dimmed'} style={{ flex: 'none', minWidth: 58 }}>
|
||||
{rev.atLabel}
|
||||
</Text>
|
||||
{/* автор + via */}
|
||||
<Group gap={4} wrap="nowrap" style={{ flex: 1, minWidth: 0, alignItems: 'baseline', overflow: 'hidden' }}>
|
||||
<Text fz={12} fw={isAgent ? 600 : 400} c={isAgent ? undefined : 'dimmed'} truncate style={{ flex: 'none', maxWidth: 100 }}>
|
||||
{isAgent ? a.role : a.name}
|
||||
</Text>
|
||||
{isAgent && <Text fz={11} c="dimmed" truncate>· via {a.triggeredBy}</Text>}
|
||||
</Group>
|
||||
{/* бейдж — только SAVED */}
|
||||
{rev.saved && <Badge size="sm" radius="sm" variant="light" color="blue">SAVED</Badge>}
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─────────────────────────── Мини-календарь ─────────────────────────── */
|
||||
|
||||
function MiniCalendar({ cal }: { cal: NonNullable<PageHistoryModalProps['calendar']> }) {
|
||||
const { colorScheme } = useMantineColorScheme();
|
||||
const dark = colorScheme === 'dark';
|
||||
return (
|
||||
<Box p="10px 12px 8px" style={(t) => ({ borderBottom: `1px solid ${t.colorScheme === 'dark' ? t.colors.dark[5] : t.colors.gray[1]}` })}>
|
||||
<Group gap={6} mb={6}>
|
||||
<ActionIcon variant="subtle" color="gray" size="sm" onClick={cal.onPrevMonth}>‹</ActionIcon>
|
||||
<Text fz={12} fw={600}>{cal.monthLabel}</Text>
|
||||
<ActionIcon variant="subtle" color="gray" size="sm" onClick={cal.onNextMonth}>›</ActionIcon>
|
||||
<Box style={{ flex: 1 }} />
|
||||
<Button variant="subtle" size="compact-xs" onClick={cal.onToday}>Today</Button>
|
||||
</Group>
|
||||
<Box style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 2, marginBottom: 2 }}>
|
||||
{cal.weekdays.map((w) => (
|
||||
<Text key={w} ta="center" fz={8.5} fw={600} c="dimmed">{w}</Text>
|
||||
))}
|
||||
</Box>
|
||||
<Box style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 2 }}>
|
||||
{cal.days.map((d, i) => {
|
||||
const h = heat(d.count, dark);
|
||||
return (
|
||||
<Box
|
||||
key={i} onClick={() => cal.onPickDay(d)}
|
||||
style={{
|
||||
position: 'relative', height: 26, borderRadius: 6, cursor: 'pointer',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
background: d.inMonth ? h.bg : 'transparent',
|
||||
boxShadow: d.selected ? `inset 0 0 0 2px ${dark ? '#f1f3f5' : '#1a1b1e'}` : undefined,
|
||||
}}
|
||||
>
|
||||
<Text fz={10.5} fw={d.selected ? 700 : 500} style={{ color: d.inMonth ? h.fg : (dark ? '#3a3d42' : '#dee2e6') }}>
|
||||
{d.label}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
{/* легенда heatmap */}
|
||||
<Group gap={6} mt={8} align="center">
|
||||
<Text fz={9.5} c="dimmed">fewer</Text>
|
||||
{['#e7f0ff', '#a5c8ff', '#4c8dff'].map((c) => (
|
||||
<Box key={c} style={{ width: 14, height: 10, borderRadius: 2, background: c }} />
|
||||
))}
|
||||
<Text fz={9.5} c="dimmed">more revisions</Text>
|
||||
</Group>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─────────────────────────── Окно ─────────────────────────── */
|
||||
|
||||
export function PageHistoryModal(props: PageHistoryModalProps) {
|
||||
const {
|
||||
opened, onClose, revisions, selectedId, onSelect, renderVersion,
|
||||
highlightChanges, onToggleHighlight, changeNav, onlySaved, onToggleOnlySaved,
|
||||
onRestore, calendar,
|
||||
} = props;
|
||||
const [restoring, setRestoring] = useState(false);
|
||||
|
||||
const selected = revisions.find((r) => r.id === selectedId) ?? null;
|
||||
const isEmpty = revisions.length <= 1;
|
||||
|
||||
// группировка по dayGroup, с фильтром Only saved
|
||||
const groups = useMemo(() => {
|
||||
const list = onlySaved ? revisions.filter((r) => r.saved) : revisions;
|
||||
const map: { head: string; items: Revision[] }[] = [];
|
||||
for (const r of list) {
|
||||
let g = map.find((x) => x.head === r.dayGroup);
|
||||
if (!g) { g = { head: r.dayGroup, items: [] }; map.push(g); }
|
||||
g.items.push(r);
|
||||
}
|
||||
return map;
|
||||
}, [revisions, onlySaved]);
|
||||
|
||||
const restore = useCallback(async () => {
|
||||
if (!selected || selected.isCurrent) return;
|
||||
setRestoring(true);
|
||||
try { await onRestore(selected); } finally { setRestoring(false); }
|
||||
}, [selected, onRestore]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened} onClose={onClose} withCloseButton={false}
|
||||
size="80rem" radius="lg" padding={0}
|
||||
styles={{ body: { height: '80vh', maxHeight: 760, display: 'flex', flexDirection: 'column' } }}
|
||||
overlayProps={{ backgroundOpacity: 0.5, blur: 1 }}
|
||||
>
|
||||
{/* ── single-row toolbar ── */}
|
||||
<Group gap={14} h={60} px={16} wrap="nowrap" style={(t) => ({ flex: 'none', borderBottom: `1px solid ${t.colorScheme === 'dark' ? t.colors.dark[5] : t.colors.gray[1]}` })}>
|
||||
<Text fz={16} fw={600}>Page history</Text>
|
||||
<Box style={(t) => ({ width: 1, height: 22, background: t.colorScheme === 'dark' ? t.colors.dark[4] : t.colors.gray[2] })} />
|
||||
<Stack gap={1} style={{ minWidth: 0 }}>
|
||||
<Text fz={12} fw={600} truncate>{selected ? `${selected.dayGroup} · ${selected.atLabel}` : '—'}</Text>
|
||||
<Text fz={10.5} c="dimmed">selected version</Text>
|
||||
</Stack>
|
||||
|
||||
<Box style={{ flex: 1 }} />
|
||||
|
||||
{/* diff cluster */}
|
||||
<Group gap={2} p={3} wrap="nowrap" style={(t) => ({ background: t.colorScheme === 'dark' ? t.colors.dark[6] : '#f4f6f8', borderRadius: 10 })}>
|
||||
<Button variant="white" size="compact-sm" onClick={() => onToggleHighlight(!highlightChanges)}
|
||||
leftSection={<Switch checked={highlightChanges} onChange={() => {}} size="xs" tabIndex={-1} styles={{ track: { cursor: 'pointer' } }} />}
|
||||
styles={{ root: { boxShadow: '0 1px 2px rgba(0,0,0,.08)' } }}>
|
||||
Highlight changes
|
||||
</Button>
|
||||
{changeNav && (
|
||||
<>
|
||||
<Text fz={12} fw={600} c="dimmed" px={6}>{changeNav.index} / {changeNav.total}</Text>
|
||||
<Box style={{ display: 'flex' }}>
|
||||
<ActionIcon variant="subtle" color="gray" size="lg" disabled={!highlightChanges} onClick={changeNav.onPrev} style={{ width: 26 }}>↑</ActionIcon>
|
||||
<ActionIcon variant="subtle" color="gray" size="lg" disabled={!highlightChanges} onClick={changeNav.onNext} style={{ width: 26 }}>↓</ActionIcon>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
<Box style={(t) => ({ width: 1, height: 22, background: t.colorScheme === 'dark' ? t.colors.dark[4] : t.colors.gray[2] })} />
|
||||
|
||||
<Button color="blue" onClick={restore} loading={restoring} disabled={!selected || selected.isCurrent}>
|
||||
Restore this version
|
||||
</Button>
|
||||
<ActionIcon variant="subtle" color="gray" size="lg" onClick={onClose}>✕</ActionIcon>
|
||||
</Group>
|
||||
|
||||
{/* ── body ── */}
|
||||
<Box style={{ flex: 1, display: 'flex', minHeight: 0 }}>
|
||||
{/* left: nav panel */}
|
||||
<Stack gap={0} style={(t) => ({ flex: 'none', width: 280, minHeight: 0, borderRight: `1px solid ${t.colorScheme === 'dark' ? t.colors.dark[5] : t.colors.gray[1]}`, background: t.colorScheme === 'dark' ? t.colors.dark[7] : '#fcfcfd' })}>
|
||||
<Group h={44} px={16} style={(t) => ({ flex: 'none', borderBottom: `1px solid ${t.colorScheme === 'dark' ? t.colors.dark[5] : t.colors.gray[1]}` })}>
|
||||
<Switch checked={onlySaved} onChange={(e) => onToggleOnlySaved(e.currentTarget.checked)} size="sm" label="Only saved" labelPosition="right" styles={{ label: { fontSize: 13, fontWeight: 500 } }} />
|
||||
</Group>
|
||||
|
||||
{calendar && <MiniCalendar cal={calendar} />}
|
||||
|
||||
<ScrollArea style={{ flex: 1 }}>
|
||||
{groups.map((g) => (
|
||||
<Box key={g.head}>
|
||||
<Text px={16} pt={9} pb={5} fz={10.5} fw={600} tt="uppercase" c="dimmed" style={{ letterSpacing: '.05em', position: 'sticky', top: 0, zIndex: 2, background: 'var(--mantine-color-body)' }}>
|
||||
{g.head}
|
||||
</Text>
|
||||
{g.items.map((r) => (
|
||||
<RevisionRow key={r.id} rev={r} selected={r.id === selectedId} onSelect={() => onSelect(r.id)} />
|
||||
))}
|
||||
</Box>
|
||||
))}
|
||||
</ScrollArea>
|
||||
</Stack>
|
||||
|
||||
{/* right: rendered version */}
|
||||
<ScrollArea style={{ flex: 1, minWidth: 0 }} bg="var(--mantine-color-default-hover)">
|
||||
{isEmpty ? (
|
||||
<Stack align="center" justify="center" h="100%" gap={6} p={40}>
|
||||
<Text fw={600} fz={14}>No earlier versions</Text>
|
||||
<Text fz={12.5} c="dimmed" ta="center">У страницы пока одна версия — сравнивать не с чем.</Text>
|
||||
</Stack>
|
||||
) : (
|
||||
<Box p="26px 0" maw={660} mx="auto">
|
||||
{renderVersion(selected)}
|
||||
</Box>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</Box>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export default PageHistoryModal;
|
||||
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* TimeWorkedModal — редизайн окна «Time worked on this article».
|
||||
* Mantine v7. Light/dark.
|
||||
*
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* ЧТО ЭТО
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* Сводка трудозатрат по дням в виде суточных таймлайнов. Главное отличие от
|
||||
* старой версии: на барах ВИДНО время суток. Реализовано двумя способами
|
||||
* (проп `axis`):
|
||||
* - 'grid' — ось часов 00–06–12–18–24 сверху + вертикальные деления,
|
||||
* ночные часы (0–6, 21–24) слегка затемнены. По умолчанию.
|
||||
* - 'phases' — цветные полосы фаз дня за блоками (Ночь/Утро/День/Вечер),
|
||||
* период суток читается сразу, без счёта делений.
|
||||
*
|
||||
* Блоки позиционируются по времени: left = start/24, width = dur/24.
|
||||
* Интенсивность (opacity) блока = длительность/плотность работы, чтобы
|
||||
* очень короткие сессии не терялись (минимальная видимая ширина задана).
|
||||
* Hover-тултип на блоке: начало–конец · длительность.
|
||||
*
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* УСТАНОВКА / ИСПОЛЬЗОВАНИЕ
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* import { TimeWorkedModal, DaySummary } from './TimeWorkedModal';
|
||||
*
|
||||
* <TimeWorkedModal
|
||||
* opened={open}
|
||||
* onClose={() => setOpen(false)}
|
||||
* totalLabel="≈ 34h"
|
||||
* agentLabel="≈ 1h 20m" // undefined → строку agent не показываем
|
||||
* days={days} // DaySummary[]
|
||||
* axis="grid" // 'grid' | 'phases'
|
||||
* tz="Europe/Moscow"
|
||||
* inactivityGapMin={15}
|
||||
* />
|
||||
*
|
||||
* Требует MantineProvider на корне.
|
||||
*
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* ФОРМАТ ДАННЫХ
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* interface Block {
|
||||
* start: number; // час начала в сутках, 0..24 (напр. 13.7 = 13:42)
|
||||
* end: number; // час конца
|
||||
* kind: 'work' | 'agent';
|
||||
* }
|
||||
* interface DaySummary {
|
||||
* label: string; // «Mon 29 Jun»
|
||||
* totalLabel: string; // «1h 24m» | «—» для пустого дня
|
||||
* blocks: Block[]; // [] → пустой день (полупрозрачная дорожка, итог «—»)
|
||||
* isToday?: boolean; // сегодня — неполные сутки (рисуем границу «сейчас»)
|
||||
* nowFraction?: number;// 0..1 позиция «сейчас» для isToday
|
||||
* }
|
||||
*
|
||||
* Данные уже есть в бэкенде трудозатрат: сессии с началом/концом + тип
|
||||
* (work/agent). Часы = локальные к tz. Изменений API не требуется.
|
||||
*
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* СОСТОЯНИЯ (нарисованы/поддержаны)
|
||||
* ─────────────────────────────────────────────────────────────────────────
|
||||
* - День: с активностью (work+agent) / только work / только agent / пустой (—).
|
||||
* - Сегодня: граница «сейчас» на дорожке (nowFraction).
|
||||
* - Короткий блок: минимальная ширина, не исчезает.
|
||||
* - Пустая панель целиком: нет трудозатрат → EmptyState.
|
||||
* - Длинный период: вертикальный скролл списка дней, шапка/легенда липкие.
|
||||
* - Тёмная тема: токены Mantine.
|
||||
*/
|
||||
import { Modal, Box, Group, Stack, Text, ActionIcon, ScrollArea, Tooltip, useMantineColorScheme } from '@mantine/core';
|
||||
|
||||
/* ─────────────────────────── Типы ─────────────────────────── */
|
||||
|
||||
export interface Block { start: number; end: number; kind: 'work' | 'agent'; }
|
||||
export interface DaySummary {
|
||||
label: string;
|
||||
totalLabel: string;
|
||||
blocks: Block[];
|
||||
isToday?: boolean;
|
||||
nowFraction?: number;
|
||||
}
|
||||
export interface TimeWorkedModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
totalLabel: string;
|
||||
agentLabel?: string;
|
||||
days: DaySummary[];
|
||||
axis?: 'grid' | 'phases';
|
||||
tz?: string;
|
||||
inactivityGapMin?: number;
|
||||
}
|
||||
|
||||
const WORK = '#3b82f6';
|
||||
const AGENT = '#c026d3';
|
||||
|
||||
const PHASES = [
|
||||
{ name: 'Ночь', s: 0, e: 6, bg: 'rgba(99,102,241,.10)', lg: '#e8eaff', fg: '#5b60c9' },
|
||||
{ name: 'Утро', s: 6, e: 12, bg: 'rgba(245,159,0,.10)', lg: '#fff2dc', fg: '#b5820e' },
|
||||
{ name: 'День', s: 12, e: 18, bg: 'rgba(56,178,172,.10)', lg: '#dcf5f2', fg: '#1a857d' },
|
||||
{ name: 'Вечер', s: 18, e: 24, bg: 'rgba(139,92,246,.11)', lg: '#efe7ff', fg: '#6d43c0' },
|
||||
];
|
||||
|
||||
/* ─────────────────────────── Блок активности ─────────────────────────── */
|
||||
|
||||
function fmtHour(h: number) {
|
||||
const hh = Math.floor(h);
|
||||
const mm = Math.round((h - hh) * 60);
|
||||
return `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`;
|
||||
}
|
||||
function fmtDur(h: number) {
|
||||
const total = Math.round(h * 60);
|
||||
const hh = Math.floor(total / 60), mm = total % 60;
|
||||
return hh ? `${hh}h ${mm}m` : `${mm}m`;
|
||||
}
|
||||
|
||||
function ActivityBlock({ b }: { b: Block }) {
|
||||
const left = (b.start / 24) * 100;
|
||||
const width = Math.max(((b.end - b.start) / 24) * 100, 0.6);
|
||||
const dur = b.end - b.start;
|
||||
const opacity = dur < 0.16 ? 0.5 : dur < 0.35 ? 0.8 : 1;
|
||||
return (
|
||||
<Tooltip label={`${fmtHour(b.start)} – ${fmtHour(b.end)} · ${fmtDur(dur)}`} withArrow openDelay={120} fz={11}>
|
||||
<Box style={{
|
||||
position: 'absolute', top: 5, height: 14, left: `${left}%`, width: `${width}%`,
|
||||
borderRadius: 2, background: b.kind === 'agent' ? AGENT : WORK, opacity, cursor: 'default',
|
||||
}} />
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─────────────────────────── Дорожка дня ─────────────────────────── */
|
||||
|
||||
function DayTrack({ d, axis, dark }: { d: DaySummary; axis: 'grid' | 'phases'; dark: boolean }) {
|
||||
const trackBg = axis === 'grid'
|
||||
? 'linear-gradient(90deg, rgba(90,100,130,.10) 0 25%, rgba(90,100,130,.02) 25% 87.5%, rgba(90,100,130,.10) 87.5% 100%)'
|
||||
: (dark ? 'rgba(255,255,255,.04)' : '#f6f8fa');
|
||||
|
||||
return (
|
||||
<Group gap={0} h={30} wrap="nowrap">
|
||||
<Text style={{ flex: 'none', width: 92 }} fz={13} c="dimmed">{d.label}</Text>
|
||||
<Box style={{ position: 'relative', flex: 1, height: 24, margin: '0 4px', borderRadius: 5, overflow: 'hidden', background: trackBg }}>
|
||||
{/* фон: полосы фаз или деления сетки */}
|
||||
{axis === 'phases'
|
||||
? PHASES.map((ph) => (
|
||||
<Box key={ph.name} style={{ position: 'absolute', top: 0, bottom: 0, left: `${(ph.s / 24) * 100}%`, width: `${((ph.e - ph.s) / 24) * 100}%`, background: ph.bg }} />
|
||||
))
|
||||
: [25, 50, 75].map((p) => (
|
||||
<Box key={p} style={{ position: 'absolute', top: 0, bottom: 0, left: `${p}%`, width: 1, background: 'rgba(120,130,150,.16)' }} />
|
||||
))}
|
||||
{/* блоки */}
|
||||
{d.blocks.map((b, i) => <ActivityBlock key={i} b={b} />)}
|
||||
{/* граница «сейчас» для сегодняшнего дня */}
|
||||
{d.isToday && d.nowFraction != null && (
|
||||
<Box style={{ position: 'absolute', top: 0, bottom: 0, left: `${d.nowFraction * 100}%`, width: 2, background: '#fa5252' }} />
|
||||
)}
|
||||
</Box>
|
||||
<Text style={{ flex: 'none', width: 64, textAlign: 'right' }} fz={12.5} fw={500} c={d.totalLabel === '—' ? 'dimmed' : undefined}>
|
||||
{d.totalLabel}
|
||||
</Text>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─────────────────────────── Окно ─────────────────────────── */
|
||||
|
||||
export function TimeWorkedModal(props: TimeWorkedModalProps) {
|
||||
const { opened, onClose, totalLabel, agentLabel, days, axis = 'grid', tz = 'Europe/Moscow', inactivityGapMin = 15 } = props;
|
||||
const { colorScheme } = useMantineColorScheme();
|
||||
const dark = colorScheme === 'dark';
|
||||
const isEmpty = days.length === 0 || days.every((d) => d.blocks.length === 0);
|
||||
|
||||
return (
|
||||
<Modal opened={opened} onClose={onClose} withCloseButton={false} size="46rem" radius="lg" padding={0}
|
||||
overlayProps={{ backgroundOpacity: 0.5, blur: 1 }}>
|
||||
<Box p="22px 24px 20px">
|
||||
{/* header */}
|
||||
<Group mb={14}>
|
||||
<Text fz={17} fw={600}>Time worked on this article</Text>
|
||||
<Box style={{ flex: 1 }} />
|
||||
<ActionIcon variant="subtle" color="gray" size="lg" onClick={onClose}>✕</ActionIcon>
|
||||
</Group>
|
||||
|
||||
{/* summary */}
|
||||
<Group align="baseline" gap={16} mb={axis === 'grid' ? 8 : 16}>
|
||||
<Text fz={22} fw={700}>{totalLabel}</Text>
|
||||
{agentLabel && <Text fz={13} c="dimmed">agent: {agentLabel}</Text>}
|
||||
</Group>
|
||||
|
||||
{/* legend (grid only) */}
|
||||
{axis === 'grid' && (
|
||||
<Group gap={16} mb={16}>
|
||||
<Group gap={6}><Box w={12} h={12} style={{ borderRadius: 3, background: WORK }} /><Text fz={12} fw={500} c="dimmed">Work</Text></Group>
|
||||
<Group gap={6}><Box w={12} h={12} style={{ borderRadius: 3, background: AGENT }} /><Text fz={12} fw={500} c="dimmed">Agent</Text></Group>
|
||||
</Group>
|
||||
)}
|
||||
|
||||
{isEmpty ? (
|
||||
<Stack align="center" gap={6} p="48px 20px">
|
||||
<Text fw={600} fz={14}>No time tracked yet</Text>
|
||||
<Text fz={12.5} c="dimmed" ta="center">По этой статье ещё нет трудозатрат.</Text>
|
||||
</Stack>
|
||||
) : (
|
||||
<>
|
||||
{/* axis header (sticky) */}
|
||||
<Group gap={0} mb={5} wrap="nowrap" style={{ position: 'sticky', top: 0, zIndex: 2, background: 'var(--mantine-color-body)' }}>
|
||||
<Box style={{ flex: 'none', width: 92 }} />
|
||||
{axis === 'grid' ? (
|
||||
<Box style={{ flex: 1, position: 'relative', height: 14, margin: '0 4px' }}>
|
||||
{[['0%', '00', 'flex-start'], ['25%', '06', 'center'], ['50%', '12', 'center'], ['75%', '18', 'center'], ['100%', '24', 'flex-end']].map(([l, t, al]) => (
|
||||
<Text key={t as string} fz={10} fw={500} c="dimmed" style={{ position: 'absolute', left: l as string, transform: al === 'center' ? 'translateX(-50%)' : al === 'flex-end' ? 'translateX(-100%)' : undefined }}>{t}</Text>
|
||||
))}
|
||||
</Box>
|
||||
) : (
|
||||
<Box style={{ flex: 1, display: 'flex', height: 16, margin: '0 4px', borderRadius: 4, overflow: 'hidden' }}>
|
||||
{PHASES.map((ph) => (
|
||||
<Box key={ph.name} style={{ flex: ph.e - ph.s, display: 'flex', alignItems: 'center', justifyContent: 'center', background: ph.lg, color: ph.fg, font: '600 9.5px system-ui' }}>{ph.name}</Box>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
<Box style={{ flex: 'none', width: 64 }} />
|
||||
</Group>
|
||||
|
||||
{/* day rows */}
|
||||
<ScrollArea.Autosize mah="60vh" type="hover">
|
||||
{days.map((d, i) => <DayTrack key={i} d={d} axis={axis} dark={dark} />)}
|
||||
</ScrollArea.Autosize>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Text mt={16} fz={11.5} c="dimmed">Estimate · timezone {tz} · inactivity gap {inactivityGapMin} min</Text>
|
||||
</Box>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export default TimeWorkedModal;
|
||||
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"1 year": "1 year",
|
||||
"30 days": "30 days",
|
||||
"90 days": "90 days",
|
||||
"A new version is available": "A new version is available",
|
||||
"Account": "Account",
|
||||
"Active": "Active",
|
||||
@@ -10,11 +13,16 @@
|
||||
"Add space members": "Add space members",
|
||||
"Add to favorites": "Add to favorites",
|
||||
"Admin": "Admin",
|
||||
"API key created": "API key created",
|
||||
"API key revoked": "API key revoked",
|
||||
"API keys across the workspace.": "API keys across the workspace.",
|
||||
"Are you sure you want to delete this group? Members will lose access to resources this group has access to.": "Are you sure you want to delete this group? Members will lose access to resources this group has access to.",
|
||||
"Are you sure you want to delete this page?": "Are you sure you want to delete this page?",
|
||||
"Are you sure you want to remove this user from the group? The user will lose access to resources this group has access to.": "Are you sure you want to remove this user from the group? The user will lose access to resources this group has access to.",
|
||||
"Are you sure you want to remove this user from the space? The user will lose all access to this space.": "Are you sure you want to remove this user from the space? The user will lose all access to this space.",
|
||||
"Are you sure you want to restore this version? Any changes not versioned will be lost.": "Are you sure you want to restore this version? Any changes not versioned will be lost.",
|
||||
"Are you sure you want to revoke \"{{name}}\"? Any client using this key will immediately lose access. This cannot be undone.": "Are you sure you want to revoke \"{{name}}\"? Any client using this key will immediately lose access. This cannot be undone.",
|
||||
"Author": "Author",
|
||||
"Can become members of groups and spaces in workspace": "Can become members of groups and spaces in workspace",
|
||||
"Can create and edit pages in space.": "Can create and edit pages in space.",
|
||||
"Can edit": "Can edit",
|
||||
@@ -33,7 +41,9 @@
|
||||
"Confirm": "Confirm",
|
||||
"Copy as Markdown": "Copy as Markdown",
|
||||
"Copy link": "Copy link",
|
||||
"Copy your API key now and store it somewhere safe. For security reasons it will not be shown again.": "Copy your API key now and store it somewhere safe. For security reasons it will not be shown again.",
|
||||
"Create": "Create",
|
||||
"Create API key": "Create API key",
|
||||
"Create group": "Create group",
|
||||
"Create page": "Create page",
|
||||
"Create space": "Create space",
|
||||
@@ -55,7 +65,14 @@
|
||||
"e.g Sales": "e.g Sales",
|
||||
"e.g Space for product team": "e.g Space for product team",
|
||||
"e.g Space for sales team to collaborate": "e.g Space for sales team to collaborate",
|
||||
"e.g. CI deploy token": "e.g. CI deploy token",
|
||||
"Edit": "Edit",
|
||||
"Expiring soon": "Expiring soon",
|
||||
"Failed to create API key": "Failed to create API key",
|
||||
"Failed to load API keys.": "Failed to load API keys.",
|
||||
"Failed to revoke API key": "Failed to revoke API key",
|
||||
"Never used": "Never used",
|
||||
"No API keys yet": "No API keys yet",
|
||||
"Read": "Read",
|
||||
"Edit group": "Edit group",
|
||||
"Email": "Email",
|
||||
@@ -134,6 +151,8 @@
|
||||
"page": "page",
|
||||
"Page deleted successfully": "Page deleted successfully",
|
||||
"Page history": "Page history",
|
||||
"Revoke API key": "Revoke API key",
|
||||
"Revoke {{name}}": "Revoke {{name}}",
|
||||
"Select version": "Select version",
|
||||
"Highlight changes": "Highlight changes",
|
||||
"Page import is in progress. Please do not close this tab.": "Page import is in progress. Please do not close this tab.",
|
||||
@@ -189,6 +208,9 @@
|
||||
"Template": "Template",
|
||||
"Templates": "Templates",
|
||||
"Theme": "Theme",
|
||||
"This key expires within 30 days": "This key expires within 30 days",
|
||||
"This key has expired": "This key has expired",
|
||||
"This key never expires": "This key never expires",
|
||||
"To change your email, you have to enter your password and new email.": "To change your email, you have to enter your password and new email.",
|
||||
"Toggle full page width": "Toggle full page width",
|
||||
"Unable to import pages. Please try again.": "Unable to import pages. Please try again.",
|
||||
@@ -196,6 +218,7 @@
|
||||
"Untitled": "Untitled",
|
||||
"Updated successfully": "Updated successfully",
|
||||
"User": "User",
|
||||
"Within the last hour": "Within the last hour",
|
||||
"Workspace": "Workspace",
|
||||
"Workspace Name": "Workspace Name",
|
||||
"Workspace settings": "Workspace settings",
|
||||
@@ -426,6 +449,7 @@
|
||||
"Write anything. Enter \"/\" for commands": "Write anything. Enter \"/\" for commands",
|
||||
"Write...": "Write...",
|
||||
"Column count": "Column count",
|
||||
"Your personal API keys.": "Your personal API keys.",
|
||||
"{{count}} Columns": "{{count}} Columns",
|
||||
"{{count}} command available_one": "1 command available",
|
||||
"{{count}} command available_other": "{{count}} commands available",
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"1 year": "1 год",
|
||||
"30 days": "30 дней",
|
||||
"90 days": "90 дней",
|
||||
"A new version is available": "Доступна новая версия",
|
||||
"Account": "Аккаунт",
|
||||
"Active": "Активный",
|
||||
@@ -10,11 +13,16 @@
|
||||
"Add space members": "Добавить участников пространства",
|
||||
"Add to favorites": "Добавить в избранное",
|
||||
"Admin": "Администратор",
|
||||
"API key created": "API ключ создан",
|
||||
"API key revoked": "API ключ отозван",
|
||||
"API keys across the workspace.": "API ключи всего рабочего пространства.",
|
||||
"Are you sure you want to delete this group? Members will lose access to resources this group has access to.": "Вы уверены, что хотите удалить эту группу? Участники потеряют доступ к материалам, к которым у этой группы есть доступ.",
|
||||
"Are you sure you want to delete this page?": "Вы уверены, что хотите удалить эту страницу?",
|
||||
"Are you sure you want to remove this user from the group? The user will lose access to resources this group has access to.": "Вы уверены, что хотите удалить этого пользователя из группы? Пользователь потеряет доступ к материалам, к которым есть доступ у этой группы.",
|
||||
"Are you sure you want to remove this user from the space? The user will lose all access to this space.": "Вы уверены, что хотите удалить этого пользователя из пространства? Пользователь потеряет весь доступ к этому пространству.",
|
||||
"Are you sure you want to restore this version? Any changes not versioned will be lost.": "Вы уверены, что хотите восстановить эту версию? Все не зафиксированные изменения будут потеряны.",
|
||||
"Are you sure you want to revoke \"{{name}}\"? Any client using this key will immediately lose access. This cannot be undone.": "Вы уверены, что хотите отозвать «{{name}}»? Любой клиент, использующий этот ключ, немедленно потеряет доступ. Это действие нельзя отменить.",
|
||||
"Author": "Автор",
|
||||
"Can become members of groups and spaces in workspace": "Могут становиться участниками групп и пространств в рабочей области",
|
||||
"Can create and edit pages in space.": "Может создавать и редактировать страницы в пространстве.",
|
||||
"Can edit": "Может изменять",
|
||||
@@ -33,7 +41,9 @@
|
||||
"Confirm": "Подтвердить",
|
||||
"Copy as Markdown": "Копировать как Markdown",
|
||||
"Copy link": "Копировать ссылку",
|
||||
"Copy your API key now and store it somewhere safe. For security reasons it will not be shown again.": "Скопируйте API ключ сейчас и сохраните его в надёжном месте. В целях безопасности он больше не будет показан.",
|
||||
"Create": "Создать",
|
||||
"Create API key": "Создать API ключ",
|
||||
"Create group": "Создать группу",
|
||||
"Create page": "Создать страницу",
|
||||
"Create space": "Создать пространство",
|
||||
@@ -46,6 +56,7 @@
|
||||
"Are you sure you want to delete this page? This will delete its children and page history. This action is irreversible.": "Вы уверены, что хотите удалить эту страницу? Это удалит её дочерние страницы, а также историю страницы. Это действие необратимо.",
|
||||
"Description": "Описание",
|
||||
"Details": "Подробности",
|
||||
"Done": "Готово",
|
||||
"e.g ACME": "например, ACME",
|
||||
"e.g ACME Inc": "например, ACME Inc",
|
||||
"e.g Developers": "например, Developers",
|
||||
@@ -55,7 +66,15 @@
|
||||
"e.g Sales": "например, Sales",
|
||||
"e.g Space for product team": "например, Пространство для команды продукта",
|
||||
"e.g Space for sales team to collaborate": "например, Пространство для совместной работы команды продаж",
|
||||
"e.g. CI deploy token": "например, токен деплоя CI",
|
||||
"Edit": "Редактировать",
|
||||
"Expiring soon": "Скоро истекает",
|
||||
"Failed to create API key": "Не удалось создать API ключ",
|
||||
"Failed to load API keys.": "Не удалось загрузить API ключи.",
|
||||
"Failed to revoke API key": "Не удалось отозвать API ключ",
|
||||
"Name is required": "Имя обязательно",
|
||||
"Never used": "Не использовался",
|
||||
"No API keys yet": "Пока нет API ключей",
|
||||
"Read": "Чтение",
|
||||
"Edit group": "Редактировать группу",
|
||||
"Email": "Электронная почта",
|
||||
@@ -134,6 +153,8 @@
|
||||
"page": "страница",
|
||||
"Page deleted successfully": "Страница успешно удалена",
|
||||
"Page history": "История страницы",
|
||||
"Revoke API key": "Отозвать API ключ",
|
||||
"Revoke {{name}}": "Отозвать {{name}}",
|
||||
"Select version": "Выбрать версию",
|
||||
"Highlight changes": "Выделить изменения",
|
||||
"Page import is in progress. Please do not close this tab.": "Импорт страницы в процессе. Пожалуйста, не закрывайте эту вкладку.",
|
||||
@@ -189,6 +210,9 @@
|
||||
"Template": "Шаблон",
|
||||
"Templates": "Шаблоны",
|
||||
"Theme": "Тема",
|
||||
"This key expires within 30 days": "Этот ключ истекает в течение 30 дней",
|
||||
"This key has expired": "Этот ключ истек",
|
||||
"This key never expires": "Этот ключ никогда не истекает",
|
||||
"To change your email, you have to enter your password and new email.": "Чтобы изменить электронную почту, вам нужно ввести пароль и новый адрес.",
|
||||
"Toggle full page width": "Переключить полную ширину страницы",
|
||||
"Unable to import pages. Please try again.": "Не удалось импортировать страницы. Пожалуйста, попробуйте ещё раз.",
|
||||
@@ -196,6 +220,7 @@
|
||||
"Untitled": "Без названия",
|
||||
"Updated successfully": "Успешно обновлено",
|
||||
"User": "Пользователь",
|
||||
"Within the last hour": "За последний час",
|
||||
"Workspace": "Рабочее пространство",
|
||||
"Workspace Name": "Название рабочего пространства",
|
||||
"Workspace settings": "Настройки рабочего пространства",
|
||||
@@ -432,6 +457,7 @@
|
||||
"Write anything. Enter \"/\" for commands": "Пишите что угодно. Введите \"/\" для команд",
|
||||
"Write...": "Напишите...",
|
||||
"Column count": "Количество столбцов",
|
||||
"Your personal API keys.": "Ваши личные API ключи.",
|
||||
"{{count}} Columns": "{count, plural, one{# столбец} few{# столбца} many{# столбцов} other{# столбца}}",
|
||||
"{{count}} command available_one": "Доступна 1 команда",
|
||||
"{{count}} command available_other": "Доступно {{count}} команд",
|
||||
|
||||
@@ -44,6 +44,12 @@ const AccountSettings = lazy(
|
||||
const AccountPreferences = lazy(
|
||||
() => import("@/pages/settings/account/account-preferences.tsx"),
|
||||
);
|
||||
// #506 — lazy leaf (own chunk): the API-keys management page is route-split so
|
||||
// its code (Mantine table/modals + the create/revoke flow) stays out of the
|
||||
// entry bundle (post-#342 bundle discipline).
|
||||
const AccountApiKeys = lazy(
|
||||
() => import("@/pages/settings/account/account-api-keys.tsx"),
|
||||
);
|
||||
const WorkspaceSettings = lazy(
|
||||
() => import("@/pages/settings/workspace/workspace-settings"),
|
||||
);
|
||||
@@ -105,6 +111,7 @@ export default function App() {
|
||||
path={"account/preferences"}
|
||||
element={<AccountPreferences />}
|
||||
/>
|
||||
<Route path={"account/api-keys"} element={<AccountApiKeys />} />
|
||||
<Route path={"workspace"} element={<WorkspaceSettings />} />
|
||||
<Route path={"ai"} element={<AiSettings />} />
|
||||
<Route path={"members"} element={<WorkspaceMembers />} />
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
IconBrush,
|
||||
IconWorld,
|
||||
IconSparkles,
|
||||
IconKey,
|
||||
} from "@tabler/icons-react";
|
||||
import { Link, useLocation } from "react-router-dom";
|
||||
import classes from "./settings.module.css";
|
||||
@@ -46,6 +47,11 @@ const groupedData: DataGroup[] = [
|
||||
icon: IconBrush,
|
||||
path: "/settings/account/preferences",
|
||||
},
|
||||
{
|
||||
label: "API keys",
|
||||
icon: IconKey,
|
||||
path: "/settings/account/api-keys",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
fireEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from "@testing-library/react";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { ModalsProvider } from "@mantine/modals";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { Provider, createStore } from "jotai";
|
||||
import { UserRole } from "@/lib/types";
|
||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
||||
import { IApiKey } from "@/features/api-key/types/api-key.types";
|
||||
|
||||
// Mock the service layer so no real HTTP is attempted; every test drives the
|
||||
// component through these three functions.
|
||||
vi.mock("@/features/api-key/services/api-key-service", () => ({
|
||||
getApiKeys: vi.fn(),
|
||||
createApiKey: vi.fn(),
|
||||
revokeApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
import {
|
||||
getApiKeys,
|
||||
createApiKey,
|
||||
revokeApiKey,
|
||||
} from "@/features/api-key/services/api-key-service";
|
||||
import ApiKeysManager from "./api-keys-manager";
|
||||
|
||||
// matchMedia (read by MantineProvider) is stubbed globally in vitest.setup.ts.
|
||||
|
||||
const ISO_SOON = new Date(Date.now() + 10 * 864e5).toISOString();
|
||||
const ISO_FAR = new Date(Date.now() + 200 * 864e5).toISOString();
|
||||
const ISO_EXPIRED = new Date(Date.now() - 3 * 864e5).toISOString();
|
||||
|
||||
// Dump the storage stub via the Web Storage API — its data lives in a closure
|
||||
// (see vitest.setup.ts), so JSON.stringify(localStorage) would be vacuous.
|
||||
function storageDump(): string {
|
||||
let out = "";
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const k = localStorage.key(i) as string;
|
||||
out += `${k}=${localStorage.getItem(k)};`;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeKey(overrides: Partial<IApiKey> = {}): IApiKey {
|
||||
return {
|
||||
id: "key-1",
|
||||
name: "CI token",
|
||||
expiresAt: ISO_FAR,
|
||||
lastUsedAt: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
creator: { id: "u1", name: "Alice", email: "a@x.io", avatarUrl: null },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function renderManager(role: UserRole) {
|
||||
const store = createStore();
|
||||
store.set(currentUserAtom, {
|
||||
user: { id: "me", role } as never,
|
||||
workspace: {} as never,
|
||||
});
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
const utils = render(
|
||||
<Provider store={store}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MantineProvider>
|
||||
<ModalsProvider>
|
||||
<ApiKeysManager />
|
||||
</ModalsProvider>
|
||||
</MantineProvider>
|
||||
</QueryClientProvider>
|
||||
</Provider>,
|
||||
);
|
||||
return { store, queryClient, ...utils };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe("ApiKeysManager — list rendering", () => {
|
||||
it("renders an explicit expiry date and highlights a <30-day key (acceptance #3)", async () => {
|
||||
vi.mocked(getApiKeys).mockResolvedValue([
|
||||
makeKey({ id: "k-soon", name: "Soon key", expiresAt: ISO_SOON }),
|
||||
makeKey({ id: "k-far", name: "Far key", expiresAt: ISO_FAR }),
|
||||
]);
|
||||
|
||||
renderManager(UserRole.MEMBER);
|
||||
|
||||
await screen.findByText("Soon key");
|
||||
// Explicit dates, not "in N days": the year is rendered verbatim.
|
||||
const soonYear = new Date(ISO_SOON).getFullYear().toString();
|
||||
expect(screen.getAllByText(new RegExp(soonYear)).length).toBeGreaterThan(0);
|
||||
// Exactly one key is inside the 30-day warning window.
|
||||
expect(screen.getAllByText("Expiring soon")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('shows "Expired" (not "Expiring soon") for an already-expired key', async () => {
|
||||
vi.mocked(getApiKeys).mockResolvedValue([
|
||||
makeKey({ id: "k-dead", name: "Dead key", expiresAt: ISO_EXPIRED }),
|
||||
]);
|
||||
renderManager(UserRole.MEMBER);
|
||||
await screen.findByText("Dead key");
|
||||
// A past expiry is labelled "Expired", never the forward-looking badge.
|
||||
expect(screen.getByText("Expired")).toBeDefined();
|
||||
expect(screen.queryByText("Expiring soon")).toBeNull();
|
||||
});
|
||||
|
||||
it('shows "Never" for an unlimited key and no highlight', async () => {
|
||||
vi.mocked(getApiKeys).mockResolvedValue([
|
||||
makeKey({ id: "k-forever", name: "Forever", expiresAt: null }),
|
||||
]);
|
||||
renderManager(UserRole.MEMBER);
|
||||
await screen.findByText("Forever");
|
||||
expect(screen.getByText("Never")).toBeDefined();
|
||||
expect(screen.queryByText("Expiring soon")).toBeNull();
|
||||
});
|
||||
|
||||
it("empty list shows the empty state", async () => {
|
||||
vi.mocked(getApiKeys).mockResolvedValue([]);
|
||||
renderManager(UserRole.MEMBER);
|
||||
expect(await screen.findByText("No API keys yet")).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ApiKeysManager — admin vs member view (acceptance #6)", () => {
|
||||
it("a member does NOT see the author column", async () => {
|
||||
vi.mocked(getApiKeys).mockResolvedValue([
|
||||
makeKey({ creator: { id: "me", name: "Me", email: "m@x.io", avatarUrl: null } }),
|
||||
]);
|
||||
renderManager(UserRole.MEMBER);
|
||||
await screen.findByText("CI token");
|
||||
// Author header absent + creator name not rendered (no author column).
|
||||
expect(screen.queryByText("Author")).toBeNull();
|
||||
expect(screen.queryByText("Me")).toBeNull();
|
||||
});
|
||||
|
||||
it("an admin sees the author column with the creator's name", async () => {
|
||||
vi.mocked(getApiKeys).mockResolvedValue([
|
||||
makeKey({ creator: { id: "u1", name: "Alice", email: "a@x.io", avatarUrl: null } }),
|
||||
]);
|
||||
renderManager(UserRole.ADMIN);
|
||||
await screen.findByText("CI token");
|
||||
expect(screen.getByText("Author")).toBeDefined();
|
||||
expect(screen.getByText("Alice")).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ApiKeysManager — revoke (acceptance #4)", () => {
|
||||
it("revoke removes the row from the list", async () => {
|
||||
vi.mocked(getApiKeys)
|
||||
.mockResolvedValueOnce([
|
||||
makeKey({ id: "k1", name: "Doomed" }),
|
||||
makeKey({ id: "k2", name: "Survivor" }),
|
||||
])
|
||||
// After revoke, invalidation refetches the reduced list.
|
||||
.mockResolvedValue([makeKey({ id: "k2", name: "Survivor" })]);
|
||||
vi.mocked(revokeApiKey).mockResolvedValue();
|
||||
|
||||
renderManager(UserRole.MEMBER);
|
||||
await screen.findByText("Doomed");
|
||||
|
||||
fireEvent.click(screen.getByLabelText("Revoke Doomed"));
|
||||
// Confirm modal → click the destructive confirm button.
|
||||
const confirm = await screen.findByRole("button", { name: "Revoke" });
|
||||
fireEvent.click(confirm);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByText("Doomed")).toBeNull(),
|
||||
);
|
||||
expect(screen.getByText("Survivor")).toBeDefined();
|
||||
expect(revokeApiKey).toHaveBeenCalledWith("k1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ApiKeysManager — show-once token (acceptance #1 & #2)", () => {
|
||||
it("shows the token once, then discards it from the UI, localStorage and query cache", async () => {
|
||||
const SECRET = "gm_secret-token-value-xyz";
|
||||
vi.mocked(getApiKeys).mockResolvedValue([]);
|
||||
vi.mocked(createApiKey).mockResolvedValue({
|
||||
token: SECRET,
|
||||
apiKey: {
|
||||
id: "new-1",
|
||||
name: "My key",
|
||||
expiresAt: ISO_FAR,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
|
||||
const { queryClient } = renderManager(UserRole.MEMBER);
|
||||
await screen.findByText("No API keys yet");
|
||||
|
||||
// Open create modal (use the header CTA), fill the name, submit.
|
||||
fireEvent.click(
|
||||
screen.getAllByRole("button", { name: "Create API key" })[0],
|
||||
);
|
||||
const nameInput = await screen.findByLabelText(/Name/);
|
||||
fireEvent.change(nameInput, { target: { value: "My key" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create" }));
|
||||
|
||||
// Token is shown exactly once in the show-once modal.
|
||||
const tokenEl = await screen.findByTestId("api-key-token");
|
||||
expect(tokenEl.textContent).toBe(SECRET);
|
||||
|
||||
// Close the modal → token discarded from the DOM.
|
||||
fireEvent.click(screen.getByRole("button", { name: "Done" }));
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId("api-key-token")).toBeNull(),
|
||||
);
|
||||
|
||||
// Acceptance #2: the secret is nowhere in localStorage or the react-query
|
||||
// caches (query cache never carried it; the mutation copy was reset()).
|
||||
// Non-vacuous: currentUser IS in storage, so the dump is exercised.
|
||||
const dump = storageDump();
|
||||
expect(dump).toContain("currentUser");
|
||||
expect(dump).not.toContain(SECRET);
|
||||
const cacheDump = JSON.stringify(
|
||||
queryClient.getQueryCache().getAll().map((q) => q.state.data),
|
||||
);
|
||||
expect(cacheDump).not.toContain(SECRET);
|
||||
const mutationDump = JSON.stringify(
|
||||
queryClient.getMutationCache().getAll().map((m) => m.state.data),
|
||||
);
|
||||
expect(mutationDump).not.toContain(SECRET);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import { useState } from "react";
|
||||
import {
|
||||
ActionIcon,
|
||||
Badge,
|
||||
Button,
|
||||
Center,
|
||||
Group,
|
||||
Loader,
|
||||
Stack,
|
||||
Table,
|
||||
Text,
|
||||
Tooltip,
|
||||
} from "@mantine/core";
|
||||
import { modals } from "@mantine/modals";
|
||||
import { notifications } from "@mantine/notifications";
|
||||
import { IconAlertTriangle, IconKey, IconTrash } from "@tabler/icons-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useUserRole from "@/hooks/use-user-role.tsx";
|
||||
import { formatLocalized, useDateFnsLocale } from "@/lib/date-locale";
|
||||
import { timeAgo } from "@/lib/time";
|
||||
import {
|
||||
useApiKeysQuery,
|
||||
useCreateApiKeyMutation,
|
||||
useRevokeApiKeyMutation,
|
||||
} from "@/features/api-key/queries/api-key-query";
|
||||
import {
|
||||
IApiKey,
|
||||
ICreateApiKeyResponse,
|
||||
} from "@/features/api-key/types/api-key.types";
|
||||
import {
|
||||
isExpired,
|
||||
isExpiringSoon,
|
||||
lastUsedBucket,
|
||||
} from "@/features/api-key/utils";
|
||||
import { CreateApiKeyModal } from "./create-api-key-modal";
|
||||
import { ShowTokenModal } from "./show-token-modal";
|
||||
|
||||
export default function ApiKeysManager() {
|
||||
const { t } = useTranslation();
|
||||
const locale = useDateFnsLocale();
|
||||
// Manage-on-API === Owner/Admin server-side, so the admin (workspace-wide)
|
||||
// list + "author" column mirror exactly the roles the server serves the
|
||||
// whole-workspace response to.
|
||||
const { isAdmin } = useUserRole();
|
||||
|
||||
const { data: keys, isLoading, isError } = useApiKeysQuery();
|
||||
const createMutation = useCreateApiKeyMutation();
|
||||
const revokeMutation = useRevokeApiKeyMutation();
|
||||
|
||||
const [createOpened, setCreateOpened] = useState(false);
|
||||
// SECURITY: the show-once token lives ONLY here, in this component's local
|
||||
// state. It is never written to localStorage, the query cache or a log. Closing
|
||||
// the modal sets it back to null (handleCloseToken) — discarded forever.
|
||||
const [createdKey, setCreatedKey] = useState<ICreateApiKeyResponse | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const handleCreate = async (values: {
|
||||
name: string;
|
||||
expiresAt: string | null;
|
||||
}): Promise<boolean> => {
|
||||
try {
|
||||
const res = await createMutation.mutateAsync(values);
|
||||
setCreateOpened(false);
|
||||
// Move the token into local state, then immediately purge react-query's
|
||||
// own copy of the mutation result so the secret does not linger in the
|
||||
// mutation cache.
|
||||
setCreatedKey(res);
|
||||
createMutation.reset();
|
||||
return true;
|
||||
} catch {
|
||||
notifications.show({
|
||||
message: t("Failed to create API key"),
|
||||
color: "red",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleCloseToken = () => {
|
||||
// Token discarded — the only copy the UI ever held is dropped here.
|
||||
setCreatedKey(null);
|
||||
};
|
||||
|
||||
const openRevokeModal = (key: IApiKey) =>
|
||||
modals.openConfirmModal({
|
||||
title: t("Revoke API key"),
|
||||
centered: true,
|
||||
children: (
|
||||
<Text size="sm">
|
||||
{t(
|
||||
'Are you sure you want to revoke "{{name}}"? Any client using this key will immediately lose access. This cannot be undone.',
|
||||
{ name: key.name },
|
||||
)}
|
||||
</Text>
|
||||
),
|
||||
labels: { confirm: t("Revoke"), cancel: t("Cancel") },
|
||||
confirmProps: { color: "red" },
|
||||
onConfirm: () => revokeMutation.mutate(key.id),
|
||||
});
|
||||
|
||||
const formatDate = (iso: string) =>
|
||||
formatLocalized(new Date(iso), "MMM dd, yyyy", "PP", locale);
|
||||
|
||||
const renderLastUsed = (lastUsedAt: string | null) => {
|
||||
switch (lastUsedBucket(lastUsedAt)) {
|
||||
case "never":
|
||||
return t("Never used");
|
||||
case "recent":
|
||||
return t("Within the last hour");
|
||||
case "stale":
|
||||
// Coarse relative time — last_used_at is throttled to ~1h server-side,
|
||||
// so we don't promise finer precision.
|
||||
return timeAgo(new Date(lastUsedAt as string));
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Center py="xl">
|
||||
<Loader size="sm" />
|
||||
</Center>
|
||||
);
|
||||
}
|
||||
|
||||
const rows = (keys ?? []).map((key) => {
|
||||
// Mutually exclusive: an already-expired key is labelled "Expired" (a past
|
||||
// expiry) rather than the forward-looking "Expiring soon". isExpiringSoon
|
||||
// also matches past expiries, so gate "soon" on !expired.
|
||||
const expired = isExpired(key.expiresAt);
|
||||
const soon = !expired && isExpiringSoon(key.expiresAt);
|
||||
return (
|
||||
<Table.Tr key={key.id}>
|
||||
<Table.Td>
|
||||
<Text fw={500}>{key.name}</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>{formatDate(key.createdAt)}</Table.Td>
|
||||
<Table.Td>
|
||||
{key.expiresAt ? (
|
||||
<Group gap={6} wrap="nowrap">
|
||||
<Text size="sm">{formatDate(key.expiresAt)}</Text>
|
||||
{expired && (
|
||||
<Tooltip label={t("This key has expired")} withArrow>
|
||||
<Badge
|
||||
color="red"
|
||||
variant="light"
|
||||
size="sm"
|
||||
leftSection={<IconAlertTriangle size={12} />}
|
||||
>
|
||||
{t("Expired")}
|
||||
</Badge>
|
||||
</Tooltip>
|
||||
)}
|
||||
{soon && (
|
||||
<Tooltip
|
||||
label={t("This key expires within 30 days")}
|
||||
withArrow
|
||||
>
|
||||
<Badge
|
||||
color="orange"
|
||||
variant="light"
|
||||
size="sm"
|
||||
leftSection={<IconAlertTriangle size={12} />}
|
||||
>
|
||||
{t("Expiring soon")}
|
||||
</Badge>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Group>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("Never")}
|
||||
</Text>
|
||||
)}
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" c="dimmed">
|
||||
{renderLastUsed(key.lastUsedAt)}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
{isAdmin && (
|
||||
<Table.Td>
|
||||
<Text size="sm">
|
||||
{key.creator?.name ?? key.creator?.email ?? t("Unknown")}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
)}
|
||||
<Table.Td style={{ textAlign: "right" }}>
|
||||
<Tooltip label={t("Revoke")} withArrow>
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
color="red"
|
||||
aria-label={t("Revoke {{name}}", { name: key.name })}
|
||||
onClick={() => openRevokeModal(key)}
|
||||
>
|
||||
<IconTrash size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<Group justify="space-between" mb="md">
|
||||
<Text size="sm" c="dimmed">
|
||||
{isAdmin
|
||||
? t("API keys across the workspace.")
|
||||
: t("Your personal API keys.")}
|
||||
</Text>
|
||||
<Button
|
||||
leftSection={<IconKey size={16} />}
|
||||
onClick={() => setCreateOpened(true)}
|
||||
>
|
||||
{t("Create API key")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
{isError ? (
|
||||
<Text c="red" size="sm">
|
||||
{t("Failed to load API keys.")}
|
||||
</Text>
|
||||
) : rows.length === 0 ? (
|
||||
<Stack align="center" gap="xs" py="xl">
|
||||
<IconKey size={32} opacity={0.4} />
|
||||
<Text c="dimmed">{t("No API keys yet")}</Text>
|
||||
<Button
|
||||
variant="light"
|
||||
leftSection={<IconKey size={16} />}
|
||||
onClick={() => setCreateOpened(true)}
|
||||
>
|
||||
{t("Create API key")}
|
||||
</Button>
|
||||
</Stack>
|
||||
) : (
|
||||
<Table.ScrollContainer minWidth={600}>
|
||||
<Table verticalSpacing="sm" highlightOnHover>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>{t("Name")}</Table.Th>
|
||||
<Table.Th>{t("Created")}</Table.Th>
|
||||
<Table.Th>{t("Expires")}</Table.Th>
|
||||
<Table.Th>{t("Last used")}</Table.Th>
|
||||
{isAdmin && <Table.Th>{t("Author")}</Table.Th>}
|
||||
<Table.Th />
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>{rows}</Table.Tbody>
|
||||
</Table>
|
||||
</Table.ScrollContainer>
|
||||
)}
|
||||
|
||||
<CreateApiKeyModal
|
||||
opened={createOpened}
|
||||
onClose={() => setCreateOpened(false)}
|
||||
onSubmit={handleCreate}
|
||||
loading={createMutation.isPending}
|
||||
/>
|
||||
|
||||
<ShowTokenModal created={createdKey} onClose={handleCloseToken} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { Button, Group, Modal, Select, Stack, TextInput } from "@mantine/core";
|
||||
import { useForm } from "@mantine/form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
ApiKeyLifetime,
|
||||
DEFAULT_LIFETIME,
|
||||
lifetimeToExpiresAt,
|
||||
} from "@/features/api-key/utils";
|
||||
|
||||
interface Props {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
// Resolves the create request, returning true on success. The parent owns the
|
||||
// mutation (and the token it returns); this modal only collects the name +
|
||||
// lifetime. On failure (false) the form state is kept so the user can retry.
|
||||
onSubmit: (values: {
|
||||
name: string;
|
||||
expiresAt: string | null;
|
||||
}) => Promise<boolean>;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
interface FormValues {
|
||||
name: string;
|
||||
lifetime: ApiKeyLifetime;
|
||||
}
|
||||
|
||||
export function CreateApiKeyModal({
|
||||
opened,
|
||||
onClose,
|
||||
onSubmit,
|
||||
loading,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
initialValues: {
|
||||
name: "",
|
||||
lifetime: DEFAULT_LIFETIME,
|
||||
},
|
||||
validate: {
|
||||
name: (value) =>
|
||||
value.trim().length === 0 ? t("Name is required") : null,
|
||||
},
|
||||
});
|
||||
|
||||
const lifetimeOptions: { value: ApiKeyLifetime; label: string }[] = [
|
||||
{ value: "30d", label: t("30 days") },
|
||||
{ value: "90d", label: t("90 days") },
|
||||
{ value: "1y", label: t("1 year") },
|
||||
{ value: "never", label: t("No expiration") },
|
||||
];
|
||||
|
||||
const handleSubmit = form.onSubmit(async (values) => {
|
||||
const ok = await onSubmit({
|
||||
name: values.name.trim(),
|
||||
expiresAt: lifetimeToExpiresAt(values.lifetime),
|
||||
});
|
||||
// Reset only after a successful submit so a failed create keeps the form
|
||||
// state (the parent surfaces the error via a notification).
|
||||
if (ok) form.reset();
|
||||
});
|
||||
|
||||
const handleClose = () => {
|
||||
form.reset();
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={handleClose}
|
||||
title={t("Create API key")}
|
||||
centered
|
||||
>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<Stack gap="sm">
|
||||
<TextInput
|
||||
label={t("Name")}
|
||||
placeholder={t("e.g. CI deploy token")}
|
||||
data-autofocus
|
||||
withAsterisk
|
||||
{...form.getInputProps("name")}
|
||||
/>
|
||||
<Select
|
||||
label={t("Expiration")}
|
||||
data={lifetimeOptions}
|
||||
allowDeselect={false}
|
||||
checkIconPosition="right"
|
||||
{...form.getInputProps("lifetime")}
|
||||
/>
|
||||
<Group justify="flex-end" mt="xs">
|
||||
<Button variant="default" onClick={handleClose} type="button">
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" loading={loading}>
|
||||
{t("Create")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Code,
|
||||
Group,
|
||||
Modal,
|
||||
Stack,
|
||||
Text,
|
||||
} from "@mantine/core";
|
||||
import { IconAlertTriangle, IconCheck, IconCopy } from "@tabler/icons-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { CopyButton } from "@/components/common/copy-button";
|
||||
import { formatLocalized, useDateFnsLocale } from "@/lib/date-locale";
|
||||
import { ICreateApiKeyResponse } from "@/features/api-key/types/api-key.types";
|
||||
|
||||
interface Props {
|
||||
// The freshly-created key incl. its token. Owned by the parent; this modal
|
||||
// only renders it and never copies it into its own persistent state.
|
||||
created: ICreateApiKeyResponse | null;
|
||||
// Closing MUST discard the token in the parent (set the `created` prop back to
|
||||
// null) — the token is shown exactly once.
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function ShowTokenModal({ created, onClose }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const locale = useDateFnsLocale();
|
||||
|
||||
const expiresAt = created?.apiKey.expiresAt ?? null;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={created !== null}
|
||||
onClose={onClose}
|
||||
title={t("API key created")}
|
||||
centered
|
||||
// No dismiss-on-outside-click: the token is irretrievable, so closing is a
|
||||
// deliberate act (the user confirms they have saved it).
|
||||
closeOnClickOutside={false}
|
||||
>
|
||||
{created && (
|
||||
<Stack gap="sm">
|
||||
<Alert
|
||||
color="orange"
|
||||
icon={<IconAlertTriangle size={18} />}
|
||||
variant="light"
|
||||
>
|
||||
{t(
|
||||
"Copy your API key now and store it somewhere safe. For security reasons it will not be shown again.",
|
||||
)}
|
||||
</Alert>
|
||||
|
||||
<div>
|
||||
<Text size="sm" c="dimmed" mb={4}>
|
||||
{t("Token")}
|
||||
</Text>
|
||||
<Group gap="xs" wrap="nowrap" align="flex-start">
|
||||
<Code
|
||||
block
|
||||
data-testid="api-key-token"
|
||||
style={{ flex: 1, wordBreak: "break-all" }}
|
||||
>
|
||||
{created.token}
|
||||
</Code>
|
||||
<CopyButton value={created.token}>
|
||||
{({ copied, copy }) => (
|
||||
<Button
|
||||
variant="light"
|
||||
size="xs"
|
||||
color={copied ? "teal" : "blue"}
|
||||
leftSection={
|
||||
copied ? (
|
||||
<IconCheck size={16} />
|
||||
) : (
|
||||
<IconCopy size={16} />
|
||||
)
|
||||
}
|
||||
onClick={copy}
|
||||
>
|
||||
{copied ? t("Copied") : t("Copy")}
|
||||
</Button>
|
||||
)}
|
||||
</CopyButton>
|
||||
</Group>
|
||||
</div>
|
||||
|
||||
<Text size="sm" c="dimmed">
|
||||
{expiresAt
|
||||
? t("Expires {{date}}", {
|
||||
date: formatLocalized(
|
||||
new Date(expiresAt),
|
||||
"MMM dd, yyyy",
|
||||
"PP",
|
||||
locale,
|
||||
),
|
||||
})
|
||||
: t("This key never expires")}
|
||||
</Text>
|
||||
|
||||
<Group justify="flex-end" mt="xs">
|
||||
<Button onClick={onClose}>{t("Done")}</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import {
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
import { notifications } from "@mantine/notifications";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
createApiKey,
|
||||
getApiKeys,
|
||||
revokeApiKey,
|
||||
} from "@/features/api-key/services/api-key-service";
|
||||
import {
|
||||
IApiKey,
|
||||
ICreateApiKey,
|
||||
ICreateApiKeyResponse,
|
||||
} from "@/features/api-key/types/api-key.types";
|
||||
|
||||
export const API_KEYS_QUERY_KEY = ["api-keys"];
|
||||
|
||||
export function useApiKeysQuery(): UseQueryResult<IApiKey[], Error> {
|
||||
return useQuery({
|
||||
queryKey: API_KEYS_QUERY_KEY,
|
||||
queryFn: () => getApiKeys(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create mutation.
|
||||
*
|
||||
* SECURITY: the response contains the token exactly once. This hook deliberately
|
||||
* does NOT stash it anywhere — the caller reads it from `mutateAsync`'s resolved
|
||||
* value, moves it into the show-once modal's local state, then calls
|
||||
* `mutation.reset()` to purge react-query's own copy immediately. `gcTime: 0`
|
||||
* is a second belt so nothing lingers in the mutation cache after the observer
|
||||
* unmounts. The list is invalidated here (the list carries no token).
|
||||
*/
|
||||
export function useCreateApiKeyMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<ICreateApiKeyResponse, Error, ICreateApiKey>({
|
||||
mutationFn: (data) => createApiKey(data),
|
||||
gcTime: 0,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: API_KEYS_QUERY_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useRevokeApiKeyMutation() {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<void, Error, string>({
|
||||
mutationFn: (id) => revokeApiKey(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: API_KEYS_QUERY_KEY });
|
||||
notifications.show({ message: t("API key revoked") });
|
||||
},
|
||||
onError: () => {
|
||||
notifications.show({
|
||||
message: t("Failed to revoke API key"),
|
||||
color: "red",
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// Mock the api-client (axios instance). vi.mock replaces the whole module, so
|
||||
// the real response interceptor — which returns `response.data`, i.e. the
|
||||
// server envelope { data, success, status } — is bypassed. Our mocked post/get
|
||||
// therefore resolve to that post-interceptor envelope shape directly, and the
|
||||
// service under test reads `.data` off it to unwrap the inner payload. This is
|
||||
// the one bug-prone line the component tests (which fully mock the service)
|
||||
// never exercise.
|
||||
const { post, get } = vi.hoisted(() => ({ post: vi.fn(), get: vi.fn() }));
|
||||
vi.mock("@/lib/api-client", () => ({
|
||||
default: { post, get },
|
||||
}));
|
||||
|
||||
import {
|
||||
createApiKey,
|
||||
getApiKeys,
|
||||
} from "@/features/api-key/services/api-key-service";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("api-key-service response-contract unwrap", () => {
|
||||
it("createApiKey unwraps the envelope to { token, apiKey }", async () => {
|
||||
const payload = {
|
||||
token: "gm_secret-abc",
|
||||
apiKey: {
|
||||
id: "key-1",
|
||||
name: "CI token",
|
||||
expiresAt: "2027-07-11T12:00:00.000Z",
|
||||
createdAt: "2026-07-11T12:00:00.000Z",
|
||||
},
|
||||
};
|
||||
// The server envelope as the interceptor hands it to the service.
|
||||
post.mockResolvedValue({ data: payload, success: true, status: 200 });
|
||||
|
||||
const result = await createApiKey({
|
||||
name: "CI token",
|
||||
expiresAt: "2027-07-11T12:00:00.000Z",
|
||||
});
|
||||
|
||||
// The inner payload only — not the { data, success, status } wrapper.
|
||||
expect(result).toEqual(payload);
|
||||
expect(result.token).toBe("gm_secret-abc");
|
||||
expect(result.apiKey).toEqual(payload.apiKey);
|
||||
expect(post).toHaveBeenCalledWith("/api-keys/create", {
|
||||
name: "CI token",
|
||||
expiresAt: "2027-07-11T12:00:00.000Z",
|
||||
});
|
||||
});
|
||||
|
||||
it("getApiKeys unwraps the envelope to the array of rows", async () => {
|
||||
const rows = [
|
||||
{
|
||||
id: "key-1",
|
||||
name: "CI token",
|
||||
expiresAt: null,
|
||||
lastUsedAt: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: "key-2",
|
||||
name: "Deploy token",
|
||||
expiresAt: "2027-01-01T00:00:00.000Z",
|
||||
lastUsedAt: null,
|
||||
createdAt: "2026-02-01T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
post.mockResolvedValue({ data: rows, success: true, status: 200 });
|
||||
|
||||
const result = await getApiKeys();
|
||||
|
||||
expect(result).toEqual(rows);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(post).toHaveBeenCalledWith("/api-keys/list");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import api from "@/lib/api-client";
|
||||
import {
|
||||
IApiKey,
|
||||
ICreateApiKey,
|
||||
ICreateApiKeyResponse,
|
||||
} from "@/features/api-key/types/api-key.types";
|
||||
|
||||
// Mint a new key. The response carries the token ONCE — the caller must move it
|
||||
// straight into the show-once modal's local state and never cache it. See
|
||||
// queries/api-key-query.ts (gcTime: 0 + query invalidation) and
|
||||
// components/api-keys-manager.tsx `handleCreate` (createMutation.reset() right
|
||||
// after reading the token) for the reset()-after-read pattern.
|
||||
export async function createApiKey(
|
||||
data: ICreateApiKey,
|
||||
): Promise<ICreateApiKeyResponse> {
|
||||
const res = await api.post<ICreateApiKeyResponse>("/api-keys/create", data);
|
||||
return res.data as ICreateApiKeyResponse;
|
||||
}
|
||||
|
||||
// List the caller's keys (or, for an admin, every key in the workspace with
|
||||
// creator attribution). Never returns token material.
|
||||
export async function getApiKeys(): Promise<IApiKey[]> {
|
||||
const res = await api.post<IApiKey[]>("/api-keys/list");
|
||||
return res.data as IApiKey[];
|
||||
}
|
||||
|
||||
// Revocation is server-side immediate; the caller drops the row on success.
|
||||
export async function revokeApiKey(id: string): Promise<void> {
|
||||
await api.post("/api-keys/revoke", { id });
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Compact creator attribution embedded in the admin (workspace-wide) list. A
|
||||
// normal member's list only ever contains their own keys, so the field is
|
||||
// present but redundant; the author column is only rendered for admins.
|
||||
export interface IApiKeyCreator {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
avatarUrl: string | null;
|
||||
}
|
||||
|
||||
// A single api-key row as returned by `POST /api/api-keys/list`. Note: the list
|
||||
// NEVER carries token material — only metadata.
|
||||
export interface IApiKey {
|
||||
id: string;
|
||||
name: string;
|
||||
// ISO string, or null for an unlimited ("never expires") key.
|
||||
expiresAt: string | null;
|
||||
// ISO string, or null if the key was never used. Throttled to ~1h server-side
|
||||
// (#501), so the UI must not promise sub-hour precision.
|
||||
lastUsedAt: string | null;
|
||||
createdAt: string;
|
||||
creator?: IApiKeyCreator | null;
|
||||
}
|
||||
|
||||
// Payload for `POST /api/api-keys/create`. `expiresAt`: an ISO date string for a
|
||||
// bounded lifetime, or null for an unlimited key. (undefined would let the
|
||||
// server apply its 1-year default, but the form always sends an explicit value.)
|
||||
export interface ICreateApiKey {
|
||||
name: string;
|
||||
expiresAt: string | null;
|
||||
}
|
||||
|
||||
// The metadata half of the create response. The token itself is carried
|
||||
// separately (see ICreateApiKeyResponse) and is shown exactly once.
|
||||
export interface ICreatedApiKey {
|
||||
id: string;
|
||||
name: string;
|
||||
expiresAt: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
// Response of `POST /api/api-keys/create`. `token` is the ONLY time the secret
|
||||
// is ever returned — it must live only in the show-once modal's local state and
|
||||
// must never be cached, persisted or logged.
|
||||
export interface ICreateApiKeyResponse {
|
||||
token: string;
|
||||
apiKey: ICreatedApiKey;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
DEFAULT_LIFETIME,
|
||||
EXPIRY_WARNING_DAYS,
|
||||
isExpired,
|
||||
isExpiringSoon,
|
||||
lastUsedBucket,
|
||||
lifetimeToExpiresAt,
|
||||
} from "./utils";
|
||||
|
||||
const NOW = new Date("2026-07-11T12:00:00.000Z");
|
||||
const daysFromNow = (n: number) =>
|
||||
new Date(NOW.getTime() + n * 24 * 60 * 60 * 1000).toISOString();
|
||||
|
||||
describe("lifetimeToExpiresAt", () => {
|
||||
it("default lifetime is 1 year (acceptance #7)", () => {
|
||||
expect(DEFAULT_LIFETIME).toBe("1y");
|
||||
const iso = lifetimeToExpiresAt("1y", NOW);
|
||||
expect(iso).toBe("2027-07-11T12:00:00.000Z");
|
||||
});
|
||||
|
||||
it('"never" sends null (acceptance #7)', () => {
|
||||
expect(lifetimeToExpiresAt("never", NOW)).toBeNull();
|
||||
});
|
||||
|
||||
it("30d / 90d map to the exact future instant", () => {
|
||||
expect(lifetimeToExpiresAt("30d", NOW)).toBe(daysFromNow(30));
|
||||
expect(lifetimeToExpiresAt("90d", NOW)).toBe(daysFromNow(90));
|
||||
});
|
||||
});
|
||||
|
||||
describe("isExpiringSoon (acceptance #3 highlight)", () => {
|
||||
it("an unlimited key is never 'soon'", () => {
|
||||
expect(isExpiringSoon(null, NOW)).toBe(false);
|
||||
});
|
||||
|
||||
it("highlights a key expiring within the 30-day window", () => {
|
||||
expect(isExpiringSoon(daysFromNow(EXPIRY_WARNING_DAYS - 1), NOW)).toBe(true);
|
||||
expect(isExpiringSoon(daysFromNow(10), NOW)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not highlight a key well outside the window", () => {
|
||||
expect(isExpiringSoon(daysFromNow(EXPIRY_WARNING_DAYS + 1), NOW)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isExpiringSoon(daysFromNow(200), NOW)).toBe(false);
|
||||
});
|
||||
|
||||
it("an already-expired key is highlighted", () => {
|
||||
expect(isExpiringSoon(daysFromNow(-3), NOW)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isExpired (past vs future expiry)", () => {
|
||||
it("an unlimited key is never expired", () => {
|
||||
expect(isExpired(null, NOW)).toBe(false);
|
||||
});
|
||||
|
||||
it("a past expiry is expired", () => {
|
||||
expect(isExpired(daysFromNow(-3), NOW)).toBe(true);
|
||||
expect(isExpired(daysFromNow(-1), NOW)).toBe(true);
|
||||
});
|
||||
|
||||
it("a future expiry is not expired (even within the warning window)", () => {
|
||||
expect(isExpired(daysFromNow(1), NOW)).toBe(false);
|
||||
expect(isExpired(daysFromNow(EXPIRY_WARNING_DAYS - 1), NOW)).toBe(false);
|
||||
expect(isExpired(daysFromNow(200), NOW)).toBe(false);
|
||||
});
|
||||
|
||||
it("an expiry exactly at 'now' counts as expired (boundary is inclusive)", () => {
|
||||
expect(isExpired(NOW.toISOString(), NOW)).toBe(true);
|
||||
});
|
||||
|
||||
it("is mutually distinguishable from isExpiringSoon: expired vs soon-but-future", () => {
|
||||
// A key 3 days in the past: expired, and (by design) also matches
|
||||
// isExpiringSoon — the UI resolves this by checking isExpired first.
|
||||
expect(isExpired(daysFromNow(-3), NOW)).toBe(true);
|
||||
// A key 10 days in the future: NOT expired, but expiring soon.
|
||||
expect(isExpired(daysFromNow(10), NOW)).toBe(false);
|
||||
expect(isExpiringSoon(daysFromNow(10), NOW)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("lastUsedBucket (within-the-last-hour semantics)", () => {
|
||||
const minutesAgo = (n: number) =>
|
||||
new Date(NOW.getTime() - n * 60 * 1000).toISOString();
|
||||
|
||||
it("null last-used is 'never'", () => {
|
||||
expect(lastUsedBucket(null, NOW)).toBe("never");
|
||||
});
|
||||
|
||||
it("under an hour is 'recent' (no sub-hour precision promised)", () => {
|
||||
expect(lastUsedBucket(minutesAgo(5), NOW)).toBe("recent");
|
||||
expect(lastUsedBucket(minutesAgo(59), NOW)).toBe("recent");
|
||||
});
|
||||
|
||||
it("over an hour is 'stale'", () => {
|
||||
expect(lastUsedBucket(minutesAgo(90), NOW)).toBe("stale");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { addDays, addYears, differenceInMinutes } from "date-fns";
|
||||
|
||||
// The single early-warning window (#501/#506): keys whose expiry is closer than
|
||||
// this are visually highlighted in the list. Also used to classify a key as
|
||||
// already-expired (a negative "days until" is < 30 too).
|
||||
export const EXPIRY_WARNING_DAYS = 30;
|
||||
|
||||
// last_used_at is throttled to ~1h server-side, so anything under an hour is
|
||||
// shown as the coarse "within the last hour" rather than a false-precise
|
||||
// "5 minutes ago".
|
||||
export const LAST_USED_THROTTLE_MINUTES = 60;
|
||||
|
||||
export type ApiKeyLifetime = "30d" | "90d" | "1y" | "never";
|
||||
|
||||
export const DEFAULT_LIFETIME: ApiKeyLifetime = "1y";
|
||||
|
||||
// Maps a lifetime choice to the `expiresAt` payload sent to the server: an ISO
|
||||
// string for a bounded lifetime, or null for an explicit unlimited key.
|
||||
export function lifetimeToExpiresAt(
|
||||
lifetime: ApiKeyLifetime,
|
||||
now: Date = new Date(),
|
||||
): string | null {
|
||||
switch (lifetime) {
|
||||
case "30d":
|
||||
return addDays(now, 30).toISOString();
|
||||
case "90d":
|
||||
return addDays(now, 90).toISOString();
|
||||
case "1y":
|
||||
return addYears(now, 1).toISOString();
|
||||
case "never":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// True when a bounded key's expiry is already in the past (or exactly now). An
|
||||
// unlimited key (null) is never expired. This is distinct from "expiring soon":
|
||||
// the two states are mutually exclusive at the call site (see api-keys-manager),
|
||||
// so an already-expired key is labelled "Expired", not "Expiring soon".
|
||||
export function isExpired(
|
||||
expiresAt: string | null,
|
||||
now: Date = new Date(),
|
||||
): boolean {
|
||||
if (!expiresAt) return false;
|
||||
const expiry = new Date(expiresAt).getTime();
|
||||
if (Number.isNaN(expiry)) return false;
|
||||
return expiry <= now.getTime();
|
||||
}
|
||||
|
||||
// True when a bounded key expires within the warning window (or is already
|
||||
// expired). An unlimited key (null) is never "expiring soon". Callers that need
|
||||
// to distinguish an already-past expiry should check isExpired() first, as this
|
||||
// predicate deliberately also covers the already-expired case.
|
||||
export function isExpiringSoon(
|
||||
expiresAt: string | null,
|
||||
now: Date = new Date(),
|
||||
): boolean {
|
||||
if (!expiresAt) return false;
|
||||
const expiry = new Date(expiresAt).getTime();
|
||||
if (Number.isNaN(expiry)) return false;
|
||||
const msLeft = expiry - now.getTime();
|
||||
return msLeft < EXPIRY_WARNING_DAYS * 24 * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
// Classifies last-used recency so the caller can pick the honest label without
|
||||
// promising sub-hour precision. Returns "never", "recent" (< 1h) or "stale".
|
||||
export function lastUsedBucket(
|
||||
lastUsedAt: string | null,
|
||||
now: Date = new Date(),
|
||||
): "never" | "recent" | "stale" {
|
||||
if (!lastUsedAt) return "never";
|
||||
const used = new Date(lastUsedAt);
|
||||
if (Number.isNaN(used.getTime())) return "never";
|
||||
return differenceInMinutes(now, used) < LAST_USED_THROTTLE_MINUTES
|
||||
? "recent"
|
||||
: "stale";
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { IComment } from "@/features/comment/types/comment.types";
|
||||
|
||||
// matchMedia (read by MantineProvider) is stubbed globally in vitest.setup.ts.
|
||||
|
||||
// The suggestion mutations reach react-query/network — stub them so the card
|
||||
// renders in isolation. We assert the Apply/Dismiss gating and that the click
|
||||
// hands the {commentId, pageId} pair to the existing mutation unchanged.
|
||||
const applyMutateAsync = vi.fn();
|
||||
const dismissMutateAsync = vi.fn();
|
||||
vi.mock("@/features/comment/queries/comment-query", () => ({
|
||||
useApplySuggestionMutation: () => ({
|
||||
mutateAsync: applyMutateAsync,
|
||||
isPending: false,
|
||||
}),
|
||||
useDismissSuggestionMutation: () => ({
|
||||
mutateAsync: dismissMutateAsync,
|
||||
isPending: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
// CommentContentView -> mention-view -> page-query/share-query pull in the app
|
||||
// entry (createRoot) as a side effect; stub the queries so the card renders in
|
||||
// isolation.
|
||||
vi.mock("@/features/page/queries/page-query.ts", () => ({
|
||||
usePageQuery: () => ({ data: undefined, isLoading: false, isError: false }),
|
||||
}));
|
||||
vi.mock("@/features/share/queries/share-query.ts", () => ({
|
||||
useSharePageQuery: () => ({ data: undefined }),
|
||||
}));
|
||||
// space-query.ts -> main.tsx (createRoot) is a module side effect reached via the
|
||||
// mention view; stub it so importing the card is side-effect free.
|
||||
vi.mock("@/features/space/queries/space-query.ts", () => ({
|
||||
useSpaceQuery: () => ({ data: undefined }),
|
||||
useGetSpaceBySlugQuery: () => ({ data: undefined }),
|
||||
}));
|
||||
|
||||
import AgentEditCard from "./agent-edit-card";
|
||||
|
||||
const body = (text: string) =>
|
||||
JSON.stringify({
|
||||
type: "doc",
|
||||
content: [{ type: "paragraph", content: [{ type: "text", text }] }],
|
||||
});
|
||||
|
||||
const edit = (over?: Partial<IComment>): IComment =>
|
||||
({
|
||||
id: "c-1",
|
||||
content: body("[Существенно] tighten the wording"),
|
||||
creatorId: "user-1",
|
||||
pageId: "page-1",
|
||||
workspaceId: "ws-1",
|
||||
createdAt: new Date(),
|
||||
createdSource: "agent",
|
||||
aiChatId: "chat-1",
|
||||
agent: { name: "Corrector", emoji: "✏️", avatarUrl: null },
|
||||
launcher: { name: "Alice", avatarUrl: null },
|
||||
creator: { id: "user-1", name: "Corrector", avatarUrl: null } as any,
|
||||
selection: "old wording here",
|
||||
suggestedText: "new wording here",
|
||||
...over,
|
||||
}) as IComment;
|
||||
|
||||
function renderCard(
|
||||
comment: IComment,
|
||||
canEdit = true,
|
||||
canComment = true,
|
||||
userSpaceRole?: string,
|
||||
) {
|
||||
return render(
|
||||
<MantineProvider>
|
||||
<AgentEditCard
|
||||
comment={comment}
|
||||
canComment={canComment}
|
||||
canEdit={canEdit}
|
||||
userSpaceRole={userSpaceRole}
|
||||
/>
|
||||
</MantineProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("AgentEditCard — suggested edit diff + Apply (#315)", () => {
|
||||
it("renders the было→стало diff and an Apply button when canEdit, not applied/resolved", () => {
|
||||
const { container } = renderCard(edit(), true);
|
||||
// Both diff lines are present (old struck-through, new added).
|
||||
expect(container.textContent).toContain("old wording here");
|
||||
expect(container.textContent).toContain("new wording here");
|
||||
// Diff line signs (aria-hidden) present for a replacement.
|
||||
expect(container.textContent).toContain("−");
|
||||
expect(container.textContent).toContain("+");
|
||||
expect(screen.getByRole("button", { name: "Apply" })).toBeDefined();
|
||||
});
|
||||
|
||||
it("hides Apply when canEdit is false (still shows the diff)", () => {
|
||||
const { container } = renderCard(edit(), false);
|
||||
expect(container.textContent).toContain("new wording here");
|
||||
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||
});
|
||||
|
||||
it("hides Apply once the thread is resolved", () => {
|
||||
renderCard(edit({ resolvedAt: new Date() }), true);
|
||||
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||
});
|
||||
|
||||
it("hides Apply once suggestionAppliedAt is set", () => {
|
||||
renderCard(edit({ suggestionAppliedAt: new Date() }), true);
|
||||
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||
});
|
||||
|
||||
it("calls the apply mutation with {commentId, pageId} on click", () => {
|
||||
applyMutateAsync.mockClear();
|
||||
renderCard(edit(), true);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
|
||||
expect(applyMutateAsync).toHaveBeenCalledWith({
|
||||
commentId: "c-1",
|
||||
pageId: "page-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("a pure insertion (empty selection) hides the removed line", () => {
|
||||
const { container } = renderCard(
|
||||
edit({ selection: "", suggestedText: "added text" }),
|
||||
true,
|
||||
);
|
||||
// No "−" del sign — nothing was removed.
|
||||
expect(container.textContent).not.toContain("−");
|
||||
expect(container.textContent).toContain("+");
|
||||
});
|
||||
|
||||
it("a pure deletion (empty suggestedText) hides the added line", () => {
|
||||
const { container } = renderCard(
|
||||
edit({ selection: "removed text", suggestedText: "" }),
|
||||
true,
|
||||
);
|
||||
expect(container.textContent).not.toContain("+");
|
||||
expect(container.textContent).toContain("−");
|
||||
});
|
||||
});
|
||||
|
||||
describe("AgentEditCard — Dismiss gate (#329/#338)", () => {
|
||||
it("shows Dismiss alongside Apply for an admin who can edit/comment", () => {
|
||||
renderCard(edit(), true, true, "admin");
|
||||
expect(screen.getByRole("button", { name: "Apply" })).toBeDefined();
|
||||
expect(screen.getByRole("button", { name: "Dismiss" })).toBeDefined();
|
||||
});
|
||||
|
||||
it("shows Dismiss but NOT Apply for an admin commenter who cannot edit", () => {
|
||||
renderCard(edit(), false, true, "admin");
|
||||
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||
expect(screen.getByRole("button", { name: "Dismiss" })).toBeDefined();
|
||||
});
|
||||
|
||||
it("hides Dismiss for a non-owner non-admin (mirrors server 403, #338 F5)", () => {
|
||||
renderCard(edit(), false, true, "member");
|
||||
expect(screen.queryByRole("button", { name: "Dismiss" })).toBeNull();
|
||||
});
|
||||
|
||||
it("hides Dismiss when the viewer cannot comment", () => {
|
||||
renderCard(edit(), false, false, "admin");
|
||||
expect(screen.queryByRole("button", { name: "Dismiss" })).toBeNull();
|
||||
});
|
||||
|
||||
it("calls the dismiss mutation with {commentId, pageId} on click", () => {
|
||||
dismissMutateAsync.mockClear();
|
||||
renderCard(edit(), true, true, "admin");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
|
||||
expect(dismissMutateAsync).toHaveBeenCalledWith({
|
||||
commentId: "c-1",
|
||||
pageId: "page-1",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("AgentEditCard — provenance", () => {
|
||||
it("renders the agent avatar stack (provenance) for the edit author (#300)", () => {
|
||||
renderCard(edit(), true);
|
||||
// The agent role name is shown by the provenance stack.
|
||||
expect(screen.getAllByText("Corrector").length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// The owner-or-admin gate uses the currentUser atom; clear localStorage so a
|
||||
// previous test's seed never leaks into the non-owner assertions above.
|
||||
beforeEach(() => localStorage.clear());
|
||||
afterEach(() => localStorage.clear());
|
||||
});
|
||||
@@ -0,0 +1,400 @@
|
||||
import React, { useMemo } from "react";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Group,
|
||||
Stack,
|
||||
Text,
|
||||
useMantineColorScheme,
|
||||
useMantineTheme,
|
||||
} from "@mantine/core";
|
||||
import { useAtom } from "jotai";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AgentAvatarStack } from "@/components/ui/agent-avatar-stack.tsx";
|
||||
import CommentContentView from "@/features/comment/components/comment-content-view";
|
||||
import { IComment } from "@/features/comment/types/comment.types";
|
||||
import {
|
||||
canShowApply,
|
||||
canShowDismiss,
|
||||
computeSuggestionDiff,
|
||||
Segment,
|
||||
} from "@/features/comment/utils/suggestion";
|
||||
import { commentContentToText } from "@/features/comment/utils/comment-content-to-text";
|
||||
import {
|
||||
isSignificant,
|
||||
parseSeverity,
|
||||
Severity,
|
||||
} from "@/features/comment/utils/severity";
|
||||
import {
|
||||
useApplySuggestionMutation,
|
||||
useDismissSuggestionMutation,
|
||||
} from "@/features/comment/queries/comment-query";
|
||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom.ts";
|
||||
import { useTimeAgo } from "@/hooks/use-time-ago";
|
||||
|
||||
// Scroll the document to this comment's inline mark and flash it — the same
|
||||
// anchor navigation the old panel used (handleCommentClick). Used both by a card
|
||||
// click and by an explicit "Go to text" affordance.
|
||||
function scrollToCommentMark(commentId: string) {
|
||||
const el = document.querySelector(
|
||||
`.comment-mark[data-comment-id="${commentId}"]`,
|
||||
);
|
||||
if (el) {
|
||||
el.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
el.classList.add("comment-highlight");
|
||||
setTimeout(() => el.classList.remove("comment-highlight"), 3000);
|
||||
}
|
||||
}
|
||||
|
||||
// Make otherwise-invisible edited whitespace legible inside a highlighted diff
|
||||
// fragment (a pure-space insertion/deletion would otherwise look like nothing
|
||||
// changed).
|
||||
function visibleWhitespace(s: string): string {
|
||||
return s.replace(/ /g, "␣").replace(/\t/g, "⇥");
|
||||
}
|
||||
|
||||
// One line of the intraline diff. `kind==="del"` is the old ("было") line drawn
|
||||
// red with a strike-through; `kind==="ins"` is the new ("стало") line drawn
|
||||
// green. Only the `changed` segments carry the emphasised mark background — the
|
||||
// common segments read as plain context (git/GitHub-style, #331).
|
||||
function DiffLine({
|
||||
segments,
|
||||
kind,
|
||||
}: {
|
||||
segments: Segment[];
|
||||
kind: "del" | "ins";
|
||||
}) {
|
||||
const theme = useMantineTheme();
|
||||
const { colorScheme } = useMantineColorScheme();
|
||||
const dark = colorScheme === "dark";
|
||||
const isDel = kind === "del";
|
||||
const sign = isDel ? "−" : "+";
|
||||
const signColor = isDel
|
||||
? theme.colors.red[dark ? 5 : 6]
|
||||
: theme.colors.green[dark ? 5 : 6];
|
||||
const baseColor = isDel
|
||||
? dark
|
||||
? theme.colors.gray[5]
|
||||
: theme.colors.gray[6]
|
||||
: dark
|
||||
? theme.colors.gray[1]
|
||||
: theme.colors.dark[9];
|
||||
const markBg = isDel
|
||||
? dark
|
||||
? "rgba(224,49,49,.22)"
|
||||
: "#ffe3e3"
|
||||
: dark
|
||||
? "rgba(47,158,68,.22)"
|
||||
: "#d3f9d8";
|
||||
const markFg = isDel
|
||||
? dark
|
||||
? theme.colors.red[3]
|
||||
: theme.colors.red[8]
|
||||
: dark
|
||||
? theme.colors.green[3]
|
||||
: theme.colors.green[9];
|
||||
|
||||
return (
|
||||
<Group gap={7} wrap="nowrap" align="flex-start">
|
||||
<Text
|
||||
ff="monospace"
|
||||
fw={600}
|
||||
fz={12}
|
||||
c={signColor}
|
||||
w={11}
|
||||
ta="center"
|
||||
aria-hidden
|
||||
style={{ flex: "none", lineHeight: 1.5 }}
|
||||
>
|
||||
{sign}
|
||||
</Text>
|
||||
<Text fz={13.5} c={baseColor} style={{ lineHeight: 1.45 }}>
|
||||
{segments.map((seg, i) =>
|
||||
seg.changed ? (
|
||||
<Box
|
||||
key={i}
|
||||
component="mark"
|
||||
px={3}
|
||||
fw={600}
|
||||
style={{
|
||||
background: markBg,
|
||||
color: markFg,
|
||||
borderRadius: 3,
|
||||
textDecoration: isDel ? "line-through" : "none",
|
||||
}}
|
||||
>
|
||||
{visibleWhitespace(seg.text)}
|
||||
</Box>
|
||||
) : (
|
||||
<Box
|
||||
key={i}
|
||||
component="span"
|
||||
style={{ textDecoration: isDel ? "line-through" : "none" }}
|
||||
>
|
||||
{seg.text}
|
||||
</Box>
|
||||
),
|
||||
)}
|
||||
</Text>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
// The "было → стало" block. A pure insertion (empty `before`) hides the old
|
||||
// line; a pure deletion (empty `after`) hides the new line.
|
||||
function DiffBlock({ before, after }: { before: Segment[]; after: Segment[] }) {
|
||||
const pureInsert = before.length === 0;
|
||||
const pureDelete = after.length === 0;
|
||||
return (
|
||||
<Stack gap={1}>
|
||||
{!pureInsert && <DiffLine segments={before} kind="del" />}
|
||||
{!pureDelete && <DiffLine segments={after} kind="ins" />}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
const SEV_DOT: Record<Severity, { color: string; shade: number }> = {
|
||||
critical: { color: "red", shade: 6 },
|
||||
major: { color: "orange", shade: 6 },
|
||||
minor: { color: "gray", shade: 5 },
|
||||
// A neutral, deliberately faint dot — NOT the minor grey — so an untagged or
|
||||
// verdict-only edit never reads as a graded severity.
|
||||
unknown: { color: "gray", shade: 3 },
|
||||
};
|
||||
|
||||
function SeverityDot({ severity }: { severity: Severity }) {
|
||||
return (
|
||||
<Box
|
||||
w={8}
|
||||
h={8}
|
||||
aria-hidden
|
||||
style={(t) => ({
|
||||
flex: "none",
|
||||
borderRadius: "50%",
|
||||
background: t.colors[SEV_DOT[severity].color][SEV_DOT[severity].shade],
|
||||
})}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface AgentEditCardProps {
|
||||
comment: IComment;
|
||||
canComment: boolean;
|
||||
canEdit?: boolean;
|
||||
userSpaceRole?: string;
|
||||
// Whether to render the per-card agent avatar + timestamp. A card inside a
|
||||
// collapsed run omits it (the RunHeader carries the one provenance line);
|
||||
// a standalone card shows it (#300 provenance must be visible on the card).
|
||||
showProvenance?: boolean;
|
||||
}
|
||||
|
||||
// Type A — the diff-first agent suggested-edit card. It carries NO TipTap editor
|
||||
// (a perf win vs. the old row, #340); the body renders through the static
|
||||
// CommentContentView. Apply/Dismiss reuse the existing mutations and gates
|
||||
// verbatim — the reskin changes presentation only, not the 409/404/400 toast
|
||||
// semantics or the authz gating.
|
||||
function AgentEditCard({
|
||||
comment,
|
||||
canComment,
|
||||
canEdit,
|
||||
userSpaceRole,
|
||||
showProvenance = true,
|
||||
}: AgentEditCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const [currentUser] = useAtom(currentUserAtom);
|
||||
const applySuggestionMutation = useApplySuggestionMutation();
|
||||
const dismissSuggestionMutation = useDismissSuggestionMutation();
|
||||
const createdAtAgo = useTimeAgo(comment.createdAt);
|
||||
|
||||
const diff = useMemo(
|
||||
() =>
|
||||
computeSuggestionDiff(comment.selection ?? "", comment.suggestedText ?? ""),
|
||||
[comment.selection, comment.suggestedText],
|
||||
);
|
||||
|
||||
const severity = useMemo(
|
||||
() => parseSeverity(commentContentToText(comment.content)),
|
||||
[comment.content],
|
||||
);
|
||||
|
||||
// Owner-or-space-admin gate (#338), mirrored from the old row so we never
|
||||
// render a Dismiss the server would 403.
|
||||
const isOwnerOrAdmin =
|
||||
currentUser?.user?.id === comment.creatorId || userSpaceRole === "admin";
|
||||
|
||||
const showApply = canShowApply(comment, canEdit);
|
||||
const showDismiss = canShowDismiss(comment, canComment, isOwnerOrAdmin);
|
||||
const pending =
|
||||
applySuggestionMutation.isPending || dismissSuggestionMutation.isPending;
|
||||
|
||||
const handleApply = async () => {
|
||||
try {
|
||||
await applySuggestionMutation.mutateAsync({
|
||||
commentId: comment.id,
|
||||
pageId: comment.pageId,
|
||||
});
|
||||
} catch (error) {
|
||||
// Errors (incl. 409 "text changed") surface via the mutation's onError.
|
||||
console.error("Failed to apply suggestion:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDismiss = async () => {
|
||||
try {
|
||||
await dismissSuggestionMutation.mutateAsync({
|
||||
commentId: comment.id,
|
||||
pageId: comment.pageId,
|
||||
});
|
||||
} catch (error) {
|
||||
// Idempotent 404 is reconciled to success in the mutation's onError.
|
||||
console.error("Failed to dismiss suggestion:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const sevLabel =
|
||||
severity === "critical"
|
||||
? t("Critical")
|
||||
: severity === "major"
|
||||
? t("Major")
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Box
|
||||
p="10px 12px"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => scrollToCommentMark(comment.id)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
scrollToCommentMark(comment.id);
|
||||
}
|
||||
}}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<Stack gap={8}>
|
||||
{showProvenance && comment.agent && (
|
||||
<Group
|
||||
gap={8}
|
||||
wrap="nowrap"
|
||||
justify="space-between"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<AgentAvatarStack
|
||||
agent={comment.agent}
|
||||
launcher={comment.launcher}
|
||||
aiChatId={comment.aiChatId}
|
||||
/>
|
||||
<Text size="xs" c="dimmed" style={{ flex: "none" }}>
|
||||
{createdAtAgo}
|
||||
</Text>
|
||||
</Group>
|
||||
)}
|
||||
|
||||
<DiffBlock before={diff.old} after={diff.new} />
|
||||
|
||||
{/* Agent rationale — rendered through the static ProseMirror view, not
|
||||
restructured into a flat string. */}
|
||||
<Box fz="xs" c="dimmed">
|
||||
<CommentContentView content={comment.content} />
|
||||
</Box>
|
||||
|
||||
<Group gap={8} wrap="nowrap" onClick={(e) => e.stopPropagation()}>
|
||||
<SeverityDot severity={severity} />
|
||||
{sevLabel && (
|
||||
<Text
|
||||
fz={10}
|
||||
fw={600}
|
||||
tt="uppercase"
|
||||
c="dimmed"
|
||||
style={{ letterSpacing: ".06em", flex: 1 }}
|
||||
>
|
||||
{sevLabel}
|
||||
</Text>
|
||||
)}
|
||||
<Box style={{ flex: 1 }} />
|
||||
{showDismiss && (
|
||||
<Button
|
||||
size="compact-sm"
|
||||
variant="default"
|
||||
color="gray"
|
||||
loading={dismissSuggestionMutation.isPending}
|
||||
disabled={pending}
|
||||
onClick={handleDismiss}
|
||||
>
|
||||
{t("Dismiss")}
|
||||
</Button>
|
||||
)}
|
||||
{showApply && (
|
||||
<Button
|
||||
size="compact-sm"
|
||||
color="green"
|
||||
loading={applySuggestionMutation.isPending}
|
||||
disabled={pending}
|
||||
onClick={handleApply}
|
||||
>
|
||||
{t("Apply")}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// Series header for a collapsed agent run: ONE provenance line for N edits,
|
||||
// with a "N edits · M major" tally. There is intentionally NO "Accept all"
|
||||
// button / progress / Stop (rejected by product) and NO "K applied" counter
|
||||
// (uncomputable after the #329 hard-delete). Purely visual.
|
||||
export function RunHeader({ comments }: { comments: IComment[] }) {
|
||||
const { t } = useTranslation();
|
||||
const head = comments[0];
|
||||
const createdAtAgo = useTimeAgo(head?.createdAt);
|
||||
|
||||
const majors = useMemo(
|
||||
() =>
|
||||
comments.filter((c) =>
|
||||
isSignificant(parseSeverity(commentContentToText(c.content))),
|
||||
).length,
|
||||
[comments],
|
||||
);
|
||||
|
||||
if (!head) return null;
|
||||
|
||||
return (
|
||||
<Box
|
||||
p="11px 13px"
|
||||
style={{ borderBottom: "1px solid var(--mantine-color-default-border)" }}
|
||||
>
|
||||
<Group gap={10} wrap="nowrap" justify="space-between">
|
||||
{head.agent ? (
|
||||
<AgentAvatarStack
|
||||
agent={head.agent}
|
||||
launcher={head.launcher}
|
||||
aiChatId={head.aiChatId}
|
||||
/>
|
||||
) : (
|
||||
<Text size="sm" fw={600}>
|
||||
{head.creator?.name}
|
||||
</Text>
|
||||
)}
|
||||
<Text size="xs" c="dimmed" style={{ flex: "none" }}>
|
||||
{createdAtAgo}
|
||||
</Text>
|
||||
</Group>
|
||||
<Text fz={11.5} c="dimmed" mt={4}>
|
||||
{t("{{count}} edits", { count: comments.length })}
|
||||
{majors > 0 && (
|
||||
<>
|
||||
{" · "}
|
||||
<Text span c="orange.7" fw={600} inherit>
|
||||
{t("{{count}} major", { count: majors })}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default React.memo(AgentEditCard);
|
||||
@@ -156,125 +156,6 @@ describe("CommentListItem — agent avatar stack", () => {
|
||||
// only guards the insertion gate (agent → stack, user → no stack).
|
||||
});
|
||||
|
||||
describe("CommentListItem — suggested edit (#315)", () => {
|
||||
const suggestion = (over?: Partial<IComment>): IComment =>
|
||||
baseComment({
|
||||
selection: "old wording here",
|
||||
suggestedText: "new wording here",
|
||||
...over,
|
||||
});
|
||||
|
||||
it("renders the было→стало diff and an Apply button when canEdit and not applied/resolved", () => {
|
||||
const { container } = renderItem(suggestion(), true);
|
||||
// Old text appears as the selection quote (a single unsplit Text node).
|
||||
expect(screen.getAllByText("old wording here").length).toBeGreaterThan(0);
|
||||
// The new line is now rendered as per-fragment spans (intraline diff, #331),
|
||||
// so it is no longer a single text node — assert the concatenated content.
|
||||
expect(container.textContent).toContain("new wording here");
|
||||
// Apply button is present.
|
||||
expect(screen.getByRole("button", { name: "Apply" })).toBeDefined();
|
||||
// No Applied badge yet.
|
||||
expect(screen.queryByText("Applied")).toBeNull();
|
||||
});
|
||||
|
||||
it("hides the Apply button when canEdit is false", () => {
|
||||
const { container } = renderItem(suggestion(), false);
|
||||
// Diff still renders (as per-fragment spans, #331)...
|
||||
expect(container.textContent).toContain("new wording here");
|
||||
// ...but no Apply button.
|
||||
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||
});
|
||||
|
||||
it("shows an Applied badge (no Apply button) once suggestionAppliedAt is set", () => {
|
||||
renderItem(suggestion({ suggestionAppliedAt: new Date() }), true);
|
||||
expect(screen.getByText("Applied")).toBeDefined();
|
||||
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||
});
|
||||
|
||||
it("hides the Apply button once the thread is resolved", () => {
|
||||
renderItem(suggestion({ resolvedAt: new Date() }), true);
|
||||
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||
});
|
||||
|
||||
it("calls the apply mutation when the Apply button is clicked", () => {
|
||||
applyMutateAsync.mockClear();
|
||||
renderItem(suggestion(), true);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
|
||||
expect(applyMutateAsync).toHaveBeenCalledWith({
|
||||
commentId: "c-1",
|
||||
pageId: "page-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not render the diff block for a reply (child) comment", () => {
|
||||
renderItem(
|
||||
suggestion({ parentCommentId: "c-0" }),
|
||||
true,
|
||||
);
|
||||
expect(screen.queryByText("new wording here")).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("CommentListItem — dismiss suggestion (#329)", () => {
|
||||
const suggestion = (over?: Partial<IComment>): IComment =>
|
||||
baseComment({
|
||||
selection: "old wording here",
|
||||
suggestedText: "new wording here",
|
||||
...over,
|
||||
});
|
||||
|
||||
// A space admin (userSpaceRole="admin") satisfies the owner-or-admin gate
|
||||
// regardless of who authored the comment; the tests below use it as the lever
|
||||
// since the currentUser atom is unseeded (null) in this harness.
|
||||
it("renders a Dismiss button alongside Apply when canEdit and canComment (owner/admin)", () => {
|
||||
renderItem(suggestion(), true, true, "admin");
|
||||
expect(screen.getByRole("button", { name: "Apply" })).toBeDefined();
|
||||
expect(screen.getByRole("button", { name: "Dismiss" })).toBeDefined();
|
||||
});
|
||||
|
||||
it("shows Dismiss but NOT Apply for an admin commenter who cannot edit", () => {
|
||||
renderItem(suggestion(), false, true, "admin");
|
||||
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||
expect(screen.getByRole("button", { name: "Dismiss" })).toBeDefined();
|
||||
});
|
||||
|
||||
it("hides Dismiss when the viewer cannot comment", () => {
|
||||
renderItem(suggestion(), false, false, "admin");
|
||||
expect(screen.queryByRole("button", { name: "Dismiss" })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "Apply" })).toBeNull();
|
||||
});
|
||||
|
||||
it("hides Dismiss for a non-owner non-admin even with canComment (#338 F5: mirrors server 403)", () => {
|
||||
// canComment=true but NOT a space admin and NOT the comment owner (the
|
||||
// currentUser atom is null while the comment is authored by user-1), so the
|
||||
// server would 403 a dismiss — the button must not be shown at all.
|
||||
renderItem(suggestion(), false, true, "member");
|
||||
expect(screen.queryByRole("button", { name: "Dismiss" })).toBeNull();
|
||||
});
|
||||
|
||||
it("hides Dismiss once the thread is resolved", () => {
|
||||
renderItem(suggestion({ resolvedAt: new Date() }), true, true, "admin");
|
||||
expect(screen.queryByRole("button", { name: "Dismiss" })).toBeNull();
|
||||
});
|
||||
|
||||
it("hides Dismiss (shows the Applied badge) once applied", () => {
|
||||
renderItem(suggestion({ suggestionAppliedAt: new Date() }), true, true, "admin");
|
||||
expect(screen.queryByRole("button", { name: "Dismiss" })).toBeNull();
|
||||
expect(screen.getByText("Applied")).toBeDefined();
|
||||
});
|
||||
|
||||
it("calls the dismiss mutation when the Dismiss button is clicked", () => {
|
||||
dismissMutateAsync.mockClear();
|
||||
renderItem(suggestion(), true, true, "admin");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
|
||||
expect(dismissMutateAsync).toHaveBeenCalledWith({
|
||||
commentId: "c-1",
|
||||
pageId: "page-1",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("canShowApply predicate", () => {
|
||||
const c = (over?: Partial<IComment>): IComment =>
|
||||
({ suggestedText: "x", ...over }) as IComment;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Group, Text, Box, Badge, Button } from "@mantine/core";
|
||||
import { Group, Text, Box } from "@mantine/core";
|
||||
import { AgentAvatarStack } from "@/components/ui/agent-avatar-stack.tsx";
|
||||
import React, { useMemo, useRef, useState } from "react";
|
||||
import React, { useRef, useState } from "react";
|
||||
import classes from "./comment.module.css";
|
||||
import { useAtom, useAtomValue } from "jotai";
|
||||
import { useTimeAgo } from "@/hooks/use-time-ago";
|
||||
@@ -12,18 +12,11 @@ import CommentMenu from "@/features/comment/components/comment-menu";
|
||||
import ResolveComment from "@/features/comment/components/resolve-comment";
|
||||
import { useHover } from "@mantine/hooks";
|
||||
import {
|
||||
useApplySuggestionMutation,
|
||||
useDeleteCommentMutation,
|
||||
useDismissSuggestionMutation,
|
||||
useResolveCommentMutation,
|
||||
useUpdateCommentMutation,
|
||||
} from "@/features/comment/queries/comment-query";
|
||||
import { IComment } from "@/features/comment/types/comment.types";
|
||||
import {
|
||||
canShowApply,
|
||||
canShowDismiss,
|
||||
computeSuggestionDiff,
|
||||
} from "@/features/comment/utils/suggestion";
|
||||
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom.ts";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -32,13 +25,21 @@ interface CommentListItemProps {
|
||||
comment: IComment;
|
||||
pageId: string;
|
||||
canComment: boolean;
|
||||
// Real page-edit permission (page.permissions.canEdit) — gates the suggestion
|
||||
// "Apply" button. Distinct from `canComment`, which may be looser (viewers
|
||||
// allowed to comment cannot apply edits).
|
||||
// Real page-edit permission (page.permissions.canEdit). Kept on the props for
|
||||
// parity with the container's wiring even though the thread row itself no
|
||||
// longer renders the suggestion Apply button (that moved to AgentEditCard).
|
||||
canEdit?: boolean;
|
||||
userSpaceRole?: string;
|
||||
}
|
||||
|
||||
// Type B — the thread ROW. Renders a single human OR agent-without-edit comment
|
||||
// in the redesigned visual: provenance avatar, author + timeago, hover-revealed
|
||||
// resolve + edit/delete menu, the anchored selection quote, and the body through
|
||||
// the static CommentContentView (or the inline TipTap editor while editing). It
|
||||
// is used for both a top-level thread comment and, recursively, each reply row.
|
||||
// ALL wiring (update/delete/resolve mutations, owner/admin gate, anchor nav) is
|
||||
// the same logic the old row carried — only the presentation changed, and the
|
||||
// agent suggested-edit block was lifted out into AgentEditCard.
|
||||
function CommentListItem({
|
||||
comment,
|
||||
pageId,
|
||||
@@ -55,29 +56,20 @@ function CommentListItem({
|
||||
const updateCommentMutation = useUpdateCommentMutation();
|
||||
const deleteCommentMutation = useDeleteCommentMutation(comment.pageId);
|
||||
const resolveCommentMutation = useResolveCommentMutation();
|
||||
const applySuggestionMutation = useApplySuggestionMutation();
|
||||
const dismissSuggestionMutation = useDismissSuggestionMutation();
|
||||
const [currentUser] = useAtom(currentUserAtom);
|
||||
const createdAtAgo = useTimeAgo(comment.createdAt);
|
||||
|
||||
// Intraline "before -> after" diff (#331) for a suggested edit: only the
|
||||
// fragments that actually changed get emphasised inside the red/green block,
|
||||
// instead of striking through / greening the whole line. Memoised on the
|
||||
// (selection, suggestedText) pair so it recomputes only when they change.
|
||||
const suggestionDiff = useMemo(
|
||||
() =>
|
||||
comment.suggestedText != null
|
||||
? computeSuggestionDiff(comment.selection ?? "", comment.suggestedText)
|
||||
: null,
|
||||
[comment.selection, comment.suggestedText],
|
||||
);
|
||||
// `canEdit`/`pageId` are threaded through for wiring parity with the container;
|
||||
// the thread row does not itself gate on them (Apply lives on AgentEditCard).
|
||||
void canEdit;
|
||||
void pageId;
|
||||
|
||||
// Owner-or-space-admin gate (#338): mirrors the server authz for both the
|
||||
// comment menu (edit/delete) and the suggestion Dismiss button, so we never
|
||||
// render an action the server will 403.
|
||||
// Owner-or-space-admin gate (#338): mirrors the server authz for the comment
|
||||
// menu (edit/delete), so we never render an action the server will 403.
|
||||
const isOwnerOrAdmin =
|
||||
currentUser?.user?.id === comment.creatorId || userSpaceRole === "admin";
|
||||
|
||||
const isAgent = comment.createdSource === "agent" && !!comment.agent;
|
||||
|
||||
async function handleUpdateComment() {
|
||||
try {
|
||||
@@ -121,34 +113,9 @@ function CommentListItem({
|
||||
}
|
||||
}
|
||||
|
||||
async function handleApplySuggestion() {
|
||||
try {
|
||||
await applySuggestionMutation.mutateAsync({
|
||||
commentId: comment.id,
|
||||
pageId: comment.pageId,
|
||||
});
|
||||
} catch (error) {
|
||||
// Errors surface via the mutation's onError notification (incl. 409).
|
||||
console.error("Failed to apply suggestion:", error);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDismissSuggestion() {
|
||||
try {
|
||||
await dismissSuggestionMutation.mutateAsync({
|
||||
commentId: comment.id,
|
||||
pageId: comment.pageId,
|
||||
});
|
||||
} catch (error) {
|
||||
// Idempotent races are reconciled to success in the mutation's onError;
|
||||
// anything else surfaces there as a notification.
|
||||
console.error("Failed to dismiss suggestion:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function handleCommentClick(comment: IComment) {
|
||||
function handleCommentClick(target: IComment) {
|
||||
const el = document.querySelector(
|
||||
`.comment-mark[data-comment-id="${comment.id}"]`,
|
||||
`.comment-mark[data-comment-id="${target.id}"]`,
|
||||
);
|
||||
if (el) {
|
||||
el.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
@@ -169,10 +136,10 @@ function CommentListItem({
|
||||
|
||||
return (
|
||||
<Box ref={ref} pb={6}>
|
||||
<Group gap="xs">
|
||||
{comment.createdSource === "agent" && comment.agent ? (
|
||||
<Group gap="xs" wrap="nowrap" align="flex-start">
|
||||
{isAgent ? (
|
||||
<AgentAvatarStack
|
||||
agent={comment.agent}
|
||||
agent={comment.agent!}
|
||||
launcher={comment.launcher}
|
||||
aiChatId={comment.aiChatId}
|
||||
showName={false}
|
||||
@@ -185,13 +152,13 @@ function CommentListItem({
|
||||
/>
|
||||
)}
|
||||
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
|
||||
{comment.createdSource === "agent" && comment.agent ? (
|
||||
{isAgent ? (
|
||||
<>
|
||||
<Text size="xs" fw={600} lineClamp={1} lh={1.2}>
|
||||
{comment.agent.name}
|
||||
{comment.agent!.name}
|
||||
</Text>
|
||||
{comment.launcher && (
|
||||
<>
|
||||
@@ -262,87 +229,6 @@ function CommentListItem({
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Suggested-edit (#315): "было → стало" diff for a top-level comment
|
||||
carrying a suggestion. Old text struck-through/red, new text green. */}
|
||||
{!comment.parentCommentId && comment.suggestedText && (
|
||||
<Box className={classes.suggestionBlock}>
|
||||
{comment.selection && (
|
||||
// Old line: read as removed as a whole (line-through/red); only the
|
||||
// changed fragments carry the extra intraline emphasis.
|
||||
<Text size="xs" className={classes.suggestionOld}>
|
||||
{suggestionDiff?.old.map((segment, index) => (
|
||||
<span
|
||||
key={index}
|
||||
className={segment.changed ? classes.suggestionChanged : undefined}
|
||||
>
|
||||
{segment.text}
|
||||
</span>
|
||||
))}
|
||||
</Text>
|
||||
)}
|
||||
<Text size="xs" className={classes.suggestionNew}>
|
||||
{suggestionDiff?.new.map((segment, index) => (
|
||||
<span
|
||||
key={index}
|
||||
className={segment.changed ? classes.suggestionChanged : undefined}
|
||||
>
|
||||
{segment.text}
|
||||
</span>
|
||||
))}
|
||||
</Text>
|
||||
|
||||
{comment.suggestionAppliedAt ? (
|
||||
<Badge
|
||||
size="sm"
|
||||
color="green"
|
||||
variant="light"
|
||||
mt={6}
|
||||
aria-label={t("Applied")}
|
||||
>
|
||||
{t("Applied")}
|
||||
</Badge>
|
||||
) : (
|
||||
(canShowApply(comment, canEdit) ||
|
||||
canShowDismiss(comment, canComment, isOwnerOrAdmin)) && (
|
||||
<Group gap="xs" mt={6}>
|
||||
{canShowApply(comment, canEdit) && (
|
||||
<Button
|
||||
size="compact-xs"
|
||||
variant="light"
|
||||
color="green"
|
||||
onClick={handleApplySuggestion}
|
||||
loading={applySuggestionMutation.isPending}
|
||||
disabled={
|
||||
applySuggestionMutation.isPending ||
|
||||
dismissSuggestionMutation.isPending
|
||||
}
|
||||
>
|
||||
{t("Apply")}
|
||||
</Button>
|
||||
)}
|
||||
{/* Dismiss ("Не применять", #329): removes the suggestion
|
||||
without changing the page text. Gated on canComment. */}
|
||||
{canShowDismiss(comment, canComment, isOwnerOrAdmin) && (
|
||||
<Button
|
||||
size="compact-xs"
|
||||
variant="subtle"
|
||||
color="gray"
|
||||
onClick={handleDismissSuggestion}
|
||||
loading={dismissSuggestionMutation.isPending}
|
||||
disabled={
|
||||
applySuggestionMutation.isPending ||
|
||||
dismissSuggestionMutation.isPending
|
||||
}
|
||||
>
|
||||
{t("Dismiss")}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
)
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{!isEditing ? (
|
||||
<CommentContentView content={comment.content} />
|
||||
) : (
|
||||
@@ -350,7 +236,9 @@ function CommentListItem({
|
||||
<CommentEditor
|
||||
defaultContent={comment.content}
|
||||
editable={true}
|
||||
onUpdate={(newContent: any) => { editContentRef.current = newContent; }}
|
||||
onUpdate={(newContent: any) => {
|
||||
editContentRef.current = newContent;
|
||||
}}
|
||||
onSave={handleUpdateComment}
|
||||
autofocus={true}
|
||||
/>
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
Center,
|
||||
Divider,
|
||||
Group,
|
||||
Paper,
|
||||
Box,
|
||||
Stack,
|
||||
Tabs,
|
||||
Badge,
|
||||
@@ -14,6 +14,9 @@ import {
|
||||
Tooltip,
|
||||
} from "@mantine/core";
|
||||
import CommentListItem from "@/features/comment/components/comment-list-item";
|
||||
import AgentEditCard, {
|
||||
RunHeader,
|
||||
} from "@/features/comment/components/agent-edit-card";
|
||||
import {
|
||||
useCommentsQuery,
|
||||
useCreateCommentMutation,
|
||||
@@ -22,6 +25,10 @@ import CommentEditor from "@/features/comment/components/comment-editor";
|
||||
import CommentActions from "@/features/comment/components/comment-actions";
|
||||
import { useFocusWithin } from "@mantine/hooks";
|
||||
import { IComment } from "@/features/comment/types/comment.types.ts";
|
||||
import {
|
||||
groupAgentRuns,
|
||||
CommentRenderUnit,
|
||||
} from "@/features/comment/utils/group-agent-runs";
|
||||
import { usePageMetaQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { extractPageSlugId } from "@/lib";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -69,6 +76,32 @@ export function sortResolvedByResolvedAt(resolved: IComment[]): IComment[] {
|
||||
);
|
||||
}
|
||||
|
||||
// The redesigned card shell: a rounded, bordered surface on the panel body. Both
|
||||
// a thread card and an agent-run group live inside one of these.
|
||||
function PanelCard({
|
||||
children,
|
||||
...rest
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
[key: string]: unknown;
|
||||
}) {
|
||||
return (
|
||||
<Box
|
||||
m="8px 10px"
|
||||
p={0}
|
||||
style={{
|
||||
background: "var(--mantine-color-body)",
|
||||
border: "1px solid var(--mantine-color-default-border)",
|
||||
borderRadius: 10,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
||||
const { t } = useTranslation();
|
||||
const { pageSlug } = useParams();
|
||||
@@ -90,6 +123,8 @@ function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
||||
canEdit ||
|
||||
(space?.settings?.comments?.allowViewerComments === true);
|
||||
|
||||
const userSpaceRole = space?.membership?.role;
|
||||
|
||||
// Separate active and resolved comments
|
||||
const { activeComments, resolvedComments } = useMemo(() => {
|
||||
if (!comments?.items) {
|
||||
@@ -113,6 +148,17 @@ function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
||||
};
|
||||
}, [comments]);
|
||||
|
||||
// Collapse each tab's top-level list into render units (a lone comment or a
|
||||
// collapsed agent run). Purely visual — the underlying data is untouched.
|
||||
const activeUnits = useMemo(
|
||||
() => groupAgentRuns(activeComments),
|
||||
[activeComments],
|
||||
);
|
||||
const resolvedUnits = useMemo(
|
||||
() => groupAgentRuns(resolvedComments),
|
||||
[resolvedComments],
|
||||
);
|
||||
|
||||
// Index replies by their parent once, instead of an O(n^2) filter per thread.
|
||||
// The map ref changes on any comments update, so MemoizedChildComments re-runs
|
||||
// (cheap) and re-looks-up, while memoized CommentListItems skip unchanged items.
|
||||
@@ -168,56 +214,104 @@ function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
||||
[createCommentAsync, page?.id],
|
||||
);
|
||||
|
||||
const renderComments = useCallback(
|
||||
(comment: IComment) => (
|
||||
<Paper
|
||||
shadow="sm"
|
||||
radius="md"
|
||||
p="xs"
|
||||
mb="xs"
|
||||
withBorder
|
||||
key={comment.id}
|
||||
data-comment-id={comment.id}
|
||||
>
|
||||
<div>
|
||||
<CommentListItem
|
||||
// The full subtree for ONE top-level comment: its head card (thread row or
|
||||
// agent edit card), its nested replies, and a lazily-mounted reply editor.
|
||||
// Shared by a standalone card and a card inside an agent-run group so the
|
||||
// reply threading / lazy editor (#340) is wired identically in both.
|
||||
const renderCommentSubtree = useCallback(
|
||||
(comment: IComment, isEdit: boolean, showProvenance: boolean) => (
|
||||
<>
|
||||
{isEdit ? (
|
||||
<AgentEditCard
|
||||
comment={comment}
|
||||
pageId={page?.id}
|
||||
canComment={canComment}
|
||||
canEdit={canEdit}
|
||||
userSpaceRole={space?.membership?.role}
|
||||
userSpaceRole={userSpaceRole}
|
||||
showProvenance={showProvenance}
|
||||
/>
|
||||
) : (
|
||||
<Box p="xs">
|
||||
<CommentListItem
|
||||
comment={comment}
|
||||
pageId={page?.id}
|
||||
canComment={canComment}
|
||||
canEdit={canEdit}
|
||||
userSpaceRole={userSpaceRole}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box px="xs">
|
||||
<MemoizedChildComments
|
||||
childrenByParent={childrenByParent}
|
||||
parentId={comment.id}
|
||||
pageId={page?.id}
|
||||
canComment={canComment}
|
||||
canEdit={canEdit}
|
||||
userSpaceRole={space?.membership?.role}
|
||||
userSpaceRole={userSpaceRole}
|
||||
/>
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{!comment.resolvedAt && canComment && (
|
||||
<>
|
||||
<Box px="xs" pb="xs">
|
||||
<Divider my={2} />
|
||||
<CommentEditorWithActions
|
||||
commentId={comment.id}
|
||||
onSave={handleAddReply}
|
||||
/>
|
||||
</>
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
</>
|
||||
),
|
||||
[
|
||||
childrenByParent,
|
||||
handleAddReply,
|
||||
page?.id,
|
||||
space?.membership?.role,
|
||||
userSpaceRole,
|
||||
canComment,
|
||||
canEdit,
|
||||
],
|
||||
);
|
||||
|
||||
// Render one collapsed unit: a standalone card (thread or lone edit) or an
|
||||
// agent-run group (one RunHeader over N stacked edit cards).
|
||||
const renderUnit = useCallback(
|
||||
(unit: CommentRenderUnit) => {
|
||||
if (unit.kind === "single") {
|
||||
const c = unit.comment;
|
||||
const isEdit =
|
||||
c.createdSource === "agent" &&
|
||||
c.suggestedText != null &&
|
||||
!c.parentCommentId;
|
||||
return (
|
||||
<PanelCard key={c.id} data-comment-id={c.id}>
|
||||
{renderCommentSubtree(c, isEdit, true)}
|
||||
</PanelCard>
|
||||
);
|
||||
}
|
||||
|
||||
// A collapsed agent run: one header, then each edit card (provenance
|
||||
// suppressed on the cards — the header carries the single provenance line).
|
||||
return (
|
||||
<PanelCard key={unit.key}>
|
||||
<RunHeader comments={unit.comments} />
|
||||
{unit.comments.map((c) => (
|
||||
<Box
|
||||
key={c.id}
|
||||
data-comment-id={c.id}
|
||||
style={{
|
||||
borderTop: "1px solid var(--mantine-color-default-border)",
|
||||
}}
|
||||
>
|
||||
{renderCommentSubtree(c, true, false)}
|
||||
</Box>
|
||||
))}
|
||||
</PanelCard>
|
||||
);
|
||||
},
|
||||
[renderCommentSubtree],
|
||||
);
|
||||
|
||||
if (isCommentsLoading) {
|
||||
return <></>;
|
||||
}
|
||||
@@ -226,8 +320,6 @@ function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
||||
return <div>{t("Error loading comments.")}</div>;
|
||||
}
|
||||
|
||||
const totalComments = activeComments.length + resolvedComments.length;
|
||||
|
||||
const pageCommentInput = canComment ? (
|
||||
<PageCommentInput
|
||||
onSave={handleAddPageComment}
|
||||
@@ -328,7 +420,7 @@ function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
||||
</Stack>
|
||||
</Center>
|
||||
) : (
|
||||
activeComments.map(renderComments)
|
||||
activeUnits.map(renderUnit)
|
||||
)}
|
||||
</Tabs.Panel>
|
||||
|
||||
@@ -347,7 +439,7 @@ function CommentListWithTabs({ onClose }: CommentListWithTabsProps) {
|
||||
</Stack>
|
||||
</Center>
|
||||
) : (
|
||||
resolvedComments.map(renderComments)
|
||||
resolvedUnits.map(renderUnit)
|
||||
)}
|
||||
</Tabs.Panel>
|
||||
</div>
|
||||
|
||||
@@ -21,53 +21,6 @@
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* Suggested-edit (#315) "было → стало" diff block. */
|
||||
.suggestionBlock {
|
||||
margin-top: 8px;
|
||||
margin-left: 6px;
|
||||
padding: 6px;
|
||||
border-radius: var(--mantine-radius-sm);
|
||||
border: 1px solid var(--mantine-color-default-border);
|
||||
overflow-wrap: break-word;
|
||||
word-break: break-word;
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.suggestionOld {
|
||||
text-decoration: line-through;
|
||||
color: var(--mantine-color-red-7);
|
||||
background: var(--mantine-color-red-light);
|
||||
border-radius: 2px;
|
||||
padding: 1px 3px;
|
||||
}
|
||||
|
||||
.suggestionNew {
|
||||
color: var(--mantine-color-green-9);
|
||||
background: var(--mantine-color-green-light);
|
||||
border-radius: 2px;
|
||||
padding: 1px 3px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* Intraline diff (#331): the fragment that actually changed within the
|
||||
red "before" / green "after" block. It inherits the surrounding red/green
|
||||
framing and adds a stronger tint plus bold weight so the eye lands on the
|
||||
changed letters/words (git/GitHub-style) rather than the whole line. The
|
||||
container's line-through (old) / green (new) still marks the full line. */
|
||||
.suggestionChanged {
|
||||
/* Stronger tint of the surrounding red/green so the changed fragment pops
|
||||
within the block. `currentColor` follows the parent's red (old) or green
|
||||
(new) text colour. No `text-decoration` here on purpose: the old block's
|
||||
inherited line-through must survive on the changed letters too. */
|
||||
background: color-mix(in srgb, currentColor 22%, transparent);
|
||||
border-radius: 2px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.commentEditor {
|
||||
|
||||
&[data-editable][data-surface="muted"] .ProseMirror:not(.focused) {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { groupAgentRuns, runKey, GROUP_MIN } from "./group-agent-runs";
|
||||
import { IComment } from "@/features/comment/types/comment.types";
|
||||
|
||||
const editComment = (id: string, over?: Partial<IComment>): IComment =>
|
||||
({
|
||||
id,
|
||||
createdSource: "agent",
|
||||
aiChatId: "chat-1",
|
||||
agent: { name: "Corrector" },
|
||||
suggestedText: "new text",
|
||||
parentCommentId: null,
|
||||
...over,
|
||||
}) as unknown as IComment;
|
||||
|
||||
const human = (id: string): IComment =>
|
||||
({ id, createdSource: "user", parentCommentId: null }) as unknown as IComment;
|
||||
|
||||
describe("runKey", () => {
|
||||
it("keys a groupable agent edit on aiChatId + agent.name", () => {
|
||||
expect(runKey(editComment("a"))).toBe("chat-1:Corrector");
|
||||
});
|
||||
|
||||
it("is null for an external MCP agent (aiChatId null)", () => {
|
||||
expect(runKey(editComment("a", { aiChatId: null }))).toBeNull();
|
||||
});
|
||||
|
||||
it("is null for a non-edit agent comment (no suggestedText)", () => {
|
||||
expect(runKey(editComment("a", { suggestedText: null }))).toBeNull();
|
||||
});
|
||||
|
||||
it("is null for a reply (has parentCommentId)", () => {
|
||||
expect(runKey(editComment("a", { parentCommentId: "p" }))).toBeNull();
|
||||
});
|
||||
|
||||
it("is null for a human comment", () => {
|
||||
expect(runKey(human("a"))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("groupAgentRuns", () => {
|
||||
it("collapses >= GROUP_MIN same chat+role edits into one run at the first position", () => {
|
||||
const units = groupAgentRuns([
|
||||
editComment("e1"),
|
||||
editComment("e2"),
|
||||
editComment("e3"),
|
||||
]);
|
||||
expect(units).toHaveLength(1);
|
||||
expect(units[0].kind).toBe("run");
|
||||
if (units[0].kind === "run") {
|
||||
expect(units[0].key).toBe("chat-1:Corrector");
|
||||
expect(units[0].comments.map((c) => c.id)).toEqual(["e1", "e2", "e3"]);
|
||||
}
|
||||
expect(GROUP_MIN).toBe(2);
|
||||
});
|
||||
|
||||
it("renders a lone edit as a single (below the threshold)", () => {
|
||||
const units = groupAgentRuns([editComment("e1")]);
|
||||
expect(units).toHaveLength(1);
|
||||
expect(units[0].kind).toBe("single");
|
||||
});
|
||||
|
||||
it("never groups external MCP edits (aiChatId null) — each is a single", () => {
|
||||
const units = groupAgentRuns([
|
||||
editComment("m1", { aiChatId: null }),
|
||||
editComment("m2", { aiChatId: null }),
|
||||
]);
|
||||
expect(units).toHaveLength(2);
|
||||
expect(units.every((u) => u.kind === "single")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not collapse two different roles sharing one chat", () => {
|
||||
const units = groupAgentRuns([
|
||||
editComment("a", { agent: { name: "Corrector" } as any }),
|
||||
editComment("b", { agent: { name: "FactChecker" } as any }),
|
||||
]);
|
||||
// Each key has count 1 -> both remain singles.
|
||||
expect(units).toHaveLength(2);
|
||||
expect(units.every((u) => u.kind === "single")).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves order and keeps human threads as singles interleaved with a run", () => {
|
||||
const units = groupAgentRuns([
|
||||
human("h1"),
|
||||
editComment("e1"),
|
||||
editComment("e2"),
|
||||
human("h2"),
|
||||
]);
|
||||
// h1 single, then the run (emitted at e1's position, e2 absorbed), then h2.
|
||||
expect(units.map((u) => u.kind)).toEqual(["single", "run", "single"]);
|
||||
if (units[1].kind === "run") {
|
||||
expect(units[1].comments.map((c) => c.id)).toEqual(["e1", "e2"]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { IComment } from "@/features/comment/types/comment.types";
|
||||
|
||||
// A visual-only series threshold: this many agent suggested-edits sharing one
|
||||
// run key collapse under a single RunHeader. A group of one renders as a plain
|
||||
// standalone card (no header). Policy constant — no env override.
|
||||
export const GROUP_MIN = 2;
|
||||
|
||||
// One rendered unit of the top-level comment list: either a collapsed agent-run
|
||||
// group (>= GROUP_MIN suggested-edits from the same chat+role) or a single
|
||||
// comment (a human thread, an agent thread without an edit, or a lone edit).
|
||||
export interface AgentRunGroup {
|
||||
kind: "run";
|
||||
key: string;
|
||||
comments: IComment[];
|
||||
}
|
||||
export interface SingleUnit {
|
||||
kind: "single";
|
||||
comment: IComment;
|
||||
}
|
||||
export type CommentRenderUnit = AgentRunGroup | SingleUnit;
|
||||
|
||||
// The grouping key of a top-level agent suggested-edit, or null when the comment
|
||||
// is not a groupable edit. The key pins BOTH the AI chat and the acting role
|
||||
// (`aiChatId + ":" + agent.name`) so two roles running in the same chat do not
|
||||
// collapse under one header. A comment with `aiChatId == null` (an external MCP
|
||||
// agent) has no chat to group by — it is deliberately never groupable and always
|
||||
// renders as a single card (a time-bucketed synthetic run would split/merge runs
|
||||
// arbitrarily and choke on ISO `createdAt`). PURE.
|
||||
export function runKey(c: IComment): string | null {
|
||||
if (
|
||||
c.createdSource === "agent" &&
|
||||
c.suggestedText != null &&
|
||||
!c.parentCommentId &&
|
||||
c.aiChatId != null &&
|
||||
c.agent?.name
|
||||
) {
|
||||
return `${c.aiChatId}:${c.agent.name}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Collapse an ORDERED list of top-level comments into render units, preserving
|
||||
// list order: a run is emitted in place of its FIRST member (later members are
|
||||
// absorbed), everything else stays a single unit. Grouping is computed over the
|
||||
// snapshot handed in; a streamed page / WS update may later promote a single
|
||||
// edit into a run as more members arrive — that is acceptable (purely visual).
|
||||
// PURE — no React/DOM, no mutation of the input.
|
||||
export function groupAgentRuns(comments: IComment[]): CommentRenderUnit[] {
|
||||
// First pass: tally groupable edits per key so we know which keys clear
|
||||
// GROUP_MIN before we start emitting.
|
||||
const counts = new Map<string, number>();
|
||||
for (const c of comments) {
|
||||
const key = runKey(c);
|
||||
if (key) counts.set(key, (counts.get(key) ?? 0) + 1);
|
||||
}
|
||||
|
||||
const emitted = new Set<string>();
|
||||
const units: CommentRenderUnit[] = [];
|
||||
for (const c of comments) {
|
||||
const key = runKey(c);
|
||||
if (key && (counts.get(key) ?? 0) >= GROUP_MIN) {
|
||||
// Emit the whole run once, at the position of its first member; skip the
|
||||
// absorbed later members.
|
||||
if (emitted.has(key)) continue;
|
||||
emitted.add(key);
|
||||
units.push({
|
||||
kind: "run",
|
||||
key,
|
||||
comments: comments.filter((x) => runKey(x) === key),
|
||||
});
|
||||
} else {
|
||||
units.push({ kind: "single", comment: c });
|
||||
}
|
||||
}
|
||||
return units;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { parseSeverity, isSignificant } from "./severity";
|
||||
|
||||
describe("parseSeverity — exact importance dictionary", () => {
|
||||
it("maps the Russian importance tags", () => {
|
||||
expect(parseSeverity("[Критично] fix now")).toBe("critical");
|
||||
expect(parseSeverity("[Существенно] tighten")).toBe("major");
|
||||
expect(parseSeverity("[Незначительно] nit")).toBe("minor");
|
||||
});
|
||||
|
||||
it("maps the English equivalents and is case-insensitive", () => {
|
||||
expect(parseSeverity("[Critical] x")).toBe("critical");
|
||||
expect(parseSeverity("[MAJOR] x")).toBe("major");
|
||||
expect(parseSeverity("[minor] x")).toBe("minor");
|
||||
expect(parseSeverity("[критично] x")).toBe("critical");
|
||||
});
|
||||
|
||||
it("treats fact-checker verdicts as unknown, NOT a severity", () => {
|
||||
expect(parseSeverity("[Неверно] this is wrong")).toBe("unknown");
|
||||
expect(parseSeverity("[Не проверено] can't verify")).toBe("unknown");
|
||||
expect(parseSeverity("[Непроверяемо] x")).toBe("unknown");
|
||||
expect(parseSeverity("[Это мнение] x")).toBe("unknown");
|
||||
});
|
||||
|
||||
it("treats a typo'd / unrecognised tag as unknown (never falls back to minor)", () => {
|
||||
expect(parseSeverity("[Существенное] typo ending")).toBe("unknown");
|
||||
expect(parseSeverity("[whatever] x")).toBe("unknown");
|
||||
});
|
||||
|
||||
it("returns unknown for no tag or empty input", () => {
|
||||
expect(parseSeverity("plain body, no tag")).toBe("unknown");
|
||||
expect(parseSeverity("")).toBe("unknown");
|
||||
});
|
||||
|
||||
it("finds the recognised importance tag even after a leading verdict tag", () => {
|
||||
expect(parseSeverity("[Неверно] [Существенно] body")).toBe("major");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isSignificant", () => {
|
||||
it("counts only major and critical", () => {
|
||||
expect(isSignificant("critical")).toBe(true);
|
||||
expect(isSignificant("major")).toBe(true);
|
||||
expect(isSignificant("minor")).toBe(false);
|
||||
expect(isSignificant("unknown")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
// Severity of an agent suggested-edit, parsed CLIENT-SIDE from the importance
|
||||
// tag the editorial role prompts emit at the head of the comment body
|
||||
// (`[Критично]` / `[Существенно]` / `[Незначительно]`, or their English
|
||||
// equivalents). It is a DISPLAY-ONLY signal: it drives the coloured dot on the
|
||||
// edit card and the "M major" counter in a run header. It never gates an action.
|
||||
//
|
||||
// `unknown` is a first-class value, NOT a synonym for `minor`: any bracketed
|
||||
// text that is not in the exact dictionary — a Fact-checker verdict
|
||||
// (`[Неверно]`, `[Не проверено]`, `[Непроверяемо]`, `[Это мнение]`), a typo
|
||||
// (`[Существенное]`), or the absence of a tag — resolves to `unknown` and draws
|
||||
// a neutral dot. Passing an unrecognised tag off as `minor` would mis-label it.
|
||||
export type Severity = "critical" | "major" | "minor" | "unknown";
|
||||
|
||||
// EXACT (case-insensitive) dictionary. Only these tokens map to a real severity;
|
||||
// everything else falls through to `unknown` on purpose.
|
||||
const SEVERITY_TAGS: Record<string, Severity> = {
|
||||
критично: "critical",
|
||||
существенно: "major",
|
||||
незначительно: "minor",
|
||||
critical: "critical",
|
||||
major: "major",
|
||||
minor: "minor",
|
||||
};
|
||||
|
||||
// Parse the first RECOGNISED importance tag out of the flattened comment text
|
||||
// (use `commentContentToText` to obtain it). Scans every `[...]` token so a tag
|
||||
// that trails a verdict still counts; the first exact-dictionary hit wins. When
|
||||
// no token matches the dictionary the result is `unknown`. PURE — no React/DOM.
|
||||
export function parseSeverity(text: string): Severity {
|
||||
if (!text) return "unknown";
|
||||
const matches = text.matchAll(/\[([^\]]+)\]/g);
|
||||
for (const m of matches) {
|
||||
const tag = m[1].trim().toLowerCase();
|
||||
const sev = SEVERITY_TAGS[tag];
|
||||
if (sev) return sev;
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
// Whether a severity counts toward the "M major" tally in a run header: only the
|
||||
// genuinely significant ones (major + critical). `minor` and `unknown` do not.
|
||||
export function isSignificant(severity: Severity): boolean {
|
||||
return severity === "major" || severity === "critical";
|
||||
}
|
||||
@@ -36,6 +36,7 @@ const STATIC_ROUTES = new Set<string>([
|
||||
'/setup/register',
|
||||
'/settings/account/profile',
|
||||
'/settings/account/preferences',
|
||||
'/settings/account/api-keys',
|
||||
'/settings/workspace',
|
||||
'/settings/ai',
|
||||
'/settings/members',
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import SettingsTitle from "@/components/settings/settings-title.tsx";
|
||||
import ApiKeysManager from "@/features/api-key/components/api-keys-manager";
|
||||
import { getAppName } from "@/lib/config.ts";
|
||||
import { Helmet } from "react-helmet-async";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export default function AccountApiKeys() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<>
|
||||
<Helmet>
|
||||
<title>
|
||||
{t("API keys")} - {getAppName()}
|
||||
</title>
|
||||
</Helmet>
|
||||
<SettingsTitle title={t("API keys")} />
|
||||
|
||||
<ApiKeysManager />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -14,9 +14,11 @@
|
||||
*/
|
||||
|
||||
/*
|
||||
* Push the top-anchored toast containers below the top chrome (fixed 45px
|
||||
* header + optional 45px format toolbar + ~6px gap) so a toast (z-index 10000)
|
||||
* neither covers nor intercepts clicks on the header/toolbar (both z-index 99).
|
||||
* Anchor the top toast containers to the very top edge of the viewport (a small
|
||||
* 8px gap), above the header/search chrome, per product request. The toast
|
||||
* (z-index 10000) therefore renders over the header/toolbar (both z-index 99)
|
||||
* for the few seconds it is visible — intentional, since it is the top-most,
|
||||
* in-the-line-of-sight surface.
|
||||
*
|
||||
* Scoped to [data-position^='top'] on purpose. Mantine renders ALL SIX position
|
||||
* containers simultaneously (`position` only routes toasts into one via the
|
||||
@@ -34,7 +36,7 @@
|
||||
* (the :where() contributes 0), regardless of stylesheet order.
|
||||
*/
|
||||
.mantine-Notifications-root[data-position^='top'] {
|
||||
top: 96px;
|
||||
top: 8px;
|
||||
}
|
||||
|
||||
[data-mantine-color-scheme='light'] .mantine-Notification-root {
|
||||
|
||||
@@ -63,3 +63,15 @@ vi.stubGlobal("matchMedia", (query: string) => ({
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mantine's ScrollArea (used by Table.ScrollContainer, ScrollArea, etc.) reads
|
||||
// `ResizeObserver` in a layout effect on mount, which jsdom does not implement.
|
||||
// A no-op stub lets any test rendering those components mount cleanly.
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -370,10 +370,12 @@ describe('AiChatService.stream — abortSignal wiring (#184 F3)', () => {
|
||||
);
|
||||
});
|
||||
|
||||
// #490 reactive branch: a provider CONTEXT-OVERFLOW 400 in onError is classified,
|
||||
// records a distinguishable cause, and stamps metadata.replayOverflow so the NEXT
|
||||
// turn's budgeter trims aggressively (the recovery that un-bricks the chat).
|
||||
it('#490: a context-overflow 400 stamps replayOverflow on the finalized row', async () => {
|
||||
// #490/#520 reactive branch: a provider CONTEXT-OVERFLOW 400 in onError is
|
||||
// classified, records a distinguishable cause, and stamps the consecutive-overflow
|
||||
// COUNTER (metadata.replayOverflowCount) so the NEXT turn's budgeter trims with
|
||||
// escalating aggression (the recovery that un-bricks the chat). This is a fresh
|
||||
// chat (empty history -> prior streak 0), so the first overflow stamps count 1.
|
||||
it('#490/#520: a context-overflow 400 stamps replayOverflowCount=1 on the finalized row', async () => {
|
||||
jest
|
||||
.spyOn(Logger.prototype, 'error')
|
||||
.mockImplementation(() => undefined as never);
|
||||
@@ -397,11 +399,14 @@ describe('AiChatService.stream — abortSignal wiring (#184 F3)', () => {
|
||||
metadata: Record<string, unknown>;
|
||||
};
|
||||
expect(patch.status).toBe('error');
|
||||
expect(patch.metadata.replayOverflow).toBe(true);
|
||||
// First overflow on a fresh chat -> k = prior(0) + 1 = 1.
|
||||
expect(patch.metadata.replayOverflowCount).toBe(1);
|
||||
// The legacy boolean is no longer written (the counter supersedes it).
|
||||
expect('replayOverflow' in patch.metadata).toBe(false);
|
||||
expect(patch.metadata.error).toContain('контекстное окно');
|
||||
});
|
||||
|
||||
it('#490: a non-overflow error does NOT stamp replayOverflow', async () => {
|
||||
it('#490/#520: a non-overflow error does NOT stamp the overflow counter', async () => {
|
||||
jest
|
||||
.spyOn(Logger.prototype, 'error')
|
||||
.mockImplementation(() => undefined as never);
|
||||
@@ -412,6 +417,7 @@ describe('AiChatService.stream — abortSignal wiring (#184 F3)', () => {
|
||||
status: string;
|
||||
metadata: Record<string, unknown>;
|
||||
};
|
||||
expect('replayOverflowCount' in patch.metadata).toBe(false);
|
||||
expect('replayOverflow' in patch.metadata).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -30,13 +30,16 @@ import {
|
||||
STEP_LIMIT_NO_ANSWER_MARKER,
|
||||
OUTPUT_DEGENERATION_ERROR,
|
||||
lastAssistantContextTokens,
|
||||
lastAssistantReplayOverflow,
|
||||
lastAssistantReplayOverflowCount,
|
||||
seedActivatedTools,
|
||||
} from './ai-chat.service';
|
||||
import type { AiChatMessage, Workspace } from '@docmost/db/types/entity.types';
|
||||
import { buildSystemPrompt } from './ai-chat.prompt';
|
||||
import type { McpClientsService } from './external-mcp/mcp-clients.service';
|
||||
import { resolveEffectiveReplayThreshold } from './history-budget';
|
||||
import {
|
||||
resolveEffectiveReplayThreshold,
|
||||
REPLAY_MIN_FLOOR_TOKENS,
|
||||
} from './history-budget';
|
||||
|
||||
/**
|
||||
* Unit tests for compactToolOutput: the pure helper that shrinks tool outputs
|
||||
@@ -554,49 +557,129 @@ describe('seedActivatedTools', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('lastAssistantReplayOverflow', () => {
|
||||
describe('lastAssistantReplayOverflowCount', () => {
|
||||
const row = (
|
||||
role: string,
|
||||
metadata: Record<string, unknown> | null,
|
||||
): AiChatMessage => ({ role, metadata }) as unknown as AiChatMessage;
|
||||
|
||||
it('is true only when the LAST assistant turn overflowed', () => {
|
||||
it('reads the consecutive-overflow count from the LAST assistant turn', () => {
|
||||
expect(
|
||||
lastAssistantReplayOverflow([
|
||||
row('assistant', { replayOverflow: true }),
|
||||
lastAssistantReplayOverflowCount([
|
||||
row('assistant', { replayOverflowCount: 3 }),
|
||||
row('user', null),
|
||||
]),
|
||||
).toBe(true);
|
||||
// A recovered (later, non-overflow) assistant turn clears it.
|
||||
).toBe(3);
|
||||
// A recovered (later, non-overflow) assistant turn resets it to 0 — the read
|
||||
// stops at the most recent assistant row, which carries no count.
|
||||
expect(
|
||||
lastAssistantReplayOverflow([
|
||||
row('assistant', { replayOverflow: true }),
|
||||
lastAssistantReplayOverflowCount([
|
||||
row('assistant', { replayOverflowCount: 3 }),
|
||||
row('user', null),
|
||||
row('assistant', { contextTokens: 5 }),
|
||||
]),
|
||||
).toBe(false);
|
||||
expect(lastAssistantReplayOverflow([])).toBe(false);
|
||||
).toBe(0);
|
||||
expect(lastAssistantReplayOverflowCount([])).toBe(0);
|
||||
});
|
||||
|
||||
// #490 reactive recovery: a prior turn stamped `replayOverflow` must make the
|
||||
// NEXT turn's effective budget the AGGRESSIVE 0.5x cut — that harder trim is
|
||||
// what un-bricks a chat that just 400'd on the context window. This exercises
|
||||
// the exact wiring the service uses: read the stamp, then scale the threshold.
|
||||
it('#490: a prior replayOverflow drives the next turn to the 0.5x aggressive budget', () => {
|
||||
// BACK-COMPAT (#520): an in-flight row written by the pre-#520 boolean stamp
|
||||
// (`replayOverflow: true`, no count) reads as k=1 — the old single 0.5× behavior —
|
||||
// so a chat mid-recovery across the deploy does not regress.
|
||||
it('#520 back-compat: a legacy boolean replayOverflow reads as k=1', () => {
|
||||
expect(
|
||||
lastAssistantReplayOverflowCount([
|
||||
row('assistant', { replayOverflow: true }),
|
||||
row('user', null),
|
||||
]),
|
||||
).toBe(1);
|
||||
// A legacy row with the flag absent/false is k=0.
|
||||
expect(
|
||||
lastAssistantReplayOverflowCount([row('assistant', { contextTokens: 5 })]),
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
// A corrupt/negative persisted count never yields a negative k.
|
||||
it('clamps a corrupt negative count to 0', () => {
|
||||
expect(
|
||||
lastAssistantReplayOverflowCount([
|
||||
row('assistant', { replayOverflowCount: -4 }),
|
||||
]),
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
// #490/#520 reactive recovery: the prior consecutive-overflow count `k` drives
|
||||
// the next turn's effective budget to an ESCALATING cut (0.5**k) — each further
|
||||
// consecutive 400 tightens it, which is what un-bricks a chat that keeps
|
||||
// overflowing. This exercises the exact wiring the service uses: read the count,
|
||||
// then scale the threshold.
|
||||
it('#490/#520: the prior count drives the next turn to the escalating aggressive budget', () => {
|
||||
const history = [
|
||||
row('assistant', { replayOverflow: true }),
|
||||
row('assistant', { replayOverflowCount: 1 }),
|
||||
row('user', null),
|
||||
];
|
||||
const priorOverflowed = lastAssistantReplayOverflow(history);
|
||||
expect(priorOverflowed).toBe(true);
|
||||
// Base budget 100k -> aggressive recovery halves it to 50k this turn.
|
||||
expect(resolveEffectiveReplayThreshold(100_000, priorOverflowed)).toBe(50_000);
|
||||
const k = lastAssistantReplayOverflowCount(history);
|
||||
expect(k).toBe(1);
|
||||
// Base budget 100k -> first-overflow recovery halves it to 50k this turn.
|
||||
expect(resolveEffectiveReplayThreshold(100_000, k)).toBe(50_000);
|
||||
// A second consecutive overflow (k=2) quarters it.
|
||||
expect(resolveEffectiveReplayThreshold(100_000, 2)).toBe(25_000);
|
||||
// Odd base floors, not rounds.
|
||||
expect(resolveEffectiveReplayThreshold(99_999, true)).toBe(49_999);
|
||||
// No prior overflow -> the base budget is used verbatim (no aggressive cut).
|
||||
expect(resolveEffectiveReplayThreshold(100_000, false)).toBe(100_000);
|
||||
expect(resolveEffectiveReplayThreshold(99_999, 1)).toBe(49_999);
|
||||
// No prior overflow (k=0) -> the base budget is used verbatim (no cut).
|
||||
expect(resolveEffectiveReplayThreshold(100_000, 0)).toBe(100_000);
|
||||
// An explicit off-switch (null) is never overridden, even on recovery.
|
||||
expect(resolveEffectiveReplayThreshold(null, true)).toBeNull();
|
||||
expect(resolveEffectiveReplayThreshold(null, 3)).toBeNull();
|
||||
});
|
||||
|
||||
// #520 escalation table + convergence: the cut deepens each consecutive overflow
|
||||
// and is CLAMPED at the floor so it converges (un-bricks even against a small
|
||||
// real window), instead of the old fixed single 0.5× that stuck at 50k forever.
|
||||
it('#520: escalates and converges to the floor, un-bricking a small real window', () => {
|
||||
const base = 100_000;
|
||||
expect(resolveEffectiveReplayThreshold(base, 0)).toBe(base);
|
||||
expect(resolveEffectiveReplayThreshold(base, 1)).toBe(50_000);
|
||||
expect(resolveEffectiveReplayThreshold(base, 2)).toBe(25_000);
|
||||
expect(resolveEffectiveReplayThreshold(base, 3)).toBe(12_500);
|
||||
|
||||
// Residual-brick regression (#520): with the flat-default base (100k) and a real
|
||||
// model window of ~40k, the OLD fixed 0.5× stuck at 50k forever (> 40k -> 400s
|
||||
// again, never recovers). The escalating cut drops BELOW 40k after enough
|
||||
// consecutive overflows -> the history finally fits -> the chat un-bricks.
|
||||
const realWindow = 40_000;
|
||||
// k=1 (50k) still exceeds the window — the old behavior's terminal state.
|
||||
expect(resolveEffectiveReplayThreshold(base, 1)).toBeGreaterThan(realWindow);
|
||||
// But escalation converges under the window within a couple more turns.
|
||||
const converged = [2, 3, 4, 5].some(
|
||||
(k) => (resolveEffectiveReplayThreshold(base, k) as number) < realWindow,
|
||||
);
|
||||
expect(converged).toBe(true);
|
||||
|
||||
// Convergence is bounded BELOW by the floor: a large k never trims below it.
|
||||
for (const k of [4, 8, 20, 100]) {
|
||||
expect(resolveEffectiveReplayThreshold(base, k)).toBe(REPLAY_MIN_FLOOR_TOKENS);
|
||||
expect(
|
||||
resolveEffectiveReplayThreshold(base, k) as number,
|
||||
).toBeGreaterThanOrEqual(REPLAY_MIN_FLOOR_TOKENS);
|
||||
}
|
||||
});
|
||||
|
||||
// The floor never RAISES a legitimately small configured budget above itself —
|
||||
// that would re-overflow the very window it was configured for. Under #520 Option B
|
||||
// recovery MAY cut it BELOW itself (down to floor(0.5×base) = the old 0.5× cut).
|
||||
it('#520: never inflates a small configured budget above itself (may cut below)', () => {
|
||||
const small = 5_000; // below the floor
|
||||
const floor = Math.min(REPLAY_MIN_FLOOR_TOKENS, Math.floor(small * 0.5)); // 2500
|
||||
expect(resolveEffectiveReplayThreshold(small, 0)).toBe(small);
|
||||
// Even under escalation the effective threshold never exceeds the base, and never
|
||||
// drops below the absolute floor.
|
||||
for (const k of [1, 2, 3, 10]) {
|
||||
const t = resolveEffectiveReplayThreshold(small, k) as number;
|
||||
expect(t).toBeLessThanOrEqual(small);
|
||||
expect(t).toBeGreaterThanOrEqual(floor);
|
||||
}
|
||||
// Option B: on overflow it DOES cut below the configured budget (old floor==budget
|
||||
// behavior would keep this at `small`).
|
||||
expect(resolveEffectiveReplayThreshold(small, 1)).toBe(floor);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -930,21 +1013,50 @@ describe('flushAssistant', () => {
|
||||
expect(flushed.metadata.error).toBe('boom');
|
||||
});
|
||||
|
||||
// #490 observability: the replay budgeter's decision is stamped on the turn.
|
||||
it('records replayTrimmedToTokens + replayOverflow when provided', () => {
|
||||
// #490/#520 observability: the replay budgeter's decision is stamped on the turn,
|
||||
// now including the consecutive-overflow COUNTER (#520) the next turn escalates on.
|
||||
it('records replayTrimmedToTokens + replayOverflowCount when provided', () => {
|
||||
const f = flushAssistant([], '', 'error', {
|
||||
error: 'ctx',
|
||||
replayTrimmedToTokens: 42_000,
|
||||
replayOverflow: true,
|
||||
replayOverflowCount: 2,
|
||||
});
|
||||
expect(f.metadata.replayTrimmedToTokens).toBe(42_000);
|
||||
expect(f.metadata.replayOverflow).toBe(true);
|
||||
expect(f.metadata.replayOverflowCount).toBe(2);
|
||||
});
|
||||
|
||||
it('omits the replay metadata when not provided', () => {
|
||||
const f = flushAssistant([], '', 'completed', { finishReason: 'stop' });
|
||||
expect('replayTrimmedToTokens' in f.metadata).toBe(false);
|
||||
expect('replayOverflow' in f.metadata).toBe(false);
|
||||
expect('replayOverflowCount' in f.metadata).toBe(false);
|
||||
expect('replayBelowConfiguredBudget' in f.metadata).toBe(false);
|
||||
});
|
||||
|
||||
// #520 Option B observability: the turn is marked when recovery replayed BELOW the
|
||||
// admin-configured budget, so the UI/telemetry can surface "config too large".
|
||||
it('stamps replayBelowConfiguredBudget when recovery cut below the configured budget', () => {
|
||||
const f = flushAssistant([], '', 'error', {
|
||||
error: 'ctx',
|
||||
replayOverflowCount: 2,
|
||||
replayBelowConfiguredBudget: true,
|
||||
});
|
||||
// MUTATION SENTINEL: dropping the metadata stamp in flushAssistant reddens this.
|
||||
expect(f.metadata.replayBelowConfiguredBudget).toBe(true);
|
||||
});
|
||||
|
||||
it('omits replayBelowConfiguredBudget on a normal in-budget replay', () => {
|
||||
// false/omitted must NOT leave the flag on the turn (only the below-budget case).
|
||||
const off = flushAssistant([], '', 'completed', {
|
||||
replayBelowConfiguredBudget: false,
|
||||
});
|
||||
expect('replayBelowConfiguredBudget' in off.metadata).toBe(false);
|
||||
});
|
||||
|
||||
// A clean finalize (no overflow -> count 0/omitted) leaves NO counter, which the
|
||||
// next turn reads as k=0 — the reset that ends a recovery streak.
|
||||
it('omits replayOverflowCount for a zero/absent count (reset semantics)', () => {
|
||||
const zero = flushAssistant([], '', 'completed', { replayOverflowCount: 0 });
|
||||
expect('replayOverflowCount' in zero.metadata).toBe(false);
|
||||
});
|
||||
|
||||
// #274 observability: the page-change diff the agent saw this turn is persisted
|
||||
|
||||
@@ -141,9 +141,10 @@ const OUTPUT_DEGENERATION_ERROR =
|
||||
|
||||
// Prefix recorded on the assistant row when the provider rejected the turn for
|
||||
// CONTEXT OVERFLOW (#490): the replayed history exceeded the model's window. The
|
||||
// row is ALSO stamped `metadata.replayOverflow` so the NEXT turn's budgeter trims
|
||||
// aggressively (the reactive recovery — the overflowing turn had no usage signal
|
||||
// to trigger preventive trimming, so the classified 400 is what un-bricks it).
|
||||
// row is ALSO stamped `metadata.replayOverflowCount` (the consecutive-overflow
|
||||
// counter, #520) so the NEXT turn's budgeter trims with escalating aggression (the
|
||||
// reactive recovery — the overflowing turn had no usage signal to trigger
|
||||
// preventive trimming, so the classified 400 is what un-bricks it).
|
||||
export const CONTEXT_OVERFLOW_ERROR_PREFIX =
|
||||
'Диалог превысил контекстное окно модели; история будет агрессивно ' +
|
||||
'сокращена на следующем ходу.';
|
||||
@@ -1228,27 +1229,52 @@ export class AiChatService implements OnModuleInit, OnModuleDestroy {
|
||||
}
|
||||
// Last turn's provider-reported context size (authoritative when present).
|
||||
const priorContextTokens = lastAssistantContextTokens(oldHistory);
|
||||
// Reactive recovery (#490): if the LAST turn was rejected for context
|
||||
// overflow (stamped by onError), trim AGGRESSIVELY this turn — the
|
||||
// overflowing turn produced no usage signal, so a normal-threshold trim may
|
||||
// not shrink enough to fit. This is what un-bricks a chat that just 400'd.
|
||||
const priorOverflowed = lastAssistantReplayOverflow(oldHistory);
|
||||
// Reactive recovery (#490/#520): `k` = how many CONSECUTIVE preceding turns
|
||||
// were rejected for context overflow (stamped by onError). Each consecutive
|
||||
// overflow trims MORE aggressively (resolveEffectiveReplayThreshold scales the
|
||||
// budget by 0.5**k, clamped at the floor) so recovery ESCALATES until the
|
||||
// history fits — the overflowing turn produced no usage signal, so a single
|
||||
// fixed cut may not shrink enough when the real model window is small. This is
|
||||
// what un-bricks a chat that keeps 400'ing on the context window.
|
||||
const priorOverflowCount = lastAssistantReplayOverflowCount(oldHistory);
|
||||
const effectiveThreshold = resolveEffectiveReplayThreshold(
|
||||
replayBudget.thresholdTokens,
|
||||
priorOverflowed,
|
||||
priorOverflowCount,
|
||||
);
|
||||
if (priorOverflowed) {
|
||||
this.logger.warn(
|
||||
`AI chat (chat ${chatId}): previous turn hit context overflow; ` +
|
||||
`applying aggressive replay budget (${effectiveThreshold} tokens).`,
|
||||
);
|
||||
// #520 Option B: recovery MAY cut the replay budget BELOW the admin-configured
|
||||
// window when the provider keeps proving non-fit (the anti-brick invariant of
|
||||
// the reactive branch beats a config that a 400 has disproved). Surface it so
|
||||
// the admin sees their window is factually too large, and mark the turn so the
|
||||
// UI/telemetry can show it. Only true when actually below (not on in-budget
|
||||
// escalation edge cases); k>0 implies below for any budget >= 2 tokens.
|
||||
const replayBelowConfiguredBudget =
|
||||
replayBudget.thresholdTokens != null &&
|
||||
effectiveThreshold != null &&
|
||||
effectiveThreshold < replayBudget.thresholdTokens;
|
||||
if (priorOverflowCount > 0) {
|
||||
if (replayBelowConfiguredBudget) {
|
||||
this.logger.warn(
|
||||
`AI chat (chat ${chatId}): configured replay budget ` +
|
||||
`(${replayBudget.thresholdTokens} tokens) does not fit the model — ` +
|
||||
`replaying BELOW it at ${effectiveThreshold} tokens after ` +
|
||||
`${priorOverflowCount} consecutive context overflow(s) ` +
|
||||
`(escalation level ${priorOverflowCount}). Lower chatContextWindow ` +
|
||||
`to match the model's real context window.`,
|
||||
);
|
||||
} else {
|
||||
this.logger.warn(
|
||||
`AI chat (chat ${chatId}): ${priorOverflowCount} consecutive context ` +
|
||||
`overflow(s); applying escalated aggressive replay budget ` +
|
||||
`(${effectiveThreshold} tokens).`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const preTrim = trimHistoryForReplay(
|
||||
messages,
|
||||
effectiveThreshold,
|
||||
// A prior OVERFLOW means the provider count is stale/absent — force the
|
||||
// char-estimate path by ignoring priorContextTokens on recovery.
|
||||
priorOverflowed ? undefined : priorContextTokens,
|
||||
priorOverflowCount > 0 ? undefined : priorContextTokens,
|
||||
);
|
||||
messages = preTrim.messages;
|
||||
// Observability (#490): record the budgeter's decision on the turn so the UI
|
||||
@@ -1903,6 +1929,10 @@ export class AiChatService implements OnModuleInit, OnModuleDestroy {
|
||||
pageChanged,
|
||||
partsCache,
|
||||
replayTrimmedToTokens,
|
||||
// #520 Option B: mark the turn when recovery replayed BELOW the
|
||||
// configured budget (only when it actually did).
|
||||
replayBelowConfiguredBudget:
|
||||
replayBelowConfiguredBudget || undefined,
|
||||
}),
|
||||
);
|
||||
// #184/#487: the RUN is finalized ALWAYS (never gated on the message).
|
||||
@@ -1981,7 +2011,16 @@ export class AiChatService implements OnModuleInit, OnModuleDestroy {
|
||||
pageChanged,
|
||||
partsCache,
|
||||
replayTrimmedToTokens,
|
||||
replayOverflow: overflow || undefined,
|
||||
// #520: escalate the consecutive-overflow counter so the NEXT turn
|
||||
// trims MORE aggressively (0.5**k). k grows by 1 each consecutive
|
||||
// overflow; a clean finalize omits the field, resetting it to 0.
|
||||
replayOverflowCount: overflow
|
||||
? priorOverflowCount + 1
|
||||
: undefined,
|
||||
// #520 Option B: mark the turn when THIS replay was already below the
|
||||
// configured budget (only when it actually was).
|
||||
replayBelowConfiguredBudget:
|
||||
replayBelowConfiguredBudget || undefined,
|
||||
}),
|
||||
);
|
||||
// #184: settle the RUN as failed, carrying the provider/transport cause.
|
||||
@@ -2413,22 +2452,39 @@ export function seedActivatedTools(
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the most recent assistant turn was rejected for CONTEXT OVERFLOW
|
||||
* (#490): its row carries `metadata.replayOverflow` (stamped by the stream's
|
||||
* onError). The next turn's budgeter reads this to trim aggressively — the
|
||||
* reactive recovery. Only the LAST assistant turn matters (an older overflow was
|
||||
* already recovered), so we stop at the first assistant row scanning backwards.
|
||||
* How many CONSECUTIVE recent turns were rejected for CONTEXT OVERFLOW (#490/#520):
|
||||
* `k`, read from the most recent assistant row's `metadata.replayOverflowCount`
|
||||
* (stamped by the stream's onError, incremented each consecutive overflow and reset
|
||||
* to 0 on any clean finalize). The next turn's budgeter feeds this to
|
||||
* {@link resolveEffectiveReplayThreshold} to trim with ESCALATING aggression — the
|
||||
* reactive recovery. Only the LAST assistant turn matters (its count already carries
|
||||
* the consecutive streak; an older overflow followed by a clean turn was recovered),
|
||||
* so we stop at the first assistant row scanning backwards.
|
||||
*
|
||||
* BACK-COMPAT: a row written by the pre-#520 boolean stamp (`replayOverflow: true`,
|
||||
* no count) is read as k=1 — the old single 0.5× behavior — so in-flight chats do
|
||||
* not regress across the deploy.
|
||||
*/
|
||||
export function lastAssistantReplayOverflow(
|
||||
export function lastAssistantReplayOverflowCount(
|
||||
history: ReadonlyArray<AiChatMessage>,
|
||||
): boolean {
|
||||
): number {
|
||||
for (let i = history.length - 1; i >= 0; i--) {
|
||||
const row = history[i];
|
||||
if (row.role !== 'assistant') continue;
|
||||
const meta = (row.metadata ?? {}) as { replayOverflow?: unknown };
|
||||
return meta.replayOverflow === true;
|
||||
const meta = (row.metadata ?? {}) as {
|
||||
replayOverflowCount?: unknown;
|
||||
replayOverflow?: unknown;
|
||||
};
|
||||
if (typeof meta.replayOverflowCount === 'number') {
|
||||
// Guard against a corrupt/negative persisted value.
|
||||
return meta.replayOverflowCount > 0
|
||||
? Math.floor(meta.replayOverflowCount)
|
||||
: 0;
|
||||
}
|
||||
// Back-compat: legacy boolean stamp -> one overflow (0.5× cut).
|
||||
return meta.replayOverflow === true ? 1 : 0;
|
||||
}
|
||||
return false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** The last message with role 'user' from a useChat payload, if any. */
|
||||
@@ -3084,9 +3140,16 @@ export function flushAssistant(
|
||||
// the (estimated) token size it trimmed to — the UI can show "replay truncated
|
||||
// at N tokens". Omitted when nothing was trimmed.
|
||||
replayTrimmedToTokens?: number;
|
||||
// #490 reactive branch: set when the provider rejected this turn for context
|
||||
// overflow. Stamped into metadata so the NEXT turn's budgeter trims aggressively.
|
||||
replayOverflow?: boolean;
|
||||
// #490/#520 reactive branch: the consecutive context-overflow count for THIS
|
||||
// turn (prior streak + 1) when the provider rejected it for context overflow.
|
||||
// Stamped into metadata so the NEXT turn's budgeter trims with escalating
|
||||
// aggression (0.5**k). Omitted (undefined) on a clean turn, which resets k to 0.
|
||||
replayOverflowCount?: number;
|
||||
// #520 Option B observability: true when recovery replayed this turn's history
|
||||
// BELOW the admin-configured budget (the configured window did not fit and the
|
||||
// anti-brick invariant cut past it). Omitted on a normal in-budget replay so the
|
||||
// flag marks ONLY the "config is factually too large" case.
|
||||
replayBelowConfiguredBudget?: boolean;
|
||||
},
|
||||
): AssistantFlush {
|
||||
const finished = capturedSteps ?? [];
|
||||
@@ -3139,7 +3202,10 @@ export function flushAssistant(
|
||||
metadata.maxContextTokens = extra.maxContextTokens;
|
||||
if (extra?.replayTrimmedToTokens)
|
||||
metadata.replayTrimmedToTokens = extra.replayTrimmedToTokens;
|
||||
if (extra?.replayOverflow) metadata.replayOverflow = true;
|
||||
if (extra?.replayOverflowCount && extra.replayOverflowCount > 0)
|
||||
metadata.replayOverflowCount = extra.replayOverflowCount;
|
||||
if (extra?.replayBelowConfiguredBudget)
|
||||
metadata.replayBelowConfiguredBudget = true;
|
||||
if (extra?.error) metadata.error = extra.error;
|
||||
// Persist the page-change diff the agent saw this turn (#274 observability),
|
||||
// so history / the Markdown export can show what the user changed. Only when
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { randomBytes } from 'crypto';
|
||||
import { Client } from 'pg';
|
||||
import { flushAssistant, serializeSteps } from './ai-chat.service';
|
||||
import {
|
||||
flushAssistant,
|
||||
serializeSteps,
|
||||
lastAssistantReplayOverflowCount,
|
||||
} from './ai-chat.service';
|
||||
import type { AiChatMessage } from '@docmost/db/types/entity.types';
|
||||
|
||||
/**
|
||||
* #490 write-volume regression — an OBSERVABLE-PROPERTY test on a LIVE Postgres,
|
||||
@@ -207,3 +212,111 @@ describe('#490 write-volume on a live Postgres (pg_current_wal_lsn delta)', () =
|
||||
expect(v2).toBeLessThan(v1 * 0.75);
|
||||
}, 120_000);
|
||||
});
|
||||
|
||||
/**
|
||||
* #520 reactive-recovery COUNTER lifecycle on a LIVE Postgres — proves the
|
||||
* consecutive-overflow count survives a real jsonb metadata round-trip (the persist
|
||||
* path), not just an in-memory object. flushAssistant BUILDS the row metadata, we
|
||||
* WRITE it to a jsonb column, READ it back, then reconstruct the assistant row and
|
||||
* run lastAssistantReplayOverflowCount over it — exactly the read the next turn does.
|
||||
*
|
||||
* The lifecycle proven end-to-end through pg:
|
||||
* - consecutive overflows INCREMENT k (1 -> 2 -> 3);
|
||||
* - a CLEAN finalize omits the field, which the reader treats as a RESET to 0;
|
||||
* - a legacy boolean row (`replayOverflow: true`) reads back as k=1 (back-compat).
|
||||
*/
|
||||
describe('#520 overflow-counter lifecycle on a live Postgres (jsonb round-trip)', () => {
|
||||
let client: Client | undefined;
|
||||
let available = false;
|
||||
|
||||
beforeAll(async () => {
|
||||
try {
|
||||
client = new Client(CONN);
|
||||
await client.connect();
|
||||
await client.query('SELECT 1');
|
||||
available = true;
|
||||
} catch {
|
||||
available = false;
|
||||
client = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await client?.end().catch(() => undefined);
|
||||
});
|
||||
|
||||
// Round-trip an arbitrary metadata object through a real jsonb column and read it
|
||||
// back as the reconstructed assistant row the next turn would load.
|
||||
async function roundTrip(
|
||||
c: Client,
|
||||
metadata: unknown,
|
||||
): Promise<AiChatMessage> {
|
||||
await c.query('UPDATE _wal_counter SET metadata=$1 WHERE id=1', [
|
||||
JSON.stringify(metadata),
|
||||
]);
|
||||
const back = (await c.query('SELECT metadata FROM _wal_counter WHERE id=1'))
|
||||
.rows[0].metadata as Record<string, unknown>;
|
||||
return { role: 'assistant', metadata: back } as unknown as AiChatMessage;
|
||||
}
|
||||
|
||||
it('increments across consecutive overflows, resets on a clean turn, and honors the legacy boolean', async () => {
|
||||
if (!available || !client) {
|
||||
console.warn('SKIP: gitmost-test-pg not reachable; skipping counter test.');
|
||||
return;
|
||||
}
|
||||
const c = client;
|
||||
await c.query('DROP TABLE IF EXISTS _wal_counter');
|
||||
await c.query('CREATE TABLE _wal_counter(id int primary key, metadata jsonb)');
|
||||
await c.query("INSERT INTO _wal_counter VALUES (1, '{}'::jsonb)");
|
||||
|
||||
// Turn 1 overflow: prior streak 0 -> stamp k=1 (as the service does: prior+1).
|
||||
let prior = lastAssistantReplayOverflowCount([]); // fresh chat
|
||||
expect(prior).toBe(0);
|
||||
let row = await roundTrip(
|
||||
c,
|
||||
flushAssistant([], '', 'error', {
|
||||
error: 'ctx',
|
||||
replayOverflowCount: prior + 1,
|
||||
}).metadata,
|
||||
);
|
||||
prior = lastAssistantReplayOverflowCount([row]);
|
||||
expect(prior).toBe(1);
|
||||
|
||||
// Turn 2 overflow: prior 1 -> stamp k=2.
|
||||
row = await roundTrip(
|
||||
c,
|
||||
flushAssistant([], '', 'error', {
|
||||
error: 'ctx',
|
||||
replayOverflowCount: prior + 1,
|
||||
}).metadata,
|
||||
);
|
||||
prior = lastAssistantReplayOverflowCount([row]);
|
||||
expect(prior).toBe(2);
|
||||
|
||||
// Turn 3 overflow: prior 2 -> stamp k=3.
|
||||
row = await roundTrip(
|
||||
c,
|
||||
flushAssistant([], '', 'error', {
|
||||
error: 'ctx',
|
||||
replayOverflowCount: prior + 1,
|
||||
}).metadata,
|
||||
);
|
||||
prior = lastAssistantReplayOverflowCount([row]);
|
||||
expect(prior).toBe(3);
|
||||
|
||||
// Turn 4 CLEAN finalize: no overflow -> the field is omitted -> reset to 0.
|
||||
row = await roundTrip(
|
||||
c,
|
||||
flushAssistant([], 'all good', 'completed', { finishReason: 'stop' })
|
||||
.metadata,
|
||||
);
|
||||
expect('replayOverflowCount' in (row.metadata as object)).toBe(false);
|
||||
expect(lastAssistantReplayOverflowCount([row])).toBe(0);
|
||||
|
||||
// Back-compat: a row persisted by the pre-#520 boolean stamp reads back as k=1.
|
||||
row = await roundTrip(c, { replayOverflow: true });
|
||||
expect(lastAssistantReplayOverflowCount([row])).toBe(1);
|
||||
|
||||
await c.query('DROP TABLE IF EXISTS _wal_counter');
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
@@ -1,14 +1,146 @@
|
||||
import type { ModelMessage } from 'ai';
|
||||
import {
|
||||
resolveReplayBudget,
|
||||
resolveEffectiveReplayThreshold,
|
||||
isContextOverflowError,
|
||||
estimateMessagesTokens,
|
||||
trimHistoryForReplay,
|
||||
REPLAY_BUDGET_DEFAULT_TOKENS,
|
||||
REPLAY_BUDGET_WINDOW_FRACTION,
|
||||
REPLAY_MIN_FLOOR_TOKENS,
|
||||
REPLAY_TRUNCATION_MARKER,
|
||||
REPLAY_TURN_COLLAPSED_MARKER,
|
||||
} from './history-budget';
|
||||
|
||||
describe('resolveEffectiveReplayThreshold (#520 iterative escalation)', () => {
|
||||
// The escalation table: each consecutive overflow (k) deepens the cut by 0.5×.
|
||||
it('scales the base by 0.5**k, flooring (not rounding) fractional tokens', () => {
|
||||
const base = 100_000;
|
||||
expect(resolveEffectiveReplayThreshold(base, 0)).toBe(base); // k=0: unchanged
|
||||
expect(resolveEffectiveReplayThreshold(base, 1)).toBe(50_000); // 0.5×
|
||||
expect(resolveEffectiveReplayThreshold(base, 2)).toBe(25_000); // 0.25×
|
||||
expect(resolveEffectiveReplayThreshold(base, 3)).toBe(12_500); // 0.125×
|
||||
// Floors, not rounds.
|
||||
expect(resolveEffectiveReplayThreshold(99_999, 1)).toBe(49_999);
|
||||
});
|
||||
|
||||
it('passes a null base (trimming OFF) through unchanged for any k', () => {
|
||||
for (const k of [0, 1, 2, 5, 100]) {
|
||||
expect(resolveEffectiveReplayThreshold(null, k)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
// The crux of #520: convergence. A large k is clamped at REPLAY_MIN_FLOOR_TOKENS,
|
||||
// so the escalation CONVERGES to a small-but-usable budget instead of trimming to
|
||||
// zero — and, unlike the old fixed 0.5× that stuck at 50k, it drops far enough to
|
||||
// fit a small real model window.
|
||||
it('clamps a large k at the floor (converges, never below)', () => {
|
||||
const base = 100_000;
|
||||
for (const k of [4, 6, 10, 50, 200]) {
|
||||
const t = resolveEffectiveReplayThreshold(base, k) as number;
|
||||
expect(t).toBe(REPLAY_MIN_FLOOR_TOKENS);
|
||||
expect(t).toBeGreaterThanOrEqual(REPLAY_MIN_FLOOR_TOKENS);
|
||||
}
|
||||
});
|
||||
|
||||
// Residual-brick regression (#520): flat-default base 100k, real window ~40k. The
|
||||
// OLD fixed single 0.5× stuck at 50k > 40k forever (re-overflows every turn — the
|
||||
// brick). The iterative cut drops BELOW 40k after a couple more consecutive
|
||||
// overflows, so the history finally fits and the chat un-bricks.
|
||||
it('un-bricks: escalation drops below a small real window the fixed 0.5× never could', () => {
|
||||
const base = 100_000;
|
||||
const realWindow = 40_000;
|
||||
// The old terminal state: 0.5× = 50k, still above the window.
|
||||
expect(resolveEffectiveReplayThreshold(base, 1)).toBeGreaterThan(realWindow);
|
||||
// Escalation converges under the window.
|
||||
const converged = [2, 3, 4, 5].some(
|
||||
(k) => (resolveEffectiveReplayThreshold(base, k) as number) < realWindow,
|
||||
);
|
||||
expect(converged).toBe(true);
|
||||
// MUTATION SENTINEL: reverting `** k` to `** 1` (fixed 0.5×) makes every k yield
|
||||
// 50k, so `converged` above would be FALSE and this test reddens. Removing the
|
||||
// floor reddens the clamp test instead.
|
||||
});
|
||||
|
||||
// "Don't INFLATE above itself" is still an invariant: the floor never RAISES a
|
||||
// legitimately small configured budget above itself (that would re-overflow the
|
||||
// very window it was set for). Under #520 Option B the floor is min(FLOOR,
|
||||
// floor(0.5×base)), so for a base BELOW the floor recovery MAY cut it further —
|
||||
// down to floor(0.5×base), i.e. AT LEAST the old single 0.5× cut — but never above.
|
||||
it('never inflates a small configured budget above itself (may cut below it, #520 Option B)', () => {
|
||||
const small = 5_000; // below REPLAY_MIN_FLOOR_TOKENS
|
||||
const floor = Math.min(REPLAY_MIN_FLOOR_TOKENS, Math.floor(small * 0.5)); // 2500
|
||||
expect(resolveEffectiveReplayThreshold(small, 0)).toBe(small); // k=0 unchanged
|
||||
for (const k of [1, 2, 3, 10]) {
|
||||
const t = resolveEffectiveReplayThreshold(small, k) as number;
|
||||
// Invariant: never RAISED above the configured budget.
|
||||
expect(t).toBeLessThanOrEqual(small);
|
||||
// Option B: never trimmed below the absolute floor (converges).
|
||||
expect(t).toBeGreaterThanOrEqual(floor);
|
||||
}
|
||||
// The old single 0.5× cut is reached (and pinned) — recovery is never WORSE than
|
||||
// before, and DOES cut below the configured budget on overflow (Option B). Under
|
||||
// the old floor==budget behavior this would be `small` (5000), not `floor`.
|
||||
expect(resolveEffectiveReplayThreshold(small, 1)).toBe(floor);
|
||||
});
|
||||
|
||||
// #520 Option B: with a configured window (NOT the flat default), repeated overflow
|
||||
// escalates the replay budget BELOW the configured budget, down to the absolute
|
||||
// floor — the chat must not brick even when the configured window is too large for
|
||||
// the model. A CLEAN turn (k back to 0) restores the full configured budget.
|
||||
it('escalates below the configured budget down to the floor, and resets on a clean turn', () => {
|
||||
// Configured context window 8000 -> budget = floor(0.7 × 8000) = 5600 (the code's
|
||||
// window->budget ratio; compute it, do not hardcode).
|
||||
const window = 8_000;
|
||||
const budget = resolveReplayBudget(window).thresholdTokens as number;
|
||||
expect(budget).toBe(Math.floor(REPLAY_BUDGET_WINDOW_FRACTION * window)); // 5600
|
||||
|
||||
// The absolute floor for this budget = min(FLOOR, floor(0.5 × budget)) = 2800
|
||||
// (a "small window": 0.5×budget < REPLAY_MIN_FLOOR_TOKENS), which is BELOW the
|
||||
// 5600 configured budget.
|
||||
const floor = Math.min(
|
||||
REPLAY_MIN_FLOOR_TOKENS,
|
||||
Math.floor(budget * 0.5),
|
||||
); // 2800
|
||||
expect(floor).toBe(2_800);
|
||||
expect(floor).toBeLessThan(budget); // below the configured budget
|
||||
|
||||
// k=0 -> full configured budget (no overflow yet).
|
||||
expect(resolveEffectiveReplayThreshold(budget, 0)).toBe(budget);
|
||||
// k=1 -> cut BELOW the configured budget to the 0.5× floor (2800). This is the
|
||||
// MUTATION SENTINEL: with the OLD floor==configured-budget behavior this would be
|
||||
// max(2800, 5600) = 5600 (never below budget), so the assertion reddens.
|
||||
expect(resolveEffectiveReplayThreshold(budget, 1)).toBe(floor);
|
||||
expect(resolveEffectiveReplayThreshold(budget, 1)).toBeLessThan(budget);
|
||||
// k>=2 stays at the floor (converges, never below it).
|
||||
for (const k of [2, 3, 5, 20]) {
|
||||
expect(resolveEffectiveReplayThreshold(budget, k)).toBe(floor);
|
||||
}
|
||||
|
||||
// A CLEAN turn resets k to 0 -> the full configured budget is restored (recovery
|
||||
// is not sticky; it only bites while the provider keeps proving non-fit).
|
||||
expect(resolveEffectiveReplayThreshold(budget, 0)).toBe(budget);
|
||||
});
|
||||
|
||||
// #520 Option B, LARGE window: a big configured budget escalates in DISTINCT steps
|
||||
// below itself, converging to the fixed absolute floor REPLAY_MIN_FLOOR_TOKENS.
|
||||
it('a large configured budget escalates below itself down to REPLAY_MIN_FLOOR_TOKENS', () => {
|
||||
const budget = resolveReplayBudget(200_000).thresholdTokens as number; // 140000
|
||||
// The floor for a large window is the fixed REPLAY_MIN_FLOOR_TOKENS (8k), well
|
||||
// BELOW the configured budget.
|
||||
expect(
|
||||
Math.min(REPLAY_MIN_FLOOR_TOKENS, Math.floor(budget * 0.5)),
|
||||
).toBe(REPLAY_MIN_FLOOR_TOKENS);
|
||||
const seq = [0, 1, 2, 3, 4, 5, 6].map(
|
||||
(k) => resolveEffectiveReplayThreshold(budget, k) as number,
|
||||
);
|
||||
expect(seq).toEqual([140_000, 70_000, 35_000, 17_500, 8_750, 8_000, 8_000]);
|
||||
// Every escalated step (k>=1) is below the configured budget; convergence floor.
|
||||
for (const t of seq.slice(1)) expect(t).toBeLessThan(budget);
|
||||
expect(seq[seq.length - 1]).toBe(REPLAY_MIN_FLOOR_TOKENS);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveReplayBudget', () => {
|
||||
it('uses floor(0.7 x window) for a configured window (no cap)', () => {
|
||||
// 0.7 x 60k = 42k
|
||||
|
||||
@@ -22,10 +22,35 @@ export const REPLAY_BUDGET_DEFAULT_TOKENS = 100_000;
|
||||
/** Fraction of a configured context window used as the budget. */
|
||||
export const REPLAY_BUDGET_WINDOW_FRACTION = 0.7;
|
||||
/**
|
||||
* Fraction of the normal budget used for the REACTIVE re-trim after a provider
|
||||
* context-overflow 400 — the preventive estimate under-counted, so cut harder.
|
||||
* Per-step fraction of the normal budget applied on the REACTIVE re-trim after a
|
||||
* provider context-overflow 400 — the preventive estimate under-counted, so cut
|
||||
* harder. This is now applied ITERATIVELY: with `k` consecutive overflow turns the
|
||||
* budget is scaled by `fraction ** k` (k=1 -> 0.5×, k=2 -> 0.25×, …), so recovery
|
||||
* ESCALATES turn over turn until the replayed history finally fits, instead of the
|
||||
* old single fixed 0.5× cut that could never un-brick a chat whose real model
|
||||
* window is smaller than 0.5 × the (unconfigured, flat-default) base budget (#520).
|
||||
*/
|
||||
export const REPLAY_AGGRESSIVE_FRACTION = 0.5;
|
||||
/**
|
||||
* Absolute lower bound (tokens) on the escalating reactive budget: the iterative
|
||||
* cut is clamped here so it CONVERGES (a fixed floor, not an ever-shrinking value
|
||||
* that would eventually trim everything). Rationale: below ~8k tokens a chat cannot
|
||||
* carry meaningful recent context, and even a small real model window comfortably
|
||||
* fits this much — keep-recent-turns still applies on top, so a handful of recent
|
||||
* turns survive.
|
||||
*
|
||||
* #520 Option B: for a LARGE configured window this floor sits BELOW the configured
|
||||
* replay budget, and recovery is allowed to escalate PAST the configured budget down
|
||||
* to it — "the chat must not brick on overflow" is an INVARIANT of the reactive
|
||||
* branch, and a configured window is a claim about model capacity, not a promise
|
||||
* about replay size; once the provider proves non-fit with a 400, reality beats the
|
||||
* config. This does NOT change the NORMAL path's upper bound (#510 Option A still
|
||||
* respects the configured budget while it fits) — it is survival once non-fit is
|
||||
* proven. For a SMALL configured window the effective floor is instead the old
|
||||
* single 0.5× cut (never worse than before, and never RAISED above the budget); see
|
||||
* {@link resolveEffectiveReplayThreshold}.
|
||||
*/
|
||||
export const REPLAY_MIN_FLOOR_TOKENS = 8_000;
|
||||
/**
|
||||
* Turns (a user message + its assistant/tool replies) kept FULL at the tail,
|
||||
* including the current one — never trimmed. Older turns are compacted first.
|
||||
@@ -85,22 +110,48 @@ export function resolveReplayBudget(rawContextWindow: unknown): ReplayBudget {
|
||||
}
|
||||
|
||||
/**
|
||||
* The effective replay threshold for THIS turn, given the base budget and whether
|
||||
* the PREVIOUS turn hit a context-overflow 400 (the reactive-recovery signal,
|
||||
* `metadata.replayOverflow`). On recovery the base budget is scaled down by
|
||||
* {@link REPLAY_AGGRESSIVE_FRACTION}: the overflowing turn produced no usage
|
||||
* signal, so the preventive estimate under-counted and a normal-threshold trim may
|
||||
* not shrink enough to fit — this harder cut is what un-bricks the chat.
|
||||
* The effective replay threshold for THIS turn, given the base budget and `k` — the
|
||||
* number of CONSECUTIVE preceding turns that hit a context-overflow 400 (the
|
||||
* reactive-recovery signal `metadata.replayOverflowCount`, read from the last
|
||||
* assistant row). On recovery the base budget is scaled down ITERATIVELY by
|
||||
* {@link REPLAY_AGGRESSIVE_FRACTION} ** k and clamped at {@link REPLAY_MIN_FLOOR_TOKENS}:
|
||||
* - k=0 -> base unchanged (no overflow: nothing to recover from).
|
||||
* - k=1 -> floor(0.5 × base); k=2 -> floor(0.25 × base); … each further consecutive
|
||||
* overflow tightens the cut, so recovery ESCALATES until the history fits.
|
||||
* - the escalation is clamped at the floor so it CONVERGES — this is what un-bricks
|
||||
* a chat whose real model window is smaller than a single 0.5× cut of the base
|
||||
* (e.g. an unconfigured window: flat-default base 100k, real window <50k) (#520).
|
||||
*
|
||||
* The overflowing turn produced no usage signal, so the preventive estimate
|
||||
* under-counted and a normal-threshold (or single fixed 0.5×) trim may not shrink
|
||||
* enough to fit; the escalating cut is what recovers such a chat.
|
||||
*
|
||||
* A `null` base budget (trimming OFF) is passed through unchanged: an explicit
|
||||
* off-switch is never overridden by the recovery path.
|
||||
*
|
||||
* The absolute floor is `min(REPLAY_MIN_FLOOR_TOKENS, floor(0.5 × base))` (#520
|
||||
* Option B):
|
||||
* - LARGE window (floor(0.5 × base) >= REPLAY_MIN_FLOOR_TOKENS) -> the fixed
|
||||
* REPLAY_MIN_FLOOR_TOKENS, which is BELOW the configured budget: escalation is
|
||||
* ALLOWED to cut past the configured budget down to this absolute minimum, so a
|
||||
* chat whose real model window is far smaller than the configured window still
|
||||
* un-bricks (the invariant beats a config reality disproved with a 400).
|
||||
* - SMALL window (floor(0.5 × base) < REPLAY_MIN_FLOOR_TOKENS) -> floor(0.5 ×
|
||||
* base), i.e. AT LEAST the old single 0.5× cut: recovery is never WORSE than the
|
||||
* pre-#520 behavior, and the floor is still never RAISED above the configured
|
||||
* budget itself (that would re-overflow the very window it was set for).
|
||||
*/
|
||||
export function resolveEffectiveReplayThreshold(
|
||||
thresholdTokens: number | null,
|
||||
priorOverflowed: boolean,
|
||||
k: number,
|
||||
): number | null {
|
||||
if (!priorOverflowed || thresholdTokens == null) return thresholdTokens;
|
||||
return Math.floor(thresholdTokens * REPLAY_AGGRESSIVE_FRACTION);
|
||||
if (thresholdTokens == null || k <= 0) return thresholdTokens;
|
||||
const scaled = Math.floor(thresholdTokens * REPLAY_AGGRESSIVE_FRACTION ** k);
|
||||
const floor = Math.min(
|
||||
REPLAY_MIN_FLOOR_TOKENS,
|
||||
Math.floor(thresholdTokens * REPLAY_AGGRESSIVE_FRACTION),
|
||||
);
|
||||
return Math.max(scaled, floor);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user