From e42a5eb0b45f271fb2e34a18fc3f9185b4d3624c Mon Sep 17 00:00:00 2001 From: le king fu Date: Sun, 15 Nov 2026 17:06:27 -0500 Subject: [PATCH] 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 --- web/src/app/(app)/assistants/page.test.ts | 328 ++++++++++++ web/src/app/(app)/assistants/page.tsx | 43 ++ web/src/app/(app)/layout.tsx | 6 +- web/src/app/api/agent-actions/route.test.ts | 529 +++++++++++++++++++ web/src/app/api/agent-actions/route.ts | 34 ++ web/src/components/AssistantsConnect.tsx | 102 ++++ web/src/components/AssistantsCreated.tsx | 48 ++ web/src/components/AssistantsJournal.tsx | 127 +++++ web/src/components/AssistantsPanel.tsx | 94 ++++ web/src/components/AssistantsTokens.tsx | 262 ++++++++++ web/src/components/Header.tsx | 18 +- web/src/i18n/en.json | 83 +++ web/src/i18n/fr.json | 83 +++ web/src/i18n/parity.test.ts | 49 ++ web/src/lib/assistants.test.ts | 550 ++++++++++++++++++++ web/src/lib/assistants.ts | 271 ++++++++++ 16 files changed, 2624 insertions(+), 3 deletions(-) create mode 100644 web/src/app/(app)/assistants/page.test.ts create mode 100644 web/src/app/(app)/assistants/page.tsx create mode 100644 web/src/app/api/agent-actions/route.test.ts create mode 100644 web/src/app/api/agent-actions/route.ts create mode 100644 web/src/components/AssistantsConnect.tsx create mode 100644 web/src/components/AssistantsCreated.tsx create mode 100644 web/src/components/AssistantsJournal.tsx create mode 100644 web/src/components/AssistantsPanel.tsx create mode 100644 web/src/components/AssistantsTokens.tsx create mode 100644 web/src/i18n/parity.test.ts create mode 100644 web/src/lib/assistants.test.ts create mode 100644 web/src/lib/assistants.ts diff --git a/web/src/app/(app)/assistants/page.test.ts b/web/src/app/(app)/assistants/page.test.ts new file mode 100644 index 0000000..7480355 --- /dev/null +++ b/web/src/app/(app)/assistants/page.test.ts @@ -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 { + 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 { + 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 { + 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 { + 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); + const signOut = source.indexOf('href="/api/logto/sign-out"'); + expect(entry).toBeGreaterThan(-1); + expect(source.match(/href="\/assistants"/g)).toHaveLength(1); + expect(source.match(/'.length)).toMatch(/^\s*\)\}/); + expect(source.slice(link, end)).toContain('t("assistants.title")'); + expect(end).toBeLessThan(signOut); + }); +}); diff --git a/web/src/app/(app)/assistants/page.tsx b/web/src/app/(app)/assistants/page.tsx new file mode 100644 index 0000000..ba2b1f6 --- /dev/null +++ b/web/src/app/(app)/assistants/page.tsx @@ -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 ( + tokenView(token, now))} + // Expired tokens count, as in createAgentToken. + atLimit={tokens.length >= MAX_AGENT_TOKENS} + journal={journalPageView(journal)} + serverUrl={mcpServerUrl(logtoConfig.baseUrl)} + /> + ); +} diff --git a/web/src/app/(app)/layout.tsx b/web/src/app/(app)/layout.tsx index 59ebe55..8633870 100644 --- a/web/src/app/(app)/layout.tsx +++ b/web/src/app/(app)/layout.tsx @@ -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({
-
+
{children}
diff --git a/web/src/app/api/agent-actions/route.test.ts b/web/src/app/api/agent-actions/route.test.ts new file mode 100644 index 0000000..5ba9b08 --- /dev/null +++ b/web/src/app/api/agent-actions/route.test.ts @@ -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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 }] }); + }); +}); diff --git a/web/src/app/api/agent-actions/route.ts b/web/src/app/api/agent-actions/route.ts new file mode 100644 index 0000000..594f66f --- /dev/null +++ b/web/src/app/api/agent-actions/route.ts @@ -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)); +} diff --git a/web/src/components/AssistantsConnect.tsx b/web/src/components/AssistantsConnect.tsx new file mode 100644 index 0000000..3506e69 --- /dev/null +++ b/web/src/components/AssistantsConnect.tsx @@ -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 ? ( + + {part.text} + + ) : ( + {part.text} + ), + )} + + ); +} + +// A block to copy. It scrolls sideways inside its frame instead of widening +// the page. +function Template({ text }: { text: string }) { + return ( +
+      {text}
+    
+ ); +} + +function Help({ title, children }: { title: string; children: React.ReactNode }) { + return ( +
+ {title} +
{children}
+
+ ); +} + +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 ( +
+

{t("assistants.connect.heading")}

+ +
+

{t("assistants.connect.url")}

+