feat(web): "Assistants IA" page: tokens, connection help, action journal (#205)

The page where a user of the pilot creates, limits and revokes agent
tokens, finds how to connect an assistant, and sees what each token wrote.

- app/(app)/assistants/page.tsx: server component; no session redirects to
  /auth, an account outside the pilot gets notFound() before anything is
  read; it reads the tokens and the first 50 lines of the journal at one
  instant and sends plain data to the client components.
- components/Assistants*.tsx: five blocks (warning, tokens and creation
  form, the token just created, connection help, journal). The value of a
  token lives in the state of AssistantsPanel only.
- GET /api/agent-actions: requireAssistantsSession(), the `read` limit, a
  validated `?before=` cursor (400 when it is not one), 50 lines per page.
- lib/assistants.ts: label keys, connection templates, what the browser
  receives, the journal cursor, and the dates as pure functions of the
  instant, the locale and the time zone. Type-only imports: it goes to the
  browser.
- Header.tsx: `showAssistants` adds the menu entry, which (app)/layout.tsx
  sets from mcpAllowed().
- i18n: the 65 texts of the issue under `assistants`, generated from its
  two tables; parity.test.ts compares fr.json and en.json.

Resolves #205

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-15 17:06:27 -05:00
commit e3a5dd2281
16 changed files with 2624 additions and 3 deletions

View file

@ -0,0 +1,328 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID as u } from 'node:crypto';
import { isValidElement, type ReactElement, type ReactNode } from 'react';
import { describe, it, expect, beforeAll, beforeEach, afterAll, afterEach, vi } from 'vitest';
import type { PGlite } from 'electric-sql-pglite';
// The server side of the « Assistants IA » page (#205): the real page and the
// real layout of the app, called as functions, against an in-memory Postgres
// (PGlite) with the companion migrations. The real pilot, the real token and
// journal queries run. Nothing is rendered: the tests read the element each
// function returns, that is, what the server sends to the client components.
// Replaced: the Logto session helper, next/headers (agentAccess.ts imports
// it), redirect() and notFound(), which throw here as they do in Next, and
// the client components, which only serve as markers.
const h = await vi.hoisted(async () => {
const { PGlite } = await import('electric-sql-pglite');
// logto.ts reads the variable once, when it is first loaded.
const initialBaseUrl = process.env.LOGTO_BASE_URL;
process.env.LOGTO_BASE_URL = 'https://liste.example.test/ignored/path';
return {
pg: new PGlite() as PGlite,
session: null as { userId: string; name?: string } | null,
initialBaseUrl,
};
});
vi.mock('@/db/client', async () => {
const { drizzle } = await import('drizzle-orm/pglite');
const schema = await import('@/db/schema');
return { db: drizzle(h.pg, { schema }) };
});
vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => h.session }));
vi.mock('next/headers', () => ({ headers: async () => new Headers() }));
vi.mock('next/navigation', () => ({
redirect: (to: string) => {
throw new Error(`REDIRECT ${to}`);
},
notFound: () => {
throw new Error('NOT_FOUND');
},
}));
vi.mock('@/components/AssistantsPanel', () => ({ AssistantsPanel: () => null }));
vi.mock('@/components/Sidebar', () => ({ Sidebar: () => null }));
vi.mock('@/components/Header', () => ({ Header: () => null }));
vi.mock('@/components/AppShell', () => ({ AppShell: () => null }));
const { default: AssistantsPage } = await import('./page');
const { default: AppLayout } = await import('../layout');
const { AssistantsPanel } = await import('@/components/AssistantsPanel');
const { Header } = await import('@/components/Header');
const { db } = await import('@/db/client');
const { recordAction } = await import('@/lib/agentJournal');
const { MAX_AGENT_TOKENS } = await import('@/lib/agentTokens');
const MINUTE_MS = 60 * 1000;
const DAY_MS = 24 * 60 * MINUTE_MS;
type TokenProps = {
id: string; name: string; scope: string; hint: string;
createdAt: string; lastUsedAt: string | null; expiresAt: string | null; expired: boolean;
};
type LineProps = { id: string; tool: string; tokenName: string; tokenRevoked: boolean; entityName: string | null; createdAt: string };
type PanelProps = {
tokens: TokenProps[];
atLimit: boolean;
journal: { actions: LineProps[]; nextCursor: string | null };
serverUrl: string;
};
const initialPilot = process.env.MCP_ALLOWED_SUBS;
function pilot(value: string | undefined) {
if (value === undefined) delete process.env.MCP_ALLOWED_SUBS;
else process.env.MCP_ALLOWED_SUBS = value;
}
// Each test creates its own accounts (#148), with invented ids.
const newAccount = () => `user-${u()}`;
const sha256 = (value: string) => createHash('sha256').update(value).digest('hex');
type TokenFields = { name?: string; scope?: string; createdAt?: Date; lastUsedAt?: Date; expiresAt?: Date };
// A token row written straight to the table; returns its id and its hash.
async function seedToken(userId: string, fields: TokenFields = {}) {
const [id, hash] = [u(), sha256(u())];
await h.pg.query(
'insert into sl_agent_tokens (id, user_id, name, token_hash, hint, scope, created_at, last_used_at, expires_at) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)',
[
id, userId, fields.name ?? 'Assistant', hash, hash.slice(0, 4), fields.scope ?? 'read',
(fields.createdAt ?? new Date()).toISOString(), fields.lastUsedAt?.toISOString() ?? null, fields.expiresAt?.toISOString() ?? null,
],
);
return { id, hash };
}
async function seedTask(userId: string, title: string): Promise<string> {
const [listId, id] = [u(), u()];
await h.pg.query('insert into sl_lists (id, user_id, name) values ($1, $2, $3)', [listId, userId, 'List']);
await h.pg.query('insert into sl_tasks (id, user_id, title, list_id) values ($1, $2, $3, $4)', [id, userId, title, listId]);
return id;
}
// `count` journal lines of the account, a minute apart, the newest a minute ago.
async function seedLines(userId: string, count: number, entityId: string = u(), tokenName = 'Assistant'): Promise<string[]> {
for (let i = 0; i < count; i++) {
await recordAction(db, { userId, tokenId: null, tokenName, tool: 'update_task', entityType: 'task', entityId }, new Date(Date.now() - (i + 1) * MINUTE_MS));
}
const { rows } = await h.pg.query<{ id: string }>(
"select id from sl_agent_actions where user_id = $1 order by date_trunc('milliseconds', created_at) desc, id desc", [userId]);
return rows.map((row) => row.id);
}
// The element of this type in what a server component returned, null without one.
function find(node: ReactNode, type: unknown): ReactElement | null {
if (Array.isArray(node)) {
for (const child of node) {
const found = find(child, type);
if (found) return found;
}
return null;
}
if (!isValidElement(node)) return null;
if (node.type === type) return node;
return find((node.props as { children?: ReactNode }).children, type);
}
// What the page sends to the panel, for the session of `userId`.
async function panelOf(userId: string): Promise<PanelProps> {
h.session = { userId };
const element = await AssistantsPage();
expect(isValidElement(element)).toBe(true);
expect(element.type).toBe(AssistantsPanel);
return element.props as PanelProps;
}
// Whether the layout shows the menu entry to the session of `userId`.
async function menuEntryOf(userId: string): Promise<unknown> {
h.session = { userId, name: 'Someone' };
const header = find(await AppLayout({ children: null }), Header);
expect(header).not.toBeNull();
return (header!.props as { showAssistants?: unknown }).showAssistants;
}
beforeAll(async () => {
const dir = path.join(__dirname, '../../../db/migrations');
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) {
if (stmt.trim()) await h.pg.exec(stmt);
}
}
});
beforeEach(() => {
pilot('*');
h.session = null;
});
afterEach(() => {
vi.restoreAllMocks();
});
afterAll(() => {
pilot(initialPilot);
if (h.initialBaseUrl === undefined) delete process.env.LOGTO_BASE_URL;
else process.env.LOGTO_BASE_URL = h.initialBaseUrl;
});
describe('the page', () => {
it('redirects to /auth without a session', async () => {
h.session = null;
await expect(AssistantsPage()).rejects.toThrow('REDIRECT /auth');
});
it.each([
['absent', undefined],
['empty', ''],
['a list without the account', 'others'],
])('does not exist when MCP_ALLOWED_SUBS is %s: notFound(), before anything is read', async (_label, value) => {
const [A, B] = [newAccount(), newAccount()];
await seedToken(A);
await seedLines(A, 2);
pilot(value === 'others' ? `${B}, ${newAccount()}` : value);
h.session = { userId: A };
const queries = [vi.spyOn(h.pg, 'query'), vi.spyOn(h.pg, 'transaction'), vi.spyOn(h.pg, 'exec')];
await expect(AssistantsPage()).rejects.toThrow('NOT_FOUND');
expect(queries.map((spy) => spy.mock.calls.length)).toEqual([0, 0, 0]);
// Control: for an account of the pilot, the same spies see the page read.
pilot(A);
await AssistantsPage();
expect(queries[0].mock.calls.length).toBeGreaterThan(0);
});
it('exists for an account of the list, and for no other', async () => {
const [A, B] = [newAccount(), newAccount()];
pilot(` ${A} , ${newAccount()}`);
expect((await panelOf(A)).tokens).toEqual([]);
h.session = { userId: B };
await expect(AssistantsPage()).rejects.toThrow('NOT_FOUND');
});
it('sends the tokens of the account, named fields only, instants as ISO strings', async () => {
const [A, B] = [newAccount(), newAccount()];
const created = new Date(Date.now() - 100 * DAY_MS);
const used = new Date(Date.now() - 5 * MINUTE_MS);
const old = await seedToken(A, {
name: 'Hermes', scope: 'write', createdAt: created, lastUsedAt: used, expiresAt: new Date(created.getTime() + 90 * DAY_MS),
});
const recent = await seedToken(A, { name: 'Claude Code', expiresAt: new Date(Date.now() + 365 * DAY_MS) });
const never = await seedToken(A, { name: 'Sans fin', createdAt: new Date(Date.now() - DAY_MS) });
const foreign = await seedToken(B, { name: `Jeton de B ${u()}` });
const props = await panelOf(A);
// Newest first.
expect(props.tokens.map((token) => token.id)).toEqual([recent.id, never.id, old.id]);
expect(props.tokens[2]).toEqual({
id: old.id,
name: 'Hermes',
scope: 'write',
hint: old.hash.slice(0, 4),
createdAt: created.toISOString(),
lastUsedAt: used.toISOString(),
expiresAt: new Date(created.getTime() + 90 * DAY_MS).toISOString(),
// Expired ten days ago.
expired: true,
});
expect(props.tokens[0]).toMatchObject({ name: 'Claude Code', scope: 'read', lastUsedAt: null, expired: false });
expect(props.tokens[1]).toMatchObject({ name: 'Sans fin', expiresAt: null, expired: false });
expect(props.atLimit).toBe(false);
// Neither a hash, nor the account, nor anything of another account.
const sent = JSON.stringify(props);
for (const hidden of [A, B, old.hash, recent.hash, never.hash, foreign.id, foreign.hash]) expect(sent).not.toContain(hidden);
expect(sent).not.toContain('Jeton de B');
// What the server sends is plain data: nothing is lost on the way to the browser.
expect(JSON.parse(sent)).toEqual(props);
});
it('says when the account holds as many tokens as it may, expired ones counted', async () => {
const A = newAccount();
await seedToken(A, { expiresAt: new Date(Date.now() - DAY_MS) });
for (let i = 1; i < MAX_AGENT_TOKENS - 1; i++) await seedToken(A);
expect((await panelOf(A)).atLimit).toBe(false);
await seedToken(A);
const props = await panelOf(A);
expect(props.tokens).toHaveLength(10);
expect(props.atLimit).toBe(true);
});
it('sends the first 50 lines of the journal of the account, and the cursor of the next ones', async () => {
const [A, B] = [newAccount(), newAccount()];
const title = `Tâche de A ${u()}`;
const ids = await seedLines(A, 55, await seedTask(A, title), 'Hermes');
const foreignTitle = `Tâche de B ${u()}`;
const foreignIds = await seedLines(B, 3, await seedTask(B, foreignTitle), `Jeton de B ${u()}`);
const { journal } = await panelOf(A);
expect(journal.actions.map((line) => line.id)).toEqual(ids.slice(0, 50));
expect(journal.actions[0]).toEqual({
id: ids[0], tool: 'update_task', tokenName: 'Hermes', tokenRevoked: true, entityName: title, createdAt: journal.actions[0].createdAt,
});
const last = journal.actions[49];
expect(journal.nextCursor).toBe(`${Date.parse(last.createdAt)}_${last.id}`);
const sent = JSON.stringify(journal);
for (const hidden of [A, B, foreignTitle, 'Jeton de B', ...foreignIds]) expect(sent).not.toContain(hidden);
expect(JSON.parse(sent)).toEqual(journal);
});
it('leaves out the lines older than 90 days', async () => {
const A = newAccount();
await recordAction(db, { userId: A, tokenId: null, tokenName: 'Assistant', tool: 'create_task', entityType: 'task', entityId: u() }, new Date(Date.now() - 90 * DAY_MS - 60 * MINUTE_MS));
await recordAction(db, { userId: A, tokenId: null, tokenName: 'Assistant', tool: 'update_task', entityType: 'task', entityId: u() }, new Date(Date.now() - 90 * DAY_MS + 60 * MINUTE_MS));
const { journal } = await panelOf(A);
expect(journal.actions.map((line) => line.tool)).toEqual(['update_task']);
expect(journal.nextCursor).toBeNull();
});
it('gives the address of the MCP server: the origin of the site, then the route', async () => {
expect((await panelOf(newAccount())).serverUrl).toBe('https://liste.example.test/api/mcp');
});
});
describe('the account menu', () => {
it.each([
['absent', undefined],
['empty', ''],
['a list without the account', 'others'],
])('has no entry when MCP_ALLOWED_SUBS is %s', async (_label, value) => {
const A = newAccount();
pilot(value === 'others' ? `${newAccount()}, ${newAccount()}` : value);
expect(await menuEntryOf(A)).toBe(false);
});
it('has the entry for every account when the pilot is open, and for the accounts of a list', async () => {
const [A, B] = [newAccount(), newAccount()];
expect(await menuEntryOf(A)).toBe(true);
pilot(`${newAccount()},${A}`);
expect(await menuEntryOf(A)).toBe(true);
expect(await menuEntryOf(B)).toBe(false);
});
it('redirects to /auth without a session', async () => {
h.session = null;
await expect(AppLayout({ children: null })).rejects.toThrow('REDIRECT /auth');
});
// The menu only opens on a click, which nothing renders here: its source is read instead.
it('Header.tsx draws the entry inside the `showAssistants` condition, above the sign-out link', () => {
const source = fs.readFileSync(path.join(__dirname, '../../../components/Header.tsx'), 'utf8');
const entry = source.indexOf('{showAssistants && (');
const link = source.indexOf('href="/assistants"');
const end = source.indexOf('</Link>', link);
const signOut = source.indexOf('href="/api/logto/sign-out"');
expect(entry).toBeGreaterThan(-1);
expect(source.match(/href="\/assistants"/g)).toHaveLength(1);
expect(source.match(/<Link\b/g)).toHaveLength(1);
// The condition opens on the link, and closes right after it.
expect(source.slice(entry, link)).toMatch(/^\{showAssistants && \(\s*<Link\s+$/);
expect(source.slice(end + '</Link>'.length)).toMatch(/^\s*\)\}/);
expect(source.slice(link, end)).toContain('t("assistants.title")');
expect(end).toBeLessThan(signOut);
});
});

