mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-19 03:40:50 +00:00
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 <noreply@hapi.run> Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
+20
-1
@@ -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
|
||||
|
||||
@@ -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<string, string> {
|
||||
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<string, string>()
|
||||
for (const row of rows) {
|
||||
if (row.text.trim()) previews.set(row.session_id, row.text)
|
||||
}
|
||||
return previews
|
||||
}
|
||||
|
||||
getOrCreateSession(
|
||||
tag: string,
|
||||
metadata: unknown,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<WebAppEnv> {
|
||||
export function createSessionsRoutes(
|
||||
getSyncEngine: () => SyncEngine | null,
|
||||
store?: Store
|
||||
): Hono<WebAppEnv> {
|
||||
const app = new Hono<WebAppEnv>()
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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 }))
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user