Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

38.0 KB
Raw Blame
/**
 * Unit tests for MCP note tools: create_day_note, update_day_note, delete_day_note
 * (DayNotesMcp, DI-discovered — attached via the nest-mcp registry inside
 * registerTools, so every harness here keeps withTools on) and
 * create_collab_note, update_collab_note, delete_collab_note (CollabMcp,
 * DI-discovered via the same registry).
 */
import { CollabNotes } from '../../../src/db/entities/CollabNotes.entity';
import { DayNotes } from '../../../src/db/entities/DayNotes.entity';
import { TripFiles } from '../../../src/db/entities/TripFiles.entity';
import { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import { makeCollabNote } from '../../helpers/factories/collab';
import { makeTripFile } from '../../helpers/factories/files';
import { makeDayNote } from '../../helpers/factories/itinerary';
import { countRows, findRow, updateRows } from '../../helpers/factories/rows';
import { setCollabFeature } from '../../helpers/factories/settings';
import { makeDay, makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { FakeRealtimeService } from '../../helpers/fake-realtime';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
import { resetDatabase } from '../../helpers/reset-database';
import { bootTestApp } from '../../helpers/test-app';
import { MikroORM } from '@mikro-orm/core';

import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';

const { unlinkSyncMock } = vi.hoisted(() => ({
  unlinkSyncMock: vi.fn(),
}));
vi.mock('fs', async (importOriginal) => {
  const actual = await importOriginal<typeof import('fs')>();
  return { ...actual, unlinkSync: unlinkSyncMock };
});

const realtime = new FakeRealtimeService();
const broadcastMock = realtime.broadcastMock;

beforeEach(async () => {
  await resetDatabase(orm);
  broadcastMock.mockClear();
  unlinkSyncMock.mockClear();
  delete process.env.DEMO_MODE;
});

let orm: MikroORM;

beforeAll(async () => {
  orm = (await bootTestApp(realtime)).get(MikroORM);
});

afterAll(async () => {
  await (await bootTestApp(realtime)).close();
});

/** The stored day note; fails the case when it is gone. */
async function dayNote(id: number) {
  const row = await findRow(orm, DayNotes, { id });
  if (!row) throw new Error(`no day note ${id}`);
  return row;
}

/** The stored collab note; fails the case when it is gone. */
async function collabNote(id: number) {
  const row = await findRow(orm, CollabNotes, { id });
  if (!row) throw new Error(`no collab note ${id}`);
  return row;
}

async function withHarness(userId: number, fn: (h: McpHarness) => Promise<void>) {
  const h = await createMcpHarness({ realtime, userId, withResources: false });
  try {
    await fn(h);
  } finally {
    await h.cleanup();
  }
}

// ---------------------------------------------------------------------------
// create_day_note
// ---------------------------------------------------------------------------

describe('Tool: create_day_note', () => {
  it('creates a note on a day', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_day_note',
        arguments: { tripId: trip.id, dayId: day.id, text: 'Check in at noon', time: '12:00', icon: '🏨' },
      });
      const data = parseToolResult(result) as any;
      expect(data.note.text).toBe('Check in at noon');
      expect(data.note.time).toBe('12:00');
      expect(data.note.icon).toBe('🏨');
    });
  });

  it('describes text as the title and time as the body, as the planner shows them', async () => {
    const { user } = await makeUser(orm);
    await withHarness(user.id, async (h) => {
      const { tools } = await h.client.listTools();
      for (const name of ['create_day_note', 'update_day_note']) {
        const props = tools.find((t) => t.name === name)?.inputSchema.properties as Record<string, unknown>;
        // The nullable body may come out as an anyOf, so read the property whole.
        const time = JSON.stringify(props.time);
        expect(JSON.stringify(props.text)).toMatch(/title/i);
        expect(time).toMatch(/body/i);
        expect(time).not.toMatch(/time label/i);
        expect(time).toContain('"maxLength":2000');
      }
    });
  });

  it('takes a body of 2000 characters, the bound the planner allows, and refuses one more', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    await withHarness(user.id, async (h) => {
      const body = 'b'.repeat(2000);
      const result = await h.client.callTool({
        name: 'create_day_note',
        arguments: { tripId: trip.id, dayId: day.id, text: 'Museum day', time: body },
      });
      const data = parseToolResult(result) as { note: { id: number } };
      expect((await dayNote(data.note.id)).time).toBe(body);
      const tooLong = await h.client.callTool({
        name: 'create_day_note',
        arguments: { tripId: trip.id, dayId: day.id, text: 'Museum day', time: `${body}b` },
      });
      expect(tooLong.isError).toBe(true);
      expect(await countRows(orm, DayNotes, { day: day.id })).toBe(1);
    });
  });

  it('defaults icon to 📝', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_day_note',
        arguments: { tripId: trip.id, dayId: day.id, text: 'A note' },
      });
      const data = parseToolResult(result) as any;
      expect(data.note.icon).toBe('📝');
    });
  });

  it('broadcasts dayNote:created event', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    await withHarness(user.id, async (h) => {
      await h.client.callTool({ name: 'create_day_note', arguments: { tripId: trip.id, dayId: day.id, text: 'Note' } });
      expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'dayNote:created', expect.any(Object));
    });
  });

  it('persists a palette color and an explicit position', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_day_note',
        arguments: { tripId: trip.id, dayId: day.id, text: 'Ferry leaves early', color: '#dc2626', sort_order: 2 },
      });
      const data = parseToolResult(result) as any;
      const row = await dayNote(data.note.id);
      expect(row.color).toBe('#dc2626');
      expect(row.sort_order).toBe(2);
    });
  });

  it('stores no color and appends at the bottom when neither is given', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_day_note',
        arguments: { tripId: trip.id, dayId: day.id, text: 'A note' },
      });
      const data = parseToolResult(result) as any;
      const row = await dayNote(data.note.id);
      expect(row.color).toBeNull();
      expect(row.sort_order).toBe(9999);
    });
  });

  it('refuses a color outside the note palette and writes nothing', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_day_note',
        arguments: { tripId: trip.id, dayId: day.id, text: 'A note', color: '#ff0000' },
      });
      expect(result.isError).toBe(true);
      expect(await countRows(orm, DayNotes, { day: day.id })).toBe(0);
    });
  });

  it('returns error when day does not belong to trip', async () => {
    const { user } = await makeUser(orm);
    const trip1 = await makeTrip(orm, user.id);
    const trip2 = await makeTrip(orm, user.id);
    const dayFromTrip2 = await makeDay(orm, trip2.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_day_note',
        arguments: { tripId: trip1.id, dayId: dayFromTrip2.id, text: 'Note' },
      });
      expect(result.isError).toBe(true);
    });
  });

  it('returns access denied for non-member', async () => {
    const { user } = await makeUser(orm);
    const { user: other } = await makeUser(orm);
    const trip = await makeTrip(orm, other.id);
    const day = await makeDay(orm, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_day_note',
        arguments: { tripId: trip.id, dayId: day.id, text: 'X' },
      });
      expect(result.isError).toBe(true);
    });
  });
});