View file

@ -0,0 +1,43 @@
export const dynamic = "force-dynamic";
import { notFound, redirect } from "next/navigation";
import { getAuthenticatedUser } from "@/lib/auth";
import { db } from "@/db/client";
import { mcpAllowed } from "@/lib/agentAccess";
import { listActions } from "@/lib/agentJournal";
import { listAgentTokens, MAX_AGENT_TOKENS } from "@/lib/agentTokens";
import { JOURNAL_PAGE_SIZE, journalPageView, mcpServerUrl, tokenView } from "@/lib/assistants";
import { logtoConfig } from "@/lib/logto";
import { AssistantsPanel } from "@/components/AssistantsPanel";
// The « Assistants IA » page (#205): the agent tokens of the signed-in
// account, how to connect an assistant, and what the tokens wrote. It exists
// for an account of the pilot only (MCP_ALLOWED_SUBS): for any other, it
// answers like a page that does not exist, before anything is read.
export default async function AssistantsPage() {
const user = await getAuthenticatedUser();
if (!user) redirect("/auth");
const userId = user.userId;
if (!mcpAllowed(userId)) notFound();
// One instant for the whole page: the 90 days of the journal and « Expiré »
// are decided on it, here, so that the browser has no clock to read. The
// dates themselves leave as instants and are formatted in the browser, in
// the user's time zone (this container runs in UTC).
const now = new Date();
const [tokens, journal] = await Promise.all([
listAgentTokens(userId),
listActions(db, userId, { limit: JOURNAL_PAGE_SIZE }, now),
]);
return (
<AssistantsPanel
tokens={tokens.map((token) => tokenView(token, now))}
// Expired tokens count, as in createAgentToken.
atLimit={tokens.length >= MAX_AGENT_TOKENS}
journal={journalPageView(journal)}
serverUrl={mcpServerUrl(logtoConfig.baseUrl)}
/>
);
}

View file

