From 8436cc6c072efdf8b44b264519dfd3e70d63fdfc Mon Sep 17 00:00:00 2001 From: wusumac <736139669@qq.com> Date: Sat, 7 Nov 2026 00:22:16 +0800 Subject: [PATCH] feat(hub): expose last user message preview for widgets Add an additive session_last_user_messages table, backfill it for existing sessions on startup, and include lastUserMessagePreview in GET /api/sessions. The iOS widget uses it for the session subtitle without carrying full message bodies. via [HAPI](https://hapi.run) Co-Authored-By: HAPI Co-Authored-By: Claude Code --- hub/src/store/index.ts | 21 ++++++++++- hub/src/store/sessionStore.ts | 16 +++++++++ hub/src/store/sessionUserActivity.ts | 53 ++++++++++++++++++++++++++++ hub/src/web/routes/sessions.ts | 9 ++++- hub/src/web/server.ts | 2 +- shared/src/sessionSummary.ts | 2 ++ 6 files changed, 100 insertions(+), 3 deletions(-) diff --git a/hub/src/store/index.ts b/hub/src/store/index.ts index d1d6ae8e..d7628e63 100644 --- a/hub/src/store/index.ts +++ b/hub/src/store/index.ts @@ -6,7 +6,7 @@ import { MachineStore } from './machineStore' import { MessageStore } from './messageStore' import { addMessage } from './messages' import { clearCachedStatements } from './statementCache' -import { backfillLastUserMessageAt } from './sessionUserActivity' +import { backfillLastUserMessageAt, backfillLastUserMessagePreviews } from './sessionUserActivity' import type { StoredMessage } from './types' import { PushStore } from './pushStore' import { FcmStore } from './fcmStore' @@ -152,6 +152,7 @@ export class Store { this.ensureSessionShareSchema() this.ensureUsageReconciliationSchema() this.ensureLiveActivitySchema() + this.ensureSessionLastUserMessageSchema() if (dbPath !== ':memory:' && !dbPath.startsWith('file::memory:')) { for (const path of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]) { @@ -1402,6 +1403,24 @@ export class Store { `) } + /** + * Additive preview table for the last human prompt. It is created outside + * the migration ladder (older hubs must keep opening the DB) and is + * filled for existing sessions on first start; new messages update it in + * the insertion transaction. + */ + private ensureSessionLastUserMessageSchema(): void { + this.db.exec(` + CREATE TABLE IF NOT EXISTS session_last_user_messages ( + session_id TEXT PRIMARY KEY, + text TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL DEFAULT 0, + FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE + ); + `) + backfillLastUserMessagePreviews(this.db) + } + /** * Additive table for the offline usage reconciliation snapshots. Created * outside the migration ladder on purpose: it is derived data (like diff --git a/hub/src/store/sessionStore.ts b/hub/src/store/sessionStore.ts index f2060e83..8cddb97d 100644 --- a/hub/src/store/sessionStore.ts +++ b/hub/src/store/sessionStore.ts @@ -40,6 +40,22 @@ export class SessionStore { return updateSessionReadState(this.db, id, namespace, request) } + /** Latest human prompt preview per session, for list/widget display. */ + getLastUserMessagePreviews(sessionIds: readonly string[]): Map { + const ids = [...new Set(sessionIds)].filter((id) => id.length > 0) + if (ids.length === 0) return new Map() + const placeholders = ids.map(() => '?').join(', ') + const rows = this.db.prepare(` + SELECT session_id, text FROM session_last_user_messages + WHERE session_id IN (${placeholders}) + `).all(...ids) as Array<{ session_id: string; text: string }> + const previews = new Map() + for (const row of rows) { + if (row.text.trim()) previews.set(row.session_id, row.text) + } + return previews + } + getOrCreateSession( tag: string, metadata: unknown, diff --git a/hub/src/store/sessionUserActivity.ts b/hub/src/store/sessionUserActivity.ts index 5281f405..ce633c71 100644 --- a/hub/src/store/sessionUserActivity.ts +++ b/hub/src/store/sessionUserActivity.ts @@ -1,5 +1,6 @@ import type { Database } from 'bun:sqlite' import { isObject, unwrapRoleWrappedRecordEnvelope } from '@hapi/protocol' +import { extractUserPlainText } from '@hapi/protocol/messages' import { decodeMessageContent } from './contentCodec' import { prepareCached } from './statementCache' @@ -9,6 +10,15 @@ export function isUserInputMessage(content: unknown): boolean { && !(isObject(message.meta) && message.meta.isTranscriptEcho === true) } +const LAST_USER_PREVIEW_MAX_SOURCE_CHARS = 300 + +/** Display-only preview of the human prompt; never used for matching. */ +function previewText(content: unknown): string { + const message = unwrapRoleWrappedRecordEnvelope(content) + if (!message) return '' + return extractUserPlainText(message.content, LAST_USER_PREVIEW_MAX_SOURCE_CHARS)?.trim() ?? '' +} + /** Called in the message insertion transaction, never on delivery ACKs/replays. * Agent envelopes (including Claude tool results with an inner user role) are * not user input. Keep the original timestamp when importing/copying history. */ @@ -18,6 +28,49 @@ export function recordUserMessage(db: Database, sessionId: string, content: unkn UPDATE sessions SET last_user_message_at = ? WHERE id = ? AND (last_user_message_at IS NULL OR last_user_message_at < ?) `).run(createdAt, sessionId, createdAt) + prepareCached(db, ` + INSERT INTO session_last_user_messages (session_id, text, created_at) + VALUES (?, ?, ?) + ON CONFLICT(session_id) DO UPDATE SET + text = excluded.text, + created_at = excluded.created_at + WHERE excluded.created_at >= session_last_user_messages.created_at + `).run(sessionId, previewText(content), createdAt) +} + +/** One-time/on-start fill for sessions that predate the preview table. */ +export function backfillLastUserMessagePreviews(db: Database): void { + const missing = db.prepare(` + SELECT s.id + FROM sessions s + LEFT JOIN session_last_user_messages p ON p.session_id = s.id + WHERE p.session_id IS NULL + `).all() as Array<{ id: string }> + if (missing.length === 0) return + const insert = db.prepare(` + INSERT OR IGNORE INTO session_last_user_messages (session_id, text, created_at) + VALUES (?, ?, ?) + `) + const messages = db.prepare(` + SELECT content, created_at + FROM messages + WHERE session_id = ? + ORDER BY COALESCE(invoked_at, created_at) DESC, seq DESC + LIMIT 30 + `) + for (const { id } of missing) { + let preview = '' + let at = 0 + for (const row of messages.all(id) as Array<{ content: string | Uint8Array; created_at: number }>) { + const content = decodeMessageContent(row.content) + if (isUserInputMessage(content)) { + preview = previewText(content) + at = row.created_at + break + } + } + insert.run(id, preview, at) + } } /** One-time migration. Message content can be plaintext JSON or compressed; diff --git a/hub/src/web/routes/sessions.ts b/hub/src/web/routes/sessions.ts index 719e4e13..7d66442f 100644 --- a/hub/src/web/routes/sessions.ts +++ b/hub/src/web/routes/sessions.ts @@ -34,6 +34,7 @@ import type { SlashCommand } from '@hapi/protocol/apiTypes' import { Hono, type Context } from 'hono' import { bodyLimit } from 'hono/body-limit' import type { SyncEngine, Session } from '../../sync/syncEngine' +import type { Store } from '../../store' import { RpcTargetMissingError } from '../../sync/rpcGateway' import type { WebAppEnv } from '../middleware/auth' import { loadScratchlistAttachmentLimitsFromEnv } from '../../config/scratchlistAttachmentLimits' @@ -84,7 +85,10 @@ function estimateBase64Bytes(base64: string): number { return Math.floor((len * 3) / 4) - padding } -export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Hono { +export function createSessionsRoutes( + getSyncEngine: () => SyncEngine | null, + store?: Store +): Hono { const app = new Hono() app.get('/sessions', (c) => { @@ -116,11 +120,14 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho sessionRecords = sessionRecords.slice(0, limit) } const scheduledStats = engine.getFutureScheduledMessageStats(sessionRecords.map((session) => session.id)) + const previews = store?.sessions.getLastUserMessagePreviews(sessionRecords.map((session) => session.id)) ?? new Map() const sessions = sessionRecords.map((session) => { const summary = toSessionSummary(session) const scheduled = scheduledStats.get(session.id) + const preview = previews.get(session.id) return { ...summary, + ...(preview ? { lastUserMessagePreview: preview } : {}), futureScheduledMessageCount: scheduled?.count ?? 0, nextScheduledAt: scheduled?.nextScheduledAt ?? null } diff --git a/hub/src/web/server.ts b/hub/src/web/server.ts index 4e6cb846..cd97feb2 100644 --- a/hub/src/web/server.ts +++ b/hub/src/web/server.ts @@ -321,7 +321,7 @@ function createWebApp(options: { app.route('/api', createEventsRoutes(options.getSseManager, options.getSyncEngine, options.getVisibilityTracker, { isGuestTokenActive: (shareToken) => options.store.sessionShares.getActiveByToken(shareToken) !== null })) - app.route('/api', createSessionsRoutes(options.getSyncEngine)) + app.route('/api', createSessionsRoutes(options.getSyncEngine, options.store)) app.route('/api', createMessagesRoutes(options.getSyncEngine)) app.route('/api', createPermissionsRoutes(options.getSyncEngine)) app.route('/api', createMachinesRoutes(options.getSyncEngine, options.getTeamService, { dataDir: configuration.dataDir })) diff --git a/shared/src/sessionSummary.ts b/shared/src/sessionSummary.ts index 8adea158..9b3a0b32 100644 --- a/shared/src/sessionSummary.ts +++ b/shared/src/sessionSummary.ts @@ -84,6 +84,8 @@ export type SessionSummary = { createdAt?: number /** Original timestamp of the latest user message; absent before any input. */ lastUserMessageAt?: number + /** Last human prompt text, capped server-side; display-only preview. */ + lastUserMessagePreview?: string pinned?: boolean globalPinned?: boolean metadata: SessionSummaryMetadata | null