// ---------------------------------------------------------------------------
// update_day_note
// ---------------------------------------------------------------------------

describe('Tool: update_day_note', () => {
  it('updates note text, time, icon', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id, { text: 'Old text', time: '09:00', icon: '📝' });
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id, text: 'New text', time: '14:00', icon: '🍽️' },
      });
      const data = parseToolResult(result) as any;
      expect(data.note.text).toBe('New text');
      expect(data.note.time).toBe('14:00');
      expect(data.note.icon).toBe('🍽️');
    });
  });

  it('edits a note whose body is longer than 250 characters without shortening it', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    const longBody = 'Opening hours and the ticket links. '.repeat(20);
    const note = await makeDayNote(orm, day.id, trip.id, { text: 'Museum day', time: longBody });
    await withHarness(user.id, async (h) => {
      const renamed = await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id, text: 'Museums' },
      });
      expect(renamed.isError).toBeFalsy();
      const longer = `${longBody}Bring the pass.`;
      const rewritten = await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id, time: longer },
      });
      expect(rewritten.isError).toBeFalsy();
      const row = await dayNote(note.id);
      expect(row.text).toBe('Museums');
      expect(row.time).toBe(longer);
    });
  });

  it('refuses an empty title on update and keeps the stored one', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id, { text: 'Keep me' });
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id, text: '' },
      });
      expect(result.isError).toBe(true);
      expect((await dayNote(note.id)).text).toBe('Keep me');
    });
  });

  it('trims text whitespace', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id, text: '  Trimmed  ' },
      });
      const data = parseToolResult(result) as any;
      expect(data.note.text).toBe('Trimmed');
    });
  });

  it('sets color and moves the note within the day', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id, { sort_order: 9999 });
    await withHarness(user.id, async (h) => {
      await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id, color: '#16a34a', sort_order: 1.5 },
      });
      const row = await dayNote(note.id);
      expect(row.color).toBe('#16a34a');
      expect(row.sort_order).toBe(1.5);
    });
  });

  it('clears the color with an explicit null', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id);
    await updateRows(orm, DayNotes, { id: note.id }, { color: '#2563eb' });
    await withHarness(user.id, async (h) => {
      await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id, color: null },
      });
      expect((await dayNote(note.id)).color).toBeNull();
    });
  });

  it('keeps the stored color and position when neither is sent', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id, { sort_order: 3 });
    await updateRows(orm, DayNotes, { id: note.id }, { color: '#9333ea' });
    await withHarness(user.id, async (h) => {
      await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id, text: 'Only the text changed' },
      });
      const row = await dayNote(note.id);
      expect(row.color).toBe('#9333ea');
      expect(row.sort_order).toBe(3);
    });
  });

  it('refuses a color outside the note palette', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id, color: 'red' },
      });
      expect(result.isError).toBe(true);
      expect((await dayNote(note.id)).color).toBeNull();
    });
  });

  it('broadcasts dayNote:updated event', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id);
    await withHarness(user.id, async (h) => {
      await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id, text: 'Updated' },
      });
      expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'dayNote:updated', expect.any(Object));
    });
  });

  it('returns error when note not found', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: 99999, text: 'X' },
      });
      expect(result.isError).toBe(true);
    });
  });

  it('returns access denied for non-member', async () => {
    const { user } = await makeUser(orm);
    const { user: other } = await makeUser(orm);
    const trip = await makeTrip(orm, other.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'update_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id, text: 'X' },
      });
      expect(result.isError).toBe(true);
    });
  });
});

