mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 13:10:29 +00:00
feat(assistant): the assistant opens outside a trip, as a home chat about all trips
A third scope, home, next to trip and journey: threads that name neither a trip nor a journey (the CHECK now only forbids both), reached under /api/assistant by their owner only. A home turn reads the user's trips through list_trips into a short card (under way, next, later, behind, undated), offers every read (a trip's on the id the model names, checked by the tool with the user's rights) and only the writes that take no trip or journey (atlas, vacation planner, collections, tour library, settings), all held as change cards. open_trip_chat answers with a card that goes on in that trip's own chat with the question waiting in its composer. On the desktop the window opens on the home chat outside a trip; its head lists the trips to switch into and a switched trip chat has the way back. On the phone the home chat opens full screen from the dashboard head and the dock's More list, and the card opens the trip with its chat. Both run on useAssistantHome.
This commit is contained in:
+109
@@ -0,0 +1,109 @@
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
/**
|
||||
* An assistant conversation can be about no one trip or journey: the home
|
||||
* chat on the dashboard, Vacay, Atlas, the collections and the settings
|
||||
* knows all of the user's trips and works on what belongs to none of them.
|
||||
* Such a thread names neither `trip_id` nor `journey_id`, so the CHECK that
|
||||
* held every thread to exactly one of the two now only keeps a thread from
|
||||
* naming both. Every existing thread names one of them and stays as it is.
|
||||
*
|
||||
* SQLite cannot change a CHECK in place, so the table is rebuilt the way
|
||||
* Migration20200101046250 rebuilt it: with `foreign_keys = ON` a
|
||||
* `DROP TABLE assistant_threads` runs an implicit `DELETE FROM
|
||||
* assistant_threads` first, and the `ON DELETE CASCADE` on
|
||||
* `assistant_messages` and `assistant_tool_calls` would empty both. So both
|
||||
* are rebuilt as well, pointing at the new tables, and the old ones go
|
||||
* children first. Renaming each new table to its old name rewrites the
|
||||
* foreign keys that point at it. Every id is copied, so a thread, a message
|
||||
* and a proposed change keep theirs, and the indexes come back as they were.
|
||||
*
|
||||
* The home threads of a user are found through the user's trip index
|
||||
* (`user_id` first, then `trip_id` IS NULL); there are few of them.
|
||||
*/
|
||||
/** The three tables rebuilt, children first. */
|
||||
const REBUILT = ['assistant_tool_calls', 'assistant_messages', 'assistant_threads'] as const;
|
||||
|
||||
/** The indexes of the three tables, as they were before the rebuild. */
|
||||
const INDEXES = [
|
||||
'idx_assistant_threads_user_journey ON assistant_threads(user_id, journey_id, last_message_at)',
|
||||
'idx_assistant_threads_journey ON assistant_threads(journey_id)',
|
||||
'idx_assistant_threads_user_trip ON assistant_threads(user_id, trip_id, last_message_at)',
|
||||
'idx_assistant_threads_trip ON assistant_threads(trip_id)',
|
||||
'idx_assistant_messages_thread ON assistant_messages(thread_id, id)',
|
||||
'idx_assistant_tool_calls_message ON assistant_tool_calls(message_id)',
|
||||
] as const;
|
||||
|
||||
export class Migration20200101046280_an_assistant_conversation_can_be_about_no_one_trip extends Migration {
|
||||
override name = 'Migration20200101046280_an_assistant_conversation_can_be_about_no_one_trip';
|
||||
|
||||
override up(): void {
|
||||
this.addSql(`
|
||||
CREATE TABLE assistant_threads_new (
|
||||
id INTEGER PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
trip_id INTEGER REFERENCES trips(id) ON DELETE CASCADE,
|
||||
journey_id INTEGER REFERENCES journeys(id) ON DELETE CASCADE,
|
||||
title TEXT NOT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_message_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CHECK(trip_id IS NULL OR journey_id IS NULL)
|
||||
)
|
||||
`);
|
||||
this.addSql(`
|
||||
INSERT INTO assistant_threads_new (id, user_id, trip_id, journey_id, title, created_at, last_message_at)
|
||||
SELECT id, user_id, trip_id, journey_id, title, created_at, last_message_at FROM assistant_threads
|
||||
`);
|
||||
|
||||
this.addSql(`
|
||||
CREATE TABLE assistant_messages_new (
|
||||
id INTEGER PRIMARY KEY,
|
||||
thread_id INTEGER NOT NULL REFERENCES assistant_threads_new(id) ON DELETE CASCADE,
|
||||
role TEXT NOT NULL CHECK(role IN ('user', 'assistant')),
|
||||
parts TEXT NOT NULL,
|
||||
provider_state TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'complete' CHECK(status IN ('complete', 'awaiting_approval', 'aborted', 'error')),
|
||||
model TEXT,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
this.addSql(`
|
||||
INSERT INTO assistant_messages_new (id, thread_id, role, parts, provider_state, status, model, created_at)
|
||||
SELECT id, thread_id, role, parts, provider_state, status, model, created_at FROM assistant_messages
|
||||
`);
|
||||
|
||||
this.addSql(`
|
||||
CREATE TABLE assistant_tool_calls_new (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
thread_id INTEGER NOT NULL REFERENCES assistant_threads_new(id) ON DELETE CASCADE,
|
||||
message_id INTEGER NOT NULL REFERENCES assistant_messages_new(id) ON DELETE CASCADE,
|
||||
provider_call_id TEXT NOT NULL,
|
||||
tool_name TEXT NOT NULL,
|
||||
args TEXT NOT NULL,
|
||||
preview TEXT NOT NULL,
|
||||
state TEXT NOT NULL DEFAULT 'approval_requested'
|
||||
CHECK(state IN ('approval_requested', 'approved', 'rejected', 'executed', 'failed', 'expired', 'undone')),
|
||||
result TEXT,
|
||||
undo_until DATETIME,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
decided_at DATETIME,
|
||||
UNIQUE(thread_id, provider_call_id)
|
||||
)
|
||||
`);
|
||||
this.addSql(`
|
||||
INSERT INTO assistant_tool_calls_new (
|
||||
id, thread_id, message_id, provider_call_id, tool_name, args, preview, state, result, undo_until, created_at,
|
||||
decided_at
|
||||
)
|
||||
SELECT
|
||||
id, thread_id, message_id, provider_call_id, tool_name, args, preview, state, result, undo_until, created_at,
|
||||
decided_at
|
||||
FROM assistant_tool_calls
|
||||
`);
|
||||
|
||||
// Children first, so no old table is referenced when it goes; then each new one takes its old name.
|
||||
for (const table of REBUILT) this.addSql(`DROP TABLE ${table}`);
|
||||
for (const table of [...REBUILT].reverse()) this.addSql(`ALTER TABLE ${table}_new RENAME TO ${table}`);
|
||||
for (const index of INDEXES) this.addSql(`CREATE INDEX IF NOT EXISTS ${index}`);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@ import type { DB } from '../kysely/db';
|
||||
import type { AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
/** One `assistant_threads` row as stored: about a trip or about a journey, never both. */
|
||||
import type { ExpressionBuilder } from 'kysely';
|
||||
|
||||
/** One `assistant_threads` row as stored: about a trip, about a journey, or (home) about neither; never both. */
|
||||
export interface AssistantThreadRow {
|
||||
id: number;
|
||||
user_id: number;
|
||||
@@ -33,13 +35,23 @@ type RetentionKyselyDB = Pick<
|
||||
/** The column a thread names what it is about with. */
|
||||
type OwnerColumn = 'trip_id' | 'journey_id';
|
||||
|
||||
/** What a thread is about: a trip or a journey by its column, or null for the home chat, which names neither. */
|
||||
type ThreadOwner = { column: OwnerColumn; id: number } | null;
|
||||
|
||||
/** The rows of one owner: its column on its id, or for the home chat both columns empty. */
|
||||
function ownedBy(owner: ThreadOwner) {
|
||||
return (eb: ExpressionBuilder<ThreadsKyselyDB, 'assistant_threads'>) =>
|
||||
owner ? eb(owner.column, '=', owner.id) : eb.and([eb('trip_id', 'is', null), eb('journey_id', 'is', null)]);
|
||||
}
|
||||
|
||||
const COLUMNS = ['id', 'user_id', 'trip_id', 'journey_id', 'title', 'created_at', 'last_message_at'] as const;
|
||||
|
||||
/**
|
||||
* `assistant_threads`: a user's conversations about one trip, or (the Studio's)
|
||||
* about one journey. Every read and delete a request makes names the user and
|
||||
* the trip or journey next to the id, so a thread is only ever reached by its
|
||||
* owner on its own trip or journey.
|
||||
* `assistant_threads`: a user's conversations about one trip, (the Studio's)
|
||||
* about one journey, or (the home chat's, on the dashboard and the pages
|
||||
* outside a trip) about neither. Every read and delete a request makes names
|
||||
* the user and the trip, the journey or the home chat next to the id, so a
|
||||
* thread is only ever reached by its owner in its own scope.
|
||||
*/
|
||||
export class AssistantThreadsRepository extends TrekRepository<AssistantThreads> {
|
||||
private db() {
|
||||
@@ -66,22 +78,42 @@ export class AssistantThreadsRepository extends TrekRepository<AssistantThreads>
|
||||
return row.id;
|
||||
}
|
||||
|
||||
/** A new thread of the home chat, about no one trip or journey; answers its id, as `createThread` does. */
|
||||
async createHomeThread(userId: number, title: string, at: string): Promise<number> {
|
||||
const row = await this.db()
|
||||
.insertInto('assistant_threads')
|
||||
.values({ user_id: userId, title, created_at: at, last_message_at: at })
|
||||
.returning('id')
|
||||
.executeTakeFirstOrThrow();
|
||||
return row.id;
|
||||
}
|
||||
|
||||
async findOwned(id: number, userId: number, tripId: number): Promise<AssistantThreadRow | null> {
|
||||
return this.findOwnedBy(id, userId, 'trip_id', tripId);
|
||||
return this.findOwnedBy(id, userId, { column: 'trip_id', id: tripId });
|
||||
}
|
||||
|
||||
async findOwnedOnJourney(id: number, userId: number, journeyId: number): Promise<AssistantThreadRow | null> {
|
||||
return this.findOwnedBy(id, userId, 'journey_id', journeyId);
|
||||
return this.findOwnedBy(id, userId, { column: 'journey_id', id: journeyId });
|
||||
}
|
||||
|
||||
/** One of the user's home threads; null for a trip's or a journey's, or anyone else's. */
|
||||
async findOwnedAtHome(id: number, userId: number): Promise<AssistantThreadRow | null> {
|
||||
return this.findOwnedBy(id, userId, null);
|
||||
}
|
||||
|
||||
/** The user's threads on a trip, the most recently used first. */
|
||||
async listRecent(userId: number, tripId: number, limit: number): Promise<AssistantThreadRow[]> {
|
||||
return this.listRecentBy(userId, 'trip_id', tripId, limit);
|
||||
return this.listRecentBy(userId, { column: 'trip_id', id: tripId }, limit);
|
||||
}
|
||||
|
||||
/** The user's threads on a journey, the most recently used first. */
|
||||
async listRecentOnJourney(userId: number, journeyId: number, limit: number): Promise<AssistantThreadRow[]> {
|
||||
return this.listRecentBy(userId, 'journey_id', journeyId, limit);
|
||||
return this.listRecentBy(userId, { column: 'journey_id', id: journeyId }, limit);
|
||||
}
|
||||
|
||||
/** The user's home threads, the most recently used first. */
|
||||
async listRecentAtHome(userId: number, limit: number): Promise<AssistantThreadRow[]> {
|
||||
return this.listRecentBy(userId, null, limit);
|
||||
}
|
||||
|
||||
async touch(id: number, at: string): Promise<void> {
|
||||
@@ -90,12 +122,17 @@ export class AssistantThreadsRepository extends TrekRepository<AssistantThreads>
|
||||
|
||||
/** True when the thread was the user's on that trip and is gone now. */
|
||||
async deleteOwned(id: number, userId: number, tripId: number): Promise<boolean> {
|
||||
return this.deleteOwnedBy(id, userId, 'trip_id', tripId);
|
||||
return this.deleteOwnedBy(id, userId, { column: 'trip_id', id: tripId });
|
||||
}
|
||||
|
||||
/** True when the thread was the user's on that journey and is gone now. */
|
||||
async deleteOwnedOnJourney(id: number, userId: number, journeyId: number): Promise<boolean> {
|
||||
return this.deleteOwnedBy(id, userId, 'journey_id', journeyId);
|
||||
return this.deleteOwnedBy(id, userId, { column: 'journey_id', id: journeyId });
|
||||
}
|
||||
|
||||
/** True when the thread was one of the user's home threads and is gone now. */
|
||||
async deleteOwnedAtHome(id: number, userId: number): Promise<boolean> {
|
||||
return this.deleteOwnedBy(id, userId, null);
|
||||
}
|
||||
|
||||
/** Retention: drops the threads nobody wrote in since `cutoff`; answers how many went. */
|
||||
@@ -113,7 +150,9 @@ export class AssistantThreadsRepository extends TrekRepository<AssistantThreads>
|
||||
* A journey thread goes once its user neither owns the journey nor is on its
|
||||
* contributor list nor is named by one of its trip links. A link member who
|
||||
* left the linking trip keeps the thread until the link drops them; every
|
||||
* request checks the access itself, so such a thread is never reached.
|
||||
* request checks the access itself, so such a thread is never reached. A
|
||||
* home thread is about nothing anyone can lose access to: it stays until it
|
||||
* idles past the retention or its user goes.
|
||||
*/
|
||||
async deleteWithoutAccess(): Promise<number> {
|
||||
const result = await this.kysely<RetentionKyselyDB>()
|
||||
@@ -178,45 +217,35 @@ export class AssistantThreadsRepository extends TrekRepository<AssistantThreads>
|
||||
return Number(result.numDeletedRows);
|
||||
}
|
||||
|
||||
private async findOwnedBy(
|
||||
id: number,
|
||||
userId: number,
|
||||
column: OwnerColumn,
|
||||
ownerId: number,
|
||||
): Promise<AssistantThreadRow | null> {
|
||||
private async findOwnedBy(id: number, userId: number, owner: ThreadOwner): Promise<AssistantThreadRow | null> {
|
||||
const row = await this.db()
|
||||
.selectFrom('assistant_threads')
|
||||
.select(COLUMNS)
|
||||
.where('id', '=', id)
|
||||
.where('user_id', '=', userId)
|
||||
.where(column, '=', ownerId)
|
||||
.where(ownedBy(owner))
|
||||
.executeTakeFirst();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
private async listRecentBy(
|
||||
userId: number,
|
||||
column: OwnerColumn,
|
||||
ownerId: number,
|
||||
limit: number,
|
||||
): Promise<AssistantThreadRow[]> {
|
||||
private async listRecentBy(userId: number, owner: ThreadOwner, limit: number): Promise<AssistantThreadRow[]> {
|
||||
return this.db()
|
||||
.selectFrom('assistant_threads')
|
||||
.select(COLUMNS)
|
||||
.where('user_id', '=', userId)
|
||||
.where(column, '=', ownerId)
|
||||
.where(ownedBy(owner))
|
||||
.orderBy('last_message_at', 'desc')
|
||||
.orderBy('id', 'desc')
|
||||
.limit(limit)
|
||||
.execute();
|
||||
}
|
||||
|
||||
private async deleteOwnedBy(id: number, userId: number, column: OwnerColumn, ownerId: number): Promise<boolean> {
|
||||
private async deleteOwnedBy(id: number, userId: number, owner: ThreadOwner): Promise<boolean> {
|
||||
const result = await this.db()
|
||||
.deleteFrom('assistant_threads')
|
||||
.where('id', '=', id)
|
||||
.where('user_id', '=', userId)
|
||||
.where(column, '=', ownerId)
|
||||
.where(ownedBy(owner))
|
||||
.executeTakeFirst();
|
||||
return Number(result.numDeletedRows) > 0;
|
||||
}
|
||||
|
||||
@@ -103,6 +103,20 @@ export class AssistantToolCallsRepository extends TrekRepository<AssistantToolCa
|
||||
return this.findOwnedBy(id, userId, 'assistant_threads.journey_id', journeyId);
|
||||
}
|
||||
|
||||
/** A call of one of the user's home threads; null for anyone else's or one on a trip or a journey. */
|
||||
async findOwnedAtHome(id: string, userId: number): Promise<AssistantToolCallRow | null> {
|
||||
const row = await this.kysely<Pick<DB, 'assistant_tool_calls' | 'assistant_threads'>>()
|
||||
.selectFrom('assistant_tool_calls')
|
||||
.innerJoin('assistant_threads', 'assistant_threads.id', 'assistant_tool_calls.thread_id')
|
||||
.selectAll('assistant_tool_calls')
|
||||
.where('assistant_tool_calls.id', '=', id)
|
||||
.where('assistant_threads.user_id', '=', userId)
|
||||
.where('assistant_threads.trip_id', 'is', null)
|
||||
.where('assistant_threads.journey_id', 'is', null)
|
||||
.executeTakeFirst();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
private async findOwnedBy(
|
||||
id: string,
|
||||
userId: number,
|
||||
|
||||
Reference in New Issue
Block a user