| 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 | // The cached id can outlive the controller turn during startup, recovery, |
| 9 | // or a runtime rebuild. Always refresh from the tab owner before crossing |
| 10 | // the exact-turn answer/steer boundary; the optional value is only a hint |
| 11 | // for callers that have not received local state yet. |
| 12 | const authoritative = asArray(await binding.ListTabs()).find((tab) => tab.id === tabId)?.turnId; |
| 13 | return authoritative; |
| 14 | } |
| 15 | |
| 16 | type AskAnswerBindings = Pick<AppBindings, "ResolvePromptForTab" | "PendingPromptIdentitiesForTab">; |
| 17 | |
| 18 | export async function resolvePromptForTab( |
| 19 | binding: Pick<AppBindings, "ResolvePromptForTab" | "PendingPromptIdentitiesForTab">, |
| 20 | tabId: string, |
| 21 | promptId: string, |
| 22 | kind: string, |
| 23 | answer: Record<string, unknown>, |
| 24 | knownTurnId?: string, |
| 25 | knownRuntimeEpoch?: string, |
| 26 | ): Promise<void> { |
| 27 | const submit = await import("./exactPromptSubmit"); |
| 28 | return submit.resolvePromptForTab(binding, tabId, promptId, kind, answer, knownTurnId, knownRuntimeEpoch); |
| 29 | } |
| 30 | |
| 31 | // Final frontend boundary before optimistic transcript state is created. |
| 32 | export function normalizeTurnSubmit(displayText: string, submitText: string) { |
| 33 | const display = displayText.trim(); |
| 34 | const submit = submitText.trim(); |
| 35 | if (!submit) throw new Error("Message cannot be empty."); |
| 36 | return { display, submit }; |
| 37 | } |
| 38 | |
| 39 | export async function answerPromptForActiveTurn( |
| 40 | binding: AskAnswerBindings, |
| 41 | tabId: string, |
| 42 | promptId: string, |
| 43 | answers: QuestionAnswer[], |
| 44 | knownTurnId?: string, |
| 45 | knownRuntimeEpoch?: string, |
| 46 | ): Promise<void> { |
| 47 | await resolvePromptForTab(binding, tabId, promptId, "ask", { questions: answers }, knownTurnId, knownRuntimeEpoch); |
| 48 | } |
| 49 | |
| 50 | export async function steerInboxItemForActiveTurn(binding: ActiveTurnBindings, tabId: string, itemId: string, knownTurnId?: string) { |
| 51 | if (typeof binding.SteerInboxItemForTurn !== "function") return binding.SteerInboxItem(tabId, itemId); |
| 52 | const turnId = await resolveActiveTurnId(binding, tabId, knownTurnId); |
| 53 | if (!turnId) throw new Error("active turn id is unavailable; refresh and try again"); |
| 54 | return binding.SteerInboxItemForTurn(tabId, turnId, itemId); |
| 55 | } |
| 56 |