// ---------------------------------------------------------------------------
// delete_day_note
// ---------------------------------------------------------------------------

describe('Tool: delete_day_note', () => {
  it('deletes a day note', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'delete_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id },
      });
      const data = parseToolResult(result) as any;
      expect(data.success).toBe(true);
      expect(await findRow(orm, DayNotes, { id: note.id })).toBeNull();
    });
  });

  it('broadcasts dayNote:deleted event', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id);
    await withHarness(user.id, async (h) => {
      await h.client.callTool({
        name: 'delete_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id },
      });
      expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'dayNote:deleted', expect.any(Object));
    });
  });

  it('returns error when note not found', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'delete_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: 99999 },
      });
      expect(result.isError).toBe(true);
    });
  });

  it('returns access denied for non-member', async () => {
    const { user } = await makeUser(orm);
    const { user: other } = await makeUser(orm);
    const trip = await makeTrip(orm, other.id);
    const day = await makeDay(orm, trip.id);
    const note = await makeDayNote(orm, day.id, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'delete_day_note',
        arguments: { tripId: trip.id, dayId: day.id, noteId: note.id },
      });
      expect(result.isError).toBe(true);
    });
  });
});

// ---------------------------------------------------------------------------
// Scope gating (trips write, registration-time — the legacy registerDayTools
// whole-registrar `canWrite(scopes, 'trips')` early return, now the
// declarative access marker on every DayNotesMcp tool)
// ---------------------------------------------------------------------------