@ -2,6 +2,7 @@ export const dynamic = "force-dynamic";
import { redirect } from "next/navigation";
import { getAuthenticatedUser } from "@/lib/auth";
import { mcpAllowed } from "@/lib/agentAccess";
import { db } from "@/db/client";
import { slLists, slTags } from "@/db/schema";
import { eq, isNull, and, asc } from "drizzle-orm";
@ -37,7 +38,10 @@ export default async function AppLayout({
<div className="flex h-screen overflow-hidden">
<Sidebar lists={lists} tags={tags} />
<div className="flex-1 flex flex-col min-w-0">
<Header userName={user.name || user.email || ""} />
<Header
userName={user.name || user.email || ""}
showAssistants={mcpAllowed(user.userId)}
/>
<main className="flex-1 overflow-y-auto p-4 md:p-6">{children}</main>
</div>
</div>

View file

@ -0,0 +1,529 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID as u } from 'node:crypto';
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
import type { PGlite } from 'electric-sql-pglite';
// GET /api/agent-actions (#205): the real route, the real guard
// (requireAssistantsSession), the real pilot, the real journal queries and the
// real clock, against an in-memory Postgres (PGlite) with the companion
// migrations. Three modules are replaced, as in the test of the agent-token
// routes:
// - the Logto session helper gives the account of the test;
// - headers() of next/headers gives the headers of the test request
// (it throws outside a request);
// - the rate limiter records its calls and refuses on demand.
// Journal lines are written by the real recordAction, at an instant counted
// back from the real clock: the route reads the journal at the current time.
// Every request is sent to the container's host, as in production.
const h = await vi.hoisted(async () => {
const { PGlite } = await import('electric-sql-pglite');
return {
pg: new PGlite() as PGlite,
session: null as { userId: string } | null,
headers: new Headers(),
limits: [] as [userId: string, category: string][],
limited: false,
};
});
vi.mock('@/db/client', async () => {
const { drizzle } = await import('drizzle-orm/pglite');
const schema = await import('@/db/schema');
return { db: drizzle(h.pg, { schema }) };
});
vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => h.session }));
vi.mock('next/headers', () => ({ headers: async () => h.headers }));
vi.mock('@/lib/rateLimit', () => ({
rateLimit: (userId: string, category: string) => {
h.limits.push([userId, category]);
return h.limited ? Response.json({ error: 'Too many requests' }, { status: 429 }) : null;
},
}));
const { GET } = await import('./route');
const { db } = await import('@/db/client');
const { listActions, recordAction } = await import('@/lib/agentJournal');
const { createAgentToken } = await import('@/lib/agentTokens');
const { JOURNAL_PAGE_SIZE, journalPageView } = await import('@/lib/assistants');
// Origin of `request.url` in production: the container's, not the site's.
const CONTAINER = 'http://0.0.0.0:3000';
const MINUTE_MS = 60 * 1000;
const DAY_MS = 24 * 60 * MINUTE_MS;
const UNAUTHORIZED = { status: 401, json: { error: 'Unauthorized' } };
const NOT_FOUND = { status: 404, json: { error: 'Not found' } };
const INVALID_CURSOR = { status: 400, json: { error: 'Invalid cursor' } };
// Authorization headers the route refuses whatever they hold: a Logto access
// token (the mobile app's), a well-formed agent token, another scheme.
const AUTHORIZATIONS: [label: string, value: string][] = [
['a Logto access token', 'Bearer logto-access-token-of-the-test'],
['a well-formed agent token', `Bearer slmcp_${'A'.repeat(43)}`],
['another scheme', 'Basic not-a-credential'],
];
type Send = { authorization?: string; origin?: string };
type Answer = { status: number; text: string; json: unknown; headers: Headers };
type Line = { id: string; tool: string; tokenName: string; tokenRevoked: boolean; entityName: string | null; createdAt: string };
type Page = { actions: Line[]; nextCursor: string | null };
type Entry = {
tokenId?: string | null;
tokenName?: string;
tool?: string;
entityType?: 'task' | 'list' | 'tag';
entityId?: string;
};
const initialPilot = process.env.MCP_ALLOWED_SUBS;
function pilot(value: string | undefined) {
if (value === undefined) delete process.env.MCP_ALLOWED_SUBS;
else process.env.MCP_ALLOWED_SUBS = value;
}
// Each test creates its own accounts (#148): the file passes in any order.
// Invented ids: no real `sub` in the repository.
const newAccount = () => `user-${u()}`;
// An instant `minutes` before the real clock.
const minutesAgo = (minutes: number) => new Date(Date.now() - minutes * MINUTE_MS);
// The request of a session (`userId`, null without one), and the headers that
// next/headers gives the guard: the same object.
function request(userId: string | null, query: string, send: Send): Request {
h.session = userId === null ? null : { userId };
const headers = new Headers();
if (send.origin !== undefined) headers.set('origin', send.origin);
if (send.authorization !== undefined) headers.set('authorization', send.authorization);
h.headers = headers;
return new Request(`${CONTAINER}/api/agent-actions${query}`, { headers });
}
async function get(userId: string | null, query = '', send: Send = {}): Promise<Answer> {
const res = await GET(request(userId, query, send));
const text = await res.text();
return { status: res.status, text, json: text === '' ? null : JSON.parse(text) as unknown, headers: res.headers };
}
// One page of the journal of a session; `cursor` is the `nextCursor` of the page before.
async function page(userId: string, cursor?: string): Promise<Page> {
const a = await get(userId, cursor === undefined ? '' : `?before=${encodeURIComponent(cursor)}`);
expect(a.status).toBe(200);
return a.json as Page;
}
// Every page of the journal of a session, read as the « Plus anciennes » button reads them.
async function pagesOf(userId: string): Promise<Page[]> {
const pages = [await page(userId)];
while (pages[pages.length - 1].nextCursor !== null && pages.length < 20) {
pages.push(await page(userId, pages[pages.length - 1].nextCursor!));
}
return pages;
}
const idsOf = (pages: Page[]) => pages.flatMap((p) => p.actions.map((line) => line.id));
// A token row written straight to the table.
async function seedToken(userId: string, name = 'Assistant'): Promise<string> {
const id = u();
await h.pg.query(
'insert into sl_agent_tokens (id, user_id, name, token_hash, hint, scope) values ($1, $2, $3, $4, $5, $6)',
[id, userId, name, createHash('sha256').update(u()).digest('hex'), 'seed', 'write'],
);
return id;
}
async function seedTask(userId: string, title: string): Promise<string> {
const [listId, id] = [u(), u()];
await h.pg.query('insert into sl_lists (id, user_id, name) values ($1, $2, $3)', [listId, userId, 'List']);
await h.pg.query('insert into sl_tasks (id, user_id, title, list_id) values ($1, $2, $3, $4)', [id, userId, title, listId]);
return id;
}
// A journal line of the account, written by the real recordAction at `at`.
async function write(userId: string, at: Date, entry: Entry = {}): Promise<void> {
await recordAction(db, {
userId,
tokenId: entry.tokenId ?? null,
tokenName: entry.tokenName ?? 'Assistant',
tool: entry.tool ?? 'update_task',
entityType: entry.entityType ?? 'task',
entityId: entry.entityId ?? u(),
}, at);
}
// The ids of every line of an account as the table holds them, in the order
// the journal is read: the instant cut to the millisecond, then the id, both
// descending. Lines older than 90 days included.
async function stored(userId: string): Promise<string[]> {
const { rows } = await h.pg.query<{ id: string }>(
"select id from sl_agent_actions where user_id = $1 order by date_trunc('milliseconds', created_at) desc, id desc",
[userId],
);
return rows.map((row) => row.id);
}
beforeAll(async () => {
const dir = path.join(__dirname, '../../../db/migrations');
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) {
if (stmt.trim()) await h.pg.exec(stmt);
}
}
});
beforeEach(() => {
pilot('*');
h.session = null;
h.headers = new Headers();
h.limits = [];
h.limited = false;
});
afterAll(() => pilot(initialPilot));
describe('GET /api/agent-actions', () => {
it('returns the journal of the session, newest first, named fields only', async () => {
const A = newAccount();
const tokenId = await seedToken(A, 'Hermes');
const taskId = await seedTask(A, 'Acheter du lait');
const gone = u();
const [first, second, third] = [minutesAgo(30), minutesAgo(20), minutesAgo(10)];
await write(A, first, { tokenId, tokenName: 'Hermes', tool: 'create_task', entityId: taskId });
// A list that no longer exists, written by a token revoked since.
await write(A, second, { tokenId: null, tokenName: 'Ancien', tool: 'update_list', entityType: 'list', entityId: gone });
await write(A, third, { tokenId, tokenName: 'Hermes', tool: 'complete_task', entityId: taskId });
const ids = await stored(A);
const a = await get(A);
expect(a.status).toBe(200);
expect(a.json).toEqual({
actions: [
{ id: ids[0], tool: 'complete_task', tokenName: 'Hermes', tokenRevoked: false, entityName: 'Acheter du lait', createdAt: third.toISOString() },
{ id: ids[1], tool: 'update_list', tokenName: 'Ancien', tokenRevoked: true, entityName: null, createdAt: second.toISOString() },
{ id: ids[2], tool: 'create_task', tokenName: 'Hermes', tokenRevoked: false, entityName: 'Acheter du lait', createdAt: first.toISOString() },
],
nextCursor: null,
});
// Neither the account, nor the touched rows, nor the token id leave.
for (const hidden of [A, taskId, gone, tokenId]) expect(a.text).not.toContain(hidden);
expect(h.limits).toEqual([[A, 'read']]);
});
it('gives the first page the same shape as the page the server component reads', async () => {
const A = newAccount();
for (let i = 0; i < 3; i++) await write(A, minutesAgo(i + 1));
expect(await page(A)).toEqual(journalPageView(await listActions(db, A, { limit: JOURNAL_PAGE_SIZE })));
});
it('answers an account without a line with an empty page', async () => {
expect(await page(newAccount())).toEqual({ actions: [], nextCursor: null });
});
it('is a read: no Origin is asked for, and no CORS header is sent', async () => {
const A = newAccount();
await write(A, minutesAgo(1));
for (const origin of [undefined, 'https://liste.lacompagniemaximus.com', 'https://evil.example']) {
const a = await get(A, '', { origin });
expect(a.status).toBe(200);
expect(a.headers.get('access-control-allow-origin')).toBeNull();
}
});
});
describe('the session of the site only', () => {
it.each(AUTHORIZATIONS)('answers 401 to %s in an Authorization header, session or not', async (_label, authorization) => {
const A = newAccount();
await write(A, minutesAgo(1));
expect(await get(A, '', { authorization })).toMatchObject(UNAUTHORIZED);
expect(await get(null, '', { authorization })).toMatchObject(UNAUTHORIZED);
// Refused before the rate limiter is asked.
expect(h.limits).toEqual([]);
});
it('answers 401 to a live agent token of the account: a token cannot read the journal', async () => {
const A = newAccount();
const created = await createAgentToken(A, { name: 'Hermes', scope: 'write', duration: 'never' });
if (!created.ok) throw new Error('token not created');
await write(A, minutesAgo(1), { tokenId: created.row.id, tokenName: 'Hermes' });
const authorization = `Bearer ${created.token}`;
expect(await get(A, '', { authorization })).toMatchObject(UNAUTHORIZED);
expect(await get(null, '', { authorization })).toMatchObject(UNAUTHORIZED);
});
it('answers 401 without a session', async () => {
const A = newAccount();
await write(A, minutesAgo(1));
const a = await get(null);
expect(a).toMatchObject(UNAUTHORIZED);
expect(a.text).not.toContain('actions');
expect(h.limits).toEqual([]);
});
});
describe('outside the pilot', () => {
it.each([
['absent', undefined],
['empty', ''],
['a list without the account', 'others'],
])('answers 404 when MCP_ALLOWED_SUBS is %s', async (_label, value) => {
const [A, B] = [newAccount(), newAccount()];
await write(A, minutesAgo(1));
const [id] = await stored(A);
pilot(value === 'others' ? `${B}, ${newAccount()}` : value);
const a = await get(A);
expect(a).toMatchObject(NOT_FOUND);
expect(a.text).not.toContain(id);
// With a cursor too, well-formed or not: the pilot is checked first.
expect(await get(A, `?before=${Date.now()}_${id}`)).toMatchObject(NOT_FOUND);
expect(await get(A, '?before=nonsense')).toMatchObject(NOT_FOUND);
// The rate limiter was never asked.
expect(h.limits).toEqual([]);
});
it('opens to the accounts of the list, and to no other', async () => {
const [A, B] = [newAccount(), newAccount()];
await write(A, minutesAgo(1));
await write(B, minutesAgo(1));
pilot(` ${A} , ${newAccount()}`);
expect((await get(A)).status).toBe(200);
expect(await get(B)).toMatchObject(NOT_FOUND);
});
it('answers 401, not 404, to an Authorization header and to a missing session', async () => {
const A = newAccount();
pilot('');
expect(await get(A, '', { authorization: AUTHORIZATIONS[0][1] })).toMatchObject(UNAUTHORIZED);
expect(await get(null)).toMatchObject(UNAUTHORIZED);
});
});
describe('rate limit', () => {
it('counts a read of the account, and answers 429 when the limit is reached', async () => {
const A = newAccount();
await write(A, minutesAgo(1));
expect((await get(A)).status).toBe(200);
h.limited = true;
const a = await get(A);
expect(a.status).toBe(429);
expect(a.text).not.toContain('actions');
expect(h.limits).toEqual([[A, 'read'], [A, 'read']]);
});
it('checks the session, then the rate limit, then the cursor', async () => {
const A = newAccount();
h.limited = true;
// Everything wrong at once: the Authorization header decides, before the
// rate limiter is even asked.
expect((await get(A, '?before=nonsense', { authorization: AUTHORIZATIONS[0][1] })).status).toBe(401);
expect(h.limits).toEqual([]);
// The rate limit before the cursor.
expect((await get(A, '?before=nonsense')).status).toBe(429);
h.limited = false;
// The cursor last.
expect((await get(A, '?before=nonsense')).status).toBe(400);
expect(h.limits).toEqual([[A, 'read'], [A, 'read']]);
});
});
describe('two accounts', () => {
it('never see the lines of each other', async () => {
// An account with a task and a token of its own, named like no other.
const account = async () => {
const userId = newAccount();
const [title, tokenName] = [`Tâche ${u()}`, `Jeton ${u()}`];
return { userId, title, tokenName, taskId: await seedTask(userId, title), tokenId: await seedToken(userId, tokenName) };
};
const [A, B] = [await account(), await account()];
// Sixty lines each, written at the same instants: more than a page.
for (let i = 0; i < 60; i++) {
const at = minutesAgo(i + 1);
for (const { userId, tokenId, tokenName, taskId } of [A, B]) {
await write(userId, at, { tokenId, tokenName, entityId: taskId });
}
}
const ids = new Map([[A, await stored(A.userId)], [B, await stored(B.userId)]]);
expect(ids.get(A)).toHaveLength(60);
expect(ids.get(B)).toHaveLength(60);
for (const [self, other] of [[A, B], [B, A]]) {
const first = await get(self.userId);
const firstPage = first.json as Page;
const second = await get(self.userId, `?before=${encodeURIComponent(firstPage.nextCursor!)}`);
const secondPage = second.json as Page;
// Its own sixty lines, in order, and nothing else.
expect([...firstPage.actions, ...secondPage.actions].map((line) => line.id)).toEqual(ids.get(self));
expect(secondPage.nextCursor).toBeNull();
const text = first.text + second.text;
for (const hidden of [other.userId, other.title, other.tokenName, other.taskId, other.tokenId, ...ids.get(other)!]) {
expect(text).not.toContain(hidden);
}
// Control: its own names are there, on every line.
expect(text.split(self.title)).toHaveLength(61);
expect(text.split(self.tokenName)).toHaveLength(61);
}
});
it('a cursor taken from the journal of another account opens none of its lines', async () => {
const [A, B] = [newAccount(), newAccount()];
for (let i = 0; i < 55; i++) {
await write(A, minutesAgo(2 * i + 1));
await write(B, minutesAgo(2 * i + 2));
}
const [idsA, idsB] = [await stored(A), await stored(B)];
const cursorOfA = (await page(A)).nextCursor!;
expect(cursorOfA).toContain(idsA[49]);
// B sends the cursor of A: it is a position in B's own journal. The 50th
// line of A was written 99 minutes ago: the lines of B older than that.
const answer = await page(B, cursorOfA);
expect(answer.actions.map((line) => line.id)).toEqual(idsB.slice(49));
for (const id of idsA) expect(JSON.stringify(answer)).not.toContain(id);
});
it('a line that names the row of another account shows no name', async () => {
const [A, B] = [newAccount(), newAccount()];
const title = `Tâche de B ${u()}`;
// No tool writes such a line: the journal still joins on the account.
await write(A, minutesAgo(1), { entityId: await seedTask(B, title) });
const a = await get(A);
expect((a.json as Page).actions).toMatchObject([{ entityName: null }]);
expect(a.text).not.toContain(title);
});
});
describe('pages', () => {
it('reads 50 lines per page, without a gap or a repeat, across lines of the same instant', async () => {
const A = newAccount();
// 30 lines a minute apart, then 90 at one instant, then 10 older ones.
const same = minutesAgo(100);
for (let i = 0; i < 30; i++) await write(A, minutesAgo(i + 1));
for (let i = 0; i < 90; i++) await write(A, same);
for (let i = 0; i < 10; i++) await write(A, minutesAgo(200 + i));
const ids = await stored(A);
expect(ids).toHaveLength(130);
const pages = await pagesOf(A);
expect(pages.map((p) => p.actions.length)).toEqual([50, 50, 30]);
expect(idsOf(pages)).toEqual(ids);
expect(new Set(idsOf(pages)).size).toBe(130);
expect(pages[2].nextCursor).toBeNull();
// Both page breaks fall among the lines of the same instant.
for (const [before, after] of [[pages[0], pages[1]], [pages[1], pages[2]]]) {
expect(before.actions[49].createdAt).toBe(same.toISOString());
expect(after.actions[0].createdAt).toBe(same.toISOString());
}
// Newest first, all the way.
const instants = pages.flatMap((p) => p.actions.map((line) => Date.parse(line.createdAt)));
expect(instants).toEqual([...instants].sort((x, y) => y - x));
});
it('gives a cursor only when older lines follow', async () => {
const A = newAccount();
for (let i = 0; i < JOURNAL_PAGE_SIZE; i++) await write(A, minutesAgo(i + 1));
// Exactly one page: no cursor.
expect(await page(A)).toMatchObject({ nextCursor: null });
expect((await page(A)).actions).toHaveLength(50);
// One line more: a cursor, and a second page of one line.
await write(A, minutesAgo(500));
const ids = await stored(A);
const first = await page(A);
expect(first.actions.map((line) => line.id)).toEqual(ids.slice(0, 50));
const last = first.actions[49];
// The cursor is the position of the last line: its instant in milliseconds, then its id.
expect(first.nextCursor).toBe(`${Date.parse(last.createdAt)}_${last.id}`);
expect(await page(A, first.nextCursor!)).toEqual({
actions: [expect.objectContaining({ id: ids[50] })],
nextCursor: null,
});
});
it('a cursor is a position: before everything it gives nothing, after everything the first page', async () => {
const A = newAccount();
for (let i = 0; i < 3; i++) await write(A, minutesAgo(i + 1));
const ids = await stored(A);
const id = u();
expect(await page(A, `0_${id}`)).toEqual({ actions: [], nextCursor: null });
expect((await page(A, `${Date.now() + DAY_MS}_${id}`)).actions.map((line) => line.id)).toEqual(ids);
// The last instant a cursor may carry.
expect((await page(A, `253402300799999_${id}`)).actions.map((line) => line.id)).toEqual(ids);
});
});
describe('90 days', () => {
it('shows a line written less than 90 days ago, and no older one, on any page', async () => {
const A = newAccount();
const kept = new Date(Date.now() - 90 * DAY_MS + 60 * MINUTE_MS);
await write(A, minutesAgo(1), { tool: 'create_task' });
await write(A, kept, { tool: 'update_task' });
await write(A, new Date(Date.now() - 90 * DAY_MS - 60 * MINUTE_MS), { tool: 'create_list', entityType: 'list' });
await write(A, new Date(Date.now() - 200 * DAY_MS), { tool: 'create_tag', entityType: 'tag' });
const ids = await stored(A);
expect(ids).toHaveLength(4);
const a = await get(A);
const first = a.json as Page;
expect(first.actions.map((line) => line.tool)).toEqual(['create_task', 'update_task']);
expect(first.actions[1].createdAt).toBe(kept.toISOString());
expect(first.nextCursor).toBeNull();
for (const id of ids.slice(2)) expect(a.text).not.toContain(id);
// A cursor placed on the last line shown does not reach the older ones.
const beyond = await get(A, `?before=${kept.getTime()}_${ids[1]}`);
expect(beyond.json).toEqual({ actions: [], nextCursor: null });
});
it('does not count the old lines in a page', async () => {
const A = newAccount();
// 50 recent lines and 20 old ones: one full page, and no cursor.
for (let i = 0; i < 50; i++) await write(A, minutesAgo(i + 1));
for (let i = 0; i < 20; i++) await write(A, new Date(Date.now() - 91 * DAY_MS - i * MINUTE_MS));
const pages = await pagesOf(A);
expect(pages.map((p) => p.actions.length)).toEqual([50]);
expect(idsOf(pages)).toEqual((await stored(A)).slice(0, 50));
});
});
describe('a cursor that is not one', () => {
const ID = '22222222-2222-4222-8222-222222222222';
it.each([
['an empty value', ''],
['a word', 'nonsense'],
['an instant alone', '1794670330123'],
['an id alone', ID],
['an id that is not a uuid', '1794670330123_not-a-uuid'],
['an instant that is not a number', `NaN_${ID}`],
['an ISO instant', `2026-11-14T15:32:10.123Z_${ID}`],
['a negative instant', `-1_${ID}`],
['the first millisecond of year 10000', `253402300800000_${ID}`],
['an instant no Date can hold', `999999999999999_${ID}`],
['an instant of sixteen digits', `8640000000000001_${ID}`],
['SQL in the id', `1794670330123_${ID}' OR '1'='1`],
['a cursor sent twice', `1794670330123_${ID},1794670330123_${ID}`],
])('answers 400 to %s, never 500', async (_label, value) => {
const A = newAccount();
await write(A, minutesAgo(1));
const a = await get(A, `?before=${encodeURIComponent(value)}`);
expect(a).toMatchObject(INVALID_CURSOR);
expect(a.text).not.toContain('actions');
});
it('reads the first `before` of the query, and refuses it when it is not a cursor', async () => {
const A = newAccount();
await write(A, minutesAgo(1));
const [id] = await stored(A);
expect(await get(A, `?before=nonsense&before=${Date.now()}_${id}`)).toMatchObject(INVALID_CURSOR);
// Another parameter is ignored.
expect((await get(A, '?after=nonsense&limit=1000')).json).toMatchObject({ actions: [{ id }] });
});
});

View file

@ -0,0 +1,34 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { requireAssistantsSession } from '@/lib/agentAccess';
import { listActions } from '@/lib/agentJournal';
import { JOURNAL_PAGE_SIZE, decodeJournalCursor, journalPageView } from '@/lib/assistants';
import { rateLimit } from '@/lib/rateLimit';
// The journal of what the agent tokens of the signed-in account wrote (#205),
// by pages of 50 lines, newest first: the « Assistants IA » page reads its
// first page itself and asks this route for the older ones.
//
// Like the routes of the agent tokens, it does not call requireAuth():
// requireAssistantsSession() takes the session of the site only, refuses any
// Authorization header, and answers 404 outside the pilot. Order of the
// checks: session, rate limit, cursor.
export async function GET(request: Request) {
const auth = await requireAssistantsSession();
if (auth.error) return auth.error;
const rl = rateLimit(auth.userId, 'read');
if (rl) return rl;
// `?before=` is the `nextCursor` of the previous page. It comes back from
// the client: listActions would throw on a cursor that is not one.
const before = new URL(request.url).searchParams.get('before');
const cursor = before === null ? null : decodeJournalCursor(before);
if (before !== null && cursor === null) {
return NextResponse.json({ error: 'Invalid cursor' }, { status: 400 });
}
// listActions filters on the account and on the 90 days; journalPageView
// names the fields that leave.
const page = await listActions(db, auth.userId, { before: cursor, limit: JOURNAL_PAGE_SIZE });
return NextResponse.json(journalPageView(page));
}

