export interface ConversationSetupConcurrencyParams { loadHistory: () => Promise; persistMessage?: () => Promise; } export interface ConversationSetupConcurrencyResult { history: TMessage[]; persistedMessage: TMessage | null; historyError?: Error; persistenceError?: Error; } const normalizeError = (reason: unknown): Error => { if (reason instanceof Error) { return reason; } if (typeof reason === 'string') { return new Error(reason); } if (typeof reason === 'object' && reason !== null && 'message' in reason) { const message = (reason as { message: unknown }).message; return new Error(String(message)); } try { return new Error(JSON.stringify(reason, null, 2)); } catch (jsonError) { const fallbackMessage = reason !== null && reason !== undefined ? String(reason) : `[Serialization failed: ${jsonError instanceof Error ? jsonError.message : String(jsonError)}]`; return new Error(fallbackMessage); } }; /** * Runs the conversation history load and optional persistence tasks concurrently. * Converts any rejection into an error on the result object instead of throwing. */ export async function runConversationSetupConcurrency({ loadHistory, persistMessage }: ConversationSetupConcurrencyParams): Promise> { const historyPromise = loadHistory(); const persistencePromise = persistMessage ? persistMessage() : Promise.resolve(null); const [historyResult, persistenceResult] = await Promise.allSettled([ historyPromise, persistencePromise ]); let history: TMessage[] = []; let historyError: Error | undefined; if (historyResult.status === 'fulfilled') { history = historyResult.value; } else { historyError = normalizeError(historyResult.reason); } let persistedMessage: TMessage | null = null; let persistenceError: Error | undefined; if (persistenceResult.status === 'fulfilled') { persistedMessage = persistenceResult.value; } else { persistenceError = normalizeError(persistenceResult.reason); } return { history, persistedMessage, historyError, persistenceError }; }