describe('Day-note tools — scope gating', () => {
  const WRITE_TOOLS = ['create_day_note', 'update_day_note', 'delete_day_note'];

  async function listToolNames(userId: number, scopes: string[] | null): Promise<string[]> {
    const h = await createMcpHarness({ realtime, userId, withResources: false, scopes });
    try {
      return (await h.client.listTools()).tools.map((t) => t.name);
    } finally {
      await h.cleanup();
    }
  }

  it('registers all three tools with null scopes (full access)', async () => {
    const { user } = await makeUser(orm);
    const names = await listToolNames(user.id, null);
    for (const tool of WRITE_TOOLS) expect(names).toContain(tool);
  });

  it('registers no day-note tools with trips:read only (all three are writes)', async () => {
    const { user } = await makeUser(orm);
    const names = await listToolNames(user.id, ['trips:read']);
    for (const tool of WRITE_TOOLS) expect(names).not.toContain(tool);
  });

  it('registers no day-note tools for an unrelated scope', async () => {
    const { user } = await makeUser(orm);
    const names = await listToolNames(user.id, ['budget:read']);
    for (const tool of WRITE_TOOLS) expect(names).not.toContain(tool);
  });
});

// ---------------------------------------------------------------------------
// trek://trips/{tripId}/days/{dayId}/notes resource (moved from the legacy
// registerResources to DayNotesMcp)
// ---------------------------------------------------------------------------

describe('Resource: trek://trips/{tripId}/days/{dayId}/notes', () => {
  it('returns the day notes ordered by sort_order', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const day = await makeDay(orm, trip.id);
    await makeDayNote(orm, day.id, trip.id, { text: 'Second', sort_order: 5 });
    await makeDayNote(orm, day.id, trip.id, { text: 'First', sort_order: 1 });
    await withHarness(user.id, async (h) => {
      const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/days/${day.id}/notes` });
      const notes = parseResourceResult(result) as { text: string }[];
      expect(notes).toHaveLength(2);
      expect(notes[0].text).toBe('First');
      expect(notes[1].text).toBe('Second');
    });
  });

  it('returns the access-denied payload for a non-member', async () => {
    const { user } = await makeUser(orm);
    const { user: other } = await makeUser(orm);
    const trip = await makeTrip(orm, other.id);
    const day = await makeDay(orm, trip.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/days/${day.id}/notes` });
      expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
    });
  });

  it('returns the access-denied payload for a malformed id', async () => {
    const { user } = await makeUser(orm);
    await withHarness(user.id, async (h) => {
      const result = await h.client.readResource({ uri: 'trek://trips/1/days/not-a-number/notes' });
      expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
    });
  });
});

// ---------------------------------------------------------------------------
// create_collab_note
// ---------------------------------------------------------------------------