View file

@ -0,0 +1,102 @@
"use client";
import { useTranslation } from "react-i18next";
import {
TOKEN_PLACEHOLDER,
claudeCodeTemplate,
codeSpans,
genericTemplate,
hermesTemplate,
} from "@/lib/assistants";
// Block 4 of the « Assistants IA » page (#205): the address of the MCP
// server and four collapsible connection helps. While a token has just been
// created, the templates carry it (`token`); otherwise they carry the
// placeholder, and a sentence says to replace it.
// A text whose code parts are written between backticks (assistants.ts).
function CodeText({ text }: { text: string }) {
return (
<>
{codeSpans(text).map((part, index) =>
part.code ? (
<code key={index} className="font-mono text-xs">
{part.text}
</code>
) : (
<span key={index}>{part.text}</span>
),
)}
</>
);
}
// A block to copy. It scrolls sideways inside its frame instead of widening
// the page.
function Template({ text }: { text: string }) {
return (
<pre className="overflow-x-auto border border-border-light dark:border-border-dark rounded p-2 font-mono text-xs bg-surface-light dark:bg-surface-dark">
<code>{text}</code>
</pre>
);
}
function Help({ title, children }: { title: string; children: React.ReactNode }) {
return (
<details className="border border-border-light dark:border-border-dark rounded-lg px-3 py-2">
<summary className="cursor-pointer text-sm font-medium">{title}</summary>
<div className="pt-2 space-y-2 text-sm">{children}</div>
</details>
);
}
interface AssistantsConnectProps {
serverUrl: string;
// The token that was just created, null otherwise.
token: string | null;
}
export function AssistantsConnect({ serverUrl, token }: AssistantsConnectProps) {
const { t } = useTranslation();
const value = token ?? TOKEN_PLACEHOLDER;
return (
<section className="space-y-3">
<h3 className="font-semibold">{t("assistants.connect.heading")}</h3>
<div className="space-y-1">
<p className="text-xs text-foreground/50">{t("assistants.connect.url")}</p>
<Template text={serverUrl} />
</div>
{token === null && (
<p className="text-sm text-foreground/60">
<CodeText text={t("assistants.connect.replace")} />
</p>
)}
<Help title={t("assistants.connect.hermes")}>
<p>
<CodeText text={t("assistants.connect.hermesHint")} />
</p>
<Template text={hermesTemplate(serverUrl, value)} />
</Help>
<Help title={t("assistants.connect.claudeCode")}>
<p>{t("assistants.connect.claudeCodeHint")}</p>
<Template text={claudeCodeTemplate(serverUrl, value)} />
</Help>
<Help title={t("assistants.connect.claude")}>
<p>{t("assistants.connect.claudeSteps")}</p>
</Help>
<Help title={t("assistants.connect.generic")}>
<p>{t("assistants.connect.genericHint")}</p>
<Template text={genericTemplate(serverUrl, value)} />
</Help>
<p className="text-xs text-foreground/50">{t("assistants.connect.chatgpt")}</p>
</section>
);
}

View file

@ -0,0 +1,48 @@
"use client";
import { useRef, useState } from "react";
import { Check, Copy } from "lucide-react";
import { useTranslation } from "react-i18next";
// Block 3 of the « Assistants IA » page (#205): the value of the token that
// was just created, shown once. It arrives as a prop from the state of
// AssistantsPanel and is copied nowhere else. The panel keys this component
// by the token: a second creation starts again from « Copier ».
export function AssistantsCreated({ token }: { token: string }) {
const { t } = useTranslation();
const [copied, setCopied] = useState(false);
const value = useRef<HTMLElement>(null);
const copy = async () => {
try {
// navigator.clipboard only exists in a secure context (https, or
// localhost), and the browser may refuse the write.
await navigator.clipboard.writeText(token);
setCopied(true);
} catch {
// No text was validated for a copy that fails: the button keeps
// « Copier », and the value is selected, ready to be copied by hand.
setCopied(false);
if (value.current) window.getSelection()?.selectAllChildren(value.current);
}
};
return (
<section className="border border-bleu rounded-lg p-4 space-y-3 bg-surface-light dark:bg-surface-dark">
<h3 className="font-semibold">{t("assistants.created.heading")}</h3>
{/* One tap selects the whole value (select-all); it wraps instead of widening the page. */}
<code ref={value} className="block font-mono text-sm break-all select-all">
{token}
</code>
<p className="text-sm">{t("assistants.created.once")}</p>
<button
type="button"
onClick={copy}
className="flex items-center gap-2 px-3 py-1.5 text-sm bg-bleu text-white rounded-lg hover:bg-bleu/90 transition-colors"
>
{copied ? <Check size={14} /> : <Copy size={14} />}
{t(copied ? "assistants.created.copied" : "assistants.created.copy")}
</button>
</section>
);
}

View file

