mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 11:36:05 +00:00
feat(assistant): an attached file can be kept in Files, on its own or with a booking or an expense
The chips offered to keep an attached file in Files, but nothing could do it: the assistant's upload_trip_file stays denied, and the file never reached Files. A new server write, keep_attached_file, is offered to the model where the thread holds an attachment and held as a change card naming the file and the booking, expense or place it goes with. Applied, it runs the checks of a Files upload with the user's rights (the demo block, the trip, file_upload and file_edit for a link, the instance's file types, every linked id on the same trip), copies the bytes to a trip file of their own, and writes the trip file, its expense link and the attachment's pointer to it in one transaction; the members' planners get file:created after it. A second keep of the same attachment answers the file kept the first time. FilesService gains storeBytes and discardBytes so the storage write stays out of that transaction. The receipt opens the Files tab; the card's verb, its "Attached to" row and the receipt's open label are new keys in all 27 locales. Undo is not offered: no tool takes a trip file back yet.
This commit is contained in:
@@ -12,18 +12,23 @@
|
||||
* user's language, never with an error; the model reads a file only after
|
||||
* the user agreed on its card, its text reaching the model and nothing else,
|
||||
* and proposes the booking from it; an attachment of another conversation is
|
||||
* answered like one that does not exist.
|
||||
* answered like one that does not exist; a file is kept in Files with the
|
||||
* booking it belongs to, with the rights of Files, and only once.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { AssistantAttachments } from '../../src/db/entities/AssistantAttachments.entity';
|
||||
import { AssistantMessages } from '../../src/db/entities/AssistantMessages.entity';
|
||||
import { AssistantThreads } from '../../src/db/entities/AssistantThreads.entity';
|
||||
import { BookingImportService } from '../../src/nest/booking-import/booking-import.service';
|
||||
import { DemoService } from '../../src/nest/common/demo.service';
|
||||
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
|
||||
import { StorageService } from '../../src/nest/storage/storage.service';
|
||||
import { makeReservation } from '../helpers/factories/reservations';
|
||||
import { countRows, findRow, findRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { spyOnRealtime, type RealtimeSpies } from '../helpers/fake-realtime';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { sessionCookie } from './harness';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
@@ -104,6 +109,7 @@ async function answer(req: IncomingMessage, res: ServerResponse): Promise<void>
|
||||
let nestApp: INestApplication;
|
||||
let orm: MikroORM;
|
||||
let fake: HttpServer;
|
||||
let broadcasts: RealtimeSpies;
|
||||
|
||||
beforeAll(async () => {
|
||||
fake = createServer((req, res) => {
|
||||
@@ -112,6 +118,7 @@ beforeAll(async () => {
|
||||
await new Promise<void>((resolve) => fake.listen(0, '127.0.0.1', resolve));
|
||||
nestApp = await buildApp();
|
||||
orm = nestApp.get(MikroORM);
|
||||
broadcasts = spyOnRealtime(nestApp);
|
||||
await setAddonEnabled(orm, 'ai_assistant', true);
|
||||
const adminId = (await makeUser(orm, { role: 'admin' })).user.id;
|
||||
const { port } = fake.address() as AddressInfo;
|
||||
@@ -126,6 +133,7 @@ beforeEach(async () => {
|
||||
await resetRateLimits(nestApp);
|
||||
provider.requests = [];
|
||||
provider.script = [];
|
||||
broadcasts.broadcast.mockClear();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
@@ -461,4 +469,90 @@ describe('Trip assistant: attached files', () => {
|
||||
expect(await refusalOf(owner, sameTripThread.threadId, '9f1e2d3c-4b5a-4968-8776-655443322110')).toBe(message);
|
||||
expect((await findRow(orm, AssistantAttachments, { id: attachmentId }))?.shared_at).toBeNull();
|
||||
});
|
||||
|
||||
/** A chat turn in which the model proposes keeping the file, and the id the change is held under. */
|
||||
async function proposeKeep(t: { userId: number; base: string }, threadId: number, args: Record<string, unknown>) {
|
||||
provider.script = [callTools({ id: `call_keep_${threadId}`, name: 'keep_attached_file', args })];
|
||||
const turn = await post(`${t.base}/chat`, t.userId, { ...CTX, threadId, text: 'Keep it with the booking' });
|
||||
return { turn, toolCallId: ofType(turn.chunks, 'tool-approval-request')[0]?.toolCallId };
|
||||
}
|
||||
|
||||
it('ATTE2E-008: the file is kept in Files with its booking once the user applies it, and only once', async () => {
|
||||
const t = await travelerWithTrip();
|
||||
const booking = await makeReservation(orm, t.tripId, { title: 'Casa Lisboa', type: 'hotel' });
|
||||
const { threadId, attachmentId } = await threadWithFile(t);
|
||||
const { turn, toolCallId } = await proposeKeep(t, threadId, { attachmentId, reservation_id: booking.id });
|
||||
expect(provider.requests[0].tools?.map((tool) => tool.function.name)).toContain('keep_attached_file');
|
||||
expect(ofType(turn.chunks, 'data-trek-change')[0].data).toMatchObject({
|
||||
verbKey: 'keepFile',
|
||||
subject: 'AirBnB Buchung.txt',
|
||||
rows: [{ labelKey: 'attachedTo', after: 'Casa Lisboa' }],
|
||||
});
|
||||
|
||||
provider.script = [say('It is in Files now.')];
|
||||
const decided = await post(`${t.base}/threads/${threadId}/decisions`, t.userId, {
|
||||
...CTX,
|
||||
decisions: [{ toolCallId, approved: true }],
|
||||
});
|
||||
expect(ofType(decided.chunks, 'data-trek-applied')[0].data).toMatchObject({ toolCallId, entity: 'file' });
|
||||
const listed = await get(`/api/trips/${t.tripId}/files`, t.userId);
|
||||
expect(listed.status).toBe(200);
|
||||
expect(listed.body.files).toHaveLength(1);
|
||||
const [file] = listed.body.files as Array<{ id: number; original_name: string; reservation_id: number | null }>;
|
||||
expect(file).toMatchObject({ original_name: 'AirBnB Buchung.txt', reservation_id: booking.id });
|
||||
expect((await findRow(orm, AssistantAttachments, { id: attachmentId }))?.file_id).toBe(file.id);
|
||||
expect(broadcasts.broadcast).toHaveBeenCalledWith(
|
||||
String(t.tripId),
|
||||
'file:created',
|
||||
{ file: expect.objectContaining({ id: file.id }) },
|
||||
undefined,
|
||||
);
|
||||
const sent = provider.requests[1].messages.map((message) => String(message.content ?? '')).join(' ');
|
||||
expect(sent).toContain(`The attached file "AirBnB Buchung.txt" is in the trip's Files now (file id ${file.id}).`);
|
||||
const download = await get(`/api/trips/${t.tripId}/files/${file.id}/download`, t.userId);
|
||||
expect(download.status).toBe(200);
|
||||
|
||||
// A second keep of the same file answers the first one.
|
||||
const second = await proposeKeep(t, threadId, { attachmentId });
|
||||
provider.script = [say('Already there.')];
|
||||
await post(`${t.base}/threads/${threadId}/decisions`, t.userId, {
|
||||
...CTX,
|
||||
decisions: [{ toolCallId: second.toolCallId, approved: true }],
|
||||
});
|
||||
expect((await get(`/api/trips/${t.tripId}/files`, t.userId)).body.files).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('ATTE2E-009: a demo account and a member without the right to upload keep nothing', async () => {
|
||||
const t = await travelerWithTrip();
|
||||
const { threadId, attachmentId } = await threadWithFile(t);
|
||||
const tryKeep = async () => {
|
||||
const { toolCallId } = await proposeKeep(t, threadId, { attachmentId });
|
||||
provider.script = [say('Could not keep it.')];
|
||||
const decided = await post(`${t.base}/threads/${threadId}/decisions`, t.userId, {
|
||||
...CTX,
|
||||
decisions: [{ toolCallId, approved: true }],
|
||||
});
|
||||
return ofType(decided.chunks, 'tool-output-error')[0]?.errorText;
|
||||
};
|
||||
const demo = vi.spyOn(nestApp.get(DemoService), 'isDemoUserId').mockResolvedValue(true);
|
||||
try {
|
||||
expect(await tryKeep()).toBe('You are not allowed to keep files on this trip.');
|
||||
} finally {
|
||||
demo.mockRestore();
|
||||
}
|
||||
const permissions = vi.spyOn(nestApp.get(PermissionsService), 'checkPermission');
|
||||
permissions.mockImplementation((action: string) => Promise.resolve(action !== 'file_upload'));
|
||||
try {
|
||||
expect(await tryKeep()).toBe('You are not allowed to keep files on this trip.');
|
||||
} finally {
|
||||
permissions.mockRestore();
|
||||
}
|
||||
expect((await get(`/api/trips/${t.tripId}/files`, t.userId)).body.files).toHaveLength(0);
|
||||
expect(broadcasts.broadcast).not.toHaveBeenCalledWith(
|
||||
String(t.tripId),
|
||||
'file:created',
|
||||
expect.anything(),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { AgentToolPort } from '../../../../src/nest/assistant/assistant-age
|
||||
import {
|
||||
attachedPort,
|
||||
NO_SUCH_ATTACHMENT,
|
||||
KEEP_ATTACHED_FILE_SPEC,
|
||||
NO_TEXT,
|
||||
READ_ATTACHED_FILE_SPEC,
|
||||
} from '../../../../src/nest/assistant/assistant-attachment-tools';
|
||||
@@ -51,14 +52,25 @@ function base(): AgentToolPort {
|
||||
const ATTACHED = [row(OWN), row(SHARED, { shared_at: '2026-10-24 08:01:00' }), row(SCAN, { text_status: 'scanned' })];
|
||||
|
||||
describe('attachedPort', () => {
|
||||
it('ASTATL-001: offers read_attached_file only where a file of the thread holds text', () => {
|
||||
it('ASTATL-001: offers keep_attached_file where the thread holds a file, read_attached_file where one has text', () => {
|
||||
const port = base();
|
||||
expect(attachedPort(port, null)).toBe(port);
|
||||
expect(attachedPort(port, { attached: [row(SCAN, { text_status: 'scanned' })], sentTo: 'm', read: vi.fn() })).toBe(
|
||||
port,
|
||||
);
|
||||
expect(attachedPort(port, { attached: [], sentTo: 'm', read: vi.fn() })).toBe(port);
|
||||
const scanOnly = attachedPort(port, {
|
||||
attached: [row(SCAN, { text_status: 'scanned' })],
|
||||
sentTo: 'm',
|
||||
read: vi.fn(),
|
||||
});
|
||||
expect(scanOnly.specs().map((spec) => spec.name)).toEqual(['get_trip_summary', KEEP_ATTACHED_FILE_SPEC.name]);
|
||||
expect(scanOnly.pinArgs('read_attached_file', { attachmentId: SCAN })).toEqual({
|
||||
args: { attachmentId: SCAN },
|
||||
});
|
||||
const offered = attachedPort(port, { attached: ATTACHED, sentTo: 'm', read: vi.fn() });
|
||||
expect(offered.specs().map((spec) => spec.name)).toEqual(['get_trip_summary', READ_ATTACHED_FILE_SPEC.name]);
|
||||
expect(offered.specs().map((spec) => spec.name)).toEqual([
|
||||
'get_trip_summary',
|
||||
READ_ATTACHED_FILE_SPEC.name,
|
||||
KEEP_ATTACHED_FILE_SPEC.name,
|
||||
]);
|
||||
});
|
||||
|
||||
it('ASTATL-002: the first read of a file is held for the user, a shared one runs at once', () => {
|
||||
@@ -100,4 +112,16 @@ describe('attachedPort', () => {
|
||||
expect(prompt).toContain('read it with read_attached_file');
|
||||
expect(prompt).toContain('proposed with create_reservation');
|
||||
});
|
||||
|
||||
it('ASTATL-006: a keep is always held, checked, and names the file; an attachment of no one here is refused alike', () => {
|
||||
const port = attachedPort(base(), { attached: ATTACHED, sentTo: 'm', read: vi.fn() });
|
||||
expect(port.kindOf('keep_attached_file', { attachmentId: SCAN })).toBe('write');
|
||||
expect(port.pinArgs('keep_attached_file', { attachmentId: SCAN, reservation_id: 5, name: 'forged.exe' })).toEqual({
|
||||
args: { attachmentId: SCAN, reservation_id: 5, name: '2d9e.pdf' },
|
||||
});
|
||||
expect(port.pinArgs('keep_attached_file', { attachmentId: ELSEWHERE })).toEqual({ error: NO_SUCH_ATTACHMENT });
|
||||
expect(port.pinArgs('keep_attached_file', {})).toEqual({ error: NO_SUCH_ATTACHMENT });
|
||||
const bad = port.pinArgs('keep_attached_file', { attachmentId: OWN, budget_item_id: 'seven' });
|
||||
expect(bad).toEqual({ error: expect.stringContaining('Invalid arguments') });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
ASSISTANT_ATTACHMENT_TTL_DAYS,
|
||||
AssistantAttachmentsService,
|
||||
} from '../../../../src/nest/assistant/assistant-attachments.service';
|
||||
import { AssistantKeepFileService } from '../../../../src/nest/assistant/assistant-keep-file.service';
|
||||
import { LlmParseService } from '../../../../src/nest/llm-parse/llm-parse.service';
|
||||
import { StorageService } from '../../../../src/nest/storage/storage.service';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
@@ -96,6 +97,10 @@ async function make(opts: { text?: string | Error; listed?: Listed[]; failDelete
|
||||
{ provide: StorageService, useValue: storage },
|
||||
{ provide: LlmParseService, useValue: llmParse },
|
||||
{ provide: MikroORM, useValue: {} },
|
||||
{
|
||||
provide: AssistantKeepFileService,
|
||||
useValue: { keep: vi.fn(async () => ({ ok: true, value: { file: { id: 3 } } })) },
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
return { service: moduleRef.get(AssistantAttachmentsService), rows, storage, llmParse };
|
||||
@@ -212,6 +217,15 @@ describe('AssistantAttachmentsService', () => {
|
||||
});
|
||||
expect(t.service.handles('read_attached_file')).toBe(true);
|
||||
expect(t.service.handles('create_place')).toBe(false);
|
||||
const at = { userId: 7, threadId: 4, tripId: 9 };
|
||||
expect(await t.service.applyChange('keep_attached_file', at, { attachmentId: FRESH })).toEqual({
|
||||
ok: true,
|
||||
value: { file: { id: 3 } },
|
||||
});
|
||||
expect(await t.service.applyChange('create_place', at, {})).toEqual({
|
||||
ok: false,
|
||||
value: 'Unknown tool: create_place',
|
||||
});
|
||||
});
|
||||
|
||||
it('ASTATT-010: a shared file is read for the model only; one not shared yet is not read', async () => {
|
||||
|
||||
@@ -317,6 +317,41 @@ describe('toChatHistory', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('ASTHIS-005f: keeping an attached file is told after its step, whatever became of it', () => {
|
||||
const keep = (extra: Partial<Extract<AssistantMessagePart, { type: 'tool-call' }>>) =>
|
||||
toChatHistory(
|
||||
[
|
||||
row('user', [{ type: 'text', text: 'Keep it in Files' }]),
|
||||
row('assistant', [
|
||||
{ type: 'text', text: 'Here is the card.' },
|
||||
{
|
||||
type: 'tool-call',
|
||||
toolCallId: 'k',
|
||||
toolName: 'keep_attached_file',
|
||||
args: { attachmentId: 'a', name: 'a.pdf' },
|
||||
...extra,
|
||||
},
|
||||
]),
|
||||
],
|
||||
new Map(),
|
||||
);
|
||||
const kept = keep({ approval: { id: 'k', approved: true }, result: { file: { id: 31 } } });
|
||||
expect(kept.map((message) => message.role)).toEqual(['user', 'assistant', 'user']);
|
||||
expect((kept[2] as { text: string }).text).toBe(
|
||||
'The attached file "a.pdf" is in the trip\'s Files now (file id 31).',
|
||||
);
|
||||
const lastOf = (extra: Parameters<typeof keep>[0]) => (keep(extra).at(-1) as { text: string }).text;
|
||||
expect(
|
||||
lastOf({ approval: { id: 'k', approved: true }, result: 'The file could not be kept.', isError: true }),
|
||||
).toBe('The attached file "a.pdf" could not be kept in Files: The file could not be kept.');
|
||||
expect(lastOf({ approval: { id: 'k', approved: false } })).toBe(
|
||||
'The user did not keep the attached file "a.pdf" in Files.',
|
||||
);
|
||||
expect(lastOf({ result: 'No such attachment in this conversation.', isError: true })).toContain('was refused');
|
||||
expect(lastOf({ approval: { id: 'k', resolution: 'cancelled' } })).toContain('the user moved on without deciding');
|
||||
expect(lastOf({ approval: { id: 'k' } })).toContain('waits for the user to apply or discard it');
|
||||
});
|
||||
|
||||
it('ASTHIS-006: a place the user picked from the search results is told as a note, whatever became of it', () => {
|
||||
const found = (approval: AssistantToolApproval, isError = false) =>
|
||||
serverStepsNote([
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* keep_attached_file applied: the checks a Files upload runs (demo, trip,
|
||||
* rights, types, same-trip links), the bytes copied to a trip file of their
|
||||
* own, the rows written in one transaction, the broadcast after it, and a
|
||||
* second keep that answers the first file.
|
||||
*/
|
||||
import { AssistantAttachments } from '../../../../src/db/entities/AssistantAttachments.entity';
|
||||
import { AssistantKeepFileService } from '../../../../src/nest/assistant/assistant-keep-file.service';
|
||||
import { DemoService } from '../../../../src/nest/common/demo.service';
|
||||
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
|
||||
import { AllowedFileTypesService } from '../../../../src/nest/files/allowed-file-types.service';
|
||||
import { FilesService } from '../../../../src/nest/files/files.service';
|
||||
import { McpToolGuardsService } from '../../../../src/nest/mcp-shared/mcp-tool-guards.service';
|
||||
import { StorageService } from '../../../../src/nest/storage/storage.service';
|
||||
import { TripAccessService } from '../../../../src/nest/trip-membership/trip-access.service';
|
||||
import { getRepositoryToken } from '@mikro-orm/nestjs';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import { Readable } from 'node:stream';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', () => logMock);
|
||||
|
||||
const ID = '0b7c2f0e-6f6d-4a8e-9b1a-3d2c1e0f9a87';
|
||||
const AT = { userId: 7, threadId: 4, tripId: 9 };
|
||||
|
||||
interface Opts {
|
||||
demo?: boolean;
|
||||
trip?: boolean;
|
||||
upload?: boolean;
|
||||
edit?: boolean;
|
||||
allowed?: string;
|
||||
foreign?: 'reservation_id' | 'budget_item_id' | null;
|
||||
row?: Record<string, unknown> | null;
|
||||
kept?: Record<string, unknown> | undefined;
|
||||
bytes?: Buffer | Error;
|
||||
failTx?: boolean;
|
||||
}
|
||||
|
||||
async function make(opts: Opts = {}) {
|
||||
const row =
|
||||
opts.row === undefined
|
||||
? {
|
||||
id: ID,
|
||||
trip_id: 9,
|
||||
name: 'AirBnB Buchung.pdf',
|
||||
mime: 'application/pdf',
|
||||
storage_key: `assistant/${ID}.pdf`,
|
||||
file_id: null,
|
||||
}
|
||||
: opts.row;
|
||||
const rows = { findInThread: vi.fn(async () => row), setFile: vi.fn(async () => undefined) };
|
||||
const storage = {
|
||||
getStream: vi.fn(async () => {
|
||||
if (opts.bytes instanceof Error) throw opts.bytes;
|
||||
return { stream: Readable.from([opts.bytes ?? Buffer.from('%PDF')]), stat: { key: 'k', size: 4, mtimeMs: 0 } };
|
||||
}),
|
||||
};
|
||||
const created = { id: 31, original_name: 'AirBnB Buchung.pdf', reservation_id: 5, place_id: null, url: '/x' };
|
||||
const files = {
|
||||
getFileById: vi.fn(async () => opts.kept),
|
||||
findForeignLinkTarget: vi.fn(async () => opts.foreign ?? null),
|
||||
storeBytes: vi.fn(async () => 'stored.pdf'),
|
||||
discardBytes: vi.fn(async () => undefined),
|
||||
createFile: vi.fn(async () => {
|
||||
if (opts.failTx) throw new Error('disk I/O error');
|
||||
return created;
|
||||
}),
|
||||
broadcast: vi.fn(),
|
||||
};
|
||||
const guards = {
|
||||
hasTripPermission: vi.fn(async (action: string) =>
|
||||
action === 'file_upload' ? opts.upload !== false : opts.edit !== false,
|
||||
),
|
||||
};
|
||||
const uow = { transactional: vi.fn(async (fn: () => Promise<unknown>) => fn()) };
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [
|
||||
AssistantKeepFileService,
|
||||
{ provide: getRepositoryToken(AssistantAttachments), useValue: rows },
|
||||
{ provide: StorageService, useValue: storage },
|
||||
{ provide: FilesService, useValue: files },
|
||||
{ provide: AllowedFileTypesService, useValue: { get: vi.fn(async () => opts.allowed ?? 'pdf,txt') } },
|
||||
{ provide: McpToolGuardsService, useValue: guards },
|
||||
{ provide: DemoService, useValue: { isDemoUserId: vi.fn(async () => opts.demo === true) } },
|
||||
{
|
||||
provide: TripAccessService,
|
||||
useValue: { findAccessible: vi.fn(async () => (opts.trip === false ? undefined : { id: 9 })) },
|
||||
},
|
||||
{ provide: UnitOfWork, useValue: uow },
|
||||
],
|
||||
}).compile();
|
||||
return { service: moduleRef.get(AssistantKeepFileService), rows, files, guards, uow, storage };
|
||||
}
|
||||
|
||||
describe('AssistantKeepFileService', () => {
|
||||
it('ASTKEP-001: keeps the file as a trip file with its booking, in one transaction, and tells the trip after it', async () => {
|
||||
const t = await make();
|
||||
const run = await t.service.keep(AT, { attachmentId: ID, reservation_id: 5, name: 'ignored.exe' });
|
||||
expect(run).toEqual({
|
||||
ok: true,
|
||||
value: { file: { id: 31, name: 'AirBnB Buchung.pdf', reservation_id: 5, place_id: null, budget_item_id: null } },
|
||||
});
|
||||
expect(t.rows.findInThread).toHaveBeenCalledWith(ID, 4, 7);
|
||||
expect(t.files.storeBytes).toHaveBeenCalledWith({
|
||||
originalname: 'AirBnB Buchung.pdf',
|
||||
mimetype: 'application/pdf',
|
||||
bytes: Buffer.from('%PDF'),
|
||||
});
|
||||
expect(t.files.createFile).toHaveBeenCalledWith(
|
||||
9,
|
||||
{ filename: 'stored.pdf', originalname: 'AirBnB Buchung.pdf', size: 4, mimetype: 'application/pdf' },
|
||||
7,
|
||||
{ reservation_id: 5, place_id: null, budget_item_id: null, description: null },
|
||||
);
|
||||
expect(t.rows.setFile).toHaveBeenCalledWith(ID, 31);
|
||||
expect(t.uow.transactional).toHaveBeenCalledTimes(1);
|
||||
expect(t.files.broadcast).toHaveBeenCalledWith(
|
||||
'9',
|
||||
'file:created',
|
||||
{ file: expect.objectContaining({ id: 31 }) },
|
||||
undefined,
|
||||
);
|
||||
expect(t.guards.hasTripPermission).toHaveBeenCalledWith('file_edit', 9, 7);
|
||||
});
|
||||
|
||||
it('ASTKEP-002: an expense link and a description go along; a keep without a link asks no edit right', async () => {
|
||||
const t = await make();
|
||||
await t.service.keep(AT, { attachmentId: ID, budget_item_id: 12, description: 'Receipt' });
|
||||
expect(t.files.createFile.mock.calls[0][3]).toEqual({
|
||||
reservation_id: null,
|
||||
place_id: null,
|
||||
budget_item_id: 12,
|
||||
description: 'Receipt',
|
||||
});
|
||||
const plain = await make({ edit: false });
|
||||
expect((await plain.service.keep(AT, { attachmentId: ID })).ok).toBe(true);
|
||||
});
|
||||
|
||||
it('ASTKEP-003: refused for a demo account, off the trip, without the right to upload or to link', async () => {
|
||||
const refused = async (opts: Opts, args: Record<string, unknown> = { attachmentId: ID }) => {
|
||||
const t = await make(opts);
|
||||
const run = await t.service.keep(AT, args);
|
||||
expect(t.files.storeBytes).not.toHaveBeenCalled();
|
||||
return run;
|
||||
};
|
||||
const notAllowed = { ok: false, value: 'You are not allowed to keep files on this trip.' };
|
||||
expect(await refused({ demo: true })).toEqual(notAllowed);
|
||||
expect(await refused({ trip: false })).toEqual(notAllowed);
|
||||
expect(await refused({ upload: false })).toEqual(notAllowed);
|
||||
expect(await refused({ edit: false }, { attachmentId: ID, place_id: 3 })).toEqual({
|
||||
ok: false,
|
||||
value: 'You are not allowed to attach files to bookings, expenses or places on this trip.',
|
||||
});
|
||||
});
|
||||
|
||||
it('ASTKEP-004: an attachment of no one here, a type Files refuses and a link off the trip are refused', async () => {
|
||||
const run = async (opts: Opts, args: Record<string, unknown> = { attachmentId: ID }) =>
|
||||
(await make(opts)).service.keep(AT, args);
|
||||
const none = { ok: false, value: 'No such attachment in this conversation.' };
|
||||
expect(await run({ row: null })).toEqual(none);
|
||||
expect(await run({ row: { id: ID, trip_id: 99, name: 'a.pdf', mime: 'application/pdf', file_id: null } })).toEqual(
|
||||
none,
|
||||
);
|
||||
expect(await run({}, { attachmentId: 'nope' })).toEqual({ ok: false, value: 'This change can no longer be read.' });
|
||||
expect(await run({ allowed: 'jpg' })).toEqual({
|
||||
ok: false,
|
||||
value: 'This file type is not allowed on this TREK instance.',
|
||||
});
|
||||
expect(await run({ foreign: 'reservation_id' }, { attachmentId: ID, reservation_id: 404 })).toEqual({
|
||||
ok: false,
|
||||
value: 'Linked item does not belong to this trip (reservation_id).',
|
||||
});
|
||||
});
|
||||
|
||||
it('ASTKEP-005: keeping the same file twice answers the first one; a trashed one is kept again', async () => {
|
||||
const first = { id: 31, original_name: 'AirBnB Buchung.pdf', reservation_id: 5, place_id: null, deleted_at: null };
|
||||
const row = {
|
||||
id: ID,
|
||||
trip_id: 9,
|
||||
name: 'AirBnB Buchung.pdf',
|
||||
mime: 'application/pdf',
|
||||
file_id: 31,
|
||||
storage_key: 'k',
|
||||
};
|
||||
const again = await make({ row, kept: first });
|
||||
expect(await again.service.keep(AT, { attachmentId: ID })).toEqual({
|
||||
ok: true,
|
||||
value: { file: { id: 31, name: 'AirBnB Buchung.pdf', reservation_id: 5, place_id: null, budget_item_id: null } },
|
||||
});
|
||||
expect(again.files.storeBytes).not.toHaveBeenCalled();
|
||||
const trashed = await make({ row, kept: { ...first, deleted_at: '2026-10-24 09:00:00' } });
|
||||
await trashed.service.keep(AT, { attachmentId: ID });
|
||||
expect(trashed.files.createFile).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ASTKEP-006: bytes that are gone or too large keep nothing; a failed transaction drops the copied bytes', async () => {
|
||||
const gone = await make({ bytes: new Error('NoSuchKey') });
|
||||
expect(await gone.service.keep(AT, { attachmentId: ID })).toEqual({
|
||||
ok: false,
|
||||
value: 'The attached file is no longer kept, so it cannot be put into Files.',
|
||||
});
|
||||
const huge = await make({ bytes: Buffer.alloc(10 * 1024 * 1024 + 1) });
|
||||
expect((await huge.service.keep(AT, { attachmentId: ID })).ok).toBe(false);
|
||||
const failing = await make({ failTx: true });
|
||||
expect(await failing.service.keep(AT, { attachmentId: ID })).toEqual({
|
||||
ok: false,
|
||||
value: 'The file could not be kept.',
|
||||
});
|
||||
expect(failing.files.discardBytes).toHaveBeenCalledWith('stored.pdf');
|
||||
expect(failing.rows.setFile).not.toHaveBeenCalled();
|
||||
expect(failing.files.broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -360,6 +360,57 @@ describe('describeToolCall', () => {
|
||||
const note = describe_('remember_for_trip', { note: ' We travel as two. ' });
|
||||
expect(note).toMatchObject({ verbKey: 'rememberNote', subject: 'We travel as two.', rows: [] });
|
||||
});
|
||||
|
||||
it('ASTPRV-023: an attached file is read by its name and where its text goes, kept by what it goes with', () => {
|
||||
const read = describe_('read_attached_file', {
|
||||
attachmentId: 'a',
|
||||
name: 'AirBnB Buchung.pdf',
|
||||
sentTo: 'gpt-5 (api.openai.com)',
|
||||
});
|
||||
expect(read).toMatchObject({
|
||||
verbKey: 'readAttachment',
|
||||
subject: 'AirBnB Buchung.pdf',
|
||||
rows: [{ op: 'add', labelKey: 'sentTo', before: null, after: 'gpt-5 (api.openai.com)' }],
|
||||
undoable: false,
|
||||
});
|
||||
const tripCard = buildTripCard(
|
||||
1,
|
||||
7,
|
||||
{ reservations: [{ id: 5, title: 'Casa Lisboa' }], budget: { items: [{ id: 12, name: 'Deposit' }] } },
|
||||
{ places: [{ id: 12, name: 'Nishiki Market', lat: 35, lng: 135 }] },
|
||||
null,
|
||||
);
|
||||
const kept = describeToolCall(
|
||||
'keep_attached_file',
|
||||
'tc-2',
|
||||
{
|
||||
attachmentId: 'a',
|
||||
name: 'AirBnB Buchung.pdf',
|
||||
reservation_id: 5,
|
||||
budget_item_id: 12,
|
||||
place_id: 12,
|
||||
description: 'Stay',
|
||||
},
|
||||
{ ...ctx, card: tripCard },
|
||||
);
|
||||
expect(kept).toMatchObject({ verbKey: 'keepFile', subject: 'AirBnB Buchung.pdf', placeIds: [12], undoable: false });
|
||||
expect(kept.rows).toEqual([
|
||||
{ op: 'add', labelKey: 'attachedTo', before: null, after: 'Casa Lisboa, Deposit, Nishiki Market' },
|
||||
{ op: 'add', labelKey: 'description', before: null, after: 'Stay' },
|
||||
]);
|
||||
const unknown = describe_('keep_attached_file', {
|
||||
attachmentId: 'a',
|
||||
name: 'x.pdf',
|
||||
reservation_id: 77,
|
||||
budget_item_id: 78,
|
||||
});
|
||||
expect(unknown.rows[0]).toMatchObject({ labelKey: 'attachedTo', after: '#77, #78' });
|
||||
expect(describe_('keep_attached_file', { attachmentId: 'a', name: 'x.pdf' }).rows).toEqual([]);
|
||||
expect(appliedChange('keep_attached_file', 'tc', {}, { file: { id: 31 } }, null, null)).toMatchObject({
|
||||
entity: 'file',
|
||||
ids: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('appliedChange', () => {
|
||||
|
||||
@@ -93,8 +93,10 @@ const { consumeEphemeralToken } = vi.hoisted(() => ({ consumeEphemeralToken: vi.
|
||||
vi.mock('../../../src/nest/auth-core/ephemeral-tokens', () => ({ consumeEphemeralToken }));
|
||||
|
||||
const storageDelete = vi.fn();
|
||||
const storagePut = vi.fn(async () => undefined);
|
||||
const storageStub = {
|
||||
delete: storageDelete,
|
||||
put: storagePut,
|
||||
} as unknown as import('../../../src/nest/storage/storage.service').StorageService;
|
||||
// EntityManager stub (Plan 3b Task 1 RULING): verifyJwtAndLoadUser is
|
||||
// fully mocked above, so `em.getRepository` never needs to return
|
||||
@@ -448,6 +450,18 @@ describe('createFile', () => {
|
||||
expect(file.uploaded_by).toBe(user.id);
|
||||
});
|
||||
|
||||
it('FILE-SVC-061: bytes for a row written elsewhere go under a fresh key with their extension, and can be dropped', async () => {
|
||||
const filename = await svc.storeBytes({
|
||||
originalname: 'AirBnB Buchung.pdf',
|
||||
mimetype: 'application/pdf',
|
||||
bytes: Buffer.from('x'),
|
||||
});
|
||||
expect(filename).toMatch(/^[0-9a-f-]{36}\.pdf$/);
|
||||
expect(storagePut).toHaveBeenCalledWith('files', filename, expect.anything(), { contentType: 'application/pdf' });
|
||||
await svc.discardBytes(filename);
|
||||
expect(storageDelete).toHaveBeenCalledWith('files', filename);
|
||||
});
|
||||
|
||||
it('FILE-SVC-060 (R2): a failing file_links insert rolls back the trip_files row too', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const item = await insertBudgetItem(trip.id, 'Dinner');
|
||||
|
||||
Reference in New Issue
Block a user