feat(assistant): an attached file stays with its conversation

A file attached in the trip chat lived only as a buffer for the one request
that read it, so the assistant could not look at it again and nothing could
keep it in Files. Now its bytes go to storage before the turn writes anything
(under the trip files' category, which is never served by path) and a row in
the new assistant_attachments table keeps its name, type, size, hash and the
text TREK read out of it, written in the turn's opening transaction. The
message's attachment part carries the row's id; old messages without one still
read.

The text is read the way the AI import reads it, through a new public
LlmParseService.readText, and a file whose text cannot be read is kept all the
same. A storage that refuses the bytes refuses the turn before any row exists.
Deleting a thread takes its files along, and the nightly retention sweep drops
files older than seven days and bytes no row names any more.
This commit is contained in:
Maurice
2026-10-24 21:11:35 +02:00
parent 487f8dd886
commit 6a77496438
27 changed files with 1088 additions and 26 deletions
@@ -0,0 +1,60 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AssistantAttachmentsRepository } from '../repositories/AssistantAttachments.repository';
import { DbTimestampType } from '../types';
import { AssistantThreads } from './AssistantThreads.entity';
import { TripFiles } from './TripFiles.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class AssistantAttachments {
[EntityRepositoryType]?: AssistantAttachmentsRepository;
id!: string;
thread!: Ref<AssistantThreads>;
thread_id!: number;
user!: Ref<Users>;
user_id!: number;
trip!: Ref<Trips>;
trip_id!: number;
name!: string;
mime!: string;
size!: number;
sha256!: string;
storage_key!: string;
text?: string | null;
text_status!: string;
shared_at?: string | null;
file?: Ref<TripFiles> | null;
file_id?: number | null;
created_at!: string & Opt;
}
export const AssistantAttachmentsSchema = defineEntity({
class: AssistantAttachments,
repository: () => AssistantAttachmentsRepository,
indexes: [
{
name: 'idx_assistant_attachments_thread',
properties: ['thread_id', 'created_at'],
},
],
properties: {
id: p.text().primary(),
thread: () => p.manyToOne(AssistantThreads).ref().deleteRule('cascade').hidden(),
thread_id: p.integer().persist(false),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_assistant_attachments_user'),
user_id: p.integer().persist(false).index('idx_assistant_attachments_user'),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_assistant_attachments_trip'),
trip_id: p.integer().persist(false).index('idx_assistant_attachments_trip'),
name: p.text(),
mime: p.text(),
size: p.integer(),
sha256: p.text(),
storage_key: p.text(),
text: p.text().nullable(),
text_status: p.text(),
shared_at: p.type(DbTimestampType).nullable(),
file: () => p.manyToOne(TripFiles).ref().nullable().hidden().index('idx_assistant_attachments_file'),
file_id: p.integer().nullable().persist(false).index('idx_assistant_attachments_file'),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`).index('idx_assistant_attachments_created'),
},
});
@@ -1,6 +1,7 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AssistantThreadsRepository } from '../repositories/AssistantThreads.repository';
import { DbTimestampType } from '../types';
import { AssistantAttachments } from './AssistantAttachments.entity';
import { AssistantMessages } from './AssistantMessages.entity';
import { AssistantToolCalls } from './AssistantToolCalls.entity';
import { Journeys } from './Journeys.entity';
@@ -19,6 +20,7 @@ export class AssistantThreads {
title!: string;
created_at!: string & Opt;
last_message_at!: string & Opt;
assistant_attachments_collection = new Collection<AssistantAttachments>(this);
assistant_messages_collection = new Collection<AssistantMessages>(this);
assistant_tool_calls_collection = new Collection<AssistantToolCalls>(this);
}
@@ -47,6 +49,7 @@ export const AssistantThreadsSchema = defineEntity({
title: p.text(),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
last_message_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
assistant_attachments_collection: () => p.oneToMany(AssistantAttachments).mappedBy('thread').hidden(),
assistant_messages_collection: () => p.oneToMany(AssistantMessages).mappedBy('thread').hidden(),
assistant_tool_calls_collection: () => p.oneToMany(AssistantToolCalls).mappedBy('thread').hidden(),
},
@@ -1,6 +1,7 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TripFilesRepository } from '../repositories/TripFiles.repository';
import { DbTimestampType } from '../types';
import { AssistantAttachments } from './AssistantAttachments.entity';
import { CollabMessages } from './CollabMessages.entity';
import { CollabNotes } from './CollabNotes.entity';
import { DocumentSyncItems } from './DocumentSyncItems.entity';
@@ -33,6 +34,7 @@ export class TripFiles {
message?: Ref<CollabMessages> | null;
message_id?: number | null;
uploadedByRef?: Ref<Users> | null;
assistant_attachments_collection = new Collection<AssistantAttachments>(this);
document_sync_items_collection = new Collection<DocumentSyncItems>(this);
file_links_collection = new Collection<FileLinks>(this);
}
@@ -62,6 +64,7 @@ export const TripFilesSchema = defineEntity({
message: () => p.manyToOne(CollabMessages).ref().deleteRule('cascade').nullable().hidden().index('idx_trip_files_message_id'),
message_id: p.integer().nullable().persist(false).index('idx_trip_files_message_id'),
uploadedByRef: () => p.manyToOne(Users).ref().joinColumn('uploaded_by').nullable().hidden().index('idx_trip_files_uploaded_by'),
assistant_attachments_collection: () => p.oneToMany(AssistantAttachments).mappedBy('file').hidden(),
document_sync_items_collection: () => p.oneToMany(DocumentSyncItems).mappedBy('file').hidden(),
file_links_collection: () => p.oneToMany(FileLinks).mappedBy('file').hidden(),
},
+3
View File
@@ -1,6 +1,7 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TripsRepository } from '../repositories/Trips.repository';
import { DbTimestampType } from '../types';
import { AssistantAttachments } from './AssistantAttachments.entity';
import { AssistantThreads } from './AssistantThreads.entity';
import { BudgetCategoryOrder } from './BudgetCategoryOrder.entity';
import { BudgetItems } from './BudgetItems.entity';
@@ -57,6 +58,7 @@ export class Trips {
created_at?: string | null;
updated_at?: string | null;
reminder_sent_for?: string | null;
assistant_attachments_collection = new Collection<AssistantAttachments>(this);
assistant_threads_collection = new Collection<AssistantThreads>(this);
budget_category_order_collection = new Collection<BudgetCategoryOrder>(this);
budget_items_collection = new Collection<BudgetItems>(this);
@@ -122,6 +124,7 @@ export const TripsSchema = defineEntity({
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`).index('idx_trips_created_at'),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
reminder_sent_for: p.text().nullable(),
assistant_attachments_collection: () => p.oneToMany(AssistantAttachments).mappedBy('trip').hidden(),
assistant_threads_collection: () => p.oneToMany(AssistantThreads).mappedBy('trip').hidden(),
budget_category_order_collection: () => p.oneToMany(BudgetCategoryOrder).mappedBy('trip').hidden(),
budget_items_collection: () => p.oneToMany(BudgetItems).mappedBy('trip').hidden(),
+3
View File
@@ -3,6 +3,7 @@ import { UsersRepository } from '../repositories/Users.repository';
import { DbTimestampType } from '../types';
import { AiConnections } from './AiConnections.entity';
import { AssignmentParticipants } from './AssignmentParticipants.entity';
import { AssistantAttachments } from './AssistantAttachments.entity';
import { AssistantThreads } from './AssistantThreads.entity';
import { AssistantUsage } from './AssistantUsage.entity';
import { AuditLog } from './AuditLog.entity';
@@ -135,6 +136,7 @@ export class Users {
email_self_asserted: number & Opt = 0;
ai_connections_collection = new Collection<AiConnections>(this);
assignment_participants_collection = new Collection<AssignmentParticipants>(this);
assistant_attachments_collection = new Collection<AssistantAttachments>(this);
assistant_threads_collection = new Collection<AssistantThreads>(this);
assistant_usage_collection = new Collection<AssistantUsage>(this);
audit_log_collection = new Collection<AuditLog>(this);
@@ -293,6 +295,7 @@ export const UsersSchema = defineEntity({
email_self_asserted: p.integer().default(0),
ai_connections_collection: () => p.oneToMany(AiConnections).mappedBy('user').hidden(),
assignment_participants_collection: () => p.oneToMany(AssignmentParticipants).mappedBy('user').hidden(),
assistant_attachments_collection: () => p.oneToMany(AssistantAttachments).mappedBy('user').hidden(),
assistant_threads_collection: () => p.oneToMany(AssistantThreads).mappedBy('user').hidden(),
assistant_usage_collection: () => p.oneToMany(AssistantUsage).mappedBy('user').hidden(),
audit_log_collection: () => p.oneToMany(AuditLog).mappedBy('user').hidden(),
+2
View File
@@ -3,6 +3,7 @@ import { AddonsSchema } from './Addons.entity';
import { AiConnectionsSchema } from './AiConnections.entity';
import { AppSettingsSchema } from './AppSettings.entity';
import { AssignmentParticipantsSchema } from './AssignmentParticipants.entity';
import { AssistantAttachmentsSchema } from './AssistantAttachments.entity';
import { AssistantMessagesSchema } from './AssistantMessages.entity';
import { AssistantThreadsSchema } from './AssistantThreads.entity';
import { AssistantToolCallsSchema } from './AssistantToolCalls.entity';
@@ -166,6 +167,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
AiConnectionsSchema,
AppSettingsSchema,
AssignmentParticipantsSchema,
AssistantAttachmentsSchema,
AssistantMessagesSchema,
AssistantThreadsSchema,
AssistantToolCallsSchema,
@@ -0,0 +1,20 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface AssistantAttachmentsTable {
id: string;
thread_id: number;
user_id: number;
trip_id: number;
name: string;
mime: string;
size: number;
sha256: string;
storage_key: string;
text: InsertOptional<string | null>;
text_status: string;
shared_at: InsertOptional<string | null>;
file_id: InsertOptional<number | null>;
created_at: InsertOptional<string>;
}
+2
View File
@@ -4,6 +4,7 @@ import type { AddonsTable } from './Addons.table';
import type { AiConnectionsTable } from './AiConnections.table';
import type { AppSettingsTable } from './AppSettings.table';
import type { AssignmentParticipantsTable } from './AssignmentParticipants.table';
import type { AssistantAttachmentsTable } from './AssistantAttachments.table';
import type { AssistantMessagesTable } from './AssistantMessages.table';
import type { AssistantThreadsTable } from './AssistantThreads.table';
import type { AssistantToolCallsTable } from './AssistantToolCalls.table';
@@ -173,6 +174,7 @@ export interface DB {
ai_connections: AiConnectionsTable;
app_settings: AppSettingsTable;
assignment_participants: AssignmentParticipantsTable;
assistant_attachments: AssistantAttachmentsTable;
assistant_messages: AssistantMessagesTable;
assistant_threads: AssistantThreadsTable;
assistant_tool_calls: AssistantToolCallsTable;
@@ -0,0 +1,50 @@
import { Migration } from '@mikro-orm/migrations';
/**
* A file the user attaches in the trip chat stays with the conversation. Until
* now it lived only as a buffer for the one request that read it, so the
* assistant could neither look at it again nor keep it in the trip's Files.
*
* `assistant_attachments` keeps one row per attached file: who attached it,
* in which thread of which trip, its name, type, size and hash, the storage
* key its bytes sit under, and the text TREK read out of it with how that
* went (`text_status`). The text reaches the AI provider only after the user
* agreed for this one file (`shared_at`), and a file kept in Files names the
* trip file it became (`file_id`).
*
* The rows go with their thread, their user and their trip; a trip file the
* user deletes later only clears `file_id`. The retention sweep removes a row
* and its bytes after a week, or as soon as its thread is gone. Every foreign
* key leads an index, and `created_at` has one for that sweep.
*/
export class Migration20200101046300_an_attached_file_stays_with_its_conversation extends Migration {
override name = 'Migration20200101046300_an_attached_file_stays_with_its_conversation';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS assistant_attachments (
id TEXT PRIMARY KEY NOT NULL,
thread_id INTEGER NOT NULL REFERENCES assistant_threads(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
name TEXT NOT NULL,
mime TEXT NOT NULL,
size INTEGER NOT NULL,
sha256 TEXT NOT NULL,
storage_key TEXT NOT NULL,
text TEXT,
text_status TEXT NOT NULL CHECK(text_status IN ('ok', 'empty', 'scanned', 'unsupported', 'failed')),
shared_at DATETIME,
file_id INTEGER REFERENCES trip_files(id) ON DELETE SET NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
`);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_assistant_attachments_thread ON assistant_attachments(thread_id, created_at)',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_assistant_attachments_user ON assistant_attachments(user_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_assistant_attachments_trip ON assistant_attachments(trip_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_assistant_attachments_file ON assistant_attachments(file_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_assistant_attachments_created ON assistant_attachments(created_at)');
}
}
@@ -0,0 +1,196 @@
import type { AssistantAttachments } from '../entities/AssistantAttachments.entity';
import type { DB } from '../kysely/db';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/** How TREK's reading of an attached file went: text it read, none, a scan, a type it does not read, a failure. */
export type AssistantAttachmentTextStatus = 'ok' | 'empty' | 'scanned' | 'unsupported' | 'failed';
/** One `assistant_attachments` row as stored, the text included. */
export interface AssistantAttachmentRow {
id: string;
thread_id: number;
user_id: number;
trip_id: number;
name: string;
mime: string;
size: number;
sha256: string;
storage_key: string;
text: string | null;
text_status: string;
shared_at: string | null;
file_id: number | null;
created_at: string;
}
const _assistantAttachmentRowKeys: AssertRowKeys<AssistantAttachmentRow, AssistantAttachments> = true;
/** An attachment as a turn lists it: everything but its text. */
export type AssistantAttachmentSummary = Omit<AssistantAttachmentRow, 'text'>;
/** A new attachment, as AssistantAttachmentsService writes it. */
export interface AssistantAttachmentInsert {
id: string;
threadId: number;
userId: number;
tripId: number;
name: string;
mime: string;
size: number;
sha256: string;
storageKey: string;
text: string | null;
textStatus: AssistantAttachmentTextStatus;
createdAt: string;
}
/** Where an attachment's bytes sit, for the sweep and a thread's deletion. */
export interface AssistantAttachmentObject {
id: string;
storage_key: string;
}
type AttachmentsKyselyDB = Pick<DB, 'assistant_attachments'>;
const SUMMARY_COLUMNS = [
'id',
'thread_id',
'user_id',
'trip_id',
'name',
'mime',
'size',
'sha256',
'storage_key',
'text_status',
'shared_at',
'file_id',
'created_at',
] as const;
/**
* `assistant_attachments`: the files users attached in a trip chat. Every
* read a turn makes names the thread and the user next to the id, so an
* attachment is only ever reached in the conversation it was attached in,
* by the user who attached it.
*/
export class AssistantAttachmentsRepository extends TrekRepository<AssistantAttachments> {
private db() {
return this.kysely<AttachmentsKyselyDB>();
}
async insertAttachment(row: AssistantAttachmentInsert): Promise<void> {
await this.db()
.insertInto('assistant_attachments')
.values({
id: row.id,
thread_id: row.threadId,
user_id: row.userId,
trip_id: row.tripId,
name: row.name,
mime: row.mime,
size: row.size,
sha256: row.sha256,
storage_key: row.storageKey,
text: row.text,
text_status: row.textStatus,
created_at: row.createdAt,
})
.execute();
}
/** One attachment of the user's in this thread, with its text; null for anyone else's or another thread's. */
async findInThread(id: string, threadId: number, userId: number): Promise<AssistantAttachmentRow | null> {
const row = await this.db()
.selectFrom('assistant_attachments')
.selectAll()
.where('id', '=', id)
.where('thread_id', '=', threadId)
.where('user_id', '=', userId)
.executeTakeFirst();
return row ?? null;
}
/** The user's attachments in this thread, oldest first, without their text. */
async listForThread(threadId: number, userId: number): Promise<AssistantAttachmentSummary[]> {
return this.db()
.selectFrom('assistant_attachments')
.select(SUMMARY_COLUMNS)
.where('thread_id', '=', threadId)
.where('user_id', '=', userId)
.orderBy('created_at', 'asc')
.orderBy('id', 'asc')
.execute();
}
/** The texts of this thread's attachments the user let the model read, by id. */
async listSharedTexts(threadId: number, userId: number): Promise<Array<{ id: string; text: string }>> {
const rows = await this.db()
.selectFrom('assistant_attachments')
.select(['id', 'text'])
.where('thread_id', '=', threadId)
.where('user_id', '=', userId)
.where('shared_at', 'is not', null)
.where('text', 'is not', null)
.execute();
return rows.flatMap((row) => (row.text === null ? [] : [{ id: row.id, text: row.text }]));
}
/** Records that the user let the model read the attachment; the first agreement's time stays. */
async markShared(id: string, threadId: number, userId: number, at: string): Promise<boolean> {
const result = await this.db()
.updateTable('assistant_attachments')
.set({ shared_at: at })
.where('id', '=', id)
.where('thread_id', '=', threadId)
.where('user_id', '=', userId)
.where('shared_at', 'is', null)
.executeTakeFirst();
return Number(result.numUpdatedRows) > 0;
}
/** Names the trip file the attachment was kept as. */
async setFile(id: string, fileId: number): Promise<void> {
await this.db().updateTable('assistant_attachments').set({ file_id: fileId }).where('id', '=', id).execute();
}
/** Where the bytes of the user's attachments in this thread sit. */
async listObjectsOfThread(threadId: number, userId: number): Promise<AssistantAttachmentObject[]> {
return this.db()
.selectFrom('assistant_attachments')
.select(['id', 'storage_key'])
.where('thread_id', '=', threadId)
.where('user_id', '=', userId)
.execute();
}
/** Retention: the attachments made before `cutoff`, oldest first, at most `limit`. */
async listCreatedBefore(cutoff: string, limit: number): Promise<AssistantAttachmentObject[]> {
return this.db()
.selectFrom('assistant_attachments')
.select(['id', 'storage_key'])
.where('created_at', '<', cutoff)
.orderBy('created_at', 'asc')
.limit(limit)
.execute();
}
/** Which of these storage keys a row still names. */
async listKnownKeys(keys: string[]): Promise<string[]> {
if (keys.length === 0) return [];
const rows = await this.db()
.selectFrom('assistant_attachments')
.select('storage_key')
.where('storage_key', 'in', keys)
.execute();
return rows.map((row) => row.storage_key);
}
/** Drops these attachments; answers how many went. */
async deleteByIds(ids: string[]): Promise<number> {
if (ids.length === 0) return 0;
const result = await this.db().deleteFrom('assistant_attachments').where('id', 'in', ids).executeTakeFirst();
return Number(result.numDeletedRows);
}
}