@ -0,0 +1,127 @@
"use client";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
actionLabelKey,
formatDayTime,
type DateLocale,
type JournalLine,
type JournalPageView,
} from "@/lib/assistants";
// Block 5 of the « Assistants IA » page (#205): what the tokens of the
// account wrote, newest first, 50 lines at a time. The first page comes from
// the server component and follows router.refresh(); « Plus anciennes » asks
// GET /api/agent-actions for the next ones. The panel keys this component
// (journalKey): when the first page or the tokens change, it starts again
// from the first page, and an answer still on its way is dropped with the
// component that asked for it.
interface AssistantsJournalProps {
first: JournalPageView;
locale: DateLocale;
// null until the browser's zone is known: no date is shown before.
timeZone: string | null;
}
export function AssistantsJournal({ first, locale, timeZone }: AssistantsJournalProps) {
const { t } = useTranslation();
const [older, setOlder] = useState<JournalLine[]>([]);
// Where the next page starts; null once the last one is shown.
const [cursor, setCursor] = useState(first.nextCursor);
const [busy, setBusy] = useState(false);
const [loadError, setLoadError] = useState(false);
const loadOlder = async () => {
if (busy || cursor === null) return;
setBusy(true);
setLoadError(false);
try {
const res = await fetch(`/api/agent-actions?before=${encodeURIComponent(cursor)}`);
if (!res.ok) {
setLoadError(true);
return;
}
const page = (await res.json()) as JournalPageView;
setOlder((lines) => [...lines, ...page.actions]);
setCursor(page.nextCursor);
} catch {
setLoadError(true);
} finally {
setBusy(false);
}
};
const lines = [...first.actions, ...older];
return (
<section className="space-y-3">
<div className="space-y-1">
<h3 className="font-semibold">{t("assistants.journal.heading")}</h3>
<p className="text-xs text-foreground/50">{t("assistants.journal.retention")}</p>
</div>
{lines.length === 0 ? (
<p className="text-sm text-foreground/40">{t("assistants.journal.empty")}</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-xs text-left">
<thead>
<tr className="border-b border-border-light dark:border-border-dark text-foreground/50">
<th className="py-1 pr-3 font-medium">{t("assistants.journal.date")}</th>
<th className="py-1 pr-3 font-medium">{t("assistants.journal.token")}</th>
<th className="py-1 pr-3 font-medium">{t("assistants.journal.action")}</th>
<th className="py-1 font-medium">{t("assistants.journal.item")}</th>
</tr>
</thead>
<tbody>
{lines.map((line) => {
const labelKey = actionLabelKey(line.tool);
return (
<tr key={line.id} className="border-b border-border-light dark:border-border-dark align-top">
<td className="py-1.5 pr-3 whitespace-nowrap">
{timeZone && formatDayTime(line.createdAt, locale, timeZone)}
</td>
<td className="py-1.5 pr-3">
<span className="flex flex-wrap gap-1">
<span>{line.tokenName}</span>
{line.tokenRevoked && (
<span className="text-foreground/50">{t("assistants.journal.revoked")}</span>
)}
</span>
</td>
{/* A tool without a label is shown by its name, as the journal holds it. */}
<td className="py-1.5 pr-3">{labelKey ? t(labelKey) : line.tool}</td>
<td className="py-1.5">
{line.entityName ?? (
<span className="italic text-foreground/50">{t("assistants.journal.deleted")}</span>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
{loadError && (
<p role="alert" className="text-xs text-rouge">
{t("assistants.journal.loadError")}
</p>
)}
{cursor !== null && (
<button
type="button"
onClick={loadOlder}
disabled={busy}
className="text-xs text-bleu hover:underline disabled:opacity-50"
>
{t("assistants.journal.older")}
</button>
)}
</section>
);
}

View file

@ -0,0 +1,94 @@
"use client";
import { useState, useSyncExternalStore } from "react";
import { useTranslation } from "react-i18next";
import {
dateLocale,
journalKey,
type JournalPageView,
type TokenView,
} from "@/lib/assistants";
import { AssistantsTokens } from "./AssistantsTokens";
import { AssistantsCreated } from "./AssistantsCreated";
import { AssistantsConnect } from "./AssistantsConnect";
import { AssistantsJournal } from "./AssistantsJournal";
// The « Assistants IA » page (#205): five blocks, from top to bottom. The
// server component (app/(app)/assistants/page.tsx) reads the tokens and the
// first page of the journal; these components call the routes, then
// router.refresh(). Logic lives in web/src/lib/assistants.ts (tested); this
// JSX is not covered by tests.
// The value of a token that was just created, with the id of its row.
export type CreatedToken = { id: string; token: string };
// The time zone of the browser. React renders these components once on the
// server, in a container that runs in UTC, then hydrates that HTML: both
// passes read `null` here and format no date, so the first HTML never shows
// a UTC time and hydration finds the markup it expects. The zone is read
// right after, and the dates appear in the user's local time.
const subscribeToNothing = () => () => {};
const browserTimeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
const noTimeZone = () => null;
interface AssistantsPanelProps {
tokens: TokenView[];
// The account holds as many tokens as it may (MAX_AGENT_TOKENS).
atLimit: boolean;
// First page of the journal.
journal: JournalPageView;
// Address of the MCP server.
serverUrl: string;
}
export function AssistantsPanel({ tokens, atLimit, journal, serverUrl }: AssistantsPanelProps) {
const { t, i18n } = useTranslation();
// The only place the value of a token lives once POST /api/agent-tokens has
// answered: this state. It is never written to the address bar nor to any
// browser storage, and the server component never sends it. The page
// renders this component at a fixed place and without a key, so
// router.refresh() keeps the state; reloading the page erases it.
const [created, setCreated] = useState<CreatedToken | null>(null);
const timeZone = useSyncExternalStore<string | null>(subscribeToNothing, browserTimeZone, noTimeZone);
const locale = dateLocale(i18n.resolvedLanguage);
return (
<div className="max-w-2xl mx-auto w-full space-y-6">
<h2 className="text-xl font-semibold">{t("assistants.title")}</h2>
{/* 1. Warning, always visible */}
<p
role="note"
className="border border-border-light dark:border-border-dark border-l-[3px] border-l-sable rounded-lg p-4 text-sm bg-surface-light dark:bg-surface-dark"
>
{t("assistants.warning")}
</p>
{/* 2. Tokens and creation form */}
<AssistantsTokens
tokens={tokens}
atLimit={atLimit}
locale={locale}
timeZone={timeZone}
onCreated={setCreated}
// A token revoked right after its creation leaves the page with its row.
onRevoked={(id) => setCreated((current) => (current?.id === id ? null : current))}
/>
{/* 3. The token that was just created, shown once */}
{created && <AssistantsCreated key={created.id} token={created.token} />}
{/* 4. Connection help; its templates carry the new token while it is known */}
<AssistantsConnect serverUrl={serverUrl} token={created?.token ?? null} />
{/* 5. Journal. Keyed: the older pages it loaded are dropped when the
first page or the tokens change (journalKey). */}
<AssistantsJournal
key={journalKey(journal, tokens)}
first={journal}
locale={locale}
timeZone={timeZone}
/>
</div>
);
}

View file

@ -0,0 +1,262 @@
"use client";
import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import {
DEFAULT_TOKEN_DURATION,
DEFAULT_TOKEN_SCOPE,
DURATION_LABEL_KEYS,
SCOPE_LABEL_KEYS,
TOKEN_DURATIONS,
TOKEN_SCOPES,
formatDay,
formatDayTime,
validateTokenName,
type DateLocale,
type TokenDuration,
type TokenScope,
type TokenView,
} from "@/lib/assistants";
import type { CreatedToken } from "./AssistantsPanel";
// Block 2 of the « Assistants IA » page (#205): the tokens of the account,
// each with its « Révoquer » button, then the creation form, which the
// sentence `assistants.form.limit` replaces once the account holds ten.
const FIELD =
"bg-transparent border border-border-light dark:border-border-dark rounded px-2 py-1 text-sm focus:outline-none focus:border-bleu";
function TokenForm({ onCreated }: { onCreated: (created: CreatedToken) => void }) {
const { t } = useTranslation();
const router = useRouter();
const [name, setName] = useState("");
const [scope, setScope] = useState<TokenScope>(DEFAULT_TOKEN_SCOPE);
const [duration, setDuration] = useState<TokenDuration>(DEFAULT_TOKEN_DURATION);
// Key of the text to show, so that it follows the active language.
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const submit = async (event: FormEvent) => {
event.preventDefault();
if (busy) return;
const check = validateTokenName(name);
if (!check.ok) {
setError(check.reason === "empty" ? "assistants.form.nameRequired" : "assistants.form.nameTooLong");
return;
}
setBusy(true);
setError(null);
try {
const res = await fetch("/api/agent-tokens", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: check.name, scope, duration }),
});
if (res.status === 409) {
// The tenth token was created elsewhere since this page was read:
// the reloaded list replaces this form by the same sentence.
setError("assistants.form.limit");
router.refresh();
return;
}
if (!res.ok) {
setError("assistants.form.createError");
return;
}
const body = (await res.json()) as { id?: unknown; token?: unknown };
if (typeof body.id !== "string" || typeof body.token !== "string") {
setError("assistants.form.createError");
return;
}
// The only copy of the value: it goes to the state of the panel.
onCreated({ id: body.id, token: body.token });
setName("");
setScope(DEFAULT_TOKEN_SCOPE);
setDuration(DEFAULT_TOKEN_DURATION);
// Reloads the server data: the list shows the new token.
router.refresh();
} catch {
setError("assistants.form.createError");
} finally {
setBusy(false);
}
};
return (
<form
onSubmit={submit}
className="border border-border-light dark:border-border-dark rounded-lg p-4 space-y-3 bg-surface-light dark:bg-surface-dark"
>
<h4 className="text-sm font-semibold">{t("assistants.form.heading")}</h4>
<label className="flex flex-col gap-1 text-xs text-foreground/50">
{t("assistants.form.name")}
<input
value={name}
onChange={(e) => {
setName(e.target.value);
setError(null);
}}
placeholder={t("assistants.form.namePlaceholder")}
className={`w-full text-foreground placeholder:text-foreground/40 ${FIELD}`}
/>
</label>
<div className="flex flex-wrap items-center gap-3">
<label className="flex flex-col gap-1 text-xs text-foreground/50">
{t("assistants.form.scope")}
<select
value={scope}
onChange={(e) => setScope(e.target.value as TokenScope)}
className={`text-foreground ${FIELD}`}
>
{TOKEN_SCOPES.map((value) => (
<option key={value} value={value}>
{t(SCOPE_LABEL_KEYS[value])}
</option>
))}
</select>
</label>
<label className="flex flex-col gap-1 text-xs text-foreground/50">
{t("assistants.form.duration")}
<select
value={duration}
onChange={(e) => setDuration(e.target.value as TokenDuration)}
className={`text-foreground ${FIELD}`}
>
{TOKEN_DURATIONS.map((value) => (
<option key={value} value={value}>
{t(DURATION_LABEL_KEYS[value])}
</option>
))}
</select>
</label>
</div>
{error && (
<p role="alert" className="text-xs text-rouge">
{t(error)}
</p>
)}
<div className="flex justify-end">
<button
type="submit"
disabled={busy}
className="px-3 py-1.5 text-sm bg-bleu text-white rounded-lg hover:bg-bleu/90 disabled:opacity-50 transition-colors"
>
{t("assistants.form.submit")}
</button>
</div>
</form>
);
}
interface AssistantsTokensProps {
tokens: TokenView[];
atLimit: boolean;
locale: DateLocale;
// null until the browser's zone is known: no date is shown before.
timeZone: string | null;
onCreated: (created: CreatedToken) => void;
onRevoked: (tokenId: string) => void;
}
export function AssistantsTokens({ tokens, atLimit, locale, timeZone, onCreated, onRevoked }: AssistantsTokensProps) {
const { t } = useTranslation();
const router = useRouter();
const [busyId, setBusyId] = useState<string | null>(null);
const [revokeError, setRevokeError] = useState(false);
const revoke = async (token: TokenView) => {
if (busyId) return;
if (!window.confirm(t("assistants.tokens.revokeConfirm", { name: token.name }))) return;
setBusyId(token.id);
setRevokeError(false);
try {
const res = await fetch(`/api/agent-tokens/${token.id}`, { method: "DELETE" });
// 404: the token is already gone (revoked from another tab). The
// reloaded list says so better than an error would.
if (!res.ok && res.status !== 404) {
setRevokeError(true);
return;
}
onRevoked(token.id);
router.refresh();
} catch {
setRevokeError(true);
} finally {
setBusyId(null);
}
};
return (
<section className="space-y-3">
<h3 className="font-semibold">{t("assistants.tokens.heading")}</h3>
{tokens.length === 0 ? (
<p className="text-sm text-foreground/40">{t("assistants.tokens.empty")}</p>
) : (
<ul className="space-y-2">
{tokens.map((token) => (
<li
key={token.id}
className="border border-border-light dark:border-border-dark rounded-lg p-4 space-y-2 bg-surface-light dark:bg-surface-dark"
>
<div className="flex items-center justify-between gap-2">
<span className="text-sm font-medium truncate">{token.name}</span>
<button
type="button"
onClick={() => revoke(token)}
disabled={busyId !== null}
className="shrink-0 text-xs text-rouge hover:underline disabled:opacity-50"
>
{t("assistants.tokens.revoke")}
</button>
</div>
<div className="flex flex-wrap gap-3 text-xs text-foreground/50">
<span>{t(SCOPE_LABEL_KEYS[token.scope])}</span>
<span>{t("assistants.tokens.hint", { hint: token.hint })}</span>
</div>
<div className="flex flex-wrap gap-3 text-xs text-foreground/50">
{timeZone && (
<span>{t("assistants.tokens.created", { date: formatDay(token.createdAt, locale, timeZone) })}</span>
)}
{token.lastUsedAt === null ? (
<span>{t("assistants.tokens.neverUsed")}</span>
) : (
timeZone && (
<span>
{t("assistants.tokens.lastUsed", { date: formatDayTime(token.lastUsedAt, locale, timeZone) })}
</span>
)
)}
{token.expiresAt === null ? (
<span>{t("assistants.tokens.noExpiry")}</span>
) : (
timeZone && (
// `expired` was decided by the server on the instant, not on the day shown.
<span className={token.expired ? "text-rouge" : undefined}>
{t(token.expired ? "assistants.tokens.expired" : "assistants.tokens.expires", {
date: formatDay(token.expiresAt, locale, timeZone),
})}
</span>
)
)}
</div>
</li>
))}
</ul>
)}
{revokeError && (
<p role="alert" className="text-xs text-rouge">
{t("assistants.tokens.revokeError")}
</p>
)}
{atLimit ? (
<p className="text-sm text-foreground/60">{t("assistants.form.limit")}</p>
) : (
<TokenForm onCreated={onCreated} />
)}
</section>
);
}

View file

@ -1,15 +1,19 @@
"use client";
import { ThemeToggle } from "./ThemeToggle";
import { User, LogOut } from "lucide-react";
import { Bot, User, LogOut } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { useTranslation } from "react-i18next";
interface HeaderProps {
userName: string;
// The account is in the pilot of the AI assistants (#205): outside it, the
// menu has no entry for a page that answers 404.
showAssistants: boolean;
}
export function Header({ userName }: HeaderProps) {
export function Header({ userName, showAssistants }: HeaderProps) {
const { t } = useTranslation();
const [menuOpen, setMenuOpen] = useState(false);
@ -47,6 +51,16 @@ export function Header({ userName }: HeaderProps) {
<div className="px-3 py-2 text-xs text-foreground/50 truncate">
{userName}
</div>
{showAssistants && (
<Link
href="/assistants"
className="flex items-center gap-2 px-3 py-2 text-sm hover:bg-black/5 dark:hover:bg-white/10 transition-colors"
onClick={() => setMenuOpen(false)}
>
<Bot size={14} />
{t("assistants.title")}
</Link>
)}
<a
href="/api/logto/sign-out"
className="flex items-center gap-2 px-3 py-2 text-sm text-rouge hover:bg-rouge/10 transition-colors"

View file

@ -98,5 +98,88 @@
"title": "Welcome to Simpl-Liste",
"message": "Create your first list using the button in the sidebar.",
"loading": "Loading..."
},
"assistants": {
"title": "AI assistants",
"warning": "An AI assistant connected with this token can read your lists, your tasks (titles, notes, due dates) and your tags. With a \"Read and write\" token it can also add and edit them; it cannot delete anything, but its changes cannot be undone. What the assistant reads is sent to the provider of its AI model: you choose that assistant, Simpl-Liste sends nothing by itself. You can revoke this token at any time.",
"tokens": {
"heading": "Access tokens",
"empty": "No token yet.",
"hint": "ends with {{hint}}",
"created": "Created on {{date}}",
"lastUsed": "Last used: {{date}}",
"neverUsed": "Last used: never",
"expires": "Expires on {{date}}",
"noExpiry": "No expiration",
"expired": "Expired on {{date}}",
"revoke": "Revoke",
"revokeConfirm": "Revoke the token \"{{name}}\"? The assistant using it will lose access immediately.",
"revokeError": "The token could not be revoked."
},
"form": {
"heading": "Create a token",
"name": "Name",
"namePlaceholder": "For example: Hermes, Claude Code",
"scope": "Access level",
"duration": "Duration",
"submit": "Create token",
"nameRequired": "The name cannot be empty.",
"nameTooLong": "The name cannot exceed 100 characters.",
"createError": "The token could not be created.",
"limit": "You have 10 tokens, the maximum. Revoke one to create another."
},
"scope": {
"read": "Read only",
"write": "Read and write"
},
"duration": {
"90d": "90 days",
"1y": "1 year",
"never": "No expiration"
},
"created": {
"heading": "Your new token",
"once": "Copy it now: this token will not be shown again. Keep it like a password.",
"copy": "Copy",
"copied": "Copied"
},
"connect": {
"heading": "Connect an assistant",
"url": "Server address",
"replace": "Replace `slmcp_…` with your token.",
"hermes": "Hermes",
"claudeCode": "Claude Code",
"claude": "Claude (custom connector)",
"generic": "Other MCP client",
"chatgpt": "ChatGPT is not supported yet: it requires an account sign-in, planned for later.",
"hermesHint": "In `~/.hermes/config.yaml`:",
"claudeCodeHint": "In a terminal:",
"claudeSteps": "In Claude, open Customize, then Connectors, then \"Add custom connector\". Enter a name and the server address. At the \"Request headers\" step, add the Authorization header with the value Bearer followed by your token.",
"genericHint": "HTTP transport, at the server address above, with the header Authorization: Bearer followed by your token."
},
"journal": {
"heading": "Action log",
"retention": "What your assistants wrote, kept for 90 days.",
"empty": "No action yet.",
"date": "Date",
"token": "Token",
"action": "Action",
"item": "Item",
"revoked": "(revoked)",
"deleted": "deleted",
"older": "Older",
"loadError": "The log could not be loaded."
},
"action": {
"create_task": "Task created",
"update_task": "Task edited",
"complete_task": "Task completed",
"reopen_task": "Task reopened",
"set_task_tags": "Task tags changed",
"create_list": "List created",
"update_list": "List edited",
"create_tag": "Tag created",
"update_tag": "Tag edited"
}
}
}

View file

@ -98,5 +98,88 @@
"title": "Bienvenue sur Simpl-Liste",
"message": "Créez votre première liste en utilisant le bouton dans la barre latérale.",
"loading": "Chargement..."
},
"assistants": {
"title": "Assistants IA",
"warning": "Un assistant IA relié par ce jeton peut lire vos listes, vos tâches (titres, notes, échéances) et vos étiquettes. Avec un jeton « Lecture et écriture », il peut aussi en ajouter et les modifier ; il ne peut rien supprimer, mais ses modifications ne s'annulent pas. Ce que l'assistant lit est transmis au fournisseur de son modèle d'IA : c'est vous qui choisissez cet assistant, Simpl-Liste n'envoie rien de lui-même. Vous pouvez révoquer ce jeton à tout moment.",
"tokens": {
"heading": "Jetons d'accès",
"empty": "Aucun jeton pour le moment.",
"hint": "se termine par {{hint}}",
"created": "Créé le {{date}}",
"lastUsed": "Dernière utilisation : {{date}}",
"neverUsed": "Dernière utilisation : jamais",
"expires": "Expire le {{date}}",
"noExpiry": "Sans expiration",
"expired": "Expiré le {{date}}",
"revoke": "Révoquer",
"revokeConfirm": "Révoquer le jeton « {{name}} » ? L'assistant qui l'utilise perdra l'accès tout de suite.",
"revokeError": "Le jeton n'a pas pu être révoqué."
},
"form": {
"heading": "Créer un jeton",
"name": "Nom",
"namePlaceholder": "Par exemple : Hermes, Claude Code",
"scope": "Niveau",
"duration": "Durée",
"submit": "Créer le jeton",
"nameRequired": "Le nom ne peut pas être vide.",
"nameTooLong": "Le nom ne peut pas dépasser 100 caractères.",
"createError": "Le jeton n'a pas pu être créé.",
"limit": "Vous avez 10 jetons, le maximum. Révoquez-en un pour en créer un autre."
},
"scope": {
"read": "Lecture seule",
"write": "Lecture et écriture"
},
"duration": {
"90d": "90 jours",
"1y": "1 an",
"never": "Sans expiration"
},
"created": {
"heading": "Votre nouveau jeton",
"once": "Copiez-le maintenant : ce jeton ne sera plus affiché. Conservez-le comme un mot de passe.",
"copy": "Copier",
"copied": "Copié"
},
"connect": {
"heading": "Relier un assistant",
"url": "Adresse du serveur",
"replace": "Remplacez `slmcp_…` par votre jeton.",
"hermes": "Hermes",
"claudeCode": "Claude Code",
"claude": "Claude (connecteur personnalisé)",
"generic": "Autre client MCP",
"chatgpt": "ChatGPT n'est pas encore pris en charge : il exige une connexion par compte, prévue plus tard.",
"hermesHint": "Dans `~/.hermes/config.yaml` :",
"claudeCodeHint": "Dans un terminal :",
"claudeSteps": "Dans Claude, ouvrez Customize, puis Connectors, puis « Add custom connector ». Saisissez un nom et l'adresse du serveur. À l'étape « Request headers », ajoutez l'en-tête Authorization avec la valeur Bearer suivie de votre jeton.",
"genericHint": "Transport HTTP, à l'adresse du serveur ci-dessus, avec l'en-tête Authorization : Bearer suivi de votre jeton."
},
"journal": {
"heading": "Journal des actions",
"retention": "Ce que vos assistants ont écrit, conservé 90 jours.",
"empty": "Aucune action pour le moment.",
"date": "Date",
"token": "Jeton",
"action": "Action",
"item": "Élément",
"revoked": "(révoqué)",
"deleted": "supprimé",
"older": "Plus anciennes",
"loadError": "Le journal n'a pas pu être chargé."
},
"action": {
"create_task": "Tâche créée",
"update_task": "Tâche modifiée",
"complete_task": "Tâche complétée",
"reopen_task": "Tâche rouverte",
"set_task_tags": "Étiquettes de la tâche modifiées",
"create_list": "Liste créée",
"update_list": "Liste modifiée",
"create_tag": "Étiquette créée",
"update_tag": "Étiquette modifiée"
}
}
}

View file

@ -0,0 +1,49 @@
import { describe, it, expect } from 'vitest';
import fr from './fr.json';
import en from './en.json';
// The texts of the site (#205): fr.json and en.json hold the same keys, and
// no key is left without a text. Every failure names the keys in fault: each
// assertion compares a list of them with the empty list.
// Every leaf of a file, by its dotted key (`assistants.tokens.heading`).
function leaves(node: unknown, prefix = ''): [key: string, value: unknown][] {
if (node === null || typeof node !== 'object' || Array.isArray(node)) return [[prefix, node]];
return Object.entries(node).flatMap(([key, value]) => leaves(value, prefix === '' ? key : `${prefix}.${key}`));
}
// The interpolation variables of a text, sorted: `{{name}}` gives `name`.
function variables(text: unknown): string[] {
if (typeof text !== 'string') return [];
return [...text.matchAll(/\{\{\s*([^}\s]+)\s*\}\}/g)].map((match) => match[1]).sort();
}
const FILES = { fr: new Map(leaves(fr)), en: new Map(leaves(en)) };
describe('fr.json and en.json', () => {
it('hold the same keys', () => {
expect({
'in fr.json only': [...FILES.fr.keys()].filter((key) => !FILES.en.has(key)),
'in en.json only': [...FILES.en.keys()].filter((key) => !FILES.fr.has(key)),
}).toEqual({ 'in fr.json only': [], 'in en.json only': [] });
// Control: the comparison had something to read.
expect(FILES.fr.size).toBeGreaterThan(50);
});
it('hold no empty value: every key has a text', () => {
const empty = Object.entries(FILES).flatMap(([file, texts]) =>
[...texts]
.filter(([, value]) => typeof value !== 'string' || value.trim() === '')
.map(([key]) => `${file}.json: ${key}`));
expect(empty).toEqual([]);
});
it('use the same interpolation variables in both languages', () => {
const different = [...FILES.fr]
.filter(([key, text]) => variables(text).join() !== variables(FILES.en.get(key)).join())
.map(([key, text]) => `${key}: fr {${variables(text)}} en {${variables(FILES.en.get(key))}}`);
expect(different).toEqual([]);
// Control: some texts do carry a variable.
expect([...FILES.fr.values()].filter((text) => variables(text).length > 0).length).toBeGreaterThan(10);
});
});

View file

@ -0,0 +1,550 @@
import fs from 'node:fs';
import path from 'node:path';
import { describe, it, expect, vi } from 'vitest';
import fr from '@/i18n/fr.json';
import en from '@/i18n/en.json';
import type { JournalPage } from './agentJournal';
import type { AgentToken } from './agentTokens';
import {
ACTION_LABEL_KEYS, DEFAULT_TOKEN_DURATION, DEFAULT_TOKEN_SCOPE, DURATION_LABEL_KEYS, JOURNAL_PAGE_SIZE,
SCOPE_LABEL_KEYS, TOKEN_DURATIONS, TOKEN_NAME_MAX, TOKEN_PLACEHOLDER, TOKEN_SCOPES,
actionLabelKey, claudeCodeTemplate, codeSpans, dateLocale, decodeJournalCursor, encodeJournalCursor,
formatDay, formatDayTime, genericTemplate, hermesTemplate, isExpired, journalKey, journalPageView,
mcpServerUrl, tokenView, validateTokenName,
type JournalPageView, type TokenView,
} from './assistants';
// Helpers of the « Assistants IA » page (#205). assistants.ts goes to the
// browser, so it only imports types; this file may load the server modules
// it is compared with. WRITE_TOOL_NAMES lives in a module that imports the
// database client and the WebSocket notice: both are replaced, nothing here
// runs a query.
vi.mock('@/db/client', () => ({ db: {} }));
vi.mock('@/lib/ws', () => ({ notifyUserChanged: () => {} }));
const { WRITE_TOOL_NAMES } = await import('./mcp/writeTools');
const { createAgentTokenSchema } = await import('./validators');
const SOURCE = fs.readFileSync(path.join(__dirname, 'assistants.ts'), 'utf8');
const COMPONENTS = path.join(__dirname, '../components');
// The address of the site in production, and a token of the real shape.
const SERVER = 'https://liste.lacompagniemaximus.com/api/mcp';
const TOKEN = `slmcp_${'aB3-_xYz'.repeat(5)}Q9w`;
// The two blocks of issue #205, as Max validated them, comment line included.
const HERMES_BLOCK = `# Hermes — ~/.hermes/config.yaml
mcp_servers:
simpl-liste:
url: "https://liste.lacompagniemaximus.com/api/mcp"
headers:
Authorization: "Bearer slmcp_…"`;
const CLAUDE_CODE_BLOCK = `# Claude Code
claude mcp add --transport http simpl-liste https://liste.lacompagniemaximus.com/api/mcp --header "Authorization: Bearer slmcp_…"`;
const TEMPLATES = [
['hermesTemplate', hermesTemplate],
['claudeCodeTemplate', claudeCodeTemplate],
['genericTemplate', genericTemplate],
] as const;
type Texts = { [key: string]: string | Texts };
// The text of a dotted key in a language file, undefined when it has none.
function textOf(file: Texts, key: string): unknown {
return key.split('.').reduce<unknown>(
(node, part) => (node !== null && typeof node === 'object' ? (node as Texts)[part] : undefined),
file,
);
}
// Every dotted key under `assistants` in a language file.
function keysOf(node: Texts, prefix: string): string[] {
return Object.entries(node).flatMap(([key, value]) =>
typeof value === 'string' ? [`${prefix}.${key}`] : keysOf(value, `${prefix}.${key}`));
}
// Spaces as the test writes them: Intl may answer with no-break spaces.
const plain = (text: string) => text.replace(/\s/g, ' ');
const occurrences = (text: string, part: string) => text.split(part).length - 1;
function token(fields: Partial<AgentToken> = {}): AgentToken {
return {
id: '11111111-1111-4111-8111-111111111111',
name: 'Hermes',
scope: 'read',
hint: 'Q9w0',
createdAt: new Date('2026-11-14T15:32:10.123Z'),
lastUsedAt: null,
expiresAt: null,
...fields,
};
}
describe('what the browser loads', () => {
it('imports types only: zod, the database and the MCP server must not follow it to the browser', () => {
const imports = SOURCE.match(/^[ \t]*import\s[^;]*;/gm) ?? [];
// Control: the module does import the type of the write tool names.
expect(imports.some((line) => line.includes("'./mcp/writeTools'"))).toBe(true);
expect(imports.filter((line) => !/^import type \{[^}]*\} from '\.\/[A-Za-z/]+';$/.test(line))).toEqual([]);
expect(SOURCE).not.toMatch(/\bimport\(|\brequire\(|^\s*export\s.*\bfrom\s+['"]/m);
});
});
describe('creation form', () => {
it('offers the scopes and the durations of the schema, in the order of the form', () => {
expect([...TOKEN_SCOPES]).toEqual(createAgentTokenSchema.shape.scope.options);
expect([...TOKEN_DURATIONS]).toEqual(createAgentTokenSchema.shape.duration.options);
});
// Decision of Max, 2026-11-14.
it('preselects « Lecture seule » and « 1 an »', () => {
expect(DEFAULT_TOKEN_SCOPE).toBe('read');
expect(DEFAULT_TOKEN_DURATION).toBe('1y');
expect(textOf(fr, SCOPE_LABEL_KEYS[DEFAULT_TOKEN_SCOPE])).toBe('Lecture seule');
expect(textOf(fr, DURATION_LABEL_KEYS[DEFAULT_TOKEN_DURATION])).toBe('1 an');
});
it('has a label in both languages for every scope and every duration', () => {
expect(Object.keys(SCOPE_LABEL_KEYS)).toEqual([...TOKEN_SCOPES]);
expect(Object.keys(DURATION_LABEL_KEYS)).toEqual([...TOKEN_DURATIONS]);
for (const key of [...Object.values(SCOPE_LABEL_KEYS), ...Object.values(DURATION_LABEL_KEYS)]) {
expect(textOf(fr, key), key).toEqual(expect.stringMatching(/\S/));
expect(textOf(en, key), key).toEqual(expect.stringMatching(/\S/));
}
});
it.each([
['an empty name', '', 'empty'],
['a name made of spaces', ' \t ', 'empty'],
['a name of 101 characters', 'x'.repeat(101), 'tooLong'],
])('refuses %s, as the schema does', (_label, raw, reason) => {
expect(validateTokenName(raw)).toEqual({ ok: false, reason });
expect(createAgentTokenSchema.safeParse({ name: raw, scope: 'read', duration: '1y' }).success).toBe(false);
});
it.each([
['one character', 'x', 'x'],
['100 characters', 'x'.repeat(100), 'x'.repeat(100)],
['100 characters between spaces', ` ${'x'.repeat(100)}\t`, 'x'.repeat(100)],
['spaces inside the name', ' Claude Code ', 'Claude Code'],
])('accepts %s and trims it, as the schema does', (_label, raw, name) => {
expect(validateTokenName(raw)).toEqual({ ok: true, name });
expect(createAgentTokenSchema.parse({ name: raw, scope: 'read', duration: '1y' }).name).toBe(name);
});
it('bounds the name as the texts say', () => {
expect(TOKEN_NAME_MAX).toBe(100);
expect(textOf(fr, 'assistants.form.nameTooLong')).toContain(String(TOKEN_NAME_MAX));
expect(textOf(en, 'assistants.form.nameTooLong')).toContain(String(TOKEN_NAME_MAX));
});
});
describe('journal labels', () => {
it('has one label key per write tool of the MCP server', () => {
expect(Object.keys(ACTION_LABEL_KEYS).sort()).toEqual([...WRITE_TOOL_NAMES].sort());
// Control: the list of the server is the one this PR was written for.
expect(WRITE_TOOL_NAMES).toHaveLength(9);
});
it.each([...WRITE_TOOL_NAMES])('%s has its label in both languages', (tool) => {
const key = actionLabelKey(tool);
expect(key).toBe(`assistants.action.${tool}`);
expect(textOf(fr, key!)).toEqual(expect.stringMatching(/\S/));
expect(textOf(en, key!)).toEqual(expect.stringMatching(/\S/));
});
it('gives each tool a label of its own', () => {
for (const file of [fr, en]) {
const labels = WRITE_TOOL_NAMES.map((tool) => textOf(file, ACTION_LABEL_KEYS[tool]));
expect(new Set(labels).size).toBe(WRITE_TOOL_NAMES.length);
}
});
it.each(['delete_task', '', 'constructor', 'toString', '__proto__', 'CREATE_TASK'])(
'has no label for %j: the page shows the name of the tool',
(tool) => {
expect(actionLabelKey(tool)).toBeNull();
},
);
});
describe('connection templates', () => {
it('the Hermes template is the block of the issue, without its comment line', () => {
const [comment, ...block] = HERMES_BLOCK.split('\n');
expect(comment).toMatch(/^# Hermes /);
expect(hermesTemplate(SERVER)).toBe(block.join('\n'));
expect(block).toHaveLength(5);
});
it('the Claude Code template is the block of the issue, without its comment line', () => {
const [comment, ...block] = CLAUDE_CODE_BLOCK.split('\n');
expect(comment).toBe('# Claude Code');
expect(claudeCodeTemplate(SERVER)).toBe(block.join('\n'));
expect(block).toHaveLength(1);
});
it('the generic template is the address, then the Authorization header', () => {
expect(genericTemplate(SERVER)).toBe(`${SERVER}\nAuthorization: Bearer ${TOKEN_PLACEHOLDER}`);
});
it('the placeholder is the one the texts tell the user to replace', () => {
expect([...TOKEN_PLACEHOLDER].map((c) => c.codePointAt(0))).toEqual([
...[...'slmcp_'].map((c) => c.codePointAt(0)),
0x2026,
]);
for (const file of [fr, en]) {
const code = codeSpans(textOf(file, 'assistants.connect.replace') as string).filter((part) => part.code);
expect(code).toEqual([{ text: TOKEN_PLACEHOLDER, code: true }]);
}
});
it.each(TEMPLATES)('%s carries the placeholder once when no token is given', (_name, template) => {
expect(occurrences(template(SERVER), TOKEN_PLACEHOLDER)).toBe(1);
expect(template(SERVER)).toBe(template(SERVER, TOKEN_PLACEHOLDER));
});
it.each(TEMPLATES)('%s carries the token in the place of the placeholder, and nowhere else', (_name, template) => {
const filled = template(SERVER, TOKEN);
expect(filled).toBe(template(SERVER).split(TOKEN_PLACEHOLDER).join(TOKEN));
expect(occurrences(filled, TOKEN)).toBe(1);
expect(filled).not.toContain(TOKEN_PLACEHOLDER);
// The token follows `Bearer `, as the Authorization header wants it.
expect(filled).toContain(`Authorization: ${template === hermesTemplate ? '"' : ''}Bearer ${TOKEN}`);
});
it.each(TEMPLATES)('%s carries the address it is given, once', (_name, template) => {
const local = 'http://localhost:3000/api/mcp';
expect(occurrences(template(local, TOKEN), local)).toBe(1);
expect(template(local, TOKEN)).not.toContain('lacompagniemaximus');
expect(template(local, TOKEN)).toBe(template(SERVER, TOKEN).split(SERVER).join(local));
});
it('no other export takes a token: its value appears in the templates only', () => {
const takesToken = [...SOURCE.matchAll(/^export function (\w+)\(([^)]*)\)/gm)]
.filter((match) => /\btoken: string\b/.test(match[2]))
.map((match) => match[1]);
expect(takesToken.sort()).toEqual(['claudeCodeTemplate', 'genericTemplate', 'hermesTemplate']);
});
});
describe('mcpServerUrl', () => {
it.each([
['https://liste.lacompagniemaximus.com', SERVER],
['https://liste.lacompagniemaximus.com/', SERVER],
['https://liste.lacompagniemaximus.com/some/path?x=1#y', SERVER],
['http://localhost:3000', 'http://localhost:3000/api/mcp'],
['http://localhost:3150/', 'http://localhost:3150/api/mcp'],
])('the origin of %s, then the route', (baseUrl, expected) => {
expect(mcpServerUrl(baseUrl)).toBe(expected);
});
});
describe('code spans of a text', () => {
it('splits a text on its backticks', () => {
expect(codeSpans('Dans `~/.hermes/config.yaml` :')).toEqual([
{ text: 'Dans ', code: false },
{ text: '~/.hermes/config.yaml', code: true },
{ text: ' :', code: false },
]);
expect(codeSpans('`a` then `b`')).toEqual([
{ text: 'a', code: true },
{ text: ' then ', code: false },
{ text: 'b', code: true },
]);
});
it('leaves a text without backticks whole', () => {
expect(codeSpans('Dans un terminal :')).toEqual([{ text: 'Dans un terminal :', code: false }]);
expect(codeSpans('')).toEqual([]);
});
it('loses no character but the backticks', () => {
for (const file of [fr, en]) {
for (const key of ['assistants.connect.replace', 'assistants.connect.hermesHint']) {
const text = textOf(file, key) as string;
expect(codeSpans(text).map((part) => part.text).join('')).toBe(text.split('`').join(''));
expect(codeSpans(text).filter((part) => part.code)).toHaveLength(1);
}
}
});
});
describe('tokens sent to the browser', () => {
const NOW = new Date('2026-11-14T15:32:10.123Z');
it('names its fields, and sends instants as ISO strings', () => {
const view = tokenView(token({
scope: 'write',
lastUsedAt: new Date('2026-11-14T16:00:00.000Z'),
expiresAt: new Date('2027-11-14T15:32:10.123Z'),
}), NOW);
expect(view).toEqual({
id: '11111111-1111-4111-8111-111111111111',
name: 'Hermes',
scope: 'write',
hint: 'Q9w0',
createdAt: '2026-11-14T15:32:10.123Z',
lastUsedAt: '2026-11-14T16:00:00.000Z',
expiresAt: '2027-11-14T15:32:10.123Z',
expired: false,
});
expect(tokenView(token(), NOW)).toMatchObject({ lastUsedAt: null, expiresAt: null, expired: false });
});
it('leaves out a field it does not name', () => {
const row = { ...token(), tokenHash: 'not-for-the-browser', userId: 'not-for-the-browser' };
const view = tokenView(row, NOW);
expect(Object.keys(view).sort()).toEqual([
'createdAt', 'expired', 'expiresAt', 'hint', 'id', 'lastUsedAt', 'name', 'scope',
]);
expect(JSON.stringify(view)).not.toContain('not-for-the-browser');
});
// The comparison of verifyAgentToken: refused from the instant of expires_at.
it.each([
['one millisecond before its expiry', -1, false],
['at the very instant of its expiry', 0, true],
['one millisecond after its expiry', 1, true],
['a day after its expiry', 24 * 60 * 60 * 1000, true],
['a day before its expiry', -24 * 60 * 60 * 1000, false],
])('a token read %s: expired is %s', (_label, offset, expired) => {
const expiresAt = new Date('2026-11-15T04:59:59.999Z');
const now = new Date(expiresAt.getTime() + offset);
expect(isExpired(expiresAt, now)).toBe(expired);
expect(tokenView(token({ expiresAt }), now).expired).toBe(expired);
});
it('a token without expiry never expires', () => {
expect(isExpired(null, new Date('9999-12-31T23:59:59.999Z'))).toBe(false);
});
// The instant decides, not the day: this token expires at 23:59:59.999 in
// Toronto on November 14, which is already November 15 in UTC.
it('decides on the instant, whatever day it is in a time zone', () => {
const expiresAt = new Date('2026-11-15T04:59:59.999Z');
expect(formatDay(expiresAt.toISOString(), 'fr-CA', 'America/Toronto')).toBe('14 nov. 2026');
expect(formatDay(expiresAt.toISOString(), 'fr-CA', 'UTC')).toBe('15 nov. 2026');
// Earlier the same day in Toronto: not expired. A minute later, already
// the next day there: expired.
expect(isExpired(expiresAt, new Date('2026-11-14T13:00:00.000Z'))).toBe(false);
expect(isExpired(expiresAt, new Date('2026-11-15T05:00:59.999Z'))).toBe(true);
});
});
describe('journal sent to the browser', () => {
const ID = '22222222-2222-4222-8222-222222222222';
const page: JournalPage = {
actions: [{
id: ID,
tool: 'create_task',
entityType: 'task',
entityId: '33333333-3333-4333-8333-333333333333',
entityName: 'Acheter du lait',
tokenId: '44444444-4444-4444-8444-444444444444',
tokenName: 'Hermes',
tokenRevoked: false,
createdAt: new Date('2026-11-14T15:32:10.123Z'),
}],
nextCursor: { createdAt: new Date('2026-11-14T15:32:10.123Z'), id: ID },
};
it('names the fields of a line: neither the touched row, nor its type, nor the token id', () => {
const view = journalPageView(page);
expect(view).toEqual({
actions: [{
id: ID,
tool: 'create_task',
tokenName: 'Hermes',
tokenRevoked: false,
entityName: 'Acheter du lait',
createdAt: '2026-11-14T15:32:10.123Z',
}],
nextCursor: `1794670330123_${ID}`,
});
expect(JSON.stringify(view)).not.toContain('33333333');
expect(JSON.stringify(view)).not.toContain('44444444');
});
it('keeps a deleted item, a revoked token and the last page as they are', () => {
const view = journalPageView({
actions: [{ ...page.actions[0], entityName: null, tokenId: null, tokenRevoked: true }],
nextCursor: null,
});
expect(view.actions[0]).toMatchObject({ entityName: null, tokenRevoked: true });
expect(view.nextCursor).toBeNull();
expect(journalPageView({ actions: [], nextCursor: null })).toEqual({ actions: [], nextCursor: null });
});
it('shows 50 lines per page', () => {
expect(JOURNAL_PAGE_SIZE).toBe(50);
});
it('a cursor survives the round trip, to the millisecond', () => {
const cursor = { createdAt: new Date('2026-11-14T15:32:10.123Z'), id: ID };
const encoded = encodeJournalCursor(cursor);
expect(encoded).toBe(`1794670330123_${ID}`);
expect(encodeURIComponent(encoded)).toBe(encoded);
const decoded = decodeJournalCursor(encoded);
expect(decoded).toEqual(cursor);
expect(decoded!.createdAt.toISOString()).toBe('2026-11-14T15:32:10.123Z');
});
it.each([
['the epoch', `0_${ID}`, '1970-01-01T00:00:00.000Z'],
['the last millisecond of year 9999', `253402300799999_${ID}`, '9999-12-31T23:59:59.999Z'],
['an id in capitals', `1794670330123_${ID.replace('2222-4222', 'ABCD-4EF2')}`, '2026-11-14T15:32:10.123Z'],
])('reads %s', (_label, value, iso) => {
const decoded = decodeJournalCursor(value);
expect(decoded?.createdAt.toISOString()).toBe(iso);
expect(decoded?.id).toBe(value.split('_')[1]);
});
it.each([
['an empty value', ''],
['a word', 'cursor'],
['an instant alone', '1794670330123'],
['an id alone', ID],
['an id that is not a uuid', '1794670330123_not-a-uuid'],
['an id one character short', `1794670330123_${ID.slice(0, -1)}`],
['an id one character long', `1794670330123_${ID}0`],
['an instant that is not a number', `NaN_${ID}`],
['an ISO instant', `2026-11-14T15:32:10.123Z_${ID}`],
['a negative instant', `-1_${ID}`],
['an instant with a fraction', `1794670330123.5_${ID}`],
['an instant in exponent form', `1e12_${ID}`],
['an instant with a leading zero', `01794670330123_${ID}`],
['the first millisecond of year 10000', `253402300800000_${ID}`],
['an instant no Date can hold', `999999999999999_${ID}`],
['an instant of sixteen digits', `1794670330123000_${ID}`],
['a space before', ` 1794670330123_${ID}`],
['a line break after', `1794670330123_${ID}\n`],
['two cursors', `1794670330123_${ID},1794670330123_${ID}`],
['SQL in the id', `1794670330123_${ID}' OR '1'='1`],
])('refuses %s', (_label, value) => {
expect(decodeJournalCursor(value)).toBeNull();
});
it('never returns an invalid Date', () => {
for (const digits of ['0', '1', '999999999999999', '253402300799999', '253402300800000', '8640000000000001']) {
const decoded = decodeJournalCursor(`${digits}_${ID}`);
if (decoded !== null) expect(Number.isNaN(decoded.createdAt.getTime())).toBe(false);
}
});
});
describe('journalKey', () => {
const line = (id: string) => ({
id, tool: 'create_task', tokenName: 'Hermes', tokenRevoked: false, entityName: 'x', createdAt: '2026-11-14T15:32:10.123Z',
});
const first: JournalPageView = { actions: [line('a'), line('b')], nextCursor: '1_b' };
const tokens: TokenView[] = [tokenView(token({ id: 't1' }), new Date(0)), tokenView(token({ id: 't2' }), new Date(0))];
const key = journalKey(first, tokens);
it('stays the same while the first page and the tokens are the same', () => {
expect(journalKey({ ...first, actions: [...first.actions] }, [...tokens])).toBe(key);
// What a refresh changes without touching the journal: a token was used, a name changed.
expect(journalKey(
{ ...first, actions: [{ ...line('a'), entityName: 'renamed' }, line('b')] },
tokens.map((t) => ({ ...t, lastUsedAt: '2026-11-15T00:00:00.000Z' })),
)).toBe(key);
});
it.each([
['a new line', { ...first, actions: [line('c'), line('a')] }, tokens],
['a line less', { ...first, actions: [line('a')] }, tokens],
['another cursor', { ...first, nextCursor: '1_c' }, tokens],
['no older page left', { ...first, nextCursor: null }, tokens],
['a token revoked', first, tokens.slice(1)],
['a token created', first, [...tokens, tokenView(token({ id: 't3' }), new Date(0))]],
] as [string, JournalPageView, TokenView[]][])('changes with %s', (_label, page, held) => {
expect(journalKey(page, held)).not.toBe(key);
});
it('does not confuse a line with a token', () => {
expect(journalKey({ actions: [line('a')], nextCursor: null }, []))
.not.toBe(journalKey({ actions: [], nextCursor: null }, [tokenView(token({ id: 'a' }), new Date(0))]));
});
});
// The zone is always given: the result must not depend on the zone of the
// machine that runs the test, nor on the container's (UTC).
describe('dates', () => {
it('follows the active language of the site: English, or French by default', () => {
expect(dateLocale('fr')).toBe('fr-CA');
expect(dateLocale('fr-CA')).toBe('fr-CA');
expect(dateLocale('en')).toBe('en-CA');
expect(dateLocale('en-US')).toBe('en-CA');
expect(dateLocale('EN')).toBe('en-CA');
expect(dateLocale(undefined)).toBe('fr-CA');
expect(dateLocale('de')).toBe('fr-CA');
expect(dateLocale('')).toBe('fr-CA');
});
// 03:30 UTC is the evening of the day before in Toronto: 23:30 in July
// (UTC-4), 22:30 in December (UTC-5).
it.each([
['July, America/Toronto', '2026-07-15T03:30:00.000Z', 'America/Toronto', '14 juill. 2026', '14 juill. 2026, 23 h 30', 'Jul 14, 2026', 'Jul 14, 2026, 11:30 p.m.'],
['December, America/Toronto', '2026-12-15T03:30:00.000Z', 'America/Toronto', '14 déc. 2026', '14 déc. 2026, 22 h 30', 'Dec 14, 2026', 'Dec 14, 2026, 10:30 p.m.'],
['July, UTC', '2026-07-15T03:30:00.000Z', 'UTC', '15 juill. 2026', '15 juill. 2026, 03 h 30', 'Jul 15, 2026', 'Jul 15, 2026, 3:30 a.m.'],
['December, UTC', '2026-12-15T03:30:00.000Z', 'UTC', '15 déc. 2026', '15 déc. 2026, 03 h 30', 'Dec 15, 2026', 'Dec 15, 2026, 3:30 a.m.'],
['December, Asia/Tokyo', '2026-12-15T03:30:00.000Z', 'Asia/Tokyo', '15 déc. 2026', '15 déc. 2026, 12 h 30', 'Dec 15, 2026', 'Dec 15, 2026, 12:30 p.m.'],
// Ten minutes around midnight UTC: the same evening in Toronto, two days in UTC.
['just before midnight UTC, America/Toronto', '2026-11-14T23:55:00.000Z', 'America/Toronto', '14 nov. 2026', '14 nov. 2026, 18 h 55', 'Nov 14, 2026', 'Nov 14, 2026, 6:55 p.m.'],
['just after midnight UTC, America/Toronto', '2026-11-15T00:05:00.000Z', 'America/Toronto', '14 nov. 2026', '14 nov. 2026, 19 h 05', 'Nov 14, 2026', 'Nov 14, 2026, 7:05 p.m.'],
['just before midnight UTC, UTC', '2026-11-14T23:55:00.000Z', 'UTC', '14 nov. 2026', '14 nov. 2026, 23 h 55', 'Nov 14, 2026', 'Nov 14, 2026, 11:55 p.m.'],
['just after midnight UTC, UTC', '2026-11-15T00:05:00.000Z', 'UTC', '15 nov. 2026', '15 nov. 2026, 00 h 05', 'Nov 15, 2026', 'Nov 15, 2026, 12:05 a.m.'],
['just after midnight UTC, Asia/Tokyo', '2026-11-15T00:05:00.000Z', 'Asia/Tokyo', '15 nov. 2026', '15 nov. 2026, 09 h 05', 'Nov 15, 2026', 'Nov 15, 2026, 9:05 a.m.'],
// Midnight in Toronto, winter and summer.
['midnight in Toronto, winter', '2026-11-14T05:00:00.000Z', 'America/Toronto', '14 nov. 2026', '14 nov. 2026, 00 h 00', 'Nov 14, 2026', 'Nov 14, 2026, 12:00 a.m.'],
['midnight in Toronto, summer', '2026-07-14T04:00:00.000Z', 'America/Toronto', '14 juill. 2026', '14 juill. 2026, 00 h 00', 'Jul 14, 2026', 'Jul 14, 2026, 12:00 a.m.'],
])('%s', (_label, iso, zone, frDay, frDayTime, enDay, enDayTime) => {
expect(plain(formatDay(iso, 'fr-CA', zone))).toBe(frDay);
expect(plain(formatDayTime(iso, 'fr-CA', zone))).toBe(frDayTime);
expect(plain(formatDay(iso, 'en-CA', zone))).toBe(enDay);
expect(plain(formatDayTime(iso, 'en-CA', zone))).toBe(enDayTime);
});
it('a token created for one year shows the same local day a year later, summer and winter', () => {
// expiresAtFor('1y'): the same instant of the next year, in UTC.
for (const created of ['2026-07-15T02:00:00.000Z', '2026-12-15T03:00:00.000Z']) {
const expires = new Date(created);
expires.setUTCFullYear(expires.getUTCFullYear() + 1);
const day = (iso: string) => plain(formatDay(iso, 'fr-CA', 'America/Toronto'));
expect(day(expires.toISOString())).toBe(day(created).replace('2026', '2027'));
// In UTC both are a day later: the zone decides the day shown.
expect(plain(formatDay(created, 'fr-CA', 'UTC'))).not.toBe(day(created));
}
});
});
describe('texts of the page', () => {
const sources = [
...fs.readdirSync(COMPONENTS).filter((file) => /^Assistants.*\.tsx$/.test(file)).map((file) => path.join(COMPONENTS, file)),
path.join(COMPONENTS, 'Header.tsx'),
path.join(__dirname, 'assistants.ts'),
];
const used = new Set(sources.flatMap((file) =>
[...fs.readFileSync(file, 'utf8').matchAll(/["'](assistants\.[A-Za-z0-9_.]+)["']/g)].map((match) => match[1])));
it('every key the page asks for has a text in both languages', () => {
// Control: the five component files and the keys were found.
expect(sources).toHaveLength(7);
expect(used.size).toBeGreaterThan(60);
expect([...used].filter((key) => typeof textOf(fr, key) !== 'string' || typeof textOf(en, key) !== 'string')).toEqual([]);
});
it('every text of `assistants` is shown by the page', () => {
const keys = keysOf(fr.assistants, 'assistants');
expect(keys).toHaveLength(65);
expect(keys.filter((key) => !used.has(key))).toEqual([]);
});
it('no component keeps the value of a token outside its state', () => {
for (const file of sources.filter((source) => /Assistants.*\.tsx$/.test(source))) {
const source = fs.readFileSync(file, 'utf8');
expect(source, file).not.toMatch(/localStorage|sessionStorage|document\.cookie|indexedDB|history\.(push|replace)State|router\.(push|replace)\(/);
}
});
});

271
web/src/lib/assistants.ts Normal file
View file

@ -0,0 +1,271 @@
// Pure helpers of the « Assistants IA » page (#205), kept out of the JSX so
// vitest covers them without a DOM, as tagEditing.ts: label keys, connection
// templates, what the page and GET /api/agent-actions send to the browser,
// the journal cursor and the dates.
//
// The client components import this module: whatever it loads at run time
// goes to the browser. Its imports are type-only, erased at build, and
// assistants.test.ts fails on any other import: the database client, zod and
// the MCP server must not follow it there (see dueDate.ts).
import type { JournalCursor, JournalPage } from './agentJournal';
import type { AgentToken, AgentTokenDuration, AgentTokenScope } from './agentTokens';
import type { WriteToolName } from './mcp/writeTools';
export type TokenScope = AgentTokenScope;
export type TokenDuration = AgentTokenDuration;
// --- Creation form -------------------------------------------------------
// The choices of the form, in the order it shows them, and the ones it
// preselects (decision of Max, 2026-11-14: « Lecture seule » and « 1 an »).
// A test compares both lists with createAgentTokenSchema.
export const TOKEN_SCOPES: readonly TokenScope[] = ['read', 'write'];
export const TOKEN_DURATIONS: readonly TokenDuration[] = ['90d', '1y', 'never'];
export const DEFAULT_TOKEN_SCOPE: TokenScope = 'read';
export const DEFAULT_TOKEN_DURATION: TokenDuration = '1y';
export const SCOPE_LABEL_KEYS: Record<TokenScope, string> = {
read: 'assistants.scope.read',
write: 'assistants.scope.write',
};
export const DURATION_LABEL_KEYS: Record<TokenDuration, string> = {
'90d': 'assistants.duration.90d',
'1y': 'assistants.duration.1y',
never: 'assistants.duration.never',
};
// Same bound as createAgentTokenSchema in validators.ts (a test compares them).
export const TOKEN_NAME_MAX = 100;
export type TokenNameCheck =
| { ok: true; name: string }
| { ok: false; reason: 'empty' | 'tooLong' };
// The name sent to POST /api/agent-tokens: trimmed, neither empty nor made of
// spaces, at most TOKEN_NAME_MAX characters once trimmed.
export function validateTokenName(raw: string): TokenNameCheck {
const name = raw.trim();
if (name.length === 0) return { ok: false, reason: 'empty' };
if (name.length > TOKEN_NAME_MAX) return { ok: false, reason: 'tooLong' };
return { ok: true, name };
}
// --- Journal labels ------------------------------------------------------
// One label per write tool of the MCP server. `Record<WriteToolName, …>`
// makes tsc refuse a write tool without a label, and assistants.test.ts
// compares these keys with WRITE_TOOL_NAMES at run time. The import above is
// a type: writeTools.ts itself never reaches the browser.
export const ACTION_LABEL_KEYS: Record<WriteToolName, string> = {
create_task: 'assistants.action.create_task',
update_task: 'assistants.action.update_task',
complete_task: 'assistants.action.complete_task',
reopen_task: 'assistants.action.reopen_task',
set_task_tags: 'assistants.action.set_task_tags',
create_list: 'assistants.action.create_list',
update_list: 'assistants.action.update_list',
create_tag: 'assistants.action.create_tag',
update_tag: 'assistants.action.update_tag',
};
// The label key of a journal line, or null for a tool this version has no
// label for (a line written by a later version): the page then shows the
// name of the tool as the journal holds it.
export function actionLabelKey(tool: string): string | null {
return Object.prototype.hasOwnProperty.call(ACTION_LABEL_KEYS, tool)
? ACTION_LABEL_KEYS[tool as WriteToolName]
: null;
}
// --- Connection help -----------------------------------------------------
// What a template shows where the token goes, until one has just been
// created. The texts `assistants.connect.replace` name the same value.
export const TOKEN_PLACEHOLDER = 'slmcp_…';
const MCP_PATH = '/api/mcp';
// The address of the MCP server: the origin of the site (LOGTO_BASE_URL, the
// address the site is reached at), then the route. A path or a trailing
// slash in the base URL is dropped.
export function mcpServerUrl(baseUrl: string): string {
return new URL(baseUrl).origin + MCP_PATH;
}
// The three templates take the address of the server and the token, which
// appears nowhere else on the page than in their output, in the place of
// TOKEN_PLACEHOLDER. They are the blocks of issue #205, checked against the
// documentation of each client on 2026-11-14, without the comment line that
// names the client there: the page says it above each block
// (`assistants.connect.hermesHint`, `claudeCodeHint`), and a `#` line pasted
// into a terminal is not a comment for every shell.
// For ~/.hermes/config.yaml.
export function hermesTemplate(serverUrl: string, token: string = TOKEN_PLACEHOLDER): string {
return [
'mcp_servers:',
' simpl-liste:',
` url: "${serverUrl}"`,
' headers:',
` Authorization: "Bearer ${token}"`,
].join('\n');
}
// For a terminal.
export function claudeCodeTemplate(serverUrl: string, token: string = TOKEN_PLACEHOLDER): string {
return `claude mcp add --transport http simpl-liste ${serverUrl} --header "Authorization: Bearer ${token}"`;
}
// For any other MCP client: the address, then the header, one per line.
export function genericTemplate(serverUrl: string, token: string = TOKEN_PLACEHOLDER): string {
return [serverUrl, `Authorization: Bearer ${token}`].join('\n');
}
// A text of fr.json or en.json may hold code between backticks, as the
// Markdown of the issue Max validated it in: the page shows these parts as
// code, without the backticks.
export type TextPart = { text: string; code: boolean };
export function codeSpans(text: string): TextPart[] {
return text
.split('`')
.map((part, index) => ({ text: part, code: index % 2 === 1 }))
.filter((part) => part.text !== '');
}
// --- What the browser receives -------------------------------------------
// A token as the page shows it. Fields named one by one: a field added to
// AgentToken reaches the browser only if it is named here. Instants are ISO
// strings: the browser formats them (the container runs in UTC).
export type TokenView = {
id: string;
name: string;
scope: TokenScope;
hint: string;
createdAt: string;
lastUsedAt: string | null;
expiresAt: string | null;
expired: boolean;
};
// Whether a token is refused at `now`: from the very instant of its expiry,
// the comparison verifyAgentToken makes (agentTokens.ts). Two instants are
// compared, never two calendar days: no time zone is involved.
export function isExpired(expiresAt: Date | null, now: Date): boolean {
return expiresAt !== null && expiresAt.getTime() <= now.getTime();
}
export function tokenView(token: AgentToken, now: Date): TokenView {
return {
id: token.id,
name: token.name,
scope: token.scope,
hint: token.hint,
createdAt: token.createdAt.toISOString(),
lastUsedAt: token.lastUsedAt === null ? null : token.lastUsedAt.toISOString(),
expiresAt: token.expiresAt === null ? null : token.expiresAt.toISOString(),
expired: isExpired(token.expiresAt, now),
};
}
// Lines of the journal per page, on the page and in GET /api/agent-actions.
export const JOURNAL_PAGE_SIZE = 50;
// A journal line as the page shows it: what it displays, and its id as a
// React key. Neither the id of the touched row, nor its type, nor the id of
// the token leaves the server.
export type JournalLine = {
id: string;
tool: string;
tokenName: string;
tokenRevoked: boolean;
entityName: string | null;
createdAt: string;
};
// The same shape for the first page, which the server component reads, and
// for the next ones, which the route returns.
export type JournalPageView = {
actions: JournalLine[];
// To send back as `?before=` to read the older lines; null on the last page.
nextCursor: string | null;
};
export function journalPageView(page: JournalPage): JournalPageView {
return {
actions: page.actions.map((action) => ({
id: action.id,
tool: action.tool,
tokenName: action.tokenName,
tokenRevoked: action.tokenRevoked,
entityName: action.entityName,
createdAt: action.createdAt.toISOString(),
})),
nextCursor: page.nextCursor === null ? null : encodeJournalCursor(page.nextCursor),
};
}
// The cursor of listActions (agentJournal.ts) as a query parameter: the
// instant in milliseconds since the epoch, an underscore, the id of the line.
const CURSOR = /^(0|[1-9]\d{0,14})_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
// The last millisecond of year 9999 in UTC: a later instant is still a valid
// Date, but PostgreSQL may refuse it in the query.
const CURSOR_MAX_MS = Date.UTC(9999, 11, 31, 23, 59, 59, 999);
export function encodeJournalCursor(cursor: JournalCursor): string {
return `${cursor.createdAt.getTime()}_${cursor.id}`;
}
// The cursor a client sent back, or null when it is not one: listActions
// throws on an invalid Date, and PostgreSQL on an id that is not a uuid. A
// well-formed cursor is only a position in the journal of the caller: it
// gives no access to a line (listActions filters on the account).
export function decodeJournalCursor(value: string): JournalCursor | null {
const match = CURSOR.exec(value);
if (!match) return null;
const ms = Number(match[1]);
if (ms > CURSOR_MAX_MS) return null;
return { createdAt: new Date(ms), id: match[2] };
}
// What the older pages of the journal were read after: the lines of the
// first page and its cursor, and the tokens of the account (revoking one
// changes how its lines read). The journal component is keyed by this value,
// so that the older pages it has loaded are dropped when it changes: kept,
// they could miss a line or show a revoked token as a live one.
export function journalKey(first: JournalPageView, tokens: readonly TokenView[]): string {
return [
first.nextCursor ?? '',
first.actions.map((action) => action.id).join(','),
tokens.map((token) => token.id).join(','),
].join('|');
}
// --- Dates ---------------------------------------------------------------
// Every date of the page is formatted in the browser, in the time zone of
// the user: these functions take the zone, and the components only have one
// once they run in a browser (AssistantsPanel.tsx). The container runs in
// UTC and formats nothing.
export type DateLocale = 'fr-CA' | 'en-CA';
// The locale of the dates for the active language of the site: English, or
// French, its default language.
export function dateLocale(language: string | undefined): DateLocale {
return language !== undefined && language.toLowerCase().startsWith('en') ? 'en-CA' : 'fr-CA';
}
// A day, « 14 nov. 2026 »: the day it is in `timeZone` at that instant.
export function formatDay(iso: string, locale: DateLocale, timeZone: string): string {
return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone }).format(new Date(iso));
}
// A day and a time, « 14 nov. 2026, 10 h 32 », in `timeZone`.
export function formatDayTime(iso: string, locale: DateLocale, timeZone: string): string {
return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short', timeZone }).format(new Date(iso));
}