/** * Server-driven session auto-titling. * * REPL-bridge workers already generate titles client-side and PATCH them via * POST-side `updateBridgeSessionTitle` (initReplBridge.ts count-1/count-3 * derivation). Headless print workers (`slz rcs one` detached worker, bridge * children) never do — their `generate_session_title` control handler exists * (print.ts) but nothing in the RCS context invokes it. This service closes * that gap from the server side: * * - `maybeRequestSessionTitle` — after a session's first completed turn * (result/result_success ingest), when the session has no title yet, * publish a `generate_session_title` control_request whose description is * the session's first user message (from the event bus log). * - `handleTitleControlResponse` — match the worker's control_response by * request_id and apply the returned title (unless a title appeared in the * meantime — rename / CLI PATCH win). * * Failure semantics: fired at most once per session per server lifetime. * Both worker backends implement `generate_session_title` (shared dispatcher * in src/bridge/controlRequestHandlers.ts) — an `error` reply means the * worker's own generation failed → we give up silently. No response at all * (worker died) → the pending entry expires lazily. */ import { randomUUID } from 'node:crypto' import { getSession, updateSessionTitle } from './session' import { publishSessionEvent } from './transport' import { getEventBus } from '../transport/event-bus' const TITLE_REQUEST_TIMEOUT_MS = 30_000 const MAX_TITLE_LENGTH = 200 const pendingBySession = new Map< string, { requestId: string; expiresAt: number } >() /** Sessions we already fired a request for (success or not — once only). */ const requestedBySession = new Set() /** Plain text of the first user message in the session event log ('' if none). */ function firstUserMessageText(sessionId: string): string { const events = getEventBus(sessionId).getEventsSince(0) for (const event of events) { if (event.type !== 'user' && event.type !== 'user_message') continue const text = extractUserText(event.payload) if (text) return text } return '' } function extractUserText(payload: unknown): string { if (!payload || typeof payload !== 'object') return '' const p = payload as Record if (typeof p.content === 'string' && p.content) return p.content const msg = p.message if (msg && typeof msg === 'object') { const mc = (msg as Record).content if (typeof mc === 'string') return mc if (Array.isArray(mc)) { const text = mc .filter( (b: unknown) => typeof b === 'object' && b !== null && (b as Record).type === 'text', ) .map( (b: Record) => (b as Record).text || '', ) .join('') if (text) return text } } return '' } /** * Fire the title request for a session if it is still untitled and we haven't * already tried. Callers: the result/result_success ingest paths (WS * ingestBridgeMessage, v2 worker-events POST). */ export function maybeRequestSessionTitle(sessionId: string): void { let session try { session = getSession(sessionId) } catch { return // store unavailable (test fixtures) — skip silently } if (!session) return if (session.title && session.title.trim()) return if (requestedBySession.has(sessionId)) return const description = firstUserMessageText(sessionId).trim() if (!description) return const requestId = `srv-title-${randomUUID()}` requestedBySession.add(sessionId) pendingBySession.set(sessionId, { requestId, expiresAt: Date.now() + TITLE_REQUEST_TIMEOUT_MS, }) publishSessionEvent( sessionId, 'control_request', { type: 'control_request', request_id: requestId, request: { subtype: 'generate_session_title', description, persist: true, }, }, 'outbound', ) } /** * Match a worker control_response against the pending title request. The * response object is the worker's `response` field ({subtype, request_id, * response: {title}}). Applies the title when the session is still untitled. */ export function handleTitleControlResponse( sessionId: string, response: unknown, ): void { if (!response || typeof response !== 'object') return const pending = pendingBySession.get(sessionId) if (!pending) return if (Date.now() > pending.expiresAt) { pendingBySession.delete(sessionId) return } const r = response as Record if (r.request_id !== pending.requestId) return pendingBySession.delete(sessionId) if (r.subtype !== 'success') return // worker error (e.g. REPL bridge) — give up const inner = r.response if (!inner || typeof inner !== 'object') return const title = typeof (inner as Record).title === 'string' ? ((inner as Record).title as string).trim() : '' if (!title || title.length > MAX_TITLE_LENGTH) return // Don't clobber a title set in the meantime (web rename, CLI PATCH). try { const session = getSession(sessionId) if (!session || (session.title && session.title.trim())) return updateSessionTitle(sessionId, title) } catch { // store unavailable — drop } } /** Test/reset hook — clear the once-only guards between isolated cases. */ export function resetSessionTitleState(): void { pendingBySession.clear() requestedBySession.clear() }