| 1 | import type { AppBindings } from "./bridge"; |
| 2 | import { asArray } from "./array"; |
| 3 | import type { QuestionAnswer } from "./types"; |
| 4 | |
| 5 | type ActiveTurnBindings = Pick<AppBindings, "ListTabs" | "SteerInboxItem" | "SteerInboxItemForTurn">; |
| 6 | |
| 7 | export async function resolveActiveTurnId(binding: Pick<AppBindings, "ListTabs">, tabId: string, known?: string): Promise<string | undefined> { |
| 8 | // Preserve the turn the user observed. Refreshing it could steer a successor |
| 9 | // turn instead; the backend owns admission and durable follow-up fallback. |
| 10 | if (known?.trim()) return known.trim(); |
| 11 | const authoritative = asArray(await binding.ListTabs()).find((tab) => tab.id === tabId)?.turnId; |
| 12 | return authoritative; |
| 13 | } |
| 14 | |
| 15 | type AskAnswerBindings = Pick<AppBindings, "ResolvePromptForTab" | "PendingPromptIdentitiesForTab">; |
| 16 | |
| 17 | export async function resolvePromptForTab( |
| 18 | binding: Pick<AppBindings, "ResolvePromptForTab" | "PendingPromptIdentitiesForTab">, |
| 19 | tabId: string, |
| 20 | promptId: string, |
| 21 | kind: string, |
| 22 | answer: Record<string, unknown>, |
| 23 | knownTurnId?: string, |
| 24 | knownRuntimeEpoch?: string, |
| 25 | ): Promise<void> { |
| 26 | const submit = await import("./exactPromptSubmit"); |
| 27 | return submit.resolvePromptForTab(binding, tabId, promptId, kind, answer, knownTurnId, knownRuntimeEpoch); |
| 28 | } |
| 29 | |
| 30 | // Final frontend boundary before optimistic transcript state is created. |
| 31 | export function normalizeTurnSubmit(displayText: string, submitText: string) { |
| 32 | const display = displayText.trim(); |
| 33 | const submit = submitText.trim(); |
| 34 | if (!submit) throw new Error("Message cannot be empty."); |
| 35 | return { display, submit }; |
| 36 | } |
| 37 | |
| 38 | export async function answerPromptForActiveTurn( |
| 39 | binding: AskAnswerBindings, |
| 40 | tabId: string, |
| 41 | promptId: string, |
| 42 | answers: QuestionAnswer[], |
| 43 | knownTurnId?: string, |
| 44 | knownRuntimeEpoch?: string, |
| 45 | ): Promise<void> { |
| 46 | await resolvePromptForTab(binding, tabId, promptId, "ask", { questions: answers }, knownTurnId, knownRuntimeEpoch); |
| 47 | } |
| 48 | |
| 49 | export async function steerInboxItemForActiveTurn(binding: ActiveTurnBindings, tabId: string, itemId: string, knownTurnId?: string) { |
| 50 | if (typeof binding.SteerInboxItemForTurn !== "function") return binding.SteerInboxItem(tabId, itemId); |
| 51 | const turnId = await resolveActiveTurnId(binding, tabId, knownTurnId); |
| 52 | if (!turnId) throw new Error("active turn id is unavailable; refresh and try again"); |
| 53 | return binding.SteerInboxItemForTurn(tabId, turnId, itemId); |
| 54 | } |
| 55 |