describe('Tool: create_collab_note', () => {
  it('creates a collab note with all fields', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_collab_note',
        arguments: { tripId: trip.id, title: 'Ideas', content: 'Visit museums', category: 'Culture', color: '#3b82f6' },
      });
      const data = parseToolResult(result) as any;
      expect(data.note.title).toBe('Ideas');
      expect(data.note.content).toBe('Visit museums');
      expect(data.note.category).toBe('Culture');
      expect(data.note.color).toBe('#3b82f6');
    });
  });

  it('defaults category to "General" and color to "#6366f1"', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_collab_note',
        arguments: { tripId: trip.id, title: 'Quick note' },
      });
      const data = parseToolResult(result) as any;
      expect(data.note.category).toBe('General');
      expect(data.note.color).toBe('#6366f1');
    });
  });

  it('persists the website link', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_collab_note',
        arguments: { tripId: trip.id, title: 'Boat tour', website: 'https://example.com/tour' },
      });
      const data = parseToolResult(result) as any;
      expect(data.note.website).toBe('https://example.com/tour');
      expect((await collabNote(data.note.id)).website).toBe('https://example.com/tour');
    });
  });

  it('stores no website when none is given', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_collab_note',
        arguments: { tripId: trip.id, title: 'Plain note' },
      });
      const data = parseToolResult(result) as any;
      expect((await collabNote(data.note.id)).website).toBeNull();
    });
  });

  it('broadcasts collab:note:created event', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    await withHarness(user.id, async (h) => {
      await h.client.callTool({ name: 'create_collab_note', arguments: { tripId: trip.id, title: 'Note' } });
      expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'collab:note:created', expect.any(Object));
    });
  });

  it('returns access denied for non-member', async () => {
    const { user } = await makeUser(orm);
    const { user: other } = await makeUser(orm);
    const trip = await makeTrip(orm, other.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'create_collab_note',
        arguments: { tripId: trip.id, title: 'X' },
      });
      expect(result.isError).toBe(true);
    });
  });
});

// ---------------------------------------------------------------------------
// update_collab_note
// ---------------------------------------------------------------------------

describe('Tool: update_collab_note', () => {
  it('updates collab note fields', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const note = await makeCollabNote(orm, trip.id, user.id, { title: 'Old', color: '#6366f1' });
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'update_collab_note',
        arguments: { tripId: trip.id, noteId: note.id, title: 'New Title', pinned: true, color: '#3b82f6' },
      });
      const data = parseToolResult(result) as any;
      expect(data.note.title).toBe('New Title');
      expect(data.note.pinned).toBe(1);
      expect(data.note.color).toBe('#3b82f6');
    });
  });

  it('sets the website link on an existing note', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const note = await makeCollabNote(orm, trip.id, user.id);
    await withHarness(user.id, async (h) => {
      await h.client.callTool({
        name: 'update_collab_note',
        arguments: { tripId: trip.id, noteId: note.id, website: 'https://example.com/museum' },
      });
      expect((await collabNote(note.id)).website).toBe('https://example.com/museum');
    });
  });

  it('clears the website with an explicit null', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const note = await makeCollabNote(orm, trip.id, user.id);
    await updateRows(orm, CollabNotes, { id: note.id }, { website: 'https://example.com/old' });
    await withHarness(user.id, async (h) => {
      await h.client.callTool({
        name: 'update_collab_note',
        arguments: { tripId: trip.id, noteId: note.id, website: null },
      });
      expect((await collabNote(note.id)).website).toBeNull();
    });
  });

  it('keeps the stored website when the field is not sent', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const note = await makeCollabNote(orm, trip.id, user.id);
    await updateRows(orm, CollabNotes, { id: note.id }, { website: 'https://example.com/keep' });
    await withHarness(user.id, async (h) => {
      await h.client.callTool({
        name: 'update_collab_note',
        arguments: { tripId: trip.id, noteId: note.id, title: 'Renamed' },
      });
      expect((await collabNote(note.id)).website).toBe('https://example.com/keep');
    });
  });

  it('refuses a website past the tool cap, the way the sibling text fields are capped', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const note = await makeCollabNote(orm, trip.id, user.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'update_collab_note',
        arguments: { tripId: trip.id, noteId: note.id, website: `https://example.com/${'x'.repeat(600)}` },
      });
      expect(result.isError).toBe(true);
      expect((await collabNote(note.id)).website).toBeNull();
    });
  });

  it('broadcasts collab:note:updated event', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const note = await makeCollabNote(orm, trip.id, user.id);
    await withHarness(user.id, async (h) => {
      await h.client.callTool({
        name: 'update_collab_note',
        arguments: { tripId: trip.id, noteId: note.id, title: 'Updated' },
      });
      expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'collab:note:updated', expect.any(Object));
    });
  });

  it('returns error when note not found', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'update_collab_note',
        arguments: { tripId: trip.id, noteId: 99999, title: 'X' },
      });
      expect(result.isError).toBe(true);
    });
  });

  it('returns access denied for non-member', async () => {
    const { user } = await makeUser(orm);
    const { user: other } = await makeUser(orm);
    const trip = await makeTrip(orm, other.id);
    const note = await makeCollabNote(orm, trip.id, other.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'update_collab_note',
        arguments: { tripId: trip.id, noteId: note.id, title: 'X' },
      });
      expect(result.isError).toBe(true);
    });
  });
});

