perf: optimize server queries, response compression, bundle splitting, and stream rendering
This commit is contained in:
15 files changed
+773
-437
No files matched your search
+78
-4
@@ -11,6 +11,8 @@ import Fastify, { type FastifyReply } from 'fastify';
|
||||
import multipart from '@fastify/multipart';
|
||||
import rateLimit from '@fastify/rate-limit';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
import { brotliCompress, constants as zlibConstants, gzip } from 'node:zlib';
|
||||
import type { PoolClient } from 'pg';
|
||||
import type { SpeechService } from './speech.ts';
|
||||
import { messageInput, registerAudioMessages } from './audio-messages.ts';
|
||||
@@ -337,6 +339,78 @@ export async function createApp(dependencies: AppDependencies = {}) {
|
||||
forceCloseConnections: true,
|
||||
});
|
||||
const streams = new Set<ServerResponse>();
|
||||
const compressGzip = promisify(gzip);
|
||||
const compressBrotli = promisify(brotliCompress);
|
||||
const compressibleType =
|
||||
/^(?:application\/(?:json|javascript)|text\/(?!event-stream)|image\/svg\+xml)/i;
|
||||
function preferredEncoding(header: unknown): 'br' | 'gzip' | null {
|
||||
const accept =
|
||||
typeof header === 'string' ? header : Array.isArray(header) ? header.join(',') : '';
|
||||
if (!accept) return null;
|
||||
let br = 0;
|
||||
let gzipQ = 0;
|
||||
let star = 0;
|
||||
for (const part of accept.split(',')) {
|
||||
const [rawName, ...params] = part.trim().toLowerCase().split(';');
|
||||
if (!rawName) continue;
|
||||
let q = 1;
|
||||
for (const param of params) {
|
||||
const [k, v] = param.trim().split('=');
|
||||
if (k === 'q') {
|
||||
const parsed = Number(v);
|
||||
q = Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
|
||||
}
|
||||
}
|
||||
if (rawName === 'br') br = Math.max(br, q);
|
||||
else if (rawName === 'gzip') gzipQ = Math.max(gzipQ, q);
|
||||
else if (rawName === '*') star = Math.max(star, q);
|
||||
}
|
||||
const brAllowed = br > 0 || (br === 0 && !/\bbr\b/i.test(accept) && star > 0);
|
||||
const gzipAllowed = gzipQ > 0 || (gzipQ === 0 && !/\bgzip\b/i.test(accept) && star > 0);
|
||||
if (brAllowed && (!gzipAllowed || br >= gzipQ)) return 'br';
|
||||
if (gzipAllowed) return 'gzip';
|
||||
return null;
|
||||
}
|
||||
app.addHook('onSend', async (request, reply, payload) => {
|
||||
if (
|
||||
payload == null ||
|
||||
reply.getHeader('content-encoding') ||
|
||||
reply.getHeader('content-range') ||
|
||||
request.method === 'HEAD' ||
|
||||
reply.statusCode < 200 ||
|
||||
reply.statusCode === 204 ||
|
||||
reply.statusCode === 206 ||
|
||||
reply.statusCode === 304
|
||||
)
|
||||
return payload;
|
||||
const contentType = String(reply.getHeader('content-type') ?? '');
|
||||
if (!compressibleType.test(contentType)) return payload;
|
||||
const raw =
|
||||
typeof payload === 'string'
|
||||
? Buffer.from(payload)
|
||||
: Buffer.isBuffer(payload)
|
||||
? payload
|
||||
: null;
|
||||
if (!raw || raw.length < 1024) return payload;
|
||||
const encoding = preferredEncoding(request.headers['accept-encoding']);
|
||||
if (!encoding) return payload;
|
||||
const compressed =
|
||||
encoding === 'br'
|
||||
? await compressBrotli(raw, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 4 } })
|
||||
: await compressGzip(raw, { level: 6 });
|
||||
reply.header('content-encoding', encoding);
|
||||
const existingVary = reply.getHeader('vary');
|
||||
const varyText = Array.isArray(existingVary)
|
||||
? existingVary.join(', ')
|
||||
: existingVary
|
||||
? String(existingVary)
|
||||
: '';
|
||||
if (!varyText) reply.header('vary', 'Accept-Encoding');
|
||||
else if (!/\baccept-encoding\b/i.test(varyText))
|
||||
reply.header('vary', `${varyText}, Accept-Encoding`);
|
||||
reply.removeHeader('content-length');
|
||||
return compressed;
|
||||
});
|
||||
const browserFrameAcks = new Map<
|
||||
string,
|
||||
{ turnId: string; browserId: string; origin?: string; acknowledge(): void }
|
||||
@@ -494,6 +568,7 @@ export async function createApp(dependencies: AppDependencies = {}) {
|
||||
recovery,
|
||||
phoneOffer,
|
||||
sleepNotice,
|
||||
tasks,
|
||||
] = await Promise.all([
|
||||
messageRows,
|
||||
hiddenMetadata,
|
||||
@@ -516,6 +591,7 @@ export async function createApp(dependencies: AppDependencies = {}) {
|
||||
chatRecovery(thread.id),
|
||||
dependencies.phoneOffer?.(),
|
||||
dependencies.sleepNotice?.(),
|
||||
dependencies.taskLedger?.(),
|
||||
]);
|
||||
const hasEarlierMessages = messages.rows.length > 150;
|
||||
const visibleIds = new Set(hiddenMessages.rows[0]!.visibleIds);
|
||||
@@ -523,12 +599,11 @@ export async function createApp(dependencies: AppDependencies = {}) {
|
||||
.slice(hasEarlierMessages ? 1 : 0)
|
||||
.filter((message) => visibleIds.has(message.id));
|
||||
const recentIds = new Set(turns.rows.map((turn) => turn.id));
|
||||
const [olderTurns, tasks, renderedMessages] = await Promise.all([
|
||||
const [olderTurns, renderedMessages] = await Promise.all([
|
||||
messageTurns(
|
||||
thread.id,
|
||||
visibleMessages.map((message) => message.turnId).filter((id) => id && !recentIds.has(id)),
|
||||
),
|
||||
dependencies.taskLedger?.(),
|
||||
messageViews(visibleMessages),
|
||||
]);
|
||||
const planning = dependencies.planningTasks?.();
|
||||
@@ -624,8 +699,7 @@ export async function createApp(dependencies: AppDependencies = {}) {
|
||||
{ statusCode: 409 },
|
||||
);
|
||||
const rows = await pool.query(
|
||||
`SELECT ${messageFields} FROM messages m
|
||||
LEFT JOIN messages target ON target.id=m.reply_to_message_id AND target.owner_id=m.owner_id AND target.hidden_at IS NULL
|
||||
`SELECT ${messageFields} FROM messages m LEFT JOIN messages target ON target.id=m.reply_to_message_id AND target.owner_id=m.owner_id AND target.hidden_at IS NULL
|
||||
WHERE m.owner_id=$1 AND m.thread_id=$4 AND m.hidden_at IS NULL AND m.created_at>=COALESCE((SELECT chat_cleared_at FROM threads WHERE id=$4 AND owner_id=$1),'-infinity') AND ${chatMessageSql}
|
||||
AND ($2::timestamptz IS NULL
|
||||
OR ($3::uuid IS NULL AND date_trunc('milliseconds',m.created_at AT TIME ZONE 'UTC') < date_trunc('milliseconds',$2::timestamptz AT TIME ZONE 'UTC'))
|
||||
|
||||
+16
-10
@@ -29,6 +29,7 @@ export const pool = createPool({
|
||||
});
|
||||
|
||||
const cancellationQueues = new WeakMap<pg.Pool, Promise<void>>();
|
||||
const cancellationPools = new WeakMap<pg.Pool, pg.Pool>();
|
||||
|
||||
export async function cancellationTransaction<T>(
|
||||
action: (client: pg.PoolClient) => Promise<T>,
|
||||
@@ -42,17 +43,19 @@ export async function cancellationTransaction<T>(
|
||||
cancellationQueues.set(database, queued);
|
||||
await previous;
|
||||
try {
|
||||
const control = createPool({
|
||||
...database.options,
|
||||
password: database.options.password,
|
||||
max: 1,
|
||||
min: 0,
|
||||
});
|
||||
try {
|
||||
return await transaction(action, control);
|
||||
} finally {
|
||||
await control.end();
|
||||
let control = cancellationPools.get(database);
|
||||
if (!control || control.ending || control.ended) {
|
||||
control = createPool({
|
||||
...database.options,
|
||||
password: database.options.password,
|
||||
max: 1,
|
||||
min: 0,
|
||||
idleTimeoutMillis: 15_000,
|
||||
allowExitOnIdle: true,
|
||||
});
|
||||
cancellationPools.set(database, control);
|
||||
}
|
||||
return await transaction(action, control);
|
||||
} finally {
|
||||
resume();
|
||||
if (cancellationQueues.get(database) === queued) cancellationQueues.delete(database);
|
||||
@@ -100,6 +103,9 @@ export async function initializeDatabase() {
|
||||
DROP TRIGGER IF EXISTS turns_session ON turns;
|
||||
CREATE TRIGGER turns_session BEFORE INSERT ON turns FOR EACH ROW EXECUTE FUNCTION turns_session();
|
||||
CREATE INDEX IF NOT EXISTS turns_session_queue ON turns(session_id,status);
|
||||
CREATE INDEX IF NOT EXISTS turns_owner_session_time ON turns(owner_id,session_id,created_at DESC,id DESC);
|
||||
CREATE INDEX IF NOT EXISTS turns_owner_thread_time ON turns(owner_id,thread_id,created_at DESC,id DESC);
|
||||
CREATE INDEX IF NOT EXISTS turns_owner_parent ON turns(owner_id,parent_turn_id) WHERE parent_turn_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS turns_owner_source ON turns(owner_id,source_id) WHERE source_id IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS turns_thread_queue ON turns(thread_id,status,created_at,id);
|
||||
CREATE INDEX IF NOT EXISTS turns_owner_time ON turns(owner_id,created_at,id);
|
||||
|
||||
@@ -506,6 +506,10 @@ export async function createIntegrations(pool: Pool, options: IntegrationOptions
|
||||
);
|
||||
}
|
||||
|
||||
const featuredOrder = new Map<string, number>(
|
||||
integrationServiceIds.map((slug, index) => [slug, index]),
|
||||
);
|
||||
|
||||
async function providerCatalog() {
|
||||
if (!provider.configured) return new Map<string, IntegrationServiceInfo>();
|
||||
let entries: IntegrationServiceInfo[];
|
||||
@@ -544,11 +548,9 @@ export async function createIntegrations(pool: Pool, options: IntegrationOptions
|
||||
for (const slug of directApps.keys()) services.set(slug, serviceInfo(slug));
|
||||
return [...services.values()]
|
||||
.sort((left, right) => {
|
||||
const featured = (slug: string) => {
|
||||
const index = (integrationServiceIds as readonly string[]).indexOf(slug);
|
||||
return index < 0 ? integrationServiceIds.length : index;
|
||||
};
|
||||
return featured(left.slug) - featured(right.slug) || left.name.localeCompare(right.name);
|
||||
const leftRank = featuredOrder.get(left.slug) ?? integrationServiceIds.length;
|
||||
const rightRank = featuredOrder.get(right.slug) ?? integrationServiceIds.length;
|
||||
return leftRank - rightRank || left.name.localeCompare(right.name);
|
||||
})
|
||||
.map((service) => ({
|
||||
...serviceInfo(service.slug),
|
||||
|
||||
+22
-14
@@ -330,6 +330,7 @@ export function createLedger({
|
||||
ALTER TABLE app_actions ADD COLUMN IF NOT EXISTS refs text[];
|
||||
CREATE INDEX IF NOT EXISTS app_actions_owner_time ON app_actions(owner_id,created_at);
|
||||
CREATE INDEX IF NOT EXISTS app_actions_turn ON app_actions(turn_id);
|
||||
CREATE INDEX IF NOT EXISTS app_actions_refs ON app_actions USING gin (refs);
|
||||
CREATE TABLE IF NOT EXISTS spending_limits (
|
||||
owner_id text PRIMARY KEY, monthly_usd double precision CHECK (monthly_usd > 0)
|
||||
);
|
||||
@@ -1267,27 +1268,33 @@ export function createLedger({
|
||||
}
|
||||
|
||||
async function read(): Promise<TrustView> {
|
||||
const [summary, daily, background, page, current] = await Promise.all([
|
||||
const [summary, daily, background, page, current, preparation] = await Promise.all([
|
||||
pool.query(
|
||||
`SELECT
|
||||
`WITH usage_window AS (
|
||||
SELECT
|
||||
COALESCE(sum(cost_usd) FILTER (WHERE created_at>now()-interval '7 days'),0)::float8 AS week,
|
||||
COALESCE(sum((details->>'estimateUsd')::float8) FILTER (WHERE ${planUsage} AND created_at>now()-interval '7 days'),0)::float8 AS week_plan,
|
||||
COALESCE(sum((details->>'estimateUsd')::float8) FILTER (WHERE ${planUsage} AND created_at>=${monthStart}),0)::float8 AS month_plan,
|
||||
COALESCE(bool_or(${unpricedUsage()} AND created_at>=${monthStart}),false) AS unpriced,
|
||||
COALESCE(bool_or(cost_usd IS NULL AND details ? 'estimateUsd' AND created_at>=${monthStart}),false) AS plan_usage
|
||||
FROM model_usage
|
||||
WHERE owner_id=$1 AND created_at>=LEAST(${monthStart},now()-interval '7 days')
|
||||
)
|
||||
SELECT
|
||||
(SELECT count(*) FROM turn_events e JOIN turns u ON u.id=e.turn_id
|
||||
WHERE u.owner_id=$1 AND e.type='tool_complete' AND e.created_at>now()-interval '7 days')::int AS things,
|
||||
(SELECT count(*) FROM app_actions WHERE owner_id=$1
|
||||
AND created_at>now()-interval '7 days')::int AS actions,
|
||||
(SELECT COALESCE(sum(cost_usd),0) FROM model_usage WHERE owner_id=$1
|
||||
AND created_at>now()-interval '7 days')::float8 AS week,
|
||||
(SELECT COALESCE(sum((details->>'estimateUsd')::float8),0) FROM model_usage WHERE owner_id=$1
|
||||
AND ${planUsage} AND created_at>now()-interval '7 days')::float8 AS week_plan,
|
||||
(SELECT COALESCE(sum((details->>'estimateUsd')::float8),0) FROM model_usage WHERE owner_id=$1
|
||||
AND ${planUsage} AND created_at>=${monthStart})::float8 AS month_plan,
|
||||
EXISTS(SELECT 1 FROM model_usage WHERE owner_id=$1 AND ${unpricedUsage()}
|
||||
AND created_at>=${monthStart}) AS unpriced,
|
||||
EXISTS(SELECT 1 FROM model_usage WHERE owner_id=$1 AND cost_usd IS NULL AND details ? 'estimateUsd'
|
||||
AND created_at>=${monthStart}) AS plan_usage,
|
||||
usage_window.week,
|
||||
usage_window.week_plan,
|
||||
usage_window.month_plan,
|
||||
usage_window.unpriced,
|
||||
usage_window.plan_usage,
|
||||
${monthStart} AS start,
|
||||
extract(day FROM date_trunc('month', now() AT TIME ZONE ${zone}) + interval '1 month - 1 day')::int AS days,
|
||||
extract(day FROM now() AT TIME ZONE ${zone})::int AS today,
|
||||
extract(epoch FROM now()-${monthStart})::float8/86400 AS elapsed`,
|
||||
extract(epoch FROM now()-${monthStart})::float8/86400 AS elapsed
|
||||
FROM usage_window`,
|
||||
[ownerId],
|
||||
),
|
||||
pool.query(
|
||||
@@ -1317,6 +1324,7 @@ export function createLedger({
|
||||
),
|
||||
entries(),
|
||||
limits(),
|
||||
preparationLimit(),
|
||||
]);
|
||||
const row = summary.rows[0];
|
||||
const elapsed = Math.min(row.days, Math.max(row.elapsed, 0));
|
||||
@@ -1359,7 +1367,7 @@ export function createLedger({
|
||||
outside: [...outside].map(([kind, costUsd]) => ({ kind, costUsd })),
|
||||
},
|
||||
...current,
|
||||
preparation: await preparationLimit(),
|
||||
preparation,
|
||||
...page,
|
||||
};
|
||||
}
|
||||
|
||||
+13
-3
@@ -90,10 +90,19 @@ export function createMemoryService(options: {
|
||||
}) {
|
||||
const storeFor = (client?: Pick<Pool, 'query'>) =>
|
||||
client && options.store.forClient ? options.store.forClient(client) : options.store;
|
||||
let cached: { version: string; bytes: Uint8Array; tree: Tree } | undefined;
|
||||
|
||||
async function load(client?: Pick<Pool, 'query'>) {
|
||||
async function load(client?: Pick<Pool, 'query'>, mutable = false) {
|
||||
const object = await storeFor(client).read(key, maxBytes);
|
||||
return { tree: parse(object?.bytes), bytes: object?.bytes, version: object?.version ?? null };
|
||||
if (!object) {
|
||||
if (!client) cached = undefined;
|
||||
return { tree: parse(undefined), bytes: undefined, version: null };
|
||||
}
|
||||
if (!client && !mutable && cached && cached.version === object.version)
|
||||
return { tree: cached.tree, bytes: cached.bytes, version: cached.version };
|
||||
const tree = parse(object.bytes);
|
||||
if (!client && !mutable) cached = { version: object.version, bytes: object.bytes, tree };
|
||||
return { tree, bytes: object.bytes, version: object.version };
|
||||
}
|
||||
|
||||
async function edit<T>(
|
||||
@@ -105,7 +114,7 @@ export function createMemoryService(options: {
|
||||
): Promise<T> {
|
||||
const activeStore = storeFor(client);
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const current = await load(client);
|
||||
const current = await load(client, true);
|
||||
if (!current.tree.enabled && !allowDisabled) throw new Error('Memory is turned off.');
|
||||
const result = change(current.tree);
|
||||
const bytes = render(current.tree);
|
||||
@@ -113,6 +122,7 @@ export function createMemoryService(options: {
|
||||
return result;
|
||||
try {
|
||||
await activeStore.write(key, bytes, { expectedVersion: current.version });
|
||||
cached = undefined;
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (!(error instanceof ObjectStoreConflict) || attempt === 2) throw error;
|
||||
|
||||
+99
-5
@@ -263,6 +263,7 @@ export function createSchedules(dependencies: ScheduleDependencies) {
|
||||
const now = dependencies.now ?? (() => new Date());
|
||||
const awake = dependencies.awakeMs ?? awakeMs;
|
||||
let workerStarted = false;
|
||||
const runsPerMonthCache = new Map<string, number | null>();
|
||||
|
||||
const transaction = <T>(operation: (client: PoolClient) => Promise<T>, shared?: PoolClient) =>
|
||||
shared ? operation(shared) : inTransaction(operation, pool);
|
||||
@@ -746,6 +747,7 @@ export function createSchedules(dependencies: ScheduleDependencies) {
|
||||
ADD COLUMN IF NOT EXISTS observation jsonb, ADD COLUMN IF NOT EXISTS observed_at timestamptz;
|
||||
CREATE INDEX IF NOT EXISTS schedule_runs_owner_time ON schedule_runs(owner_id,created_at DESC,id DESC);
|
||||
CREATE INDEX IF NOT EXISTS schedule_runs_schedule ON schedule_runs(owner_id,schedule_id,created_at DESC,id DESC);
|
||||
CREATE INDEX IF NOT EXISTS schedule_runs_schedule_scheduled ON schedule_runs(owner_id,schedule_id,scheduled_for DESC,created_at DESC,id DESC);
|
||||
CREATE INDEX IF NOT EXISTS schedule_runs_turn ON schedule_runs(owner_id,turn_id);
|
||||
`);
|
||||
if (fresh)
|
||||
@@ -976,7 +978,10 @@ export function createSchedules(dependencies: ScheduleDependencies) {
|
||||
};
|
||||
const from = now();
|
||||
const month = 30 * 86_400_000;
|
||||
const dayBucket = Math.floor(from.getTime() / 86_400_000);
|
||||
const runsPerMonth = (row: ScheduleRow) => {
|
||||
const cacheKey = `${row.cron!}\0${row.timeZone}\0${dayBucket}`;
|
||||
if (runsPerMonthCache.has(cacheKey)) return runsPerMonthCache.get(cacheKey)!;
|
||||
const times: number[] = [];
|
||||
try {
|
||||
while (
|
||||
@@ -992,9 +997,16 @@ export function createSchedules(dependencies: ScheduleDependencies) {
|
||||
times.push(...page.map((date) => date.getTime()));
|
||||
}
|
||||
} catch {
|
||||
if (times.length < 2) return null;
|
||||
if (times.length < 2) {
|
||||
runsPerMonthCache.set(cacheKey, null);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return times.length < 2 ? null : ((times.length - 1) * month) / (times.at(-1)! - times[0]!);
|
||||
const rate =
|
||||
times.length < 2 ? null : ((times.length - 1) * month) / (times.at(-1)! - times[0]!);
|
||||
if (runsPerMonthCache.size > 512) runsPerMonthCache.clear();
|
||||
runsPerMonthCache.set(cacheKey, rate);
|
||||
return rate;
|
||||
};
|
||||
for (const row of recurring) {
|
||||
const target = dependencies.workPricing?.(row.model);
|
||||
@@ -1041,7 +1053,66 @@ export function createSchedules(dependencies: ScheduleDependencies) {
|
||||
};
|
||||
}
|
||||
|
||||
async function list(page = false) {
|
||||
async function latestRunsBySchedule(scheduleIds: string[]) {
|
||||
const map = new Map<string, ScheduleRun>();
|
||||
if (!scheduleIds.length) return map;
|
||||
const rows = (
|
||||
await pool.query<RunRow>(
|
||||
`SELECT DISTINCT ON (r.schedule_id)
|
||||
r.id,r.schedule_id AS "scheduleId",r.title,r.turn_id AS "turnId",
|
||||
r.scheduled_for AS "scheduledFor",r.time_zone AS "timeZone",r.created_at AS "createdAt",
|
||||
u.status,u.error,r.observation,r.observed_at AS "observedAt",
|
||||
m.id AS "messageId",m.text AS "messageText",files.id AS "attachmentMessageId",
|
||||
to_char(r.created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "cursorAt"
|
||||
FROM (
|
||||
SELECT DISTINCT ON (schedule_id) *
|
||||
FROM schedule_runs
|
||||
WHERE owner_id=$1 AND schedule_id=ANY($2::uuid[])
|
||||
ORDER BY schedule_id,created_at DESC,id DESC
|
||||
) r ${runTurn}
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT m.id,left(m.text,4000) AS text FROM messages m
|
||||
WHERE m.turn_id=u.id AND m.owner_id=u.owner_id AND m.role='assistant'
|
||||
AND m.hidden_at IS NULL AND ${activeThreadSql('m')}
|
||||
ORDER BY (m.text<>'') DESC,m.created_at DESC,m.id DESC LIMIT 1
|
||||
) m ON true
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT m.id FROM messages m
|
||||
WHERE m.turn_id=u.id AND m.owner_id=u.owner_id AND m.role='assistant'
|
||||
AND m.hidden_at IS NULL AND ${activeThreadSql('m')}
|
||||
AND jsonb_array_length(m.attachments)>0
|
||||
ORDER BY m.created_at DESC,m.id DESC LIMIT 1
|
||||
) files ON true
|
||||
ORDER BY r.schedule_id`,
|
||||
[ownerId, scheduleIds],
|
||||
)
|
||||
).rows;
|
||||
for (const row of rows) map.set(row.scheduleId, runValue(row));
|
||||
return map;
|
||||
}
|
||||
|
||||
async function activeRunsBySchedule(scheduleIds: string[]) {
|
||||
const map = new Map<string, NonNullable<Schedule['activeRun']>>();
|
||||
if (!scheduleIds.length) return map;
|
||||
const { rows } = await pool.query<NonNullable<Schedule['activeRun']> & { scheduleId: string }>(
|
||||
`SELECT DISTINCT ON (r.schedule_id)
|
||||
r.schedule_id AS "scheduleId",r.id AS "runId",u.id AS "turnId",u.status,
|
||||
(SELECT m.id FROM messages m WHERE u.status='waiting'
|
||||
AND m.owner_id=u.owner_id AND m.thread_id=u.thread_id AND m.turn_id=u.id
|
||||
AND m.role='assistant' AND m.text<>'' AND m.hidden_at IS NULL AND ${activeThreadSql('m')}
|
||||
ORDER BY m.created_at DESC,m.id DESC LIMIT 1) AS "questionMessageId"
|
||||
FROM schedule_runs r
|
||||
JOIN turns u ON u.owner_id=r.owner_id AND u.session_id=r.turn_id
|
||||
WHERE r.owner_id=$1 AND r.schedule_id=ANY($2::uuid[]) AND (u.status IN ('queued','running')
|
||||
OR (${waitingTurnSql('u')}))
|
||||
ORDER BY r.schedule_id,(u.status='running') DESC,(u.status='queued') DESC,u.created_at DESC,u.id DESC`,
|
||||
[ownerId, scheduleIds],
|
||||
);
|
||||
for (const { scheduleId, ...run } of rows) map.set(scheduleId, run);
|
||||
return map;
|
||||
}
|
||||
|
||||
async function list(page = false): Promise<Schedule[]> {
|
||||
const rows = (
|
||||
await pool.query<ScheduleRow>(
|
||||
`SELECT ${columns} FROM schedules
|
||||
@@ -1050,8 +1121,31 @@ export function createSchedules(dependencies: ScheduleDependencies) {
|
||||
[ownerId, page],
|
||||
)
|
||||
).rows;
|
||||
const monthly = await monthlyCosts(rows);
|
||||
return Promise.all(rows.map((row) => value(row, monthly)));
|
||||
if (!rows.length) return [];
|
||||
const ids = rows.map((row) => row.id);
|
||||
const [monthly, lastRuns, activeRuns] = await Promise.all([
|
||||
monthlyCosts(rows),
|
||||
latestRunsBySchedule(ids),
|
||||
activeRunsBySchedule(ids),
|
||||
]);
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
prompt: row.prompt,
|
||||
kind: row.kind,
|
||||
cron: row.cron,
|
||||
runAt: row.runAt?.toISOString() ?? null,
|
||||
timeZone: row.timeZone,
|
||||
enabled: row.enabled,
|
||||
revision: row.revision,
|
||||
nextRun: row.nextRun?.toISOString() ?? null,
|
||||
lastRun: lastRuns.get(row.id) ?? null,
|
||||
activeRun: activeRuns.get(row.id) ?? null,
|
||||
baselineObservation: row.baselineObservation,
|
||||
watch: row.watch,
|
||||
model: row.model,
|
||||
monthlyUsd: monthly.get(row.id) ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
async function validateWatch(watch: string[] | null | undefined, client?: PoolClient) {
|
||||
|
||||
+12
-12
@@ -466,7 +466,10 @@ export async function createVault(pool: Pool, options: VaultOptions) {
|
||||
ciphertext text NOT NULL, updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS vault_cards_owner ON vault_cards(owner_id);
|
||||
CREATE INDEX IF NOT EXISTS vault_cards_owner_updated ON vault_cards(owner_id,updated_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS vault_entries_owner ON vault_entries(owner_id);
|
||||
CREATE INDEX IF NOT EXISTS vault_entries_owner_origin ON vault_entries(owner_id,origin);
|
||||
CREATE INDEX IF NOT EXISTS vault_entries_owner_updated ON vault_entries(owner_id,updated_at DESC);
|
||||
`);
|
||||
const uses = await createVaultUses(pool, owner, options.analytics, options.signal);
|
||||
let keyPromise: Promise<Buffer> | undefined;
|
||||
@@ -496,17 +499,18 @@ export async function createVault(pool: Pool, options: VaultOptions) {
|
||||
}
|
||||
|
||||
async function listEntries(): Promise<VaultListEntry[]> {
|
||||
let logins = await pool.query<EntryRow>(
|
||||
'SELECT * FROM vault_entries WHERE owner_id=$1 ORDER BY updated_at DESC',
|
||||
[owner],
|
||||
);
|
||||
const [logins, cards] = await Promise.all([
|
||||
pool.query<EntryRow>(
|
||||
'SELECT * FROM vault_entries WHERE owner_id=$1 ORDER BY updated_at DESC',
|
||||
[owner],
|
||||
),
|
||||
pool.query<CardRow>('SELECT * FROM vault_cards WHERE owner_id=$1 ORDER BY updated_at DESC', [
|
||||
owner,
|
||||
]),
|
||||
]);
|
||||
const entries: VaultListEntry[] = [];
|
||||
if (logins.rows.length) {
|
||||
const credentialKey = await key();
|
||||
logins = await pool.query<EntryRow>(
|
||||
'SELECT * FROM vault_entries WHERE owner_id=$1 ORDER BY updated_at DESC',
|
||||
[owner],
|
||||
);
|
||||
for (const entry of logins.rows) {
|
||||
try {
|
||||
const { username } = openCredential(credentialKey, entry);
|
||||
@@ -516,10 +520,6 @@ export async function createVault(pool: Pool, options: VaultOptions) {
|
||||
}
|
||||
}
|
||||
}
|
||||
const cards = await pool.query<CardRow>(
|
||||
'SELECT * FROM vault_cards WHERE owner_id=$1 ORDER BY updated_at DESC',
|
||||
[owner],
|
||||
);
|
||||
entries.push(...cards.rows.map(cardMetadata));
|
||||
return entries.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
||||
}
|
||||
|
||||
@@ -34,9 +34,9 @@ import {
|
||||
type ImagePreview,
|
||||
} from './attachment-images';
|
||||
import { PreviewLoading, PreviewUnavailable } from './attachment-status';
|
||||
import PdfPreview from './attachment-pdf';
|
||||
|
||||
const AttachmentData = lazy(() => import('./attachment-data'));
|
||||
const PdfPreview = lazy(() => import('./attachment-pdf'));
|
||||
import { FileActions, fileDrag, prepareFile } from './file-actions';
|
||||
import { apiResponse, errorMessage, responseError } from '../lib/api';
|
||||
import { Button } from './ui';
|
||||
@@ -207,7 +207,12 @@ const ArtifactView = memo(function ArtifactView({
|
||||
<AudioPlayer item={item} onDuration={(seconds) => onDetail(duration(seconds))} />
|
||||
</div>
|
||||
);
|
||||
if (kind === 'pdf') return <PdfPreview url={item.url} onDetail={onDetail} />;
|
||||
if (kind === 'pdf')
|
||||
return (
|
||||
<Suspense fallback={<PreviewLoading />}>
|
||||
<PdfPreview url={item.url} onDetail={onDetail} />
|
||||
</Suspense>
|
||||
);
|
||||
return (
|
||||
<Suspense fallback={<PreviewLoading />}>
|
||||
<AttachmentData item={item} kind={kind} mode={mode} stage={stage} onDetail={onDetail} />
|
||||
|
||||
@@ -14,14 +14,12 @@ import {
|
||||
type AttachmentTrigger,
|
||||
type ImagePreview,
|
||||
} from './attachment-images';
|
||||
import {
|
||||
loadPreviewPdf,
|
||||
PdfPage,
|
||||
type PreviewPdfDocument,
|
||||
type PreviewPdfLoading,
|
||||
} from './attachment-pdf';
|
||||
import type { loadPreviewPdf, PreviewPdfDocument, PreviewPdfLoading } from './attachment-pdf';
|
||||
|
||||
type LoadPdf = typeof loadPreviewPdf;
|
||||
const defaultLoadPdf: LoadPdf = async (...args) =>
|
||||
(await import('./attachment-pdf')).loadPreviewPdf(...args);
|
||||
const LazyPdfPage = lazy(async () => ({ default: (await import('./attachment-pdf')).PdfPage }));
|
||||
const AttachmentData = lazy(() => import('./attachment-data'));
|
||||
type DataKind = ComponentProps<typeof AttachmentData>['kind'];
|
||||
const ignoreDetail = () => {};
|
||||
@@ -157,13 +155,15 @@ function PdfThumbnail({
|
||||
return (
|
||||
<span className="attachment-card-preview" ref={element} aria-hidden="true">
|
||||
{document && (
|
||||
<PdfPage
|
||||
document={document}
|
||||
number={1}
|
||||
width={width + 24}
|
||||
onError={hide}
|
||||
onRendered={release}
|
||||
/>
|
||||
<Suspense fallback={null}>
|
||||
<LazyPdfPage
|
||||
document={document}
|
||||
number={1}
|
||||
width={width + 24}
|
||||
onError={hide}
|
||||
onRendered={release}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
@@ -274,7 +274,7 @@ export function conversationFiles(
|
||||
|
||||
export function MessageAttachments({
|
||||
attachments,
|
||||
loadDocument = loadPreviewPdf,
|
||||
loadDocument = defaultLoadPdf,
|
||||
}: {
|
||||
attachments: Artifact[];
|
||||
loadDocument?: LoadPdf;
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
lazy,
|
||||
memo,
|
||||
Suspense,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
@@ -377,7 +378,7 @@ export function WorkLabel({ work, mark = true }: { work: MessageWork; mark?: boo
|
||||
);
|
||||
}
|
||||
|
||||
export function MessageBubble({
|
||||
export const MessageBubble = memo(function MessageBubble({
|
||||
message,
|
||||
pendingAudio,
|
||||
connectedAppIds,
|
||||
@@ -718,10 +719,25 @@ export function MessageBubble({
|
||||
y: number;
|
||||
} | null>(null);
|
||||
const canOpenMenu = !streaming && Boolean(onReply || canCopy || message.role === 'assistant');
|
||||
function cancelHold() {
|
||||
const holdListeners = useRef(false);
|
||||
const cancelHold = useCallback(() => {
|
||||
if (hold.current) clearTimeout(hold.current.timer);
|
||||
hold.current = null;
|
||||
}
|
||||
if (!holdListeners.current) return;
|
||||
holdListeners.current = false;
|
||||
document.removeEventListener('scroll', cancelHold, true);
|
||||
document.removeEventListener('pointerup', cancelHold);
|
||||
document.removeEventListener('pointercancel', cancelHold);
|
||||
window.removeEventListener('blur', cancelHold);
|
||||
}, []);
|
||||
const attachHoldListeners = useCallback(() => {
|
||||
if (holdListeners.current) return;
|
||||
holdListeners.current = true;
|
||||
document.addEventListener('scroll', cancelHold, true);
|
||||
document.addEventListener('pointerup', cancelHold);
|
||||
document.addEventListener('pointercancel', cancelHold);
|
||||
window.addEventListener('blur', cancelHold);
|
||||
}, [cancelHold]);
|
||||
function openMenu(point?: { x: number; y: number }) {
|
||||
cancelHold();
|
||||
setPanel({
|
||||
@@ -761,19 +777,7 @@ export function MessageBubble({
|
||||
},
|
||||
[],
|
||||
);
|
||||
useEffect(() => {
|
||||
document.addEventListener('scroll', cancelHold, true);
|
||||
document.addEventListener('pointerup', cancelHold);
|
||||
document.addEventListener('pointercancel', cancelHold);
|
||||
window.addEventListener('blur', cancelHold);
|
||||
return () => {
|
||||
cancelHold();
|
||||
document.removeEventListener('scroll', cancelHold, true);
|
||||
document.removeEventListener('pointerup', cancelHold);
|
||||
document.removeEventListener('pointercancel', cancelHold);
|
||||
window.removeEventListener('blur', cancelHold);
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => () => cancelHold(), [cancelHold]);
|
||||
useLayoutEffect(() => {
|
||||
if (!panel || !panelElement.current) return;
|
||||
const element = panelElement.current;
|
||||
@@ -999,6 +1003,7 @@ export function MessageBubble({
|
||||
)
|
||||
return;
|
||||
const point = { x: event.clientX, y: event.clientY };
|
||||
attachHoldListeners();
|
||||
hold.current = {
|
||||
...point,
|
||||
pointerId: event.pointerId,
|
||||
@@ -1396,4 +1401,4 @@ export function MessageBubble({
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useReducer, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';
|
||||
import type { Activity, AppState } from '../../shared/contracts';
|
||||
import { api, errorMessage, post } from '../lib/api';
|
||||
import { initialStreamState, streamReducer } from '../lib/streams';
|
||||
import { initialStreamState, streamReducer, type StreamDelta } from '../lib/streams';
|
||||
import { pageDataCache } from '../lib/page-data-cache';
|
||||
import { subscribeAppEvents } from '../lib/app-events';
|
||||
import { feedbackClient } from '../lib/feedback-client';
|
||||
@@ -21,6 +21,18 @@ export function useAppState(accountId?: string) {
|
||||
const activitySeen = useRef(0);
|
||||
const stateRequestDone = useRef<Promise<void> | null>(null);
|
||||
const nextRefresh = useRef<Promise<void> | null>(null);
|
||||
const pendingDeltas = useRef(new Map<string, StreamDelta>());
|
||||
const flushFrame = useRef<number | null>(null);
|
||||
const flushDeltas = useCallback(() => {
|
||||
if (flushFrame.current !== null) {
|
||||
cancelAnimationFrame(flushFrame.current);
|
||||
flushFrame.current = null;
|
||||
}
|
||||
if (!pendingDeltas.current.size) return;
|
||||
const items = [...pendingDeltas.current.values()];
|
||||
pendingDeltas.current.clear();
|
||||
dispatchStream({ type: 'deltas', items });
|
||||
}, []);
|
||||
const cancelStateRead = useCallback(() => {
|
||||
stateRequest.current?.abort();
|
||||
stateRequest.current = null;
|
||||
@@ -36,6 +48,7 @@ export function useAppState(accountId?: string) {
|
||||
requestVersion.current++;
|
||||
}
|
||||
threadId.current = next;
|
||||
flushDeltas();
|
||||
dispatchStream({ type: 'thread', threadId: next });
|
||||
setState((current) =>
|
||||
current && current.threadId !== next
|
||||
@@ -77,6 +90,7 @@ export function useAppState(accountId?: string) {
|
||||
return;
|
||||
if (retiredThreads.current.has(next.threadId)) return;
|
||||
advanceThread(next.threadId);
|
||||
flushDeltas();
|
||||
dispatchStream({
|
||||
type: 'persisted',
|
||||
threadId: next.threadId,
|
||||
@@ -104,7 +118,7 @@ export function useAppState(accountId?: string) {
|
||||
})();
|
||||
stateRequestDone.current = request;
|
||||
return request;
|
||||
}, [advanceThread]);
|
||||
}, [advanceThread, flushDeltas]);
|
||||
|
||||
const resetConversation = useCallback(
|
||||
(expectedThreadId: string, forget = false) => {
|
||||
@@ -138,6 +152,21 @@ export function useAppState(accountId?: string) {
|
||||
active.current = true;
|
||||
let subscribed = true;
|
||||
let activityWithoutScheduleRuns = '[]';
|
||||
const queueDelta = (delta: StreamDelta) => {
|
||||
const key = `${delta.threadId ?? ''}\0${delta.turnId}\0${delta.streamId ?? ''}`;
|
||||
const existing = pendingDeltas.current.get(key);
|
||||
if (existing) {
|
||||
existing.text += delta.text;
|
||||
if (delta.done) existing.done = true;
|
||||
} else {
|
||||
pendingDeltas.current.set(key, { ...delta });
|
||||
}
|
||||
if (delta.done) {
|
||||
flushDeltas();
|
||||
return;
|
||||
}
|
||||
if (flushFrame.current === null) flushFrame.current = requestAnimationFrame(flushDeltas);
|
||||
};
|
||||
void refresh();
|
||||
const closeEvents = subscribeAppEvents(accountId, {
|
||||
open() {
|
||||
@@ -189,8 +218,7 @@ export function useAppState(accountId?: string) {
|
||||
if (!retiredThreads.current.has(data.threadId)) void refresh();
|
||||
return;
|
||||
}
|
||||
dispatchStream({
|
||||
type: 'delta',
|
||||
queueDelta({
|
||||
threadId: data.threadId,
|
||||
turnId: data.turnId,
|
||||
text: typeof data.text === 'string' ? data.text : '',
|
||||
@@ -207,11 +235,16 @@ export function useAppState(accountId?: string) {
|
||||
return () => {
|
||||
active.current = false;
|
||||
subscribed = false;
|
||||
if (flushFrame.current !== null) {
|
||||
cancelAnimationFrame(flushFrame.current);
|
||||
flushFrame.current = null;
|
||||
}
|
||||
pendingDeltas.current.clear();
|
||||
requestVersion.current++;
|
||||
cancelStateRead();
|
||||
closeEvents();
|
||||
};
|
||||
}, [refresh, advanceThread, cancelStateRead, accountId]);
|
||||
}, [refresh, advanceThread, cancelStateRead, flushDeltas, accountId]);
|
||||
|
||||
useEffect(() => {
|
||||
feedbackClient.savedMessages = state ? state.messages.length : null;
|
||||
@@ -224,8 +257,12 @@ export function useAppState(accountId?: string) {
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
const streams = Object.fromEntries(
|
||||
Object.entries(streamState.active).map(([id, stream]) => [id, stream.text]),
|
||||
const streams = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
Object.entries(streamState.active).map(([id, stream]) => [id, stream.text]),
|
||||
),
|
||||
[streamState.active],
|
||||
);
|
||||
return { state, streams, error, connected, refresh, resetConversation };
|
||||
}
|
||||
+36
-20
@@ -4,15 +4,17 @@ interface StreamState {
|
||||
completed: string[];
|
||||
}
|
||||
|
||||
export type StreamDelta = {
|
||||
turnId: string;
|
||||
text: string;
|
||||
streamId?: string;
|
||||
done?: boolean;
|
||||
threadId?: string;
|
||||
};
|
||||
|
||||
export type StreamAction =
|
||||
| {
|
||||
type: 'delta';
|
||||
turnId: string;
|
||||
text: string;
|
||||
streamId?: string;
|
||||
done?: boolean;
|
||||
threadId?: string;
|
||||
}
|
||||
| ({ type: 'delta' } & StreamDelta)
|
||||
| { type: 'deltas'; items: StreamDelta[] }
|
||||
| {
|
||||
type: 'persisted';
|
||||
streamIds: string[];
|
||||
@@ -38,7 +40,32 @@ function closeStreams(state: StreamState, ids: string[]): StreamState {
|
||||
return { ...state, active, completed };
|
||||
}
|
||||
|
||||
function applyDelta(state: StreamState, action: StreamDelta): StreamState {
|
||||
const threadId = action.threadId ?? state.threadId;
|
||||
if (threadId !== state.threadId) {
|
||||
if (state.threadId) return state;
|
||||
state = { threadId, active: {}, completed: [] };
|
||||
}
|
||||
const id = action.streamId || `turn:${action.turnId}`;
|
||||
if (action.done) return closeStreams(state, [id]);
|
||||
if (!action.text || state.completed.includes(id)) return state;
|
||||
const current = state.active[id];
|
||||
if (current && current.turnId !== action.turnId) return state;
|
||||
return {
|
||||
...state,
|
||||
active: {
|
||||
...state.active,
|
||||
[id]: { turnId: action.turnId, text: (current?.text ?? '') + action.text },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function streamReducer(state: StreamState, action: StreamAction): StreamState {
|
||||
if (action.type === 'deltas') {
|
||||
let next = state;
|
||||
for (const item of action.items) next = applyDelta(next, item);
|
||||
return next;
|
||||
}
|
||||
const threadId = action.threadId ?? state.threadId;
|
||||
if (threadId !== state.threadId) {
|
||||
if (action.type === 'delta' && state.threadId) return state;
|
||||
@@ -54,16 +81,5 @@ export function streamReducer(state: StreamState, action: StreamAction): StreamS
|
||||
.map(([id]) => id),
|
||||
]);
|
||||
}
|
||||
const id = action.streamId || `turn:${action.turnId}`;
|
||||
if (action.done) return closeStreams(state, [id]);
|
||||
if (!action.text || state.completed.includes(id)) return state;
|
||||
const current = state.active[id];
|
||||
if (current && current.turnId !== action.turnId) return state;
|
||||
return {
|
||||
...state,
|
||||
active: {
|
||||
...state.active,
|
||||
[id]: { turnId: action.turnId, text: (current?.text ?? '') + action.text },
|
||||
},
|
||||
};
|
||||
return applyDelta(state, action);
|
||||
}
|
||||
+363
-310
@@ -1038,29 +1038,33 @@ export function Chat({
|
||||
return target ? [target.id] : [];
|
||||
}),
|
||||
);
|
||||
const displayMessages: Message[] = [
|
||||
...allMessages.filter((message) => !message.cardAnswer),
|
||||
...streamEntries.map(([id, value]): Message => {
|
||||
if (!streamTimes.current.has(id)) streamTimes.current.set(id, new Date().toISOString());
|
||||
return {
|
||||
id,
|
||||
streamId: id,
|
||||
role: 'assistant',
|
||||
text: value,
|
||||
turnId: null,
|
||||
attachments: [],
|
||||
createdAt: streamTimes.current.get(id)!,
|
||||
};
|
||||
}),
|
||||
];
|
||||
const unreadIndex = displayMessages.findIndex((message) => message.id === unreadBoundary);
|
||||
const visibleMessages =
|
||||
unreadIndex > 0
|
||||
const persistedDisplayMessages = allMessages.filter((message) => !message.cardAnswer);
|
||||
const streamingMessages: Message[] = streamEntries.map(([id, value]): Message => {
|
||||
if (!streamTimes.current.has(id)) streamTimes.current.set(id, new Date().toISOString());
|
||||
return {
|
||||
id,
|
||||
streamId: id,
|
||||
role: 'assistant',
|
||||
text: value,
|
||||
turnId: null,
|
||||
attachments: [],
|
||||
createdAt: streamTimes.current.get(id)!,
|
||||
};
|
||||
});
|
||||
const hasActiveStreams = streamingMessages.length > 0;
|
||||
const persistedUnreadIndex = persistedDisplayMessages.findIndex(
|
||||
(message) => message.id === unreadBoundary,
|
||||
);
|
||||
const visiblePersistedMessages =
|
||||
persistedUnreadIndex > 0
|
||||
? [
|
||||
...collapseScreenshotMessages(displayMessages.slice(0, unreadIndex)),
|
||||
...collapseScreenshotMessages(displayMessages.slice(unreadIndex)),
|
||||
...collapseScreenshotMessages(persistedDisplayMessages.slice(0, persistedUnreadIndex)),
|
||||
...collapseScreenshotMessages(persistedDisplayMessages.slice(persistedUnreadIndex)),
|
||||
]
|
||||
: collapseScreenshotMessages(displayMessages);
|
||||
: collapseScreenshotMessages(persistedDisplayMessages);
|
||||
const visibleMessages = streamingMessages.length
|
||||
? [...visiblePersistedMessages, ...streamingMessages]
|
||||
: visiblePersistedMessages;
|
||||
const phoneOffer = state.phoneOffer;
|
||||
const phoneOfferTurn = phoneOffer?.turnId;
|
||||
const phoneOfferMessageId =
|
||||
@@ -2287,7 +2291,7 @@ export function Chat({
|
||||
returning.current = false;
|
||||
stickToBottom.current = distance <= 2;
|
||||
const since = Date.parse(allMessages.at(-1)?.createdAt ?? '') || Date.now();
|
||||
setAway((current) => (distance <= 2 ? null : (current ?? { since })));
|
||||
setAway((current) => (distance <= 24 ? null : (current ?? { since })));
|
||||
reportRead();
|
||||
loadHistoryNearTop();
|
||||
}
|
||||
@@ -2305,7 +2309,6 @@ export function Chat({
|
||||
}, [
|
||||
state.messages,
|
||||
historyPage,
|
||||
streams,
|
||||
optimistic,
|
||||
visible,
|
||||
onReadLatest,
|
||||
@@ -2315,6 +2318,312 @@ export function Chat({
|
||||
hasEarlier,
|
||||
unreadPending,
|
||||
]);
|
||||
const updateAwayRef = useRef(updateAway);
|
||||
updateAwayRef.current = updateAway;
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
const frame = requestAnimationFrame(() => updateAwayRef.current());
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [streams, visible]);
|
||||
const persistedMessageElements = useMemo(
|
||||
() =>
|
||||
visiblePersistedMessages.map((message, index) => (
|
||||
<Fragment key={message.streamId ?? message.id}>
|
||||
{(!index ||
|
||||
!isSameDay(
|
||||
visiblePersistedMessages[index - 1].createdAt,
|
||||
message.createdAt,
|
||||
dateFormat,
|
||||
)) && (
|
||||
<div
|
||||
className="day-divider"
|
||||
ref={
|
||||
!index && !hasEarlier && message.id === unreadBoundary ? unreadDivider : undefined
|
||||
}
|
||||
>
|
||||
<span>{formatDayLabel(message.createdAt, dateFormat)}</span>
|
||||
</div>
|
||||
)}
|
||||
{message.id === unreadBoundary && (index > 0 || hasEarlier) && (
|
||||
<div
|
||||
className="unread-divider"
|
||||
ref={unreadDivider}
|
||||
role="separator"
|
||||
aria-label="New messages"
|
||||
>
|
||||
<span aria-hidden="true">New messages</span>
|
||||
</div>
|
||||
)}
|
||||
{message.suggestions && !message.suggestions.offer ? (
|
||||
<TaskCards
|
||||
id={message.id}
|
||||
grouped={
|
||||
message.id !== unreadBoundary &&
|
||||
messagesAreGrouped(visiblePersistedMessages[index - 1], message, dateFormat)
|
||||
}
|
||||
suggestions={message.suggestions}
|
||||
connections={connections ?? []}
|
||||
status={(task) =>
|
||||
suggestedTaskStatus(
|
||||
{ messages: allMessages, tasks: state.tasks, turns: state.turns },
|
||||
task.title,
|
||||
allMessages.findIndex((item) => item.id === message.id),
|
||||
persistedIds,
|
||||
)
|
||||
}
|
||||
disabled={!state.configuration.llmReady || welcoming || spendingPaused}
|
||||
onStart={(task, position) => {
|
||||
captureAnalytics('task_card_started', {
|
||||
...(task.kind ? { kind: task.kind === 'ongoing' ? 'ongoing' : 'immediate' } : {}),
|
||||
origin: task.origin ?? 'learned',
|
||||
position,
|
||||
});
|
||||
void send(task.title, [], null, 'task_card');
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<MessageBubble
|
||||
key={message.streamId ?? message.id}
|
||||
message={message}
|
||||
work={startedTask(message) ? undefined : workOf(message)}
|
||||
task={chipOf(message)}
|
||||
onStopTask={
|
||||
approvalTask(message)
|
||||
? async () => {
|
||||
captureAnalytics('task_action', { action: 'stop' });
|
||||
await post(`/api/tasks/${approvalTask(message)!.id}/stop`);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
taskStopped={approvalTask(message)?.status === 'cancelled'}
|
||||
answersDisabled={sending || !state.configuration.llmReady || welcoming}
|
||||
onRetry={
|
||||
message.role === 'assistant' &&
|
||||
message.retryable &&
|
||||
!hasActiveStreams &&
|
||||
index === visiblePersistedMessages.length - 1 &&
|
||||
!sending &&
|
||||
!state.turns.some(
|
||||
(turn) => turn.status === 'running' || turn.status === 'queued',
|
||||
) &&
|
||||
state.configuration.llmReady
|
||||
? () => {
|
||||
void send(
|
||||
'Continue',
|
||||
[],
|
||||
{ id: message.id, role: 'assistant', text: message.text },
|
||||
'composer',
|
||||
);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
chosenText={cardChoices.get(message.id)}
|
||||
onChoose={
|
||||
message.presentation?.type !== 'draft' ||
|
||||
index > lastOwnerIndex ||
|
||||
cardChoices.has(message.id)
|
||||
? async (value) => {
|
||||
const replying = (id?: string) => id === message.id;
|
||||
if (replying(replyTo?.id) && composer.current?.hasDraft()) {
|
||||
composer.current.focus();
|
||||
throw new Error(
|
||||
'Send your answer from the composer to include your edits.',
|
||||
);
|
||||
}
|
||||
const result = await send(
|
||||
value,
|
||||
[],
|
||||
{ id: message.id, role: 'assistant', text: message.text },
|
||||
'answer_choice',
|
||||
);
|
||||
if (!result.sent && result.error) throw new Error(result.error);
|
||||
if (result.sent && replying(replyTo?.id) && !composer.current?.hasDraft())
|
||||
setReplyTo((current) => (replying(current?.id) ? null : current));
|
||||
return result.sent;
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onAnswer={async (value, answer) => {
|
||||
const replying = (id?: string) => id === message.id;
|
||||
if (replying(replyTo?.id) && composer.current?.hasDraft()) {
|
||||
composer.current.focus();
|
||||
throw new Error('Send your answer from the composer to include your edits.');
|
||||
}
|
||||
if (
|
||||
message.interaction?.id &&
|
||||
message.interaction.status === 'open' &&
|
||||
'choiceIds' in answer &&
|
||||
!answer.custom
|
||||
) {
|
||||
try {
|
||||
await post(`/api/interactions/${message.interaction.id}/select`, {
|
||||
optionIds: answer.choiceIds,
|
||||
});
|
||||
if (replying(replyTo?.id) && !composer.current?.hasDraft())
|
||||
setReplyTo((current) => (replying(current?.id) ? null : current));
|
||||
return true;
|
||||
} catch (caught) {
|
||||
const code = (caught as { code?: string })?.code;
|
||||
if (code === 'interaction_closed' || code === 'interaction_expired')
|
||||
return 'unavailable';
|
||||
throw caught;
|
||||
}
|
||||
}
|
||||
const result = await send(
|
||||
value,
|
||||
[],
|
||||
{ id: message.id, role: 'assistant', text: message.text },
|
||||
'answer_choice',
|
||||
undefined,
|
||||
answer,
|
||||
);
|
||||
if (result.questionUnavailable) return 'unavailable';
|
||||
if (!result.sent && result.error) throw new Error(result.error);
|
||||
if (result.sent && replying(replyTo?.id) && !composer.current?.hasDraft())
|
||||
setReplyTo((current) => (replying(current?.id) ? null : current));
|
||||
return result.sent;
|
||||
}}
|
||||
onDismiss={async () => {
|
||||
const replying = (id?: string) => id === message.id;
|
||||
const clearReply = () => {
|
||||
setUnavailableQuestions((current) => new Set([...current, message.id]));
|
||||
setReplyTo((current) => {
|
||||
if (!replying(current?.id)) return current;
|
||||
if (!composer.current?.hasDraft()) return null;
|
||||
if (!current?.answerQuestion) return current;
|
||||
const { answerQuestion: _, ...rest } = current;
|
||||
return rest;
|
||||
});
|
||||
};
|
||||
const interactionId = message.interaction?.id;
|
||||
if (interactionId) {
|
||||
if (message.interaction?.status !== 'open') {
|
||||
clearReply();
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
await post(`/api/interactions/${interactionId}/dismiss`, {});
|
||||
clearReply();
|
||||
return true;
|
||||
} catch (caught) {
|
||||
const code = (caught as { code?: string })?.code;
|
||||
if (code === 'interaction_closed' || code === 'interaction_not_found') {
|
||||
clearReply();
|
||||
return true;
|
||||
}
|
||||
throw caught;
|
||||
}
|
||||
}
|
||||
if (!message.answerChoicesPending) {
|
||||
clearReply();
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
await post(`/api/messages/${message.id}/dismiss`, {});
|
||||
clearReply();
|
||||
return true;
|
||||
} catch (caught) {
|
||||
const code = (caught as { code?: string })?.code;
|
||||
if (code === 'question_not_found' || code === 'question_unavailable') {
|
||||
clearReply();
|
||||
return true;
|
||||
}
|
||||
throw caught;
|
||||
}
|
||||
}}
|
||||
onApprove={
|
||||
message.approval
|
||||
? async (approved, label) => {
|
||||
const result = await send(
|
||||
label,
|
||||
[],
|
||||
{ id: message.id, role: 'assistant', text: message.text },
|
||||
'approval_card',
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ approvalId: message.approval!.id, approved },
|
||||
);
|
||||
if (result.questionUnavailable) return 'unavailable';
|
||||
if (!result.sent && result.error) throw new Error(result.error);
|
||||
return result.sent;
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
codeRequest={codeRequests.has(message.id)}
|
||||
pendingAudio={optimistic.find((item) => item.message.id === message.id)?.audio}
|
||||
handoffPaused={spendingPaused}
|
||||
connectedAppIds={connectedAppIds}
|
||||
streaming={false}
|
||||
arriving={arriving(message)}
|
||||
grouped={
|
||||
message.id !== unreadBoundary &&
|
||||
messagesAreGrouped(visiblePersistedMessages[index - 1], message, dateFormat)
|
||||
}
|
||||
handoff={
|
||||
message.role === 'assistant' &&
|
||||
!sending &&
|
||||
state.turns.some((turn) => turn.handoffMessageId === message.id)
|
||||
}
|
||||
onReply={
|
||||
message.turnId || persistedIds.has(message.id)
|
||||
? (quote?: string) => {
|
||||
taskReply.current = null;
|
||||
const preview =
|
||||
(message.role === 'user' ? message.displayText : undefined) ??
|
||||
message.audioCaption ??
|
||||
message.text;
|
||||
const text =
|
||||
preview.trim() || !message.presentation
|
||||
? preview
|
||||
: presentationText(message.presentation);
|
||||
setReplyTo({
|
||||
...message,
|
||||
...(message.answerChoicesPending ? { answerQuestion: true as const } : {}),
|
||||
isQuote: Boolean(quote?.trim()),
|
||||
text: quote?.trim() ? quote : text,
|
||||
});
|
||||
composer.current?.focus();
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{message.suggestions?.offer && message.suggestions.apps?.length ? (
|
||||
<SenderOffer apps={message.suggestions.apps} standalone />
|
||||
) : null}
|
||||
{message.id === phoneOfferMessageId && phoneOffer && (
|
||||
<PhoneOfferCard
|
||||
offer={phoneOffer}
|
||||
path="chat"
|
||||
viewKey={message.id}
|
||||
onAnswered={() => void refresh().catch(() => {})}
|
||||
/>
|
||||
)}
|
||||
</Fragment>
|
||||
)),
|
||||
[
|
||||
state,
|
||||
historyPage,
|
||||
hasActiveStreams,
|
||||
sending,
|
||||
welcoming,
|
||||
spendingPaused,
|
||||
connectedAppIds,
|
||||
unreadBoundary,
|
||||
hasEarlier,
|
||||
dateFormat,
|
||||
connections,
|
||||
replyTo,
|
||||
phoneOffer,
|
||||
phoneOfferMessageId,
|
||||
optimistic,
|
||||
confirmedReplyTargets,
|
||||
finishing,
|
||||
routedItem,
|
||||
unavailableQuestions,
|
||||
],
|
||||
);
|
||||
async function stop() {
|
||||
if (stopping) return;
|
||||
const captureAnalytics = analyticsForCurrentSession();
|
||||
@@ -2481,293 +2790,37 @@ export function Chat({
|
||||
aria-live="polite"
|
||||
aria-relevant="additions"
|
||||
>
|
||||
{visibleMessages.map((message, index) => (
|
||||
<Fragment key={message.streamId ?? message.id}>
|
||||
{(!index ||
|
||||
!isSameDay(
|
||||
visibleMessages[index - 1].createdAt,
|
||||
message.createdAt,
|
||||
dateFormat,
|
||||
)) && (
|
||||
<div
|
||||
className="day-divider"
|
||||
ref={
|
||||
!index && !hasEarlier && message.id === unreadBoundary
|
||||
? unreadDivider
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<span>{formatDayLabel(message.createdAt, dateFormat)}</span>
|
||||
</div>
|
||||
)}
|
||||
{message.id === unreadBoundary && (index > 0 || hasEarlier) && (
|
||||
<div
|
||||
className="unread-divider"
|
||||
ref={unreadDivider}
|
||||
role="separator"
|
||||
aria-label="New messages"
|
||||
>
|
||||
<span aria-hidden="true">New messages</span>
|
||||
</div>
|
||||
)}
|
||||
{message.suggestions && !message.suggestions.offer ? (
|
||||
<TaskCards
|
||||
id={message.id}
|
||||
grouped={
|
||||
message.id !== unreadBoundary &&
|
||||
messagesAreGrouped(visibleMessages[index - 1], message, dateFormat)
|
||||
}
|
||||
suggestions={message.suggestions}
|
||||
connections={connections ?? []}
|
||||
status={(task) =>
|
||||
suggestedTaskStatus(
|
||||
{ messages: allMessages, tasks: state.tasks, turns: state.turns },
|
||||
task.title,
|
||||
allMessages.findIndex((item) => item.id === message.id),
|
||||
persistedIds,
|
||||
)
|
||||
}
|
||||
disabled={!state.configuration.llmReady || welcoming || spendingPaused}
|
||||
onStart={(task, position) => {
|
||||
captureAnalytics('task_card_started', {
|
||||
...(task.kind
|
||||
? { kind: task.kind === 'ongoing' ? 'ongoing' : 'immediate' }
|
||||
: {}),
|
||||
origin: task.origin ?? 'learned',
|
||||
position,
|
||||
});
|
||||
void send(task.title, [], null, 'task_card');
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<MessageBubble
|
||||
message={message}
|
||||
work={startedTask(message) ? undefined : workOf(message)}
|
||||
task={chipOf(message)}
|
||||
onStopTask={
|
||||
approvalTask(message)
|
||||
? async () => {
|
||||
captureAnalytics('task_action', { action: 'stop' });
|
||||
await post(`/api/tasks/${approvalTask(message)!.id}/stop`);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
taskStopped={approvalTask(message)?.status === 'cancelled'}
|
||||
answersDisabled={sending || !state.configuration.llmReady || welcoming}
|
||||
onRetry={
|
||||
message.role === 'assistant' &&
|
||||
message.retryable &&
|
||||
index === visibleMessages.length - 1 &&
|
||||
!sending &&
|
||||
!state.turns.some(
|
||||
(turn) => turn.status === 'running' || turn.status === 'queued',
|
||||
) &&
|
||||
state.configuration.llmReady
|
||||
? () => {
|
||||
void send(
|
||||
'Continue',
|
||||
[],
|
||||
{ id: message.id, role: 'assistant', text: message.text },
|
||||
'composer',
|
||||
);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
chosenText={cardChoices.get(message.id)}
|
||||
onChoose={
|
||||
message.presentation?.type !== 'draft' ||
|
||||
index > lastOwnerIndex ||
|
||||
cardChoices.has(message.id)
|
||||
? async (value) => {
|
||||
const replying = (id?: string) => id === message.id;
|
||||
if (replying(replyTo?.id) && composer.current?.hasDraft()) {
|
||||
composer.current.focus();
|
||||
throw new Error(
|
||||
'Send your answer from the composer to include your edits.',
|
||||
);
|
||||
}
|
||||
const result = await send(
|
||||
value,
|
||||
[],
|
||||
{ id: message.id, role: 'assistant', text: message.text },
|
||||
'answer_choice',
|
||||
);
|
||||
if (!result.sent && result.error) throw new Error(result.error);
|
||||
if (
|
||||
result.sent &&
|
||||
replying(replyTo?.id) &&
|
||||
!composer.current?.hasDraft()
|
||||
)
|
||||
setReplyTo((current) => (replying(current?.id) ? null : current));
|
||||
return result.sent;
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onAnswer={async (value, answer) => {
|
||||
const replying = (id?: string) => id === message.id;
|
||||
if (replying(replyTo?.id) && composer.current?.hasDraft()) {
|
||||
composer.current.focus();
|
||||
throw new Error(
|
||||
'Send your answer from the composer to include your edits.',
|
||||
);
|
||||
}
|
||||
if (
|
||||
message.interaction?.id &&
|
||||
message.interaction.status === 'open' &&
|
||||
'choiceIds' in answer &&
|
||||
!answer.custom
|
||||
) {
|
||||
try {
|
||||
await post(`/api/interactions/${message.interaction.id}/select`, {
|
||||
optionIds: answer.choiceIds,
|
||||
});
|
||||
if (replying(replyTo?.id) && !composer.current?.hasDraft())
|
||||
setReplyTo((current) => (replying(current?.id) ? null : current));
|
||||
return true;
|
||||
} catch (caught) {
|
||||
const code = (caught as { code?: string })?.code;
|
||||
if (code === 'interaction_closed' || code === 'interaction_expired')
|
||||
return 'unavailable';
|
||||
throw caught;
|
||||
}
|
||||
}
|
||||
const result = await send(
|
||||
value,
|
||||
[],
|
||||
{ id: message.id, role: 'assistant', text: message.text },
|
||||
'answer_choice',
|
||||
undefined,
|
||||
answer,
|
||||
);
|
||||
if (result.questionUnavailable) return 'unavailable';
|
||||
if (!result.sent && result.error) throw new Error(result.error);
|
||||
if (result.sent && replying(replyTo?.id) && !composer.current?.hasDraft())
|
||||
setReplyTo((current) => (replying(current?.id) ? null : current));
|
||||
return result.sent;
|
||||
}}
|
||||
onDismiss={async () => {
|
||||
const replying = (id?: string) => id === message.id;
|
||||
const clearReply = () => {
|
||||
setUnavailableQuestions((current) => new Set([...current, message.id]));
|
||||
setReplyTo((current) => {
|
||||
if (!replying(current?.id)) return current;
|
||||
if (!composer.current?.hasDraft()) return null;
|
||||
if (!current?.answerQuestion) return current;
|
||||
const { answerQuestion: _, ...rest } = current;
|
||||
return rest;
|
||||
});
|
||||
};
|
||||
const interactionId = message.interaction?.id;
|
||||
if (interactionId) {
|
||||
if (message.interaction?.status !== 'open') {
|
||||
clearReply();
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
await post(`/api/interactions/${interactionId}/dismiss`, {});
|
||||
clearReply();
|
||||
return true;
|
||||
} catch (caught) {
|
||||
const code = (caught as { code?: string })?.code;
|
||||
if (code === 'interaction_closed' || code === 'interaction_not_found') {
|
||||
clearReply();
|
||||
return true;
|
||||
}
|
||||
throw caught;
|
||||
}
|
||||
}
|
||||
if (!message.answerChoicesPending) {
|
||||
clearReply();
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
await post(`/api/messages/${message.id}/dismiss`, {});
|
||||
clearReply();
|
||||
return true;
|
||||
} catch (caught) {
|
||||
const code = (caught as { code?: string })?.code;
|
||||
if (code === 'question_not_found' || code === 'question_unavailable') {
|
||||
clearReply();
|
||||
return true;
|
||||
}
|
||||
throw caught;
|
||||
}
|
||||
}}
|
||||
onApprove={
|
||||
message.approval
|
||||
? async (approved, label) => {
|
||||
const result = await send(
|
||||
label,
|
||||
[],
|
||||
{ id: message.id, role: 'assistant', text: message.text },
|
||||
'approval_card',
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ approvalId: message.approval!.id, approved },
|
||||
);
|
||||
if (result.questionUnavailable) return 'unavailable';
|
||||
if (!result.sent && result.error) throw new Error(result.error);
|
||||
return result.sent;
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
codeRequest={codeRequests.has(message.id)}
|
||||
pendingAudio={
|
||||
optimistic.find((item) => item.message.id === message.id)?.audio
|
||||
}
|
||||
handoffPaused={spendingPaused}
|
||||
connectedAppIds={connectedAppIds}
|
||||
streaming={streamIds.has(message.streamId ?? '')}
|
||||
arriving={arriving(message)}
|
||||
grouped={
|
||||
message.id !== unreadBoundary &&
|
||||
messagesAreGrouped(visibleMessages[index - 1], message, dateFormat)
|
||||
}
|
||||
handoff={
|
||||
message.role === 'assistant' &&
|
||||
!sending &&
|
||||
state.turns.some((turn) => turn.handoffMessageId === message.id)
|
||||
}
|
||||
onReply={
|
||||
message.turnId || persistedIds.has(message.id)
|
||||
? (quote?: string) => {
|
||||
taskReply.current = null;
|
||||
const preview =
|
||||
(message.role === 'user' ? message.displayText : undefined) ??
|
||||
message.audioCaption ??
|
||||
message.text;
|
||||
const text =
|
||||
preview.trim() || !message.presentation
|
||||
? preview
|
||||
: presentationText(message.presentation);
|
||||
setReplyTo({
|
||||
...message,
|
||||
...(message.answerChoicesPending
|
||||
? { answerQuestion: true as const }
|
||||
: {}),
|
||||
isQuote: Boolean(quote?.trim()),
|
||||
text: quote?.trim() ? quote : text,
|
||||
});
|
||||
composer.current?.focus();
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{message.suggestions?.offer && message.suggestions.apps?.length ? (
|
||||
<SenderOffer apps={message.suggestions.apps} standalone />
|
||||
) : null}
|
||||
{message.id === phoneOfferMessageId && phoneOffer && (
|
||||
<PhoneOfferCard
|
||||
offer={phoneOffer}
|
||||
path="chat"
|
||||
viewKey={message.id}
|
||||
onAnswered={() => void refresh().catch(() => {})}
|
||||
/>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
{[
|
||||
...persistedMessageElements,
|
||||
...streamingMessages.map((message, index) => {
|
||||
const previous =
|
||||
index === 0 ? visiblePersistedMessages.at(-1) : streamingMessages[index - 1];
|
||||
return (
|
||||
<Fragment key={message.streamId ?? message.id}>
|
||||
{(!previous ||
|
||||
!isSameDay(previous.createdAt, message.createdAt, dateFormat)) && (
|
||||
<div className="day-divider">
|
||||
<span>{formatDayLabel(message.createdAt, dateFormat)}</span>
|
||||
</div>
|
||||
)}
|
||||
{false}
|
||||
<MessageBubble
|
||||
key={message.streamId ?? message.id}
|
||||
message={message}
|
||||
answersDisabled={sending || !state.configuration.llmReady || welcoming}
|
||||
handoffPaused={spendingPaused}
|
||||
connectedAppIds={connectedAppIds}
|
||||
streaming
|
||||
arriving={arriving(message)}
|
||||
grouped={messagesAreGrouped(previous, message, dateFormat)}
|
||||
handoff={false}
|
||||
/>
|
||||
{null}
|
||||
{false}
|
||||
</Fragment>
|
||||
);
|
||||
}),
|
||||
]}
|
||||
{planning ? (
|
||||
<Working
|
||||
label={
|
||||
|
||||
+26
-12
@@ -1,5 +1,5 @@
|
||||
import { PageTitle } from '../components/page-title';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ActionMenu, ActionMenuItem } from '../components/action-menu';
|
||||
import { ChevronRight, CreditCard, Globe, Import, KeyRound, Plus } from '../components/icons';
|
||||
import type { VaultListEntry } from '../../shared/contracts';
|
||||
@@ -56,17 +56,31 @@ export function Vault({ hidden = false }: { hidden?: boolean }) {
|
||||
const items = entries ?? [];
|
||||
const empty = Boolean(entries) && !items.length;
|
||||
const split = !phone && !empty;
|
||||
const search = query.trim().toLowerCase();
|
||||
const visible = items
|
||||
.filter(
|
||||
(item) =>
|
||||
!search ||
|
||||
[item.label, subtitle(item), item.kind === 'card' ? '' : originLabel(item.origin)]
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
.includes(search),
|
||||
)
|
||||
.sort((a, b) => a.label.localeCompare(b.label));
|
||||
const deferredQuery = useDeferredValue(query);
|
||||
const indexed = useMemo(
|
||||
() =>
|
||||
[...items]
|
||||
.sort((a, b) => a.label.localeCompare(b.label))
|
||||
.map((item) => ({
|
||||
item,
|
||||
haystack: [
|
||||
item.label,
|
||||
subtitle(item),
|
||||
item.kind === 'card' ? '' : originLabel(item.origin),
|
||||
]
|
||||
.join(' ')
|
||||
.toLowerCase(),
|
||||
})),
|
||||
[items],
|
||||
);
|
||||
const search = deferredQuery.trim().toLowerCase();
|
||||
const visible = useMemo(
|
||||
() =>
|
||||
search
|
||||
? indexed.filter((entry) => entry.haystack.includes(search)).map((entry) => entry.item)
|
||||
: indexed.map((entry) => entry.item),
|
||||
[indexed, search],
|
||||
);
|
||||
const selected =
|
||||
items.find((item) => item.id === selectedId) ??
|
||||
(selectedId === undefined && split && !adding ? visible[0] : undefined);
|
||||
|
||||
+13
-1
@@ -12,9 +12,21 @@ export default defineConfig({
|
||||
output: {
|
||||
codeSplitting: {
|
||||
groups: [
|
||||
{
|
||||
name: 'react',
|
||||
test: /node_modules[\\/](react|react-dom|scheduler)[\\/]/,
|
||||
},
|
||||
{
|
||||
name: 'tiptap',
|
||||
test: /node_modules[\\/](@tiptap|prosemirror-[^\\/]+|orderedmap|rope-sequence|w3c-keyname)[\\/]/,
|
||||
},
|
||||
{
|
||||
name: 'markdown',
|
||||
test: /node_modules[\\/](react-markdown|remark-gfm|rehype-raw|rehype-sanitize)[\\/]/,
|
||||
test: /node_modules[\\/](react-markdown|remark-[^\\/]+|rehype-[^\\/]+|unified|mdast-[^\\/]+|hast-[^\\/]+|micromark[^\\/]*|unist-[^\\/]+|vfile[^\\/]*)[\\/]/,
|
||||
},
|
||||
{
|
||||
name: 'icons',
|
||||
test: /node_modules[\\/]lucide-react[\\/]/,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user