From 0f746472111a941793c653484216739e9dbf76d1 Mon Sep 17 00:00:00 2001 From: le king fu Date: Sun, 15 Nov 2026 13:37:00 -0500 Subject: [PATCH] feat(mcp): list and tag tools, create and rename (#204) Four write tools on the envelope of #203, for a read-write token only: create_list, update_list, create_tag and update_tag. A read-write token now sees thirteen tools, a read-only token still four. No tool deletes anything. - palette.ts (new, import-free): LIST_COLORS, TAG_COLORS, LIST_ICONS and their defaults, moved out of tagEditing.ts, which re-exports the tag palette. A test reads app/(tabs)/lists.tsx and app/(tabs)/settings.tsx and fails when the app and the companion differ. - taskWrites.ts: createList (end of the live lists of the account), updateList (live list of the account, never the Inbox), createTag (under the account lock; a live tag of the same name is returned as it is) and updateTag (updatedAt advanced). A list or a tag that is not a live row of the account is refused with list_not_found or tag_not_found: a row of another account answers like one that does not exist. - Tag names are compared in JavaScript (trimmed, NFC, lower case), not with SQL lower(), which follows the locale of the database. - A color outside the palette of the app is refused (invalid_color), an icon too (invalid_icon); a color is stored in the spelling of the palette. Resolves #204 Co-Authored-By: Claude Fable 5.2 --- web/src/app/api/mcp/route.test.ts | 719 +++++++++++++++++++++++++++++- web/src/lib/mcp/writeTools.ts | 148 +++++- web/src/lib/palette.test.ts | 137 ++++++ web/src/lib/palette.ts | 73 +++ web/src/lib/tagEditing.ts | 14 +- web/src/lib/taskWrites.test.ts | 464 ++++++++++++++++++- web/src/lib/taskWrites.ts | 252 ++++++++++- 7 files changed, 1767 insertions(+), 40 deletions(-) create mode 100644 web/src/lib/palette.test.ts create mode 100644 web/src/lib/palette.ts diff --git a/web/src/app/api/mcp/route.test.ts b/web/src/app/api/mcp/route.test.ts index 4f482d6..86ecdcd 100644 --- a/web/src/app/api/mcp/route.test.ts +++ b/web/src/app/api/mcp/route.test.ts @@ -73,6 +73,7 @@ const { TOOL_ERROR_MESSAGES, errorName } = await import('@/lib/mcp/errors'); const { instructionsFor, mcpHandler } = await import('@/lib/mcp/server'); const { WRITE_TOOL_NAMES } = await import('@/lib/mcp/writeTools'); const { listActions } = await import('@/lib/agentJournal'); +const { LIST_COLORS, LIST_ICONS, TAG_COLORS } = await import('@/lib/palette'); const { db } = await import('@/db/client'); const SITE = 'https://liste.lacompagniemaximus.com'; @@ -86,7 +87,10 @@ const ENVELOPE = { }; const ERAS = ['modern', 'legacy'] as const; const READ_TOOLS = ['get_task', 'list_lists', 'list_tags', 'list_tasks']; -const WRITE_TOOLS = ['complete_task', 'create_task', 'reopen_task', 'set_task_tags', 'update_task']; +const WRITE_TOOLS = [ + 'complete_task', 'create_list', 'create_tag', 'create_task', 'reopen_task', 'set_task_tags', 'update_list', 'update_tag', + 'update_task', +]; const READ_ONLY = { readOnlyHint: true, openWorldHint: false }; // Keys of a top-level task as a tool returns it, in order. const TASK_KEYS = [ @@ -171,6 +175,13 @@ function words(kind: string): string { return text; } +// A name a test spells letter by letter (the tests that compare two names), +// that no log line may carry either. +function spelled(text: string): string { + seen.content.push(text); + return text; +} + // Each test creates its own accounts (#148): invented ids, no real `sub`. // An account starts with its Inbox, first of its lists. async function newAccount(): Promise { @@ -191,7 +202,7 @@ type ListFields = { async function newList(account: Account, fields: ListFields = {}): Promise { const id = u(); await h.pg.query( - 'INSERT INTO sl_lists (id, user_id, name, color, icon, position, created_at, deleted_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)', + 'INSERT INTO sl_lists (id, user_id, name, color, icon, position, created_at, updated_at, deleted_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $7, $8)', [ id, account.userId, fields.name ?? words('list'), fields.color ?? null, fields.icon ?? null, fields.position ?? 1, fields.createdAt ?? '2026-01-02T00:00:00Z', fields.deletedAt ?? null, @@ -228,11 +239,16 @@ async function newTask(account: Account, fields: TaskFields = {}): Promise { +type TagFields = { name?: string; color?: string; createdAt?: string; deletedAt?: string }; + +async function newTag(account: Account, fields: TagFields = {}): Promise { const id = u(); await h.pg.query( - 'INSERT INTO sl_tags (id, user_id, name, color, deleted_at) VALUES ($1, $2, $3, $4, $5)', - [id, account.userId, fields.name ?? words('tag'), fields.color ?? '#4A90A4', fields.deletedAt ?? null], + 'INSERT INTO sl_tags (id, user_id, name, color, created_at, updated_at, deleted_at) VALUES ($1, $2, $3, $4, $5, $5, $6)', + [ + id, account.userId, fields.name ?? words('tag'), fields.color ?? '#4A90A4', fields.createdAt ?? '2026-01-03T00:00:00Z', + fields.deletedAt ?? null, + ], ); return id; } @@ -280,6 +296,24 @@ async function stored(id: string): Promise { return (await h.pg.query('SELECT * FROM sl_tasks WHERE id = $1', [id])).rows[0]; } +// Every column of sl_lists and of sl_tags, as PGlite returns a row. +type StoredList = { + id: string; user_id: string; name: string; color: string | null; icon: string | null; position: number; + is_inbox: boolean; created_at: Date; updated_at: Date; deleted_at: Date | null; +}; + +type StoredTag = { + id: string; user_id: string; name: string; color: string; created_at: Date; updated_at: Date; deleted_at: Date | null; +}; + +async function storedList(id: string): Promise { + return (await h.pg.query('SELECT * FROM sl_lists WHERE id = $1', [id])).rows[0]; +} + +async function storedTag(id: string): Promise { + return (await h.pg.query('SELECT * FROM sl_tags WHERE id = $1', [id])).rows[0]; +} + type JournalLine = { tool: string; entity_type: string; entity_id: string; token_id: string | null; token_name: string }; // The journal lines of an account, oldest first. @@ -290,9 +324,10 @@ async function journal(userId: string): Promise { )).rows; } -// The journal line a write tool leaves for a task, written with this token. -function lineOf(tool: string, taskId: string, token: Token): JournalLine { - return { tool, entity_type: 'task', entity_id: taskId, token_id: token.id, token_name: 'Assistant' }; +// The journal line a write tool leaves for the row it touched, written with +// this token: a task unless said, a list or a tag for the tools of #204. +function lineOf(tool: string, entityId: string, token: Token, type: 'task' | 'list' | 'tag' = 'task'): JournalLine { + return { tool, entity_type: type, entity_id: entityId, token_id: token.id, token_name: 'Assistant' }; } // The WebSocket notices sent to an account, in order: true for a notice that @@ -889,6 +924,20 @@ describe('the tools of a token', () => { expect(errorOf(unknown)).toEqual({ code: -32602, message: 'Tool create_task not found' }); expect(await h.pg.query('SELECT 1 FROM sl_tasks WHERE user_id = $1', [a.userId])).toMatchObject({ rows: [] }); expect(logLines('mcp-tool')).toEqual([]); + + // Nor are the tools on lists and tags (#204): a read-only token still has four tools. + expect(await listTools(a.token, { era })).toHaveLength(4); + const [list, tag] = [await newList(a), await newTag(a)]; + const before = await state(a); + for (const [name, args] of [ + ['create_list', { name: 'x' }], ['update_list', { list_id: list, name: 'x' }], + ['create_tag', { name: 'x' }], ['update_tag', { tag_id: tag, name: 'x' }], + ] as const) { + const refusedCall = await rpc(a.token, 'tools/call', { name, arguments: args }, { era }); + expect(errorOf(refusedCall)).toEqual({ code: -32602, message: `Tool ${name} not found` }); + } + expect(await state(a)).toEqual(before); + expect(logLines('mcp-tool')).toEqual([]); }); it('a read-write token sees the read tools too', async () => { @@ -896,10 +945,11 @@ describe('the tools of a token', () => { expect((await listTools(a.token)).map((tool) => tool.name)).toEqual(expect.arrayContaining(READ_TOOLS)); }); - it('a read-write token sees the five write tools as well, the same in both generations', async () => { + it('a read-write token sees the nine write tools as well, thirteen tools in all, the same in both generations', async () => { const a = await connected('write'); const [modern, legacy] = [await listTools(a.token), await listTools(a.token, { era: 'legacy' })]; expect(legacy).toEqual(modern); + expect(modern).toHaveLength(13); expect(modern.map((tool) => tool.name).sort()).toEqual([...READ_TOOLS, ...WRITE_TOOLS].sort()); // The names the journal holds are the names of the write tools, all of them. expect([...WRITE_TOOL_NAMES].sort()).toEqual(WRITE_TOOLS); @@ -911,6 +961,11 @@ describe('the tools of a token', () => { expect(byName.complete_task.annotations).toEqual({ readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }); expect(byName.reopen_task.annotations).toEqual({ readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }); expect(byName.set_task_tags.annotations).toEqual({ readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }); + // A list is added each time it is asked for; a tag of a name is added once; an update overwrites (#204). + expect(byName.create_list.annotations).toEqual({ readOnlyHint: false, destructiveHint: false, openWorldHint: false }); + expect(byName.update_list.annotations).toEqual({ readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }); + expect(byName.create_tag.annotations).toEqual({ readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }); + expect(byName.update_tag.annotations).toEqual({ readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }); for (const name of READ_TOOLS) expect(byName[name].annotations).toEqual(READ_ONLY); const inputs = Object.fromEntries(WRITE_TOOLS.map((name) => [name, byName[name].inputSchema as { properties: Json; required?: string[] }])); @@ -942,6 +997,47 @@ describe('the tools of a token', () => { expect(Object.keys(inputs.set_task_tags.properties).sort()).toEqual(['tag_ids', 'task_id']); expect(inputs.set_task_tags.required?.sort()).toEqual(['tag_ids', 'task_id']); expect(inputs.set_task_tags.properties).toMatchObject({ tag_ids: { type: 'array', maxItems: 20 } }); + + // The tools on lists and tags (#204). + expect(Object.keys(inputs.create_list.properties).sort()).toEqual(['color', 'icon', 'name']); + expect(inputs.create_list.required).toEqual(['name']); + expect(inputs.create_list.properties).toMatchObject({ + name: { type: 'string', minLength: 1, maxLength: 200 }, + color: { type: 'string', maxLength: 20 }, + icon: { type: 'string', maxLength: 50 }, + }); + expect(Object.keys(inputs.update_list.properties).sort()).toEqual(['color', 'icon', 'list_id', 'name']); + expect(inputs.update_list.required).toEqual(['list_id']); + expect(inputs.update_list.properties).toMatchObject({ + name: { type: 'string', minLength: 1, maxLength: 200 }, + color: { type: 'string', maxLength: 20 }, + }); + expect(Object.keys(inputs.create_tag.properties).sort()).toEqual(['color', 'name']); + expect(inputs.create_tag.required).toEqual(['name']); + expect(inputs.create_tag.properties).toMatchObject({ + name: { type: 'string', minLength: 1, maxLength: 100 }, + color: { type: 'string', maxLength: 20 }, + }); + expect(Object.keys(inputs.update_tag.properties).sort()).toEqual(['color', 'name', 'tag_id']); + expect(inputs.update_tag.required).toEqual(['tag_id']); + expect(inputs.update_tag.properties).toMatchObject({ + name: { type: 'string', minLength: 1, maxLength: 100 }, + color: { type: 'string', maxLength: 20 }, + }); + // A color and an icon are texts for the schema: the palette of the app + // (palette.ts) is what the model reads in their descriptions, in full. + const described = (name: string, key: string) => JSON.stringify(inputs[name].properties[key]); + for (const name of ['create_list', 'update_list']) { + for (const color of LIST_COLORS) expect(described(name, 'color')).toContain(color); + for (const icon of LIST_ICONS) expect(described(name, 'icon')).toContain(icon); + expect(described(name, 'color')).not.toContain('enum'); + } + for (const name of ['create_tag', 'update_tag']) { + for (const color of TAG_COLORS) expect(described(name, 'color')).toContain(color); + } + // update_list takes a null icon, which removes it; create_list does not. + expect(described('update_list', 'icon')).toContain('"null"'); + expect(described('create_list', 'icon')).not.toContain('"null"'); // No tool takes an account, and none deletes. const text = JSON.stringify(modern); expect(text).not.toMatch(/user_id|userId/); @@ -1447,6 +1543,611 @@ describe('the write tools and the other accounts', () => { }); }); +describe('create_list', () => { + it.each(ERAS)('creates a list after the others, returns it as list_lists does, journals it and notifies once, after the commit (%s)', async (era) => { + const a = await connected('write'); + await newList(a, { position: 4 }); + await newList(a, { position: 9, deletedAt: GONE }); + const name = words('list'); + + // The spaces around the name are not kept. + const created = await ok(a.token, 'create_list', { name: ` ${name} ` }, { era }); + expect(Object.keys(created)).toEqual(['list']); + const list = created.list as ShapedList; + // Named columns only, as list_lists: the first color of the app, no icon, no open task yet. + expect(list).toStrictEqual({ id: list.id, name, color: '#4A90A4', icon: null, is_inbox: false, open_task_count: 0 }); + // After the live lists of the account: the deleted one does not count. + expect(await storedList(list.id)).toMatchObject({ user_id: a.userId, name, position: 5, is_inbox: false, deleted_at: null }); + + expect(await journal(a.userId)).toEqual([lineOf('create_list', list.id, a, 'list')]); + expect(notices(a.userId)).toEqual([true]); + expect(logLines('mcp-tool')).toEqual([{ at: 'mcp-tool', tool: 'create_list', outcome: 'ok', ms: expect.any(Number), token: a.id }]); + + // list_lists returns the same list, last, and a task can be created in it. + expect(((await ok(a.token, 'list_lists', {}, { era })).lists as ShapedList[]).at(-1)).toEqual(list); + const task = (await ok(a.token, 'create_task', { title: words('title'), list_id: list.id }, { era })).task as ShapedTask; + expect(task.list_id).toBe(list.id); + expect(((await ok(a.token, 'list_lists', {}, { era })).lists as ShapedList[]).at(-1)).toEqual({ ...list, open_task_count: 1 }); + }); + + it('takes a color and an icon of the app, the color whatever its letter case, and lets two lists share a name', async () => { + const a = await connected('write'); + const name = words('list'); + const first = (await ok(a.token, 'create_list', { name, color: '#c17767', icon: 'ShoppingCart' })).list as ShapedList; + expect(first).toMatchObject({ name, color: '#C17767', icon: 'ShoppingCart', is_inbox: false }); + const second = (await ok(a.token, 'create_list', { name })).list as ShapedList; + expect(second).toMatchObject({ name, color: '#4A90A4', icon: null }); + expect(second.id).not.toBe(first.id); + expect(((await ok(a.token, 'list_lists')).lists as ShapedList[]).map((list) => list.id)).toEqual([a.inbox, first.id, second.id]); + expect((await journal(a.userId)).map((line) => `${line.tool} ${line.entity_type} ${line.entity_id}`).sort()) + .toEqual([first.id, second.id].map((id) => `create_list list ${id}`).sort()); + }); + + it('gives an account without a list its first list, and no Inbox', async () => { + const a = await bare(); + const list = (await ok(a.token, 'create_list', { name: words('list') })).list as ShapedList; + expect(await storedList(list.id)).toMatchObject({ user_id: a.userId, position: 1, is_inbox: false }); + expect((await ok(a.token, 'list_lists')).lists).toEqual([list]); + }); + + it.each(ERAS)('refuses a color or an icon the app does not have, with a code the model reads, and writes nothing (%s)', async (era) => { + const a = await connected('write'); + const before = await state(a); + for (const color of ['#000000', 'red', '', '#4A90A']) { + expect(await refused(a.token, 'create_list', { name: words('list'), color }, 'invalid_color', { era }), JSON.stringify(color)) + .toStrictEqual({ error: 'invalid_color', message: 'This color is not one of the allowed colors.' }); + } + // An icon is a name of the app, letter for letter. + for (const icon of ['Rocket', 'home', '']) { + expect(await refused(a.token, 'create_list', { name: words('list'), icon }, 'invalid_icon', { era }), JSON.stringify(icon)) + .toStrictEqual({ error: 'invalid_icon', message: 'This icon is not one of the allowed icons.' }); + } + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toEqual([]); + expect(logLines('mcp-tool').map((line) => line.outcome)) + .toEqual([...Array(4).fill('invalid_color'), ...Array(3).fill('invalid_icon')]); + }); + + it.each([ + ['no name', {}, 'name'], + ['an empty name', { name: '' }, 'name'], + ['a name made of spaces', { name: ' \t\n ' }, 'name'], + ['a name of 201 characters', { name: 'x'.repeat(201) }, 'name'], + ['a null name', { name: null }, 'name'], + ['a color of 21 characters', { name: 'x', color: '#'.repeat(21) }, 'color'], + ['a null color', { name: 'x', color: null }, 'color'], + ['an icon of 51 characters', { name: 'x', icon: 'x'.repeat(51) }, 'icon'], + ['a null icon', { name: 'x', icon: null }, 'icon'], + ['an account', { name: 'x', user_id: 'someone-else' }, 'user_id'], + ['a position', { name: 'x', position: 0 }, 'position'], + ['an Inbox flag', { name: 'x', is_inbox: true }, 'is_inbox'], + ])('refuses %s before the tool runs', async (_label, args, named) => { + const a = await connected('write'); + const before = await state(a); + for (const era of ERAS) expect(await invalid(a.token, 'create_list', args, { era })).toContain(named); + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toEqual([]); + }); + + it('accepts a name of 200 characters, the spaces around it not counted', async () => { + const a = await connected('write'); + expect(((await ok(a.token, 'create_list', { name: 'x'.repeat(200) })).list as ShapedList).name).toBe('x'.repeat(200)); + expect(((await ok(a.token, 'create_list', { name: ` ${'y'.repeat(200)} ` })).list as ShapedList).name).toBe('y'.repeat(200)); + }); +}); + +describe('update_list', () => { + it.each(ERAS)('changes the fields it receives, removes the icon with null, and every call is a write (%s)', async (era) => { + const a = await connected('write'); + const id = await newList(a, { color: '#C17767', icon: 'Home', position: 3 }); + await newTask(a, { list: id }); + await newTask(a, { list: id, completed: true }); + const seeded = await storedList(id); + const name = words('list'); + + const renamed = await ok(a.token, 'update_list', { list_id: id, name: ` ${name} ` }, { era }); + expect(Object.keys(renamed)).toEqual(['list']); + // As list_lists returns it, with its open tasks counted. + expect(renamed.list).toStrictEqual({ id, name, color: '#C17767', icon: 'Home', is_inbox: false, open_task_count: 1 }); + // The name was written, updated_at moved, and nothing else. + const afterRename = await storedList(id); + expect(afterRename.updated_at.getTime()).toBeGreaterThan(seeded.updated_at.getTime()); + expect(afterRename).toEqual({ ...seeded, name, updated_at: afterRename.updated_at }); + + const restyled = await ok(a.token, 'update_list', { list_id: id, color: '#8ba889', icon: 'Star' }, { era }); + expect(restyled.list).toMatchObject({ id, name, color: '#8BA889', icon: 'Star' }); + + const plain = await ok(a.token, 'update_list', { list_id: id, icon: null }, { era }); + expect(plain.list).toStrictEqual({ id, name, color: '#8BA889', icon: null, is_inbox: false, open_task_count: 1 }); + + // The values the list already has: a write all the same, a minute later. + await frozen(async (advance) => { + advance(60_000); + expect(await ok(a.token, 'update_list', { list_id: id, name, color: '#8BA889', icon: null }, { era })).toEqual(plain); + expect(await storedList(id)).toEqual({ ...seeded, name, color: '#8BA889', icon: null, updated_at: new Date(Date.now()) }); + }); + + expect(await journal(a.userId)).toEqual(Array(4).fill(lineOf('update_list', id, a, 'list'))); + expect(notices(a.userId)).toEqual([true, true, true, true]); + expect((await ok(a.token, 'list_lists', {}, { era })).lists).toContainEqual(plain.list); + }); + + it.each(ERAS)('refuses the Inbox, a list that is unknown, deleted or of another account, and a color or an icon the app does not have, and writes nothing (%s)', async (era) => { + const [a, b] = [await connected('write'), await connected('write')]; + const id = await newList(a, { color: '#C17767', icon: 'Home' }); + const foreign = await newList(b); + const cases: [Json, keyof typeof TOOL_ERROR_MESSAGES][] = [ + [{ list_id: u(), name: words('list') }, 'list_not_found'], + [{ list_id: await newList(a, { deletedAt: GONE }), name: words('list') }, 'list_not_found'], + [{ list_id: foreign, name: words('list') }, 'list_not_found'], + [{ list_id: foreign.toUpperCase(), color: '#8BA889' }, 'list_not_found'], + [{ list_id: foreign, icon: null }, 'list_not_found'], + // The Inbox of another account is not found before it is an Inbox. + [{ list_id: b.inbox, name: words('list') }, 'list_not_found'], + [{ list_id: a.inbox, name: words('list') }, 'inbox_not_editable'], + [{ list_id: a.inbox, color: '#8BA889' }, 'inbox_not_editable'], + [{ list_id: a.inbox.toUpperCase(), icon: null }, 'inbox_not_editable'], + [{ list_id: id, name: words('list'), color: 'red' }, 'invalid_color'], + [{ list_id: id, name: words('list'), icon: 'Rocket' }, 'invalid_icon'], + [{ list_id: id, icon: 'home' }, 'invalid_icon'], + // The list first, then the Inbox, then the values. + [{ list_id: u(), color: 'red' }, 'list_not_found'], + [{ list_id: a.inbox, icon: 'Rocket' }, 'inbox_not_editable'], + ]; + const before = await state(a, b); + for (const [args, code] of cases) { + // The code and its fixed message, nothing else: a list of another + // account reads like a list that does not exist. + expect(await refused(a.token, 'update_list', args, code, { era }), JSON.stringify(args)) + .toStrictEqual({ error: code, message: TOOL_ERROR_MESSAGES[code] }); + } + expect(await state(a, b)).toEqual(before); + expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]); + expect(logLines('mcp-tool').map((line) => line.outcome)).toEqual(cases.map(([, code]) => code)); + expect(TOOL_ERROR_MESSAGES.inbox_not_editable).toBe('The Inbox cannot be renamed or restyled.'); + + // The other account changes its own list, and not its Inbox either. + expect((await ok(b.token, 'update_list', { list_id: foreign, icon: 'Leaf' }, { era })).list).toMatchObject({ id: foreign, icon: 'Leaf' }); + await refused(b.token, 'update_list', { list_id: b.inbox, name: words('list') }, 'inbox_not_editable', { era }); + }); + + it('refuses a call without a field to change, and a field it does not take, before the tool runs', async () => { + const a = await connected('write'); + const id = await newList(a); + const before = await state(a); + for (const era of ERAS) { + expect(await invalid(a.token, 'update_list', { list_id: id }, { era })) + .toContain('Nothing to change: pass at least one of name, color, icon.'); + } + const cases: [Json, string][] = [ + [{ name: 'x' }, 'list_id'], + [{ list_id: 'first', name: 'x' }, 'list_id'], + [{ list_id: id, name: '' }, 'name'], + [{ list_id: id, name: ' ' }, 'name'], + [{ list_id: id, name: null }, 'name'], + [{ list_id: id, name: 'x'.repeat(201) }, 'name'], + [{ list_id: id, color: null }, 'color'], + [{ list_id: id, color: 'x'.repeat(21) }, 'color'], + [{ list_id: id, icon: 'x'.repeat(51) }, 'icon'], + // What the REST route takes and the tool does not. + [{ list_id: id, position: 0 }, 'position'], + [{ list_id: id, isInbox: true }, 'isInbox'], + [{ list_id: id, name: 'x', is_inbox: true }, 'is_inbox'], + [{ list_id: id, name: 'x', user_id: 'someone-else' }, 'user_id'], + [{ list_id: id, name: 'x', deleted_at: '2026-01-01T00:00:00Z' }, 'deleted_at'], + ]; + for (const [args, named] of cases) expect(await invalid(a.token, 'update_list', args), JSON.stringify(args)).toContain(named); + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toEqual([]); + }); +}); + +describe('create_tag', () => { + it.each(ERAS)('creates a tag, returns it as list_tags does with created true, journals it and notifies once, after the commit (%s)', async (era) => { + const a = await connected('write'); + const name = words('tag'); + + // The spaces around the name are not kept, and the color is stored in the spelling of the palette. + const created = await ok(a.token, 'create_tag', { name: ` ${name}\t`, color: '#e57373' }, { era }); + expect(Object.keys(created)).toEqual(['tag', 'created']); + const tag = created.tag as ShapedTag; + expect(created).toStrictEqual({ tag: { id: tag.id, name, color: '#E57373' }, created: true }); + expect(await storedTag(tag.id)).toMatchObject({ user_id: a.userId, name, color: '#E57373', deleted_at: null }); + + expect(await journal(a.userId)).toEqual([lineOf('create_tag', tag.id, a, 'tag')]); + expect(notices(a.userId)).toEqual([true]); + expect(logLines('mcp-tool')).toEqual([{ at: 'mcp-tool', tool: 'create_tag', outcome: 'ok', ms: expect.any(Number), token: a.id }]); + + // list_tags returns the same tag, and a task can carry it. + expect((await ok(a.token, 'list_tags', {}, { era })).tags).toEqual([tag]); + const task = (await ok(a.token, 'create_task', { title: words('title'), tag_ids: [tag.id] }, { era })).task as ShapedTask; + expect(task.tags).toEqual([tag]); + // Without a color: the first one of the app. + expect((await ok(a.token, 'create_tag', { name: words('tag') }, { era })).tag).toMatchObject({ color: '#4A90A4' }); + }); + + it.each(ERAS)('returns the tag the account already has under another letter case or with spaces around it: created false, no second tag, no journal line, no notice (%s)', async (era) => { + const a = await connected('write'); + const id = await newTag(a, { name: spelled('Courses'), color: '#C17767' }); + const before = await state(a); + + for (const name of ['courses', 'COURSES', ' Courses ', '\tcOURSES\n'].map(spelled)) { + // The tag as it is: its name, its color, and not the color asked for. + expect(await ok(a.token, 'create_tag', { name, color: '#8BA889' }, { era }), JSON.stringify(name)) + .toStrictEqual({ tag: { id, name: 'Courses', color: '#C17767' }, created: false }); + } + // Nothing was written, not even updated_at; no line, no notice. + expect(await state(a)).toEqual(before); + expect(await journal(a.userId)).toEqual([]); + expect(notices(a.userId)).toEqual([]); + expect(((await ok(a.token, 'list_tags', {}, { era })).tags as ShapedTag[]).map((tag) => tag.name)).toEqual(['Courses']); + // A call that creates nothing is still a call that succeeded. + expect(logLines('mcp-tool').filter((line) => line.tool === 'create_tag').map((line) => line.outcome)).toEqual(Array(4).fill('ok')); + }); + + it('reads an accented capital and its small letter as one letter, composed or not, and an accent as a difference', async () => { + const a = await connected('write'); + // Written by their code points, so that no editor composes or decomposes + // them: the capital E with an acute accent, its small letter, and the + // acute accent as a combining character. + const [CAPITAL, SMALL, ACCENT] = [String.fromCodePoint(0xc9), String.fromCodePoint(0xe9), String.fromCodePoint(0x301)]; + const composed = spelled(`${CAPITAL}picerie`); + const created = await ok(a.token, 'create_tag', { name: composed }); + expect(created).toMatchObject({ created: true, tag: { name: composed } }); + for (const name of [`${SMALL}picerie`, `${CAPITAL}PICERIE`, `E${ACCENT}picerie`, `e${ACCENT}PICERIE`].map(spelled)) { + expect(await ok(a.token, 'create_tag', { name }), JSON.stringify(name)).toStrictEqual({ tag: created.tag, created: false }); + } + // Without its accent, another name: a second tag. + expect(await ok(a.token, 'create_tag', { name: spelled('Epicerie') })).toMatchObject({ created: true, tag: { name: 'Epicerie' } }); + expect((await ok(a.token, 'list_tags')).tags).toHaveLength(2); + expect(await journal(a.userId)).toHaveLength(2); + }); + + it('does not take a deleted tag nor a tag of another account for the tag of the name', async () => { + const [a, b] = [await connected('write'), await connected('write')]; + const deleted = await newTag(a, { name: spelled('Courses'), deletedAt: GONE }); + const foreign = await newTag(b, { name: 'Courses', color: '#C17767' }); + const beforeB = await state(b); + + const created = await ok(a.token, 'create_tag', { name: spelled('courses') }); + expect(created).toMatchObject({ created: true, tag: { name: 'courses', color: '#4A90A4' } }); + const tag = created.tag as ShapedTag; + expect([deleted, foreign]).not.toContain(tag.id); + expect(await storedTag(tag.id)).toMatchObject({ user_id: a.userId }); + // Not a row of the other account changed, and nothing of it was read back. + expect(await state(b)).toEqual(beforeB); + expect(notices(b.userId)).toEqual([]); + expect(seen.answers.map((answered) => answered.text).join('\n')).not.toContain(foreign); + + // Each account finds its own. + expect(await ok(a.token, 'create_tag', { name: spelled('COURSES') })).toStrictEqual({ tag, created: false }); + expect(await ok(b.token, 'create_tag', { name: 'COURSES' })).toStrictEqual({ tag: { id: foreign, name: 'Courses', color: '#C17767' }, created: false }); + expect(await journal(a.userId)).toEqual([lineOf('create_tag', tag.id, a, 'tag')]); + expect(await journal(b.userId)).toEqual([]); + }); + + it('returns the oldest of several tags of the name, as the app and the site let them exist', async () => { + const a = await connected('write'); + const recent = await newTag(a, { name: spelled('courses'), createdAt: '2026-02-03T00:00:00Z' }); + const oldest = await newTag(a, { name: spelled('COURSES'), createdAt: '2026-02-01T00:00:00Z', color: '#C17767' }); + for (const name of ['courses', 'Courses'].map(spelled)) { + expect(await ok(a.token, 'create_tag', { name })).toStrictEqual({ tag: { id: oldest, name: 'COURSES', color: '#C17767' }, created: false }); + } + expect(recent).not.toBe(oldest); + expect((await ok(a.token, 'list_tags')).tags).toHaveLength(2); + }); + + // PGlite runs one transaction at a time: these two calls end on one tag + // with or without the account lock. What the lock adds, a second + // transaction that waits for the first on another connection, no test of + // this file can show; taskWrites.test.ts reads the lock itself. + it('two calls at once for the same name end on one tag, created by one of them', async () => { + const a = await connected('write'); + const [first, second] = await Promise.all([ + ok(a.token, 'create_tag', { name: spelled('Courses') }, { id: 1 }), + ok(a.token, 'create_tag', { name: spelled('courses') }, { id: 2 }), + ]); + expect([first.created, second.created].sort()).toEqual([false, true]); + expect((first.tag as ShapedTag).id).toBe((second.tag as ShapedTag).id); + expect(await journal(a.userId)).toHaveLength(1); + // The two calls overlap: only the number of notices is read here. + expect(notices(a.userId)).toHaveLength(1); + expect((await ok(a.token, 'list_tags')).tags).toHaveLength(1); + }); + + it.each(ERAS)('refuses a color the app does not have, whether a tag of the name exists or not, and writes nothing (%s)', async (era) => { + const a = await connected('write'); + await newTag(a, { name: spelled('Courses') }); + const before = await state(a); + for (const name of ['Courses', spelled('Maison')]) { + for (const color of ['#000000', 'red', '']) { + expect(await refused(a.token, 'create_tag', { name, color }, 'invalid_color', { era }), `${name} ${JSON.stringify(color)}`) + .toStrictEqual({ error: 'invalid_color', message: 'This color is not one of the allowed colors.' }); + } + } + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toEqual([]); + }); + + it.each([ + ['no name', {}, 'name'], + ['an empty name', { name: '' }, 'name'], + ['a name made of spaces', { name: ' \t\n ' }, 'name'], + ['a name of 101 characters', { name: 'x'.repeat(101) }, 'name'], + ['a null name', { name: null }, 'name'], + ['a color of 21 characters', { name: 'x', color: '#'.repeat(21) }, 'color'], + ['a null color', { name: 'x', color: null }, 'color'], + ['an icon', { name: 'x', icon: 'Home' }, 'icon'], + ['an account', { name: 'x', user_id: 'someone-else' }, 'user_id'], + ])('refuses %s before the tool runs', async (_label, args, named) => { + const a = await connected('write'); + const before = await state(a); + for (const era of ERAS) expect(await invalid(a.token, 'create_tag', args, { era })).toContain(named); + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toEqual([]); + }); + + it('accepts a name of 100 characters, the spaces around it not counted', async () => { + const a = await connected('write'); + expect(((await ok(a.token, 'create_tag', { name: 'x'.repeat(100) })).tag as ShapedTag).name).toBe('x'.repeat(100)); + expect(((await ok(a.token, 'create_tag', { name: ` ${'y'.repeat(100)} ` })).tag as ShapedTag).name).toBe('y'.repeat(100)); + }); +}); + +describe('update_tag', () => { + it.each(ERAS)('renames and recolors a tag on every task that carries it, moves its updated_at, and every call is a write (%s)', async (era) => { + const a = await connected('write'); + const id = await newTag(a, { color: '#C17767' }); + const task = await newTask(a); + await tagTask(task, id); + const [seeded, taskBefore] = [await storedTag(id), await stored(task)]; + const name = words('tag'); + + const renamed = await ok(a.token, 'update_tag', { tag_id: id, name: ` ${name} ` }, { era }); + expect(renamed).toStrictEqual({ tag: { id, name, color: '#C17767' } }); + // The pull of the app reads a tag on updated_at (#181): the name was + // written, updated_at moved, and nothing else. + const afterRename = await storedTag(id); + expect(afterRename.updated_at.getTime()).toBeGreaterThan(seeded.updated_at.getTime()); + expect(afterRename).toEqual({ ...seeded, name, updated_at: afterRename.updated_at }); + + const recolored = await ok(a.token, 'update_tag', { tag_id: id, color: '#4db6ac' }, { era }); + expect(recolored).toStrictEqual({ tag: { id, name, color: '#4DB6AC' } }); + + // The task that carries the tag shows it renamed; neither its link nor its row was written. + expect(((await ok(a.token, 'get_task', { task_id: task }, { era })).task as ShapedTask).tags).toEqual([recolored.tag]); + expect(await stored(task)).toEqual(taskBefore); + + // The values the tag already has: a write all the same, a minute later. + await frozen(async (advance) => { + advance(60_000); + expect(await ok(a.token, 'update_tag', { tag_id: id, name, color: '#4DB6AC' }, { era })).toEqual(recolored); + expect(await storedTag(id)).toEqual({ ...seeded, name, color: '#4DB6AC', updated_at: new Date(Date.now()) }); + }); + + expect(await journal(a.userId)).toEqual(Array(3).fill(lineOf('update_tag', id, a, 'tag'))); + expect(notices(a.userId)).toEqual([true, true, true]); + }); + + it('lets a tag take the name another tag already has', async () => { + const a = await connected('write'); + const first = await newTag(a, { name: spelled('Courses'), createdAt: '2026-02-01T00:00:00Z' }); + const second = await newTag(a, { name: spelled('Maison'), createdAt: '2026-02-02T00:00:00Z' }); + expect(await ok(a.token, 'update_tag', { tag_id: second, name: 'Courses' })).toMatchObject({ tag: { id: second, name: 'Courses' } }); + expect(((await ok(a.token, 'list_tags')).tags as ShapedTag[]).map((tag) => tag.name)).toEqual(['Courses', 'Courses']); + // create_tag still creates no third one: it returns the older of the two. + expect(await ok(a.token, 'create_tag', { name: spelled('courses') })).toMatchObject({ created: false, tag: { id: first } }); + }); + + it.each(ERAS)('refuses a tag that is unknown, deleted or of another account, and a color the app does not have, and writes nothing (%s)', async (era) => { + const [a, b] = [await connected('write'), await connected('write')]; + const id = await newTag(a, { color: '#C17767' }); + const foreign = await newTag(b); + const cases: [Json, keyof typeof TOOL_ERROR_MESSAGES][] = [ + [{ tag_id: u(), name: words('tag') }, 'tag_not_found'], + [{ tag_id: await newTag(a, { deletedAt: GONE }), name: words('tag') }, 'tag_not_found'], + [{ tag_id: foreign, name: words('tag') }, 'tag_not_found'], + [{ tag_id: foreign.toUpperCase(), color: '#8BA889' }, 'tag_not_found'], + [{ tag_id: id, name: words('tag'), color: 'red' }, 'invalid_color'], + [{ tag_id: id, color: '' }, 'invalid_color'], + // The tag first, then the color. + [{ tag_id: foreign, color: 'red' }, 'tag_not_found'], + ]; + const before = await state(a, b); + for (const [args, code] of cases) { + // The code and its fixed message, nothing else: a tag of another + // account reads like a tag that does not exist. + expect(await refused(a.token, 'update_tag', args, code, { era }), JSON.stringify(args)) + .toStrictEqual({ error: code, message: TOOL_ERROR_MESSAGES[code] }); + } + expect(await state(a, b)).toEqual(before); + expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]); + expect(logLines('mcp-tool').map((line) => line.outcome)).toEqual(cases.map(([, code]) => code)); + + // The other account changes its own tag. + expect((await ok(b.token, 'update_tag', { tag_id: foreign, color: '#E57373' }, { era })).tag).toMatchObject({ id: foreign, color: '#E57373' }); + }); + + it('refuses a call without a field to change, and a field it does not take, before the tool runs', async () => { + const a = await connected('write'); + const id = await newTag(a); + const before = await state(a); + for (const era of ERAS) { + expect(await invalid(a.token, 'update_tag', { tag_id: id }, { era })) + .toContain('Nothing to change: pass at least one of name, color.'); + } + const cases: [Json, string][] = [ + [{ name: 'x' }, 'tag_id'], + [{ tag_id: 'red', name: 'x' }, 'tag_id'], + [{ tag_id: id, name: '' }, 'name'], + [{ tag_id: id, name: ' ' }, 'name'], + [{ tag_id: id, name: null }, 'name'], + [{ tag_id: id, name: 'x'.repeat(101) }, 'name'], + [{ tag_id: id, color: null }, 'color'], + [{ tag_id: id, color: 'x'.repeat(21) }, 'color'], + [{ tag_id: id, icon: 'Home' }, 'icon'], + [{ tag_id: id, name: 'x', user_id: 'someone-else' }, 'user_id'], + [{ tag_id: id, name: 'x', deleted_at: '2026-01-01T00:00:00Z' }, 'deleted_at'], + ]; + for (const [args, named] of cases) expect(await invalid(a.token, 'update_tag', args), JSON.stringify(args)).toContain(named); + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toEqual([]); + }); +}); + +describe('the list and tag tools and the other accounts', () => { + it.each(ERAS)('no list or tag tool writes a row of another account, nor reads one back (%s)', async (era) => { + const [a, b] = [await connected('write'), await connected('write')]; + const [listName, tagName] = [words('list'), words('tag')]; + const listB = await newList(b, { name: listName, color: '#C17767', icon: 'Home', position: 40 }); + const tagB = await newTag(b, { name: tagName, color: '#C17767' }); + await tagTask(await newTask(b, { list: listB }), tagB); + + const attempts: [string, Json, keyof typeof TOOL_ERROR_MESSAGES][] = [ + // A list of the other account, its Inbox included: renamed, recolored, its icon set or removed. + ['update_list', { list_id: listB, name: words('list') }, 'list_not_found'], + ['update_list', { list_id: listB, color: '#8BA889' }, 'list_not_found'], + ['update_list', { list_id: listB, icon: 'Star' }, 'list_not_found'], + ['update_list', { list_id: listB, icon: null }, 'list_not_found'], + ['update_list', { list_id: b.inbox, name: words('list') }, 'list_not_found'], + // A tag of the other account: renamed, recolored. + ['update_tag', { tag_id: tagB, name: words('tag') }, 'tag_not_found'], + ['update_tag', { tag_id: tagB, color: '#8BA889' }, 'tag_not_found'], + ]; + const [before, beforeB] = [await state(a, b), await state(b)]; + for (const [name, args, code] of attempts) { + expect(await refused(a.token, name, args, code, { era }), `${name} ${JSON.stringify(args)}`) + .toStrictEqual({ error: code, message: TOOL_ERROR_MESSAGES[code] }); + } + // Not a row of either account changed, no line was journaled, nobody was notified. + expect(await state(a, b)).toEqual(before); + expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]); + // Nothing of the refusals tells one case from another, within a code. + expect(new Set(seen.answers.map((answered) => answered.text)).size).toBe(2); + + // The name of a tag of the other account is free in this one: a tag of + // the account is created, and theirs is not returned. + const own = await ok(a.token, 'create_tag', { name: tagName.toUpperCase() }, { era }); + expect(own).toMatchObject({ created: true, tag: { name: tagName.toUpperCase(), color: '#4A90A4' } }); + expect((own.tag as ShapedTag).id).not.toBe(tagB); + // A list of the account goes after the lists of the account: those of the other do not count. + const made = (await ok(a.token, 'create_list', { name: words('list') }, { era })).list as ShapedList; + expect(await storedList(made.id)).toMatchObject({ user_id: a.userId, position: 1 }); + + // The rows of the other account are as they were, and nothing of them was read back. + expect(await state(b)).toEqual(beforeB); + const answered = seen.answers.map((x) => x.text).join('\n'); + for (const leak of [listName, tagName, listB, tagB, b.inbox]) expect(answered).not.toContain(leak); + + // The other account does all of it on its own rows. + expect((await ok(b.token, 'update_list', { list_id: listB, icon: null }, { era })).list).toMatchObject({ id: listB, name: listName, icon: null, open_task_count: 1 }); + expect((await ok(b.token, 'update_tag', { tag_id: tagB, color: '#8BA889' }, { era })).tag).toStrictEqual({ id: tagB, name: tagName, color: '#8BA889' }); + expect(await ok(b.token, 'create_tag', { name: ` ${tagName.toUpperCase()} ` }, { era })).toStrictEqual({ tag: { id: tagB, name: tagName, color: '#8BA889' }, created: false }); + expect((await journal(b.userId)).map((line) => `${line.tool} ${line.entity_type} ${line.entity_id} ${line.token_id}`).sort()) + .toEqual([`update_list list ${listB} ${b.id}`, `update_tag tag ${tagB} ${b.id}`]); + expect((await journal(a.userId)).map((line) => line.tool).sort()).toEqual(['create_list', 'create_tag']); + expect([notices(a.userId), notices(b.userId)]).toEqual([[true, true], [true, true]]); + }); +}); + +describe('the journal, the notice and the limit of a write on a list or a tag', () => { + // A token revoked while its request runs (#199), as for the task tools. + it('takes the write back when its journal line cannot be written, and serves a create_tag that writes nothing', async () => { + const a = await connected('write'); + const list = await newList(a); + const tag = await newTag(a, { name: spelled('Courses') }); + const revoked = { userId: a.userId, scope: 'write', tokenId: u(), tokenName: 'Assistant' } as const; + const writes: [string, Json][] = [ + ['create_list', { name: words('list') }], + ['update_list', { list_id: list, name: words('list') }], + ['create_tag', { name: words('tag') }], + ['update_tag', { tag_id: tag, color: '#C17767' }], + ]; + const before = await state(a); + for (const [name, args] of writes) { + expect(await handled(revoked, name, args), name).toStrictEqual({ + isError: true, + data: { error: 'internal_error', message: 'The server could not complete this call. Try again later.' }, + }); + } + // Neither the list, nor the tag, nor the new names: nothing was kept, and nobody was notified. + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toEqual([]); + expect(logLines('mcp-tool').map((line) => `${line.tool} ${line.outcome}`)).toEqual(writes.map(([name]) => `${name} internal_error`)); + + // A create_tag that finds its tag writes no line: it is served. + expect(await handled(revoked, 'create_tag', { name: spelled('courses') })).toStrictEqual({ + isError: false, + data: { tag: { id: tag, name: 'Courses', color: '#4A90A4' }, created: false }, + }); + // Control: the same writes with the token of the account are kept. + for (const [name, args] of writes) await ok(a.token, name, args); + expect((await journal(a.userId)).map((line) => line.tool).sort()).toEqual(writes.map(([name]) => name).sort()); + expect(notices(a.userId)).toEqual(Array(4).fill(true)); + }); + + it('shows in the journal the name a touched list and a touched tag have now, and no name once they are deleted', async () => { + const a = await connected('write'); + const [listName, tagName] = [words('list'), words('tag')]; + const { list, tag } = await frozen(async (advance) => { + // One second apart: the journal is read newest first. + const createdList = (await ok(a.token, 'create_list', { name: words('list') })).list as ShapedList; + advance(1000); + const createdTag = (await ok(a.token, 'create_tag', { name: words('tag') })).tag as ShapedTag; + advance(1000); + await ok(a.token, 'update_list', { list_id: createdList.id, name: listName }); + advance(1000); + await ok(a.token, 'update_tag', { tag_id: createdTag.id, name: tagName }); + advance(1000); + // The name is taken: no tag is created, and no line is written. + await ok(a.token, 'create_tag', { name: tagName.toUpperCase() }); + return { list: createdList, tag: createdTag }; + }); + + // What the page of the assistants reads: four lines, each with the name the row has now. + const { actions, nextCursor } = await listActions(db, a.userId, { limit: 10 }); + expect(actions.map((action) => [action.tool, action.entityType, action.entityId, action.entityName])).toEqual([ + ['update_tag', 'tag', tag.id, tagName], + ['update_list', 'list', list.id, listName], + ['create_tag', 'tag', tag.id, tagName], + ['create_list', 'list', list.id, listName], + ]); + expect(nextCursor).toBeNull(); + for (const action of actions) expect(action).toMatchObject({ tokenId: a.id, tokenName: 'Assistant', tokenRevoked: false }); + // Every tool of a line is a name the page has a label for. + for (const action of actions) expect(WRITE_TOOL_NAMES).toContain(action.tool); + + // Deleted since, by the site or by the app: the lines stay, without a name. + await h.pg.query('UPDATE sl_lists SET deleted_at = now() WHERE id = $1', [list.id]); + await h.pg.query('UPDATE sl_tags SET deleted_at = now() WHERE id = $1', [tag.id]); + expect((await listActions(db, a.userId, { limit: 10 })).actions.map((action) => action.entityName)).toEqual([null, null, null, null]); + // Another account reads none of these lines. + expect((await listActions(db, (await newAccount()).userId, { limit: 10 })).actions).toEqual([]); + }); + + it('counts the four tools in the write limit of the account', async () => { + const a = await connected('write'); + const [list, tag] = [await newList(a), await newTag(a)]; + await frozen(async () => { + expect(exhaust(a.userId, 'mcp-write')).toBe(30); + const [before, transactions] = [await state(a), h.transactions]; + for (const [name, args] of [ + ['create_list', { name: 'x' }], ['update_list', { list_id: list, name: 'x' }], + ['create_tag', { name: 'x' }], ['update_tag', { tag_id: tag, name: 'x' }], + ] as const) { + expect(await refused(a.token, name, args, 'rate_limited')).toMatchObject({ retry_after_seconds: 60 }); + } + // Refused before the transaction: nothing written, nobody notified. + expect(h.transactions).toBe(transactions); + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toEqual([]); + // The reads are counted apart. + await ok(a.token, 'list_lists'); + await ok(a.token, 'list_tags'); + }); + }); +}); + describe('the journal and the notice of a write', () => { // A token revoked while its request runs: the request was authenticated, // and the row its journal line points to is gone (#199). diff --git a/web/src/lib/mcp/writeTools.ts b/web/src/lib/mcp/writeTools.ts index 5012169..8c3ece1 100644 --- a/web/src/lib/mcp/writeTools.ts +++ b/web/src/lib/mcp/writeTools.ts @@ -1,7 +1,9 @@ -// The write tools of the MCP server (#203), registered for a read-write token -// only. This module validates inputs and shapes outputs: every write is a -// function of taskWrites.ts, scoped to the account of the token, and every -// task leaves through renderTask (readTools.ts). +// The write tools of the MCP server, registered for a read-write token only: +// five on tasks (#203), four on lists and tags (#204). This module validates +// inputs and shapes outputs: every write is a function of taskWrites.ts, +// scoped to the account of the token; every task leaves through renderTask +// (readTools.ts), every list and every tag through shape.ts, as list_lists +// and list_tags return them. // // No tool removes a task, a list or a tag (DECISIONS.md, 2026-11-14), and a // change cannot be undone: the journal (agentJournal.ts) is its only trace. @@ -11,14 +13,20 @@ import { z } from 'zod'; import { db } from '@/db/client'; import { recordAction, type JournalEntityType } from '@/lib/agentJournal'; +import { DEFAULT_LIST_COLOR, DEFAULT_TAG_COLOR, LIST_COLORS, LIST_ICONS, TAG_COLORS } from '@/lib/palette'; import { RECURRENCES } from '@/lib/recurrence'; import type { Tx } from '@/lib/taskDelete'; -import { completeTask, createTask, reopenTask, setTaskTags, updateTask, type TaskRow } from '@/lib/taskWrites'; +import { loadOpenTaskCounts } from '@/lib/taskQueries'; +import { + completeTask, createList, createTag, createTask, reopenTask, setTaskTags, updateList, updateTag, updateTask, + type ListRow, type TagRow, type TaskRow, +} from '@/lib/taskWrites'; import { dueDateSchema } from '@/lib/validators'; import { notifyUserChanged } from '@/lib/ws'; import { ToolRefusal } from './errors'; import { renderTask } from './readTools'; import type { RegisterTool, ToolContext } from './server'; +import { shapeList, shapeTag, type ShapedList } from './shape'; // The names of the write tools: what the journal holds in its `tool` column. // A tool registered through registerWriteTool has its name here. @@ -28,6 +36,10 @@ export const WRITE_TOOL_NAMES = [ 'complete_task', 'reopen_task', 'set_task_tags', + 'create_list', + 'update_list', + 'create_tag', + 'update_tag', ] as const; export type WriteToolName = (typeof WRITE_TOOL_NAMES)[number]; @@ -112,6 +124,25 @@ function onTask(result: Value return { changed: result.changed, entityType: 'task', entityId: result.task.id, value: result }; } +// The journal line of a write on a list, and of a write on a tag. Their +// functions never answer null: a list or a tag that is not a live row of the +// account is refused by taskWrites.ts itself (`list_not_found`, +// `tag_not_found`), and `found`, whose message speaks of a task, is not used. +function onList(result: Value): WriteOutcome { + return { changed: result.changed, entityType: 'list', entityId: result.list.id, value: result }; +} + +function onTag(result: Value): WriteOutcome { + return { changed: result.changed, entityType: 'tag', entityId: result.tag.id, value: result }; +} + +// A list as list_lists returns it: its open tasks are counted after the +// commit (a list that was just created has none). +async function renderList(userId: string, list: ListRow): Promise { + const open = await loadOpenTaskCounts(userId); + return shapeList(list, open[list.id] ?? 0); +} + // `tag_ids` holds at most 20 ids, as the tag filter of list_tasks. With the // other arguments, the largest call (create_task: 8 keys and 20 ids) stays // below `maxToolInputElements` (server.ts), which bounds a hostile array @@ -165,6 +196,56 @@ const setTaskTagsInput = z.object({ tag_ids: tagIds.describe('Ids of the tags the task must have, 20 at most. An empty list removes every tag.'), }).strict(); +// A name is trimmed, then bounded: 200 characters for a list and 100 for a +// tag, as the REST API. A name made of spaces only is refused here, before +// the tool: errors.ts has no code for a name. +const listName = z.string().trim().min(1).max(200); +const tagName = z.string().trim().min(1).max(100); +// A color and an icon are bounded texts here (the bounds of the REST API), +// not enums: a value outside the palette of the app (palette.ts) reaches +// taskWrites.ts, which refuses it with a code and a message the model reads +// (`invalid_color`, `invalid_icon`). The descriptions list the values. +const color = z.string().max(20); +const icon = z.string().max(50); + +const LIST_COLOR_VALUES = `one of ${LIST_COLORS.join(', ')}`; +const TAG_COLOR_VALUES = `one of ${TAG_COLORS.join(', ')}`; +const LIST_ICON_VALUES = `one of ${LIST_ICONS.join(', ')}`; + +const createListInput = z.object({ + name: listName.describe('Name of the list, 1 to 200 characters.'), + color: color.optional().describe(`Color of the list: ${LIST_COLOR_VALUES}. Default: ${DEFAULT_LIST_COLOR}.`), + icon: icon.optional().describe(`Icon of the list: ${LIST_ICON_VALUES}. Without it, the list has no icon.`), +}).strict(); + +const UPDATE_LIST_FIELDS = ['name', 'color', 'icon'] as const; + +const updateListInput = z.object({ + list_id: z.string().uuid().describe('Id of the list. The Inbox cannot be changed.'), + name: listName.optional().describe('New name, 1 to 200 characters.'), + color: color.optional().describe(`New color: ${LIST_COLOR_VALUES}.`), + icon: icon.nullable().optional().describe(`New icon: ${LIST_ICON_VALUES}; null removes the icon.`), +}).strict().refine( + (input) => UPDATE_LIST_FIELDS.some((field) => input[field] !== undefined), + { message: `Nothing to change: pass at least one of ${UPDATE_LIST_FIELDS.join(', ')}.` }, +); + +const createTagInput = z.object({ + name: tagName.describe('Name of the tag, 1 to 100 characters.'), + color: color.optional().describe(`Color of the tag: ${TAG_COLOR_VALUES}. Default: ${DEFAULT_TAG_COLOR}. Not applied when a tag of this name already exists.`), +}).strict(); + +const UPDATE_TAG_FIELDS = ['name', 'color'] as const; + +const updateTagInput = z.object({ + tag_id: z.string().uuid().describe('Id of the tag.'), + name: tagName.optional().describe('New name, 1 to 100 characters.'), + color: color.optional().describe(`New color: ${TAG_COLOR_VALUES}.`), +}).strict().refine( + (input) => UPDATE_TAG_FIELDS.some((field) => input[field] !== undefined), + { message: `Nothing to change: pass at least one of ${UPDATE_TAG_FIELDS.join(', ')}.` }, +); + export function registerWriteTools(register: RegisterTool): void { // Adds a task: nothing existing is changed. registerWriteTool(register, { @@ -242,4 +323,61 @@ export function registerWriteTools(register: RegisterTool): void { changed: result.changed, }), }); + + // Adds a list: nothing existing is changed. Not idempotent: calling it + // again creates a second list of the same name. + registerWriteTool(register, { + name: 'create_list', + description: 'Creates a list and returns it. The list is placed after the other lists of the account. Two lists may have the same name: call list_lists first to see whether the list already exists.', + inputSchema: createListInput, + annotations: { destructiveHint: false }, + write: async (tx, input, { userId }) => onList(await createList(tx, userId, { + name: input.name, + color: input.color, + icon: input.icon, + })), + render: async ({ list }, { userId }) => ({ list: await renderList(userId, list) }), + }); + + // Overwrites values: the previous ones are lost. + registerWriteTool(register, { + name: 'update_list', + description: 'Changes the name, the color or the icon of a list and returns it. Only the fields passed are changed; a null icon removes the icon. The previous values are not kept: a change cannot be undone. The Inbox cannot be changed, and no list can be deleted.', + inputSchema: updateListInput, + annotations: { destructiveHint: true, idempotentHint: true }, + write: async (tx, input, { userId }) => onList(await updateList(tx, userId, input.list_id, { + name: input.name, + color: input.color, + icon: input.icon, + })), + render: async ({ list }, { userId }) => ({ list: await renderList(userId, list) }), + }); + + // Adds a tag, or finds the one of that name: calling it again with the same + // name returns the same tag. createTag takes the account lock, and it is + // the first statement of the transaction of the envelope. + registerWriteTool(register, { + name: 'create_tag', + description: 'Creates a tag and returns it, with created true. When the account already has a tag of this name, whatever the letter case and the spaces around it, no second tag is created: the existing tag is returned as it is, with created false, and the color passed is not applied.', + inputSchema: createTagInput, + annotations: { destructiveHint: false, idempotentHint: true }, + write: async (tx, input, { userId }) => onTag(await createTag(tx, userId, { + name: input.name, + color: input.color, + })), + render: async ({ tag, changed }) => ({ tag: shapeTag(tag), created: changed }), + }); + + // Overwrites values: the previous ones are lost, on every task that carries the tag. + registerWriteTool(register, { + name: 'update_tag', + description: 'Changes the name or the color of a tag and returns it. Only the fields passed are changed, and the tag changes on every task that carries it. The previous values are not kept: a change cannot be undone. A tag may take a name another tag already has, and no tag can be deleted.', + inputSchema: updateTagInput, + annotations: { destructiveHint: true, idempotentHint: true }, + write: async (tx, input, { userId }) => onTag(await updateTag(tx, userId, input.tag_id, { + name: input.name, + color: input.color, + })), + render: async ({ tag }) => ({ tag: shapeTag(tag) }), + }); } diff --git a/web/src/lib/palette.test.ts b/web/src/lib/palette.test.ts new file mode 100644 index 0000000..bd3e226 --- /dev/null +++ b/web/src/lib/palette.test.ts @@ -0,0 +1,137 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { describe, it, expect } from 'vitest'; +import { DEFAULT_LIST_COLOR, DEFAULT_TAG_COLOR, LIST_COLORS, LIST_ICONS, TAG_COLORS, paletteColor } from './palette'; +import * as tagEditing from './tagEditing'; + +// The palette of the companion against the one of the app (#204). The app +// lives at the root of the repository, outside web/: its sources are found +// from this file, never from the working directory. + +const ROOT = path.join(__dirname, '../../..'); +const LISTS_SCREEN = 'app/(tabs)/lists.tsx'; +const SETTINGS_SCREEN = 'app/(tabs)/settings.tsx'; + +function appSource(file: string): string { + const full = path.join(ROOT, file); + if (!fs.existsSync(full)) throw new Error(`${file} is no longer where palette.test.ts reads it: ${full}`); + return fs.readFileSync(full, 'utf8'); +} + +// What stands between the brackets of `const = [ … ]` or `= { … }`. +function literalOf(source: string, name: string, open: '[' | '{', file: string): string { + const close = open === '[' ? ']' : '}'; + const declaration = new RegExp(`\\bconst ${name}\\b[^=;]*=\\s*\\${open}([^\\${close}]*)\\${close}`); + const match = declaration.exec(source); + if (!match) throw new Error(`${name} is no longer declared as \`const ${name} = ${open} … ${close}\` in ${file}`); + return match[1]; +} + +// The entries of a literal, without its comments. An empty literal is not a +// palette: a reader that finds nothing must not let the comparison pass. +function entriesOf(body: string, name: string, file: string): string[] { + const entries = body + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/\/\/.*$/gm, '') + .split(',') + .map((entry) => entry.trim()) + .filter((entry) => entry !== ''); + if (entries.length === 0) throw new Error(`${name} is empty in ${file}`); + return entries; +} + +// The strings of an array of string literals. +function stringsOf(body: string, name: string, file: string): string[] { + return entriesOf(body, name, file).map((entry) => { + const match = /^(['"])([^'"\\]+)\1$/.exec(entry); + if (!match) throw new Error(`cannot read the entry \`${entry}\` of ${name} in ${file}`); + return match[2]; + }); +} + +// The keys of an object literal: `Key`, `Key: value` or `'key': value`. +function keysOf(body: string, name: string, file: string): string[] { + return entriesOf(body, name, file).map((entry) => { + const match = /^(?:(['"])([^'"\\]+)\1|([A-Za-z_$][\w$]*))(?:\s*:[\s\S]*)?$/.exec(entry); + if (!match) throw new Error(`cannot read the entry \`${entry}\` of ${name} in ${file}`); + return match[2] ?? match[3]; + }); +} + +describe('palette.ts', () => { + it('stays import-free: tagEditing.ts re-exports it, and the browser loads it', () => { + const source = fs.readFileSync(path.join(__dirname, 'palette.ts'), 'utf8'); + expect(source).not.toMatch(/^\s*import\s|\bimport\(|\brequire\(|^\s*export\s.*\bfrom\s+['"]/m); + expect(source).toMatch(/^export const LIST_ICONS = \[/m); + }); + + it('carries the colors and the icons of the app, in the order of the app', () => { + const lists = appSource(LISTS_SCREEN); + const settings = appSource(SETTINGS_SCREEN); + expect([...LIST_COLORS]).toEqual(stringsOf(literalOf(lists, 'LIST_COLORS', '[', LISTS_SCREEN), 'LIST_COLORS', LISTS_SCREEN)); + expect([...LIST_ICONS]).toEqual(keysOf(literalOf(lists, 'ICON_MAP', '{', LISTS_SCREEN), 'ICON_MAP', LISTS_SCREEN)); + expect([...TAG_COLORS]).toEqual(stringsOf(literalOf(settings, 'TAG_COLORS', '[', SETTINGS_SCREEN), 'TAG_COLORS', SETTINGS_SCREEN)); + }); + + it('the reader of the app sources fails on a source, a constant or an entry it no longer finds', () => { + expect(() => appSource('app/(tabs)/gone.tsx')).toThrow('app/(tabs)/gone.tsx is no longer where palette.test.ts reads it'); + // Renamed, or no longer a literal. + expect(() => literalOf("const COLORS = ['#4A90A4'];", 'LIST_COLORS', '[', 'x.tsx')).toThrow('LIST_COLORS is no longer declared'); + expect(() => literalOf('const LIST_COLORS = palette.lists;', 'LIST_COLORS', '[', 'x.tsx')).toThrow('LIST_COLORS is no longer declared'); + expect(() => literalOf('const ICON_MAP = icons();', 'ICON_MAP', '{', 'x.tsx')).toThrow('ICON_MAP is no longer declared'); + // Emptied. + expect(() => stringsOf(literalOf('const LIST_COLORS = [];', 'LIST_COLORS', '[', 'x.tsx'), 'LIST_COLORS', 'x.tsx')).toThrow('LIST_COLORS is empty in x.tsx'); + expect(() => keysOf(literalOf('const ICON_MAP = { /* none */ };', 'ICON_MAP', '{', 'x.tsx'), 'ICON_MAP', 'x.tsx')).toThrow('ICON_MAP is empty in x.tsx'); + // An entry that is not a literal. + expect(() => stringsOf("'#4A90A4', theme.blue", 'LIST_COLORS', 'x.tsx')).toThrow('cannot read the entry `theme.blue` of LIST_COLORS in x.tsx'); + expect(() => keysOf('List, ...MORE_ICONS', 'ICON_MAP', 'x.tsx')).toThrow('cannot read the entry `...MORE_ICONS` of ICON_MAP in x.tsx'); + + // Control: what it reads when the literals are there. + const source = "const ICON_MAP: Record = {\n List, // the default\n 'Shopping-Cart': Cart,\n Home: House,\n};\nconst LIST_COLORS = ['#4A90A4', \"#C17767\",\n];"; + expect(keysOf(literalOf(source, 'ICON_MAP', '{', 'x.tsx'), 'ICON_MAP', 'x.tsx')).toEqual(['List', 'Shopping-Cart', 'Home']); + expect(stringsOf(literalOf(source, 'LIST_COLORS', '[', 'x.tsx'), 'LIST_COLORS', 'x.tsx')).toEqual(['#4A90A4', '#C17767']); + }); + + it('gives a new list and a new tag the first color of their palette', () => { + expect(DEFAULT_LIST_COLOR).toBe(LIST_COLORS[0]); + expect(DEFAULT_TAG_COLOR).toBe(TAG_COLORS[0]); + expect([DEFAULT_LIST_COLOR, DEFAULT_TAG_COLOR]).toEqual(['#4A90A4', '#4A90A4']); + }); + + it('is what tagEditing.ts exports, and the only module tagEditing.ts loads', () => { + expect(tagEditing.TAG_COLORS).toBe(TAG_COLORS); + expect(tagEditing.DEFAULT_TAG_COLOR).toBe(DEFAULT_TAG_COLOR); + // A client component imports tagEditing.ts: whatever it loads goes to the browser. + const source = fs.readFileSync(path.join(__dirname, 'tagEditing.ts'), 'utf8'); + expect([...source.matchAll(/\bfrom\s+['"]([^'"]+)['"]/g)].map((match) => match[1])).toEqual(['./palette']); + expect(source).not.toMatch(/^\s*import\s|\bimport\(|\brequire\(/m); + }); +}); + +describe('paletteColor', () => { + it('finds a color of the palette whatever its letter case, and returns the spelling of the palette', () => { + for (const palette of [LIST_COLORS, TAG_COLORS]) { + for (const color of palette) { + expect(paletteColor(palette, color)).toBe(color); + expect(paletteColor(palette, color.toLowerCase())).toBe(color); + expect(paletteColor(palette, color.toUpperCase())).toBe(color); + } + } + expect(paletteColor(LIST_COLORS, '#4a90A4')).toBe('#4A90A4'); + }); + + it('finds nothing for a text that is not a color of the palette', () => { + for (const value of [ + '', '#', '#4A90A', '#4A90A44', '4A90A4', ' #4A90A4', '#4A90A4 ', '#4A90A4\n', '#000000', '#FFF', 'red', 'blue', + 'rgb(74, 144, 164)', '#4A90A4,#C17767', 'transparent', + ]) { + expect(paletteColor(LIST_COLORS, value), JSON.stringify(value)).toBeNull(); + } + }); + + it('reads the palette it is given', () => { + expect(paletteColor(['#ABCDEF'], '#abcdef')).toBe('#ABCDEF'); + expect(paletteColor(['#ABCDEF'], '#4A90A4')).toBeNull(); + expect(paletteColor([], '#4A90A4')).toBeNull(); + }); +}); diff --git a/web/src/lib/palette.ts b/web/src/lib/palette.ts new file mode 100644 index 0000000..81a9147 --- /dev/null +++ b/web/src/lib/palette.ts @@ -0,0 +1,73 @@ +// The colors and the icons a list or a tag may carry (#204): those the app +// offers in its own pickers, and no other. The app does not draw an icon it +// does not know, and its color pickers mark the selected color by comparing +// the stored text with these values, letter for letter. +// +// palette.test.ts reads the sources of the app and fails when the two sides +// differ: a color or an icon added to the app is added here in the same PR. +// +// No import here: tagEditing.ts re-exports the tag palette, and components +// that run in the browser load it. The zod schemas that use these values live +// in mcp/writeTools.ts. + +// LIST_COLORS of app/(tabs)/lists.tsx, in its order. +export const LIST_COLORS = [ + '#4A90A4', + '#C17767', + '#8BA889', + '#D4A574', + '#7B68EE', + '#E57373', + '#4DB6AC', +] as const; + +// The color the app preselects for a new list. +export const DEFAULT_LIST_COLOR = LIST_COLORS[0]; + +// TAG_COLORS of app/(tabs)/settings.tsx, in its order. +export const TAG_COLORS = [ + '#4A90A4', + '#C17767', + '#8BA889', + '#D4A574', + '#7B68EE', + '#E57373', + '#4DB6AC', +] as const; + +// The color the app preselects for a new tag. +export const DEFAULT_TAG_COLOR = TAG_COLORS[0]; + +// The keys of ICON_MAP of app/(tabs)/lists.tsx, in its order: the names the +// app stores in `icon`, and the only ones it draws. +export const LIST_ICONS = [ + 'List', + 'ShoppingCart', + 'Briefcase', + 'Home', + 'Heart', + 'Star', + 'BookOpen', + 'GraduationCap', + 'Dumbbell', + 'Utensils', + 'Plane', + 'Music', + 'Code', + 'Wrench', + 'Gift', + 'Camera', + 'Palette', + 'Dog', + 'Leaf', + 'Zap', +] as const; + +// The color of `palette` that `value` names, or null. A hex color reads the +// same in both letter cases (`#4a90a4` is `#4A90A4`): the letter case of the +// value is not compared, and the spelling returned is the one of the palette, +// the only one to store. Nothing else is tolerated: no space, no short form. +export function paletteColor(palette: readonly Color[], value: string): Color | null { + const wanted = value.toLowerCase(); + return palette.find((color) => color.toLowerCase() === wanted) ?? null; +} diff --git a/web/src/lib/tagEditing.ts b/web/src/lib/tagEditing.ts index 92943bd..f086f97 100644 --- a/web/src/lib/tagEditing.ts +++ b/web/src/lib/tagEditing.ts @@ -3,17 +3,9 @@ // after a deletion and the URL after the active filter's tag is deleted. // Same palette as the app's tag modal (app/(tabs)/settings.tsx, TAG_COLORS). -export const TAG_COLORS = [ - '#4A90A4', - '#C17767', - '#8BA889', - '#D4A574', - '#7B68EE', - '#E57373', - '#4DB6AC', -] as const; - -export const DEFAULT_TAG_COLOR = TAG_COLORS[0]; +// It lives in palette.ts (#204), which the MCP tools share and which a test +// compares with the app; the tag manager keeps importing it from here. +export { TAG_COLORS, DEFAULT_TAG_COLOR } from './palette'; // Same bound as createTagSchema / updateTagSchema in validators.ts. export const TAG_NAME_MAX = 100; diff --git a/web/src/lib/taskWrites.test.ts b/web/src/lib/taskWrites.test.ts index 59191b1..1658d24 100644 --- a/web/src/lib/taskWrites.test.ts +++ b/web/src/lib/taskWrites.test.ts @@ -2,10 +2,13 @@ import fs from 'node:fs'; import path from 'node:path'; import { randomUUID as u } from 'node:crypto'; import { describe, it, expect, beforeAll, vi } from 'vitest'; +import { sql } from 'drizzle-orm'; import type { PGlite } from 'electric-sql-pglite'; +import { LIST_COLORS, LIST_ICONS, TAG_COLORS } from './palette'; -// createTask, updateTask and setTaskTags (#203), called as the write envelope -// of the MCP tools calls them: in a transaction of the caller, against an +// createTask, updateTask and setTaskTags (#203), then createList, updateList, +// createTag and updateTag (#204), called as the write envelope of the MCP +// tools calls them: in a transaction of the caller, against an // in-memory Postgres (PGlite) with the companion migrations. completeTask and // reopenTask are tested with the route that shares them // (../app/api/tasks/route.test.ts). The database client is replaced by @@ -24,11 +27,17 @@ vi.mock('@/db/client', async () => { }); const { db } = await import('@/db/client'); -const { createTask, updateTask, setTaskTags, WriteRefusal } = await import('./taskWrites'); +const { + createTask, updateTask, setTaskTags, createList, updateList, createTag, updateTag, WriteRefusal, +} = await import('./taskWrites'); const { ToolRefusal } = await import('./mcp/errors'); type CreateInput = Parameters[2]; type Patch = Parameters[3]; +type ListInput = Parameters[2]; +type ListPatch = Parameters[3]; +type TagInput = Parameters[2]; +type TagPatch = Parameters[3]; type Account = { userId: string; inbox: string }; @@ -44,6 +53,22 @@ type TaskFields = { dueDate?: string; recurrence?: string; deletedAt?: string; }; +// Every column of sl_lists and of sl_tags, as PGlite returns a row. +type StoredList = { + id: string; user_id: string; name: string; color: string | null; icon: string | null; position: number; + is_inbox: boolean; created_at: Date; updated_at: Date; deleted_at: Date | null; +}; + +type StoredTag = { + id: string; user_id: string; name: string; color: string; created_at: Date; updated_at: Date; deleted_at: Date | null; +}; + +type ListFields = { + inbox?: boolean; name?: string; color?: string; icon?: string; position?: number; createdAt?: string; deletedAt?: string; +}; + +type TagFields = { name?: string; color?: string; createdAt?: string; deletedAt?: string }; + // When the rows of a test were written, when a deleted one was deleted, and // the instant the function under test receives. const SEEDED = '2026-11-01T10:00:00.000Z'; @@ -58,11 +83,15 @@ async function rows(sql: string, params: unknown[] = []): Promise { // one that never synced a device. const bare = () => `user-${u()}`; -async function newList(userId: string, fields: { inbox?: boolean; createdAt?: string; deletedAt?: string } = {}): Promise { +async function newList(userId: string, fields: ListFields = {}): Promise { const id = u(); await h.pg.query( - 'insert into sl_lists (id, user_id, name, is_inbox, created_at, deleted_at) values ($1, $2, $3, $4, $5, $6)', - [id, userId, fields.inbox ? 'Inbox' : 'List', fields.inbox ?? false, fields.createdAt ?? SEEDED, fields.deletedAt ?? null], + `insert into sl_lists (id, user_id, name, color, icon, position, is_inbox, created_at, updated_at, deleted_at) + values ($1, $2, $3, $4, $5, $6, $7, $8, $8, $9)`, + [ + id, userId, fields.name ?? (fields.inbox ? 'Inbox' : 'List'), fields.color ?? null, fields.icon ?? null, + fields.position ?? 0, fields.inbox ?? false, fields.createdAt ?? SEEDED, fields.deletedAt ?? null, + ], ); return id; } @@ -91,9 +120,12 @@ async function newTask(account: Account, fields: TaskFields = {}): Promise { +async function newTag(userId: string, fields: TagFields = {}): Promise { const id = u(); - await h.pg.query('insert into sl_tags (id, user_id, name, deleted_at) values ($1, $2, $3, $4)', [id, userId, 'Tag', fields.deletedAt ?? null]); + await h.pg.query( + 'insert into sl_tags (id, user_id, name, color, created_at, updated_at, deleted_at) values ($1, $2, $3, $4, $5, $5, $6)', + [id, userId, fields.name ?? 'Tag', fields.color ?? '#4A90A4', fields.createdAt ?? SEEDED, fields.deletedAt ?? null], + ); return id; } @@ -105,6 +137,32 @@ async function stored(id: string): Promise { return (await rows('select * from sl_tasks where id = $1', [id]))[0]; } +async function storedList(id: string): Promise { + return (await rows('select * from sl_lists where id = $1', [id]))[0]; +} + +async function storedTag(id: string): Promise { + return (await rows('select * from sl_tags where id = $1', [id]))[0]; +} + +// The names of the live tags of an account, in a stable order. +async function tagNames(userId: string): Promise { + return (await rows<{ name: string }>( + 'select name from sl_tags where user_id = $1 and deleted_at is null order by created_at, id', [userId], + )).map((row) => row.name); +} + +// How many transaction-level advisory locks are held on the key of an account +// (accountLock.ts): the key is the 64-bit hash of the account, which pg_locks +// shows in two halves. +async function accountLocks(executor: Pick, userId: string): Promise { + const result = await executor.execute(sql` + select count(*)::int as held from pg_locks + where locktype = 'advisory' and objsubid = 1 + and ((classid::bigint << 32) | objid::bigint) = hashtextextended(${userId}, 0)`); + return (result.rows[0] as { held: number }).held; +} + // The tags a task is linked to, whatever they are, in a stable order. async function tagsOf(taskId: string): Promise { return (await rows<{ tag_id: string }>('select tag_id from sl_task_tags where task_id = $1 order by tag_id', [taskId])) @@ -131,6 +189,10 @@ async function everything() { const create = (userId: string, input: CreateInput) => db.transaction((tx) => createTask(tx, userId, input, NOW)); const update = (userId: string, taskId: string, patch: Patch) => db.transaction((tx) => updateTask(tx, userId, taskId, patch, NOW)); const setTags = (userId: string, taskId: string, tagIds: string[]) => db.transaction((tx) => setTaskTags(tx, userId, taskId, tagIds, NOW)); +const makeList = (userId: string, input: ListInput) => db.transaction((tx) => createList(tx, userId, input, NOW)); +const changeList = (userId: string, listId: string, patch: ListPatch) => db.transaction((tx) => updateList(tx, userId, listId, patch, NOW)); +const makeTag = (userId: string, input: TagInput) => db.transaction((tx) => createTag(tx, userId, input, NOW)); +const changeTag = (userId: string, tagId: string, patch: TagPatch) => db.transaction((tx) => updateTag(tx, userId, tagId, patch, NOW)); // The code a write is refused with. The refusal is the exception the envelope // of the MCP tools renders, and it left nothing behind. @@ -480,6 +542,361 @@ describe('setTaskTags', () => { }); }); +describe('createList', () => { + it('puts a list after the live lists of the account, the Inbox counted, with the defaults of the app', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + await newList(A.userId, { position: 4 }); + // Neither a deleted list nor a list of another account counts. + await newList(A.userId, { position: 9, deletedAt: GONE }); + await newList(B.userId, { position: 50 }); + const before = await everything(); + + const result = await makeList(A.userId, { name: ' Groceries \n' }); + expect(result.changed).toBe(true); + expect(await storedList(result.list.id)).toEqual({ + id: result.list.id, user_id: A.userId, name: 'Groceries', color: '#4A90A4', icon: null, position: 5, + is_inbox: false, created_at: NOW, updated_at: NOW, deleted_at: null, + }); + // The row it returns is the row it wrote, and it wrote no other. + expect(result.list).toMatchObject({ id: result.list.id, userId: A.userId, name: 'Groceries', position: 5, isInbox: false, updatedAt: NOW }); + expect(await rows('select * from sl_lists where id <> $1 order by id', [result.list.id])).toEqual(before.lists); + + // The next one follows it. + expect((await makeList(A.userId, { name: 'Next' })).list.position).toBe(6); + // The Inbox is a list like another: an account whose only list is an Inbox at position 3. + const moved = bare(); + await newList(moved, { inbox: true, position: 3 }); + expect((await makeList(moved, { name: 'After the Inbox' })).list.position).toBe(4); + // An account without a list: the first position, and no Inbox is created for it. + const empty = bare(); + const first = await makeList(empty, { name: 'First' }); + expect(first.list.position).toBe(1); + expect(await listsOf(empty)).toEqual([{ id: first.list.id, name: 'First', is_inbox: false, deleted_at: null }]); + }); + + it('takes every color and every icon of the app, the color in the spelling of the palette, and lets two lists share a name', async () => { + const A = await newAccount(); + for (const color of LIST_COLORS) { + for (const given of [color, color.toLowerCase()]) { + const { list } = await makeList(A.userId, { name: 'Colored', color: given }); + expect((await storedList(list.id)).color, given).toBe(color); + } + } + for (const icon of LIST_ICONS) { + const { list } = await makeList(A.userId, { name: 'Drawn', icon }); + expect(await storedList(list.id)).toMatchObject({ icon, color: '#4A90A4' }); + } + const names = (await listsOf(A.userId)).map((list) => list.name); + expect(names.filter((name) => name === 'Colored')).toHaveLength(2 * LIST_COLORS.length); + expect(names.filter((name) => name === 'Drawn')).toHaveLength(LIST_ICONS.length); + }); + + it('refuses a color or an icon the app does not have, and writes nothing', async () => { + const A = await newAccount(); + for (const color of ['#000000', 'red', '', ' #4A90A4', '#4A90A', '#4A90A4;']) { + expect(await refusal(() => makeList(A.userId, { name: 'Colored', color })), JSON.stringify(color)).toBe('invalid_color'); + } + // An icon is a name of the app, letter for letter. + for (const icon of ['Rocket', 'home', 'HOME', '', 'Home ', 'List,Home']) { + expect(await refusal(() => makeList(A.userId, { name: 'Drawn', icon })), JSON.stringify(icon)).toBe('invalid_icon'); + } + expect(await refusal(() => makeList(A.userId, { name: 'Both', color: 'red', icon: 'Rocket' }))).toBe('invalid_color'); + }); +}); + +describe('updateList', () => { + it('writes the fields of the patch and no other, and moves updatedAt', async () => { + const A = await newAccount(); + const id = await newList(A.userId, { name: 'Old', color: '#C17767', icon: 'Home', position: 3 }); + const before = await storedList(id); + + const renamed = await changeList(A.userId, id, { name: ' New ' }); + expect(renamed).toMatchObject({ changed: true, list: { id, name: 'New', color: '#C17767', icon: 'Home', position: 3, updatedAt: NOW } }); + expect(await storedList(id)).toEqual({ ...before, name: 'New', updated_at: NOW }); + + // A color in the spelling of the palette, whatever the letter case given. + await changeList(A.userId, id, { color: '#8ba889', icon: 'Star' }); + expect(await storedList(id)).toEqual({ ...before, name: 'New', color: '#8BA889', icon: 'Star', updated_at: NOW }); + + // A null icon removes the icon, and nothing else. + expect(await changeList(A.userId, id, { icon: null })).toMatchObject({ changed: true, list: { id, icon: null } }); + expect(await storedList(id)).toEqual({ ...before, name: 'New', color: '#8BA889', icon: null, updated_at: NOW }); + }); + + it('moves updatedAt for a color alone and for an icon alone', async () => { + const A = await newAccount(); + for (const patch of [{ color: '#E57373' }, { icon: 'Zap' }, { icon: null }] satisfies ListPatch[]) { + const id = await newList(A.userId, { color: '#C17767', icon: 'Home' }); + const before = await storedList(id); + expect(before.updated_at).toEqual(new Date(SEEDED)); + await changeList(A.userId, id, patch); + expect(await storedList(id), JSON.stringify(patch)).toEqual({ ...before, ...patch, updated_at: NOW }); + } + }); + + it('counts a patch that changes no value as a write, and a patch without a key as none', async () => { + const A = await newAccount(); + const id = await newList(A.userId, { name: 'Same', color: '#C17767', icon: 'Home' }); + const before = await storedList(id); + + expect(await changeList(A.userId, id, {})).toMatchObject({ changed: false, list: { id, updatedAt: before.updated_at } }); + expect(await storedList(id)).toEqual(before); + + expect(await changeList(A.userId, id, { name: 'Same', color: '#C17767', icon: 'Home' })).toMatchObject({ changed: true, list: { id, updatedAt: NOW } }); + expect(await storedList(id)).toEqual({ ...before, updated_at: NOW }); + }); + + it('refuses a list that is unknown, deleted or of another account, and writes nothing', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const foreign = await newList(B.userId, { name: 'Theirs', color: '#C17767' }); + const patches: ListPatch[] = [{ name: 'Taken' }, { color: '#8BA889' }, { icon: 'Home' }, { icon: null }, {}]; + for (const listId of [u(), await newList(A.userId, { deletedAt: GONE }), foreign, foreign.toUpperCase()]) { + for (const patch of patches) { + expect(await refusal(() => changeList(A.userId, listId, patch)), `${listId} ${JSON.stringify(patch)}`).toBe('list_not_found'); + } + } + // The same list for its own account, whatever the letter case of the id. + expect(await changeList(B.userId, foreign.toUpperCase(), { name: 'Mine' })).toMatchObject({ changed: true, list: { id: foreign, name: 'Mine' } }); + }); + + it('refuses the Inbox of the account, whatever the patch, and does not tell the Inbox of another account from a list that does not exist', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const deletedInbox = await newList(A.userId, { inbox: true, deletedAt: GONE }); + // A patch that would be written, one that changes nothing, and two that would be refused for their values. + const patches: ListPatch[] = [{ name: 'Renamed' }, { color: '#C17767' }, { icon: 'Home' }, { icon: null }, {}, { color: 'red' }, { icon: 'Rocket' }]; + for (const patch of patches) { + expect(await refusal(() => changeList(A.userId, A.inbox, patch)), JSON.stringify(patch)).toBe('inbox_not_editable'); + // Not found before it is an Inbox: of another account, or deleted. + expect(await refusal(() => changeList(A.userId, B.inbox, patch)), JSON.stringify(patch)).toBe('list_not_found'); + expect(await refusal(() => changeList(A.userId, deletedInbox, patch)), JSON.stringify(patch)).toBe('list_not_found'); + } + }); + + it('refuses a color or an icon the app does not have, and writes nothing of the patch', async () => { + const A = await newAccount(); + const id = await newList(A.userId, { name: 'Kept', color: '#C17767', icon: 'Home' }); + expect(await refusal(() => changeList(A.userId, id, { name: 'Renamed', color: 'red' }))).toBe('invalid_color'); + expect(await refusal(() => changeList(A.userId, id, { name: 'Renamed', icon: 'Rocket' }))).toBe('invalid_icon'); + expect(await refusal(() => changeList(A.userId, id, { name: 'Renamed', icon: 'home' }))).toBe('invalid_icon'); + expect(await refusal(() => changeList(A.userId, id, { color: 'red', icon: 'Rocket' }))).toBe('invalid_color'); + // The list is looked for first: one that does not exist, with a color that would be refused. + expect(await refusal(() => changeList(A.userId, u(), { color: 'red' }))).toBe('list_not_found'); + }); +}); + +describe('createTag', () => { + it('creates a tag with the trimmed name and a color of the palette, the first one by default', async () => { + const A = await newAccount(); + const result = await makeTag(A.userId, { name: ' Courses\t' }); + expect(result.changed).toBe(true); + expect(await storedTag(result.tag.id)).toEqual({ + id: result.tag.id, user_id: A.userId, name: 'Courses', color: '#4A90A4', created_at: NOW, updated_at: NOW, deleted_at: null, + }); + // The row it returns is the row it wrote. + expect(result.tag).toMatchObject({ id: result.tag.id, userId: A.userId, name: 'Courses', color: '#4A90A4', updatedAt: NOW }); + + for (const color of TAG_COLORS) { + const { tag } = await makeTag(A.userId, { name: `Colored ${color}`, color: color.toLowerCase() }); + expect((await storedTag(tag.id)).color).toBe(color); + } + }); + + it('returns the live tag of the account that has the name, whatever the letter case and the spaces around it, and writes nothing', async () => { + const A = await newAccount(); + const id = await newTag(A.userId, { name: 'Courses', color: '#C17767' }); + const before = await everything(); + + for (const name of ['Courses', 'courses', 'COURSES', ' cOuRsEs ', '\tcourses\n']) { + // The tag as it is: its own name, its own color, and not the color asked for. + expect(await makeTag(A.userId, { name, color: '#8BA889' }), JSON.stringify(name)).toMatchObject({ + changed: false, tag: { id, name: 'Courses', color: '#C17767', updatedAt: new Date(SEEDED) }, + }); + } + expect(await everything()).toEqual(before); + + // A name that only starts, ends or reads like it is another name. + for (const name of ['Course', 'Courses bio', 'Mes courses', 'Cour ses']) { + expect(await makeTag(A.userId, { name }), name).toMatchObject({ changed: true, tag: { name } }); + } + expect(await tagNames(A.userId)).toHaveLength(5); + }); + + it('creates one tag for the same name asked twice, and a second call finds the first', async () => { + const A = await newAccount(); + const first = await makeTag(A.userId, { name: 'Courses' }); + const second = await makeTag(A.userId, { name: 'courses ' }); + expect([first.changed, second.changed]).toEqual([true, false]); + expect(second.tag.id).toBe(first.tag.id); + expect(await tagNames(A.userId)).toEqual(['Courses']); + }); + + it('reads an accented capital and its small letter as the same letter, composed or not, and an accent as a difference', async () => { + const A = await newAccount(); + // The letters are written by their code points, so that no editor composes + // or decomposes them: the capital E with an acute accent and its small + // letter as one character each, and the acute accent as the combining + // character that follows a plain letter. + const [CAPITAL, SMALL, ACCENT] = [String.fromCodePoint(0xc9), String.fromCodePoint(0xe9), String.fromCodePoint(0x301)]; + expect([CAPITAL.length, SMALL.length, `E${ACCENT}`.length, `E${ACCENT}`.normalize('NFC')]).toEqual([1, 1, 2, CAPITAL]); + + const composed = `${CAPITAL}picerie`; + const id = (await makeTag(A.userId, { name: composed })).tag.id; + // In small letters, in capitals, and with the accent as a combining character. + for (const name of [`${SMALL}picerie`, `${CAPITAL}PICERIE`, `E${ACCENT}picerie`, `e${ACCENT}picerie`, ` ${SMALL}PICERIE `]) { + expect(await makeTag(A.userId, { name }), JSON.stringify(name)).toMatchObject({ changed: false, tag: { id, name: composed } }); + } + // Without its accent, it is another name. + const plain = await makeTag(A.userId, { name: 'Epicerie' }); + expect(plain).toMatchObject({ changed: true, tag: { name: 'Epicerie' } }); + expect(plain.tag.id).not.toBe(id); + expect(await makeTag(A.userId, { name: 'EPICERIE' })).toMatchObject({ changed: false, tag: { id: plain.tag.id } }); + + // A name given with a combining accent is stored as it was given, and found in its composed form. + const decomposed = await makeTag(A.userId, { name: `Cafe${ACCENT}` }); + expect((await storedTag(decomposed.tag.id)).name).toBe(`Cafe${ACCENT}`); + expect((await storedTag(decomposed.tag.id)).name).toHaveLength(5); + expect(await makeTag(A.userId, { name: `CAF${CAPITAL}` })).toMatchObject({ changed: false, tag: { id: decomposed.tag.id } }); + expect(await tagNames(A.userId)).toHaveLength(3); + }); + + it('does not take a deleted tag nor a tag of another account for the tag of the name', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const deleted = await newTag(A.userId, { name: 'Courses', deletedAt: GONE }); + const foreign = await newTag(B.userId, { name: 'Courses', color: '#C17767' }); + const untouched = [await storedTag(deleted), await storedTag(foreign)]; + + const created = await makeTag(A.userId, { name: 'courses' }); + expect(created).toMatchObject({ changed: true, tag: { name: 'courses', userId: A.userId, color: '#4A90A4' } }); + expect([deleted, foreign]).not.toContain(created.tag.id); + expect([await storedTag(deleted), await storedTag(foreign)]).toEqual(untouched); + + // Each account finds its own. + expect(await makeTag(A.userId, { name: 'COURSES' })).toMatchObject({ changed: false, tag: { id: created.tag.id } }); + expect(await makeTag(B.userId, { name: 'COURSES' })).toMatchObject({ changed: false, tag: { id: foreign, color: '#C17767' } }); + }); + + it('returns the oldest of several live tags of the name', async () => { + const A = await newAccount(); + // Tags of the same name, as the app and the site let them exist. + const recent = await newTag(A.userId, { name: 'courses', createdAt: '2026-10-03T00:00:00Z' }); + const oldest = await newTag(A.userId, { name: 'COURSES', createdAt: '2026-10-01T00:00:00Z' }); + const middle = await newTag(A.userId, { name: 'Courses', createdAt: '2026-10-02T00:00:00Z' }); + await newTag(A.userId, { name: 'Courses', createdAt: '2026-09-01T00:00:00Z', deletedAt: GONE }); + const before = await everything(); + // Whatever the spelling asked for, the one of a more recent tag included. + for (const name of ['courses', 'Courses', 'COURSES']) { + expect(await makeTag(A.userId, { name }), name).toMatchObject({ changed: false, tag: { id: oldest, name: 'COURSES' } }); + } + expect([recent, middle]).not.toContain(oldest); + expect(await everything()).toEqual(before); + + // Created at the same instant: the smallest id. + const B = await newAccount(); + const twins = [await newTag(B.userId, { name: 'Twin' }), await newTag(B.userId, { name: 'twin' })].sort(); + expect(await makeTag(B.userId, { name: 'TWIN' })).toMatchObject({ changed: false, tag: { id: twins[0] } }); + }); + + it('refuses a color the app does not have, whether a tag of the name exists or not, and writes nothing', async () => { + const A = await newAccount(); + await newTag(A.userId, { name: 'Courses' }); + for (const name of ['Courses', 'Other']) { + for (const color of ['#000000', 'red', '', '#4A90A4 ']) { + expect(await refusal(() => makeTag(A.userId, { name, color })), `${name} ${JSON.stringify(color)}`).toBe('invalid_color'); + } + } + }); + + // What PGlite can show of the lock: that createTag takes the lock of its + // account, and of no other, and that it lasts as long as the transaction. + // It has a single connection: no test sees a second call wait for the first. + it('holds the lock of its account until the end of the transaction, whether it creates a tag or finds one', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + for (const name of ['Locked', 'locked']) { + await db.transaction(async (tx) => { + expect(await accountLocks(tx, A.userId)).toBe(0); + await createTag(tx, A.userId, { name }, NOW); + expect(await accountLocks(tx, A.userId)).toBe(1); + expect(await accountLocks(tx, B.userId)).toBe(0); + }); + expect(await accountLocks(db, A.userId)).toBe(0); + } + expect(await tagNames(A.userId)).toEqual(['Locked']); + }); +}); + +describe('updateTag', () => { + it('writes the fields of the patch and no other, moves updatedAt, and leaves the links of the tag alone', async () => { + const A = await newAccount(); + const id = await newTag(A.userId, { name: 'Old', color: '#C17767' }); + const task = await newTask(A); + await link(task, id); + const [before, taskBefore] = [await storedTag(id), await stored(task)]; + expect(before.updated_at).toEqual(new Date(SEEDED)); + + const renamed = await changeTag(A.userId, id, { name: ' New ' }); + expect(renamed).toMatchObject({ changed: true, tag: { id, name: 'New', color: '#C17767', updatedAt: NOW } }); + expect(await storedTag(id)).toEqual({ ...before, name: 'New', updated_at: NOW }); + + // A color in the spelling of the palette, whatever the letter case given. + await changeTag(A.userId, id, { color: '#e57373' }); + expect(await storedTag(id)).toEqual({ ...before, name: 'New', color: '#E57373', updated_at: NOW }); + + expect(await tagsOf(task)).toEqual([id]); + expect(await stored(task)).toEqual(taskBefore); + }); + + it('moves updatedAt for a color alone', async () => { + const A = await newAccount(); + const id = await newTag(A.userId, { name: 'Kept', color: '#C17767' }); + const before = await storedTag(id); + await changeTag(A.userId, id, { color: '#4DB6AC' }); + expect(await storedTag(id)).toEqual({ ...before, color: '#4DB6AC', updated_at: NOW }); + expect(before.updated_at).not.toEqual(NOW); + }); + + it('counts a patch that changes no value as a write, and a patch without a key as none', async () => { + const A = await newAccount(); + const id = await newTag(A.userId, { name: 'Same', color: '#C17767' }); + const before = await storedTag(id); + + expect(await changeTag(A.userId, id, {})).toMatchObject({ changed: false, tag: { id, updatedAt: before.updated_at } }); + expect(await storedTag(id)).toEqual(before); + + expect(await changeTag(A.userId, id, { name: 'Same', color: '#C17767' })).toMatchObject({ changed: true, tag: { id, updatedAt: NOW } }); + expect(await storedTag(id)).toEqual({ ...before, updated_at: NOW }); + }); + + it('lets a tag take the name another tag already has', async () => { + const A = await newAccount(); + const [first, second] = [await newTag(A.userId, { name: 'Courses' }), await newTag(A.userId, { name: 'Maison' })]; + expect(await changeTag(A.userId, second, { name: 'Courses' })).toMatchObject({ changed: true, tag: { id: second, name: 'Courses' } }); + expect((await storedTag(first)).name).toBe('Courses'); + expect(await tagNames(A.userId)).toEqual(['Courses', 'Courses']); + }); + + it('refuses a tag that is unknown, deleted or of another account, and writes nothing', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const foreign = await newTag(B.userId, { name: 'Theirs', color: '#C17767' }); + // The tag is looked for first: a color that would be refused does not tell the cases apart. + const patches: TagPatch[] = [{ name: 'Taken' }, { color: '#8BA889' }, {}, { color: 'red' }]; + for (const tagId of [u(), await newTag(A.userId, { deletedAt: GONE }), foreign, foreign.toUpperCase()]) { + for (const patch of patches) { + expect(await refusal(() => changeTag(A.userId, tagId, patch)), `${tagId} ${JSON.stringify(patch)}`).toBe('tag_not_found'); + } + } + // The same tag for its own account, whatever the letter case of the id. + expect(await changeTag(B.userId, foreign.toUpperCase(), { name: 'Mine' })).toMatchObject({ changed: true, tag: { id: foreign, name: 'Mine' } }); + }); + + it('refuses a color the app does not have, and writes nothing of the patch', async () => { + const A = await newAccount(); + const id = await newTag(A.userId, { name: 'Kept', color: '#C17767' }); + for (const color of ['#000000', 'red', '']) { + expect(await refusal(() => changeTag(A.userId, id, { name: 'Renamed', color })), JSON.stringify(color)).toBe('invalid_color'); + } + }); +}); + describe('the contract of the module', () => { it('writes in the transaction it receives: a rollback of the caller undoes everything', async () => { const A = await newAccount(); @@ -502,6 +919,23 @@ describe('the contract of the module', () => { expect(await everything()).toEqual(before); }); + it('writes lists and tags in the transaction it receives too: a rollback of the caller undoes them', async () => { + const A = await newAccount(); + const [list, tag] = [await newList(A.userId), await newTag(A.userId)]; + const before = await everything(); + + await expect(db.transaction(async (tx) => { + // createTag first: it opens on the account lock, as in the envelope. + expect(await createTag(tx, A.userId, { name: 'New tag' }, NOW)).toMatchObject({ changed: true }); + expect(await createList(tx, A.userId, { name: 'New list' }, NOW)).toMatchObject({ changed: true }); + expect(await updateList(tx, A.userId, list, { name: 'Renamed' }, NOW)).toMatchObject({ changed: true }); + expect(await updateTag(tx, A.userId, tag, { name: 'Renamed' }, NOW)).toMatchObject({ changed: true }); + // What a refused journal line does in an MCP tool. + throw new Error('journal line refused'); + })).rejects.toThrow('journal line refused'); + expect(await everything()).toEqual(before); + }); + it('a WriteRefusal carries its code and nothing of the request', () => { const error = new WriteRefusal('tag_not_found'); expect(error).toBeInstanceOf(ToolRefusal); @@ -538,11 +972,23 @@ describe('the contract of the module', () => { expect(source).toMatch(/async function liveTagIds\([\s\S]*?\.for\('share'\);/); expect(body('updateTask')).toContain(".where(ownTask(userId, taskId)).for('no key update');"); expect(source.match(/\.for\('share'\)/g)).toHaveLength(1); + + // createTag (#204) looks for the tag of the name under the account lock, + // which is its first statement: nothing is awaited before it. + const lock = 'await lockAccount(tx, userId);'; + expect(body('createTag').indexOf('await ')).toBe(body('createTag').indexOf(lock)); + before(body('createTag'), lock, '.from(slTags)'); + before(body('createTag'), '.from(slTags)', 'tx.insert(slTags)'); + // updateList and updateTag read the row they lock, as updateTask does. + expect(body('updateList')).toContain(".where(ownList(userId, listId)).for('no key update');"); + expect(body('updateTag')).toContain(".where(ownTag(userId, tagId)).for('no key update');"); + // No other function takes the account lock: createTask for the Inbox, createTag for the name. + expect(source.match(/await lockAccount\(tx, userId\);/g)).toHaveLength(2); }); it('taskWrites.ts deletes nothing but tag links', () => { const source = fs.readFileSync(path.join(__dirname, 'taskWrites.ts'), 'utf8'); - for (const name of ['createTask', 'updateTask', 'setTaskTags']) { + for (const name of ['createTask', 'updateTask', 'setTaskTags', 'createList', 'updateList', 'createTag', 'updateTag']) { expect(source).toMatch(new RegExp(`^export async function ${name}\\(`, 'm')); } const deletes = source.match(/\.delete\([^)]*\)/g) ?? []; diff --git a/web/src/lib/taskWrites.ts b/web/src/lib/taskWrites.ts index e4cf512..baeff23 100644 --- a/web/src/lib/taskWrites.ts +++ b/web/src/lib/taskWrites.ts @@ -1,12 +1,14 @@ -import { and, desc, eq, inArray, isNull, sql, type SQL } from 'drizzle-orm'; +import { and, asc, desc, eq, inArray, isNull, sql, type SQL } from 'drizzle-orm'; import { slLists, slTags, slTasks, slTaskTags } from '@/db/schema'; import { lockAccount } from './accountLock'; import { ToolRefusal, type ToolErrorCode } from './mcp/errors'; +import { DEFAULT_LIST_COLOR, DEFAULT_TAG_COLOR, LIST_COLORS, LIST_ICONS, TAG_COLORS, paletteColor } from './palette'; import { isRecurrence, nextOccurrence, type Recurrence } from './recurrence'; import { lockTaskForLinks, type Tx } from './taskDelete'; // Task writes shared by the site (PUT /api/tasks/[id]) and by the MCP tools -// (#203, #204), so that both paths do the same thing (#201). +// (#203), so that both paths do the same thing (#201), and the writes of the +// MCP tools on lists and tags (#204). // // Contract of every function of this module: // - the transaction `tx` is the first argument, then `userId`. The caller @@ -20,13 +22,19 @@ import { lockTaskForLinks, type Tx } from './taskDelete'; // deleted row is not a row. A link (sl_task_tags has no account column) is // only read, written or locked for a task that the function has just found // in the account; -// - the result is `{ changed, ... }`, or null when the row does not exist, is -// deleted or belongs to another account. `changed: false` means that -// nothing was written; +// - the result is `{ changed, ... }`, and `changed: false` means that nothing +// was written. A function on a task answers null when the task does not +// exist, is deleted or belongs to another account. A function on a list or +// on a tag (#204) never answers null: it refuses, with the code that names +// what is missing (`list_not_found`, `tag_not_found`), as the task +// functions refuse a list or a tag their input names. A caller cannot take +// a missing list for a missing task; // - a write that must be refused throws a WriteRefusal (#203): the caller // lets it through, and its transaction is rolled back. export type TaskRow = typeof slTasks.$inferSelect; +export type ListRow = typeof slLists.$inferSelect; +export type TagRow = typeof slTags.$inferSelect; export type CompleteTaskResult = // `next` is the occurrence that was created, null when the task has none. @@ -66,6 +74,32 @@ export type UpdateTaskResult = { changed: boolean; task: TaskRow }; export type SetTaskTagsResult = { changed: boolean; task: TaskRow }; +// What createList receives. The caller bounds the name: 1 to 200 characters +// once trimmed. +export type CreateListInput = { name: string; color?: string; icon?: string }; + +export type CreateListResult = { changed: true; list: ListRow }; + +// What updateList may change. An absent key leaves its column as it is; a +// null icon removes the icon. The caller bounds the name as for createList. +export type UpdateListPatch = { name?: string; color?: string; icon?: string | null }; + +export type UpdateListResult = { changed: boolean; list: ListRow }; + +// What createTag receives. The caller bounds the name: 1 to 100 characters +// once trimmed. +export type CreateTagInput = { name: string; color?: string }; + +// `changed: false`: the account already had a live tag of this name, which is +// returned as it is. +export type CreateTagResult = { changed: boolean; tag: TagRow }; + +// What updateTag may change. An absent key leaves its column as it is. The +// caller bounds the name as for createTag. +export type UpdateTagPatch = { name?: string; color?: string }; + +export type UpdateTagResult = { changed: boolean; tag: TagRow }; + // A write that is refused (#203): an id of the input names no live row of the // account, or the write would break a rule (two levels of tasks, a subtask in // the list of its parent). It is thrown, never returned: the transaction of @@ -117,6 +151,16 @@ async function endPosition(tx: Tx, siblings: SQL | undefined): Promise { return last + 1; } +// The live list `listId` of the account. +function ownList(userId: string, listId: string) { + return and(eq(slLists.id, listId), eq(slLists.userId, userId), isNull(slLists.deletedAt)); +} + +// The live tag `tagId` of the account. +function ownTag(userId: string, tagId: string) { + return and(eq(slTags.id, tagId), eq(slTags.userId, userId), isNull(slTags.deletedAt)); +} + // The id of the live list `listId` of the account, or null. The id is the one // the database returns: a client may write the same id in another letter // case, which a comparison of two strings would take for another list. @@ -124,10 +168,40 @@ async function ownListId(tx: Tx, userId: string, listId: string): Promise(palette: readonly Color[], value: string): Color { + const color = paletteColor(palette, value); + if (color === null) throw new WriteRefusal('invalid_color'); + return color; +} + +// An icon of the app, letter for letter: the app finds the drawing of an icon +// by its name, and shows nothing for a name it does not have. +function iconOf(value: string): string { + if (!(LIST_ICONS as readonly string[]).includes(value)) throw new WriteRefusal('invalid_icon'); + return value; +} + +// What two tag names are compared by: the name without the spaces around it, +// in its composed form (NFC), in lower case. « Courses », « courses » and +// « COURSES » are one name; so are « Épicerie » and « épicerie », and the +// same word typed with a combining accent (E followed by U+0301). An accent +// still tells two names apart: « Epicerie » is not « Épicerie ». +// +// The comparison is made here and not in SQL: `lower()` of PostgreSQL follows +// the LC_CTYPE of the database (under the C locale it leaves « É » as it is), +// so the same query would find one tag on a server and none on another. +// toLowerCase() is the Unicode mapping, whatever the locale of the process; +// normalize() needs a Node built with ICU, which every official build is. +function tagNameKey(name: string): string { + return name.trim().normalize('NFC').toLowerCase(); +} + // The live Inbox of the account: the most recent one, as POST /api/sync picks // it (resolveTaskListId). An account without one gets it here: an account // that never synced a device has no list at all. The first sync of a device @@ -435,3 +509,169 @@ export async function setTaskTags( .returning(); return { changed: true, task }; } + +// Create a list (#204), after the live lists of the account, as the app does +// (src/db/repository/lists.ts): one more than their largest position, the +// Inbox counted and a deleted list not; 1 for an account without a list. The +// list takes the name without the spaces around it; a color of LIST_COLORS +// (`invalid_color`), the first one by default; an icon of LIST_ICONS +// (`invalid_icon`), none by default. Two lists may have the same name, as in +// the app and on the site. +// +// Nothing is locked: two lists created at the same moment may take the same +// position, and then follow each other by creation. +export async function createList( + tx: Tx, + userId: string, + input: CreateListInput, + now = new Date(), +): Promise { + const color = input.color === undefined ? DEFAULT_LIST_COLOR : colorOf(LIST_COLORS, input.color); + const icon = input.icon === undefined ? null : iconOf(input.icon); + + const [{ last }] = await tx + .select({ last: sql`coalesce(max(${slLists.position}), 0)`.mapWith(Number) }) + .from(slLists) + .where(and(eq(slLists.userId, userId), isNull(slLists.deletedAt))); + + // Every column is named: nothing of the input reaches the row by itself. + const [list] = await tx.insert(slLists) + .values({ + userId, + name: input.name.trim(), + color, + icon, + position: last + 1, + isInbox: false, + createdAt: now, + updatedAt: now, + }) + .returning(); + + return { changed: true, list }; +} + +// Change the name, the color or the icon of a live list of the account +// (#204). The checks come in this order: the list is a live list of the +// account (`list_not_found`: a list of another account answers like one that +// does not exist, the Inbox of another account included); it is not the Inbox +// (`inbox_not_editable`: the app shows the Inbox under a translated name); +// the color is one of LIST_COLORS (`invalid_color`); the icon is one of +// LIST_ICONS (`invalid_icon`), or null, which removes it. +// +// Only the keys of the patch are written, and `updatedAt` moves. A patch that +// names at least one key is a write, even when every value is the one the +// list already had, as for updateTask; a patch without a key writes nothing +// (`changed: false`). The position, the account and `isInbox` are never +// written. +// +// The list row is locked before it is read (FOR NO KEY UPDATE, the lock its +// update takes anyway): what is decided from the row (live, not the Inbox) +// still holds when the row is written. +export async function updateList( + tx: Tx, + userId: string, + listId: string, + patch: UpdateListPatch, + now = new Date(), +): Promise { + const [current] = await tx.select().from(slLists).where(ownList(userId, listId)).for('no key update'); + if (!current) throw new WriteRefusal('list_not_found'); + if (current.isInbox) throw new WriteRefusal('inbox_not_editable'); + + // Every column is named: a key the patch should not carry is not written. + const fields: Partial> = {}; + if (patch.name !== undefined) fields.name = patch.name.trim(); + if (patch.color !== undefined) fields.color = colorOf(LIST_COLORS, patch.color); + if (patch.icon !== undefined) fields.icon = patch.icon === null ? null : iconOf(patch.icon); + if (Object.keys(fields).length === 0) return { changed: false, list: current }; + + const [list] = await tx.update(slLists) + .set({ ...fields, updatedAt: now }) + .where(ownList(userId, current.id)) + .returning(); + + return { changed: true, list }; +} + +// Create a tag (#204), unless the account already has a live tag of this +// name: that tag is then returned as it is (`changed: false`), nothing is +// written, and the color asked for is not applied. Two names are the same +// when their tagNameKey is: the spaces around them and the letter case do not +// count. The app and the site let two tags share a name: of several live tags +// of the name, the oldest is returned (creation instant, then id). +// +// A new tag takes the name without the spaces around it, and a color of +// TAG_COLORS (`invalid_color`), the first one by default. The color is +// checked before the name is looked for: a color outside the palette is +// refused whether the tag exists or not. +// +// The account lock comes first, as accountLock.ts wants it: of two calls at +// once for the same name, the second waits for the first, then finds its tag. +// POST /api/tags and POST /api/sync do not take this lock: a tag created by +// the site or by the app at that very moment can still be a second one. +export async function createTag( + tx: Tx, + userId: string, + input: CreateTagInput, + now = new Date(), +): Promise { + await lockAccount(tx, userId); + + const name = input.name.trim(); + const color = input.color === undefined ? DEFAULT_TAG_COLOR : colorOf(TAG_COLORS, input.color); + + // The live tags of the account, the oldest first: a few dozen rows. + const live = await tx + .select() + .from(slTags) + .where(and(eq(slTags.userId, userId), isNull(slTags.deletedAt))) + .orderBy(asc(slTags.createdAt), asc(slTags.id)); + const key = tagNameKey(name); + const existing = live.find((tag) => tagNameKey(tag.name) === key); + if (existing) return { changed: false, tag: existing }; + + // Every column is named: nothing of the input reaches the row by itself. + const [tag] = await tx.insert(slTags) + .values({ userId, name, color, createdAt: now, updatedAt: now }) + .returning(); + + return { changed: true, tag }; +} + +// Change the name or the color of a live tag of the account (#204). The tag +// is a live tag of the account (`tag_not_found`: a tag of another account +// answers like one that does not exist), then the color is one of TAG_COLORS +// (`invalid_color`). A name another tag already has is allowed, as on the +// site and in the app. +// +// Only the keys of the patch are written, and `updatedAt` moves: GET +// /api/sync pulls a tag on it, and a rename that left it behind would never +// reach the app (#181). A patch that names at least one key is a write, even +// when every value is the one the tag already had; a patch without a key +// writes nothing (`changed: false`). The links of the tag are not touched. +// +// The tag row is locked before it is read, as updateList locks its list. +export async function updateTag( + tx: Tx, + userId: string, + tagId: string, + patch: UpdateTagPatch, + now = new Date(), +): Promise { + const [current] = await tx.select().from(slTags).where(ownTag(userId, tagId)).for('no key update'); + if (!current) throw new WriteRefusal('tag_not_found'); + + // Every column is named: a key the patch should not carry is not written. + const fields: Partial> = {}; + if (patch.name !== undefined) fields.name = patch.name.trim(); + if (patch.color !== undefined) fields.color = colorOf(TAG_COLORS, patch.color); + if (Object.keys(fields).length === 0) return { changed: false, tag: current }; + + const [tag] = await tx.update(slTags) + .set({ ...fields, updatedAt: now }) + .where(ownTag(userId, current.id)) + .returning(); + + return { changed: true, tag }; +}