// ---------------------------------------------------------------------------
// delete_collab_note
// ---------------------------------------------------------------------------

describe('Tool: delete_collab_note', () => {
  it('deletes a collab note', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const note = await makeCollabNote(orm, trip.id, user.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'delete_collab_note',
        arguments: { tripId: trip.id, noteId: note.id },
      });
      const data = parseToolResult(result) as any;
      expect(data.success).toBe(true);
      expect(await findRow(orm, CollabNotes, { id: note.id })).toBeNull();
    });
  });

  it('deletes associated trip_files records from the database', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const note = await makeCollabNote(orm, trip.id, user.id);
    // Insert a trip_file linked to this note
    await makeTripFile(orm, trip.id, {
      note: note.id,
      filename: 'test-file.pdf',
      original_name: 'document.pdf',
      mime_type: 'application/pdf',
      file_size: 1024,
    });

    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'delete_collab_note',
        arguments: { tripId: trip.id, noteId: note.id },
      });
      expect((parseToolResult(result) as any).success).toBe(true);
    });

    // trip_files rows are deleted as part of the transaction
    expect(await countRows(orm, TripFiles, { note: note.id })).toBe(0);
    // note itself is deleted
    expect(await findRow(orm, CollabNotes, { id: note.id })).toBeNull();
  });

  it('broadcasts collab:note:deleted event', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const note = await makeCollabNote(orm, trip.id, user.id);
    await withHarness(user.id, async (h) => {
      await h.client.callTool({ name: 'delete_collab_note', arguments: { tripId: trip.id, noteId: note.id } });
      expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'collab:note:deleted', expect.any(Object));
    });
  });

  it('returns error when note not found', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'delete_collab_note',
        arguments: { tripId: trip.id, noteId: 99999 },
      });
      expect(result.isError).toBe(true);
    });
  });

  it('returns access denied for non-member', async () => {
    const { user } = await makeUser(orm);
    const { user: other } = await makeUser(orm);
    const trip = await makeTrip(orm, other.id);
    const note = await makeCollabNote(orm, trip.id, other.id);
    await withHarness(user.id, async (h) => {
      const result = await h.client.callTool({
        name: 'delete_collab_note',
        arguments: { tripId: trip.id, noteId: note.id },
      });
      expect(result.isError).toBe(true);
    });
  });
});

// Moved from resources.test.ts with the collab migration: the resource now
// registers via the nest-mcp registry inside registerTools (CollabMcp
// @ResourceTemplate), which resources.test.ts's withTools: false harness
// never attaches.
describe('Resource: trek://trips/{tripId}/collab-notes', () => {
  it('returns collab notes with username', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    await makeCollabNote(orm, trip.id, user.id, { title: 'Ideas' });

    await withHarness(user.id, async (h) => {
      const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/collab-notes` });
      const notes = parseResourceResult(result) as any[];
      expect(notes).toHaveLength(1);
      expect(notes[0].title).toBe('Ideas');
      expect(notes[0].username).toBeTruthy();
    });
  });

  it('returns access denied for unauthorized trip', async () => {
    const { user } = await makeUser(orm);
    const { user: other } = await makeUser(orm);
    const trip = await makeTrip(orm, other.id);

    await withHarness(user.id, async (h) => {
      const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/collab-notes` });
      const data = parseResourceResult(result) as any;
      expect(data.error).toBeTruthy();
    });
  });
});

describe('create_collab_note, as the Collab tab posts it', () => {
  it('MCP-COLLAB-002: notifies the fellow travellers like the route does, after the room heard of the note', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    const send = vi
      .spyOn((await bootTestApp(realtime)).get(NotificationsService), 'send')
      .mockResolvedValue({ attempted: 0, delivered: 0 });
    try {
      await withHarness(user.id, async (h) => {
        await h.client.callTool({ name: 'create_collab_note', arguments: { tripId: trip.id, title: 'Ideas' } });
      });
      expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'collab:note:created', expect.any(Object));
      expect(send).toHaveBeenCalledWith(
        expect.objectContaining({
          event: 'collab_message',
          actorId: user.id,
          targetId: trip.id,
          params: expect.objectContaining({ actor: user.username }),
        }),
      );
    } finally {
      send.mockRestore();
    }
  });
});

describe('Tool: list_collab_notes', () => {
  interface ListedNote {
    id: number;
    title: string;
    username: string;
    pinned: number | null;
    attachments: unknown[];
  }

  async function listNotes(userId: number, tripId: number) {
    let listed: { isError?: unknown; data: unknown } = { data: null };
    await withHarness(userId, async (h) => {
      const result = await h.client.callTool({ name: 'list_collab_notes', arguments: { tripId } });
      listed = { isError: result.isError, data: result.isError ? null : parseToolResult(result) };
    });
    return listed;
  }

  it('MCP-COLLAB-010: lists the notes of the trip, pinned first, with their author and files', async () => {
    const { user } = await makeUser(orm);
    const trip = await makeTrip(orm, user.id);
    await makeCollabNote(orm, trip.id, user.id, { title: 'Ideas' });
    const pinned = await makeCollabNote(orm, trip.id, user.id, { title: 'Restaurants' });
    await updateRows(orm, CollabNotes, { id: pinned.id }, { pinned: 1 });
    const { isError, data } = await listNotes(user.id, trip.id);
    expect(isError).not.toBe(true);
    const notes = (data as { notes: ListedNote[] }).notes;
    expect(notes.map((note) => note.title)).toEqual(['Restaurants', 'Ideas']);
    expect(notes[0]).toMatchObject({ id: pinned.id, pinned: 1, username: user.username, attachments: [] });
  });

  it('MCP-COLLAB-011: refuses a trip the user is not part of, and reads nothing', async () => {
    const { user } = await makeUser(orm);
    const { user: owner } = await makeUser(orm);
    const trip = await makeTrip(orm, owner.id);
    await makeCollabNote(orm, trip.id, owner.id, { title: 'Private' });
    const { isError, data } = await listNotes(user.id, trip.id);
    expect(isError).toBe(true);
    expect(data).toBeNull();
  });

  it('MCP-COLLAB-012: is a read, offered only while the notes are switched on', async () => {
    const { user } = await makeUser(orm);
    const names = async () => {
      const h = await createMcpHarness({ realtime, userId: user.id, withResources: false });
      try {
        return (await h.client.listTools()).tools.map((tool) => [tool.name, tool.annotations?.readOnlyHint]);
      } finally {
        await h.cleanup();
      }
    };
    expect(await names()).toContainEqual(['list_collab_notes', true]);
    await setCollabFeature(orm, 'notes', false);
    try {
      expect((await names()).map(([name]) => name)).not.toContain('list_collab_notes');
    } finally {
      await setCollabFeature(orm, 'notes', true);
    }
  });
});