Vue kit API
Controller
useCodexSurface(api)
Creates a reactive CodexSurfaceController around a renderer API.
Returned state and actions include:
- readonly
state,lastEvent, andansweredClientRequestIds; onEvent(listener);- authentication actions;
- conversation list/create/select/archive/delete/unarchive actions;
- history, settings, send, review, compact, steer, and interrupt actions;
- interrupted-turn continuation;
- message edit/delete/retry/fork actions;
- goals, approvals, client requests, and queued prompts.
The composable subscribes immediately and disposes its listeners with the current Vue effect scope.
steerMessage(prompt, options?) accepts CodexRendererSendMessageOptions, including opaque-reference attachments, just like sendMessage.
useCodexLiveChat(options)
Experimental bidirectional voice for an existing conversation. The composable owns browser microphone capture, a WebRTC peer, remote audio playback, and the live transcript. Signaling uses the same renderer API as the conversation; audio does not travel through Electron IPC or the web bridge.
import { useCodexLiveChat } from '@codex-app-sdk/vue';
const { status, error, muted, transcript, start, stop, setMuted } = useCodexLiveChat({
surface: api, // Electron preload API or createCodexWebSurfaceClient()
conversationId,
session: { voice: 'marin' }, // optional; defaults to realtime V3
});
// Call from a user gesture; the browser asks for microphone permission.
await start();
setMuted(true);
await stop();statusis a readonly ref:idle,connecting,connected,stopping, orerror.start()resolves after SDP negotiation;connectedmeans WebRTC has actually connected.erroris a readonlystring | nullref. Start/stop failures also reject their promises; catch these in UI event handlers.mutedcontrols the microphone track only. Remote audio keeps playing.transcriptcontains{ id, role, text, complete }rows. V3 canonical item events update rows by identity; legacy transcript events are also supported. These rows are session-local, not a persisted conversation-history API.sessionacceptsStartCodexLiveChatOptionsexceptsdp: optionalversion,voice,model,prompt,includeStartupContext, andflushTranscriptTailOnSessionEnd.
Create one instance per conversation and dispose/remount it when switching conversations. Scope disposal stops capture and playback, closes the peer, unsubscribes, and requests session stop. Repeated start/stop calls are coalesced. A late microphone grant or SDP answer after cancellation cannot reopen the session. Connection failures/timeouts release local media.
Requires browser WebRTC, microphone permission in a secure context (localhost works), and a Codex CLI/account with realtime access. The surface must implement startLiveChat/stopLiveChat; older custom hosts fail with an explicit error. Realtime is experimental and account/CLI availability can differ. The component lab's Live chat scenario demonstrates this alongside a normal conversation pane using the local Codex login.
Controlled pane controller
createCodexConversationPaneController() creates a thin adapter for hosts that own conversation state outside CodexSurface:
type CodexConversationPaneController<Payload = unknown> = {
state: CodexConversationPaneValueSource<CodexConversationPaneState>;
actions: CodexConversationPaneValueSource<CodexConversationPaneActions<Payload>>;
};
const paneState = computed(() => ({
identity: { conversationKey, activeTurnId, turns, messages, busy, disabled, error },
history: { hasOlder, loading, loadingOlder },
thread: { approvals, clientRequests, answeredClientRequestIds, goal, queuedPrompts, turnGitDiff, contextUsage },
composer: { state, attachments, placeholder, suggestedPrompt, leadingMenuItems, menuItems, modelMenuItems, approvalPreset, planMode, selectedModelId, selectedReasoningEffort, selectedServiceTier },
catalogs: { files, models, commands, skills, plugins, mentionGroups, modelCatalogStatus, skillCatalogStatus },
capabilities,
policy: { actionsDisabled, attachEnabled, canDeleteTurn, canEditTurn, canForkTurn, canRetryTurn, followUpsDisabled },
}));
const controller = createCodexConversationPaneController({
state: paneState,
actions: {
submit(prompt, options) { /* host transport */ },
steer(prompt, options) { /* host transport */ },
onMessageCopied(index) { /* optional analytics/UI notification */ },
forkTurn(turnId) { /* fork through this completed turn */ },
updateComposerState(next) { /* persist draft */ },
updateAttachments(next) { /* persist attachments */ },
updateSettings(settings) { /* apply settings */ },
openVisualization({ path, title }) { /* ingest and display the task-owned artifact */ },
},
});CodexConversationPaneValueSource<T> is deliberately structural: provide a plain value, a zero-argument getter, or a ref-like { readonly value: T }. This avoids Vue ComputedRef type conflicts when the host and SDK resolve different copies of Vue. Prefer a stable controller with getters or refs for individual state leaves rather than allocating a new monolithic state object for every keystroke.
When Vue is separately resolved across the host/package boundary, prefer a zero-argument getter such as state: () => paneState. The structural ref shape solves type compatibility, but the SDK must not be expected to own a foreign Vue runtime's dependency graph.
Use it with <CodexConversationPane :controller="controller" />. The complete state groups are identity, history, thread, composer, catalogs, capabilities, and policy. Actions cover submit/steer, composer updates, settings, history, turn actions, approvals, goals, queue operations, and client responses. Every action may return void or Promise<void>; rejected promises are surfaced through the pane error UI.
When the latest controlled identity.turns entry is interrupted, no turn is active, and the composer is empty, the stock composer changes Send to Continue. Activating it dispatches actions.continueInterruptedTurn(); it does not call submit or create an optimistic user row. Surface-bound panes call the equivalent SDK surface operation. A typed prompt or attachment keeps the normal submission path. Cmd+Enter invokes the same resume action while the composer is empty.
CodexConversationPane and standalone CodexComposer accept emptySendPrompt?: string (default ''). When set to non-whitespace text and the composer has no text, attachments, host context, or active command, hovering over the muted Send button enables a normal submission of that prompt. Cmd+Enter does the same unless it is steering an existing queued prompt. This does not replace the interrupted-turn action above or the busy-turn interrupt.
When an idle controlled pane submits a prompt, including a follow-up, the pane renders an optimistic user row immediately. The row survives settlement of the submit promise. For an empty conversation it also survives one identity.conversationKey change while the host creates the provider conversation. Publish authoritative messages with stable IDs through identity.messages; new matching user messages replace the optimistic row without duplication, while older identical prompts remain history. Changing an existing conversation removes its pending row. The pane also keeps its Thinking state active if provider busy briefly clears during that handoff. The host must not insert a second renderer-only optimistic row or preserve a synthetic busy flag.
composer.leadingMenuItems renders host actions after the built-in Approval item and before Goal and Plan modes, in that order. composer.menuItems remains the trailing extension point after those modes. The equivalent granular pane prop is leading-menu-items.
composer.modelMenuItems renders host actions before the built-in model rows (each with its own effort submenu) and Speed group. Clicking a model preserves the current effort when supported, otherwise selecting High, its supported default, or its first effort, in that order. Selections preserve the original host payload and dispatch through actions.menuSelect; the equivalent granular prop is model-menu-items. CodexComposerMenuHeadingItem.actions accepts action items rendered as accessible trailing icon controls in the heading row. At viewport widths up to 720px, the model selector uses a compact brain-icon button with the same model and reasoning menu; wider layouts show the model label. The model list scrolls vertically, capped at 420px or the viewport height minus 80px, whichever is smaller. Host-provided favorites and their divider stay above the scrolling model list. An oversized favorites section scrolls separately and uses at most half the menu's height. Effort submenus remain inside the viewport and outside the scrolling list's clipping area. Scrolling the model list or resizing the window closes open effort submenus; they reopen through hover or ArrowRight. The speed row shows Normal speed or Fast mode beside an information tooltip and a lightning-bolt toggle. Active speed indicators are filled and blue. When the model catalog advertises Ultrafast, the row offers a speed submenu and shows a double bolt for Ultrafast; unavailable tiers are omitted. CodexUltrafastIcon is exported for host controls: <CodexUltrafastIcon :size="16" />. It inherits currentColor and layers an outline bolt behind a filled bolt with a thin separating outline. size sets its width and height in pixels (default 16). CodexComposerMenuSubmenuItem.selectAction optionally supplies the action emitted when its trigger is clicked or activated with Enter/Space. Hover and ArrowRight still open its submenu. Without it, clicking the trigger only toggles the submenu. Menu labels and headings default to regular weight and share the 13.5px --codex-menu-font-size default across root menus, submenus, and suggestions. CodexComposerMenuItemBase.valueIcon adds a trailing icon beside value; set valueIconLabel when the icon carries meaning. valueAppearance: 'badge' renders short values as compact metadata badges. Checkbox items accept a Vue component as accessory for an icon toggle, alongside 'check' and 'switch'.
catalogs.mentionGroups adds app-owned grouped @ suggestions alongside the built-in plugin and file results. actions.mentionSelect(item, group) observes selection. The suggestion-item and mention slots customize host result rows and chips; mention is shared by composer and message rendering and identifies the active surface in its slot props.
onMessageCopied(index) is a post-action notification: the SDK always performs the clipboard write and copied-state feedback first. Omitting this hook does not disable copying.
Message forking is disabled by default. Enable it with state.policy.canForkTurn = true and handle actions.forkTurn(turnId). The compatibility props/events are canForkTurn / forkTurn in TypeScript and :can-fork-turn / @fork-turn in Vue templates. In surface-bound mode, enabling the prop delegates to the SDK surface action, which selects the newly forked conversation.
The adapter does not load conversations, clone messages, wrap reactive sources, or own a backend. Keep the controller object stable and update reactive leaves in place. When supplied, controller state and actions take precedence over legacy pane props/events, and one gesture is dispatched exactly once.
Primary components
| Component | Purpose |
|---|---|
CodexConversationPane | Complete bound or unbound conversation surface |
CodexConversationSidebar | Reusable conversation list with create, select, status, relative time, and confirmed delete actions |
CodexComposer | Full composer with menus, attachments, voice, model/reasoning/Fast mode settings, and send/steer behavior |
CodexMessageList | Conversation message collection |
CodexScrollToBottom | Reusable circular control for returning to the latest messages |
CodexMessage | One message with blocks, status, thinking, and actions |
CodexQuestionRequest | App-server question renderer used by messages and the pane footer |
CodexApprovalPrompt | Command, file-change, and permission approval UI |
CodexWorkbenchLayout | Measured sticky header/content/footer layout |
CodexConversationHistoryLoader | Restored-history loading treatment |
CodexConversationPane exposes focusComposer(). CodexComposer exposes focus(). Pass focus({ preserveSelection: true }) to focus the saved selection instead of moving the caret to the end.
Pending approvals replace the shelf and composer, one at a time in the supplied approvals order, followed by pending confirm_tool client requests, ahead of expanded questions. Native approvals and tool confirmations use one shared Approve tool call card, expandable Details, and left-aligned actions, with only their supported decision scopes. Native Allow emits approve, once; Allow for session emits approve, session. Approvals marked requiresHumanApproval show Human approval required and offer only a fresh one-time decision; an explicit server allowlist can further restrict the available actions. Tool confirmation responses use actions.clientResponse or clientResponse. Their pending tool card is hidden from the transcript, and the resolved history remains. The approval slot receives only the active approval. Resolution still uses actions.resolveApproval, the resolveApproval event, or the attached surface; the host must remove resolved approvals from its state. A rejected resolution leaves the request visible. Approvals and questions preserve draft text, selection, pending command mode and attachments. The composer returns after the last expanded request resolves or is cancelled; its saved selection is focused only if focus was still inside the resolved request. Background resolution does not steal focus.
CodexConversationPane renders both blocking tool questions and asynchronous agent-message questions with the same answer controls. A pending question replaces the shelf and composer while its turn is running. Surface-bound panes read blocking requests from the SDK snapshot; controlled panes pass them through as thread.clientRequests (or the standalone clientRequests prop). The active blocking tool card is hidden in the transcript while the question is in the composer; its answered summary remains in history. When an async question's turn ends, the composer returns with a Pending question button beside its action menu; clicking the label reopens the question, while its leading icon changes to a cancel control on hover. Answering or cancelling removes that button. Sending or steering a prompt also dismisses it, including after the conversation is reloaded. Additional questions remain available in request order. The historical agent message is not deleted. Surface-bound panes send responses through respondToClientRequest() automatically. Controlled panes dispatch actions.clientResponse; keep thread.answeredClientRequestIds current so resolved questions render consistently. The component lab's Approvals & questions scenario covers native/tool approvals, choices or free text, single or multi-step questions, and blocking or async delivery. Complete turn exposes the async pending-question chip. Questions whose options value is null render an immediately focused free-text field. Questions with isOther: true and options show an always-visible, initially one-line field beside Other. Focusing or typing in it selects Other, preserving any other selections only for multiSelect questions. Free-text answers reuse the host's composer speech support through a microphone button. Stop the microphone to review the editable transcript, or press Send/Next while recording to finish transcription and submit or advance. Send becomes available after the first recognized words; a centered, sound-responsive dot replaces the microphone while recording, keeping Send as the single primary action. Question cards omit a header that repeats the question, and an immediately preceding text part that exactly matches a structured question is not rendered twice. Distinct introductory text and short question labels remain visible. Answered questions stack their label above the answer, with wrapping and line breaks preserved. Once their ID is in answeredClientRequestIds (answered or cancelled), they fold into the turn's work details. Submitted answers survive disclosure remounts. Rehydrated surface user messages carry structured metadata.asyncQuestionAnswers, keyed by question ID, so the message list can restore answers alongside their original questions.
While busy, CodexConversationPane listens for two unhandled Escape presses within two seconds and interrupts the active turn. The first press arms the stop-square control; clicking that armed control also interrupts. Set the escapeInterrupt prop to false to disable the document-wide shortcut. When multiple panes are busy, only the pane containing document focus responds.
Controlled composer state
Set placeholder on CodexConversationPane or CodexComposer, or state.composer.placeholder when using a pane controller, for a display-only input hint. It is never inserted into the draft by suggestion acceptance keys.
Use suggestedPrompt (or state.composer.suggestedPrompt) for an actionable follow-up. A non-blank suggestion appears in place of the normal hint while the editor is empty. Unmodified Tab, Right Arrow, Space, or Enter inserts that suggestion into the draft without submitting it. Double-clicking the empty editor also accepts it without sending. Press Enter again to submit. When attachments or host context are present, Enter submits them immediately instead of accepting the suggestion. The caret moves to the end and the insertion supports normal undo. Existing text (including whitespace) is never replaced. Disabled editors, IME composition, modified acceptance shortcuts, and active command modes do not accept a prompt suggestion; suggestion-picker keyboard handling takes precedence. Without a suggestion, the placeholder retains normal editing and Tab navigation. Omitting the placeholder retains the default “Ask Codex…” hint and normal Tab navigation; an empty string hides the hint.
type CodexComposerState = {
text: string;
selectionStart: number;
selectionEnd: number;
activeCommandId?: string | null;
};CodexComposer and CodexConversationPane accept composerState and emit update:composerState continuously for text and selection-only changes. When composerState and modelValue are both supplied, composerState is authoritative. Changing conversationKey restores the incoming state without emitting an intermediate empty value. activeCommandId identifies an active command whose CodexCommandSummary.composerMode supplies the visible chip label and placeholder. Submitting serializes /<slashName-or-name> <text> and clears the active command; removing its chip preserves the current text. The built-in Goal mode can also be toggled in the + menu when capabilities.goals is true, independently of host command IDs or catalog omissions. The composer supplies the built-in /goal entry when needed. It uses the same activeCommandId state as /goal, and is mutually exclusive with Plan mode.
type CodexCommandSummary = {
// existing identity and description fields
composerMode?: {
label?: string;
placeholder?: string;
};
};Controlled attachments and steering
CodexConversationPane accepts attachments and emits attachmentsChange for host-controlled attachment queues. Changing conversationKey restores the incoming attachments value and does not emit an intermediate empty queue.
The composer-attachment-actions slot adds host-owned controls immediately before the SDK remove button for each selected attachment. Its exact scope is:
{
attachments: readonly CodexHostAttachment[];
index: number;
disabled: boolean;
}Derive the current attachment as attachments[index]; the slot intentionally does not pass a second attachment field.
The pane's submit and steering actions remain renderer-safe. Their exact attachment option type is:
submit: [prompt: string, options?: CodexRendererSendMessageOptions]
steer: [prompt: string, options?: CodexRendererSendMessageOptions]Template listeners use @steer="(prompt, options) => ...". Selected attachments are included in options.attachments and intentionally cleared after the steer intent is emitted. Each attachment contains { type, reference } plus optional image detail; renderer actions never receive a filesystem path.
CodexComposer accepts hasAttachments when the host owns the attachment queue. This enables submit with an otherwise empty prompt and emits the canonical '(no user instructions)' prompt for send, queue, or steer. It also accepts queuedPromptId; while busy with the default queue preference and an empty composer, Cmd/Ctrl+Enter emits steerQueuedPrompt for that queued item instead of submitting an empty steer. In CodexConversationPane, queued-prompt Edit loads the text into an empty composer. Enter dispatches updateQueuedPrompt(promptId, prompt), while Cmd/Ctrl+Enter dispatches steerQueuedPrompt(promptId, prompt) while busy. Queued prompt previews hide attached context and show skill, agent, and plugin names without their serialized destinations. Context-only prompts show “Attached content”. Editing and sending retain the original prompt content. The standalone (no user instructions) placeholder is hidden in conversation messages; attachments and steering labels remain visible. Queued previews use “Attached content” for this placeholder.
CodexComposer and CodexConversationPane accept followUpBehavior?: 'queue' | 'steer' (default 'queue'). Controlled panes read the same option from state.composer.followUpBehavior. While busy, Enter and the send button use the selected behavior, and Cmd/Ctrl+Enter uses the other action. The 'steer' preference reverses the queue/edit shortcut mapping above. While idle, both shortcuts use ordinary send. Shift+Enter remains a newline. Send-button labels and tooltip shortcuts reflect the effective action.
With capabilities.steerPrompt: false, either shortcut uses ordinary send instead, preserving attachments and input options; the host can queue that submission while busy. An empty composer does not steer or change an existing queued prompt. During queue editing, either shortcut saves through updateQueuedPrompt without submitting a duplicate. The shelf's Steer button remains visible but disabled.
Host-owned message selection and composer context
CodexMessageList and CodexConversationPane accept messageTextSelection (default false) and emit messageTextSelectionChange with CodexMessageTextSelection | null:
type CodexMessageTextSelection = {
text: string;
messageId?: string;
turnId?: string;
messageIndex: number;
role: 'user' | 'assistant';
anchor: { x: number; y: number; width: number; height: number };
};Only a non-empty selection contained by one rendered message is emitted. The anchor uses viewport coordinates. Scrolling, collapsing the selection, changing the conversation key, or disabling the feature emits null after an active selection.
CodexConversationPane also provides the composer-context slot and hasComposerContext. These are for host-rendered context cards whose semantics remain outside the SDK. hasComposerContext enables Send with no typed prompt; a context-only controlled submit receives an empty string so the host can serialize the cards. CodexComposer exposes the lower-level equivalent as hasExternalContent. Context-only work also supports steering while busy, including the configured follow-up behavior and Cmd/Ctrl+Enter. The host receives an empty string and serializes its context before sending or steering. Neither API modifies renderer attachments.
CodexConversationPane provides composer-shelf-actions for host-owned controls in the shelf above the composer. It renders after the built-in turn diff, queued prompts, and active goal, and receives { disabled: boolean }. The exported CodexComposerShelf exposes the same position as its actions slot with the same scope. Empty slot output does not mount an action row or shelf. Slot content does not alter SDK conversation state.
Use composer-drawers for host-owned items that belong beside queued prompts. Its scope is { disabled: boolean }. Render CodexComposerDrawer containing CodexComposerDrawerRow components; these are the same components used by queued prompts, including borders, spacing, separators, and typography. A row exposes its text through the default slot, optional author or icon through leading, and host-owned buttons through actions. Place a heavier author name in leading while inheriting the row's font size. The lower-level CodexComposerShelf exposes this position through its drawers slot, after turn diff information and before queued prompts and the active goal. Empty output does not create a shelf. Hosts own item state and actions; custom drawers do not enter the SDK prompt queue.
Leaf components
Composer and menus
CodexComposerMenu, CodexComposerMenuList, CodexComposerSendButton, CodexComposerActionMenu, CodexComposerActiveModes, CodexComposerAtMentionMenu, CodexComposerFileMentionMenu, CodexComposerPluginMenu, CodexComposerSkillMenu, CodexComposerSlashMenu, CodexComposerVoiceButton, CodexComposerVoiceField, CodexMentionChip, CodexRichTextEditor, CodexContextUsageIndicator, and CodexModelReasoningSelector.
CodexComposerMenu and CodexComposerMenuList accept pinnedItemCount (default 0). The first N root entries stay above a separately scrolling remainder, with keyboard navigation following the original item order. Pinned menus use the model selector's viewport-bounded height; a long pinned section can scroll within half that height. The model selector uses this for host menuItems and their divider.
CodexRichTextEditor exposes CodexRichTextEditorExpose for custom composer layouts that need its focus and selection controls. CodexComposerAtMentionMenu renders the combined plugin, file, and host-defined mention groups used by the stock composer.
useCodexComposerVoice(options) exposes the same recording and transcription controller used by CodexComposer for custom layouts. Options are isDisabled, isSending, onTranscript, optional transcribeAudio (batch), and optional streamingTranscription: CodexStreamingTranscription. Without overrides it uses the scoped host's optional streamingTranscription capability, falling back to batch transcription when that capability is absent. A custom transcribeAudio opts out of native streaming unless a streaming override is also supplied. The controller provides buttonDisabled, buttonLabel, buttonTitle, error, isStarting, isRecording, isTranscribing, isLive, transcript, audioLevel, stop(), cancel(), toggle(), and dispose(). transcript is a ref containing { finalText, partialText }: each event replaces this snapshot, rather than appending unstable words. onTranscript runs only once, after finalization, so the host can preserve its draft and caret until then. stop() resolves to true after nonempty final text is delivered, or false on failure, cancellation, empty speech, or a duplicate stop. cancel() and scope disposal discard unfinished text and release capture/listeners.
audioLevel is a normalized (0–1) local microphone energy ref, updated independently of recognition. It resets when capture stops or is cancelled; batch-only capture reports zero.
CodexComposerVoiceField accepts recording, optional starting, transcript, audioLevel, and before/after draft fragments. It shows quieter provisional text and a muted listening dot that grows and brightens with audioLevel, remaining still in silence, without changing layout or adding recording controls. CodexComposerVoiceButton displays a primary-colored circle with a white microphone while recording; connect its toggle event to the controller. Its recording slot replaces the microphone with custom feedback; hover reveals a crossed-out microphone as a stop affordance. In the stock composer, Escape cancels dictation and restores the draft.
Messages and media
CodexMessageBlock, CodexUserText, CodexAttachmentBlock, CodexMediaBlock, CodexImageLightbox, CodexMermaidBlock, CodexVisualizationBlock, CodexCompactionMessage, CodexMessageActions, CodexMessageEditor, CodexWorkGroup, and CodexFoldTransition.
CodexMessageActions.iconsVisible defaults to true. The stock transcript mounts action glyphs on hover, keyboard focus, touch, and the latest completed assistant message while retaining accessible buttons and stable layout for other messages.
The message block union includes an interactive HTML variant:
{ type: 'html'; source: string; title?: string; complete: boolean; phase?: MessagePhase }Assistant <artifact title="…">…</artifact> blocks and document-sized html fences produce this block. complete becomes true at the closing delimiter or when the message stops streaming (including an interrupted partial document). The stock renderer uses a persistent, opaque-origin sandbox: appended source does not reload it or re-execute prior scripts. Source changes that are not append-only reset the preview. The existing generic block slot can override this rendering, including replacing previews with inert source in a host that does not permit generated JavaScript. No new pane prop or backend API is needed. The sandbox permits HTTPS script libraries while continuing to block host access, HTTP scripts, and API fetches; CDN requests require network access. See interactive HTML previews for syntax, controls, and sandbox restrictions.
Inline image previews are capped at 360 CSS pixels or half the viewport height, whichever is smaller. Tall screenshots remain fully visible without cropping. Image attachments and media open CodexImageLightbox by default. Override message image clicks with either CodexConversationPane's openImage prop or the controlled pane's actions.openImage(image, context). The handler owns the click when it returns void or true; return false to use the stock lightbox. Within a conversation pane or message list, the stock viewer navigates assistant images from the loaded history with side arrows or Left/Right keys. It loads the selected original on demand and stops at either end. User attachments open individually. Gallery navigation does not fetch older history or Working details. The exported renderer-safe types are CodexMessageImage, CodexMessageImageContext, CodexMessageImageOpenIntent, and CodexMessageImageOpenHandler.
Visualization annotations use a separate host contract because their task-owned HTML paths are not conversation files. Controlled panes receive actions.openVisualization({ path, title }); non-controller panes can use the openVisualization prop or event. The exported payload type is CodexConversationVisualization. The SDK does not execute or embed the HTML, and it never degrades visualization clicks to openLink.
CodexMediaBlock owns its generated-image footer actions: fullscreen delegates to the same overridable image-opening contract, copy writes the rendered image blob to the browser clipboard and shows a brief check confirmation, and download uses browser download behavior without entering the conversation-link routing path.
CodexMessageImageContext.intent distinguishes the semantic action: open comes from clicking the inline image, while fullscreen comes from the explicit maximize control. Pane handlers also receive the absolute message index and adapted message; direct leaf-component handlers receive the intent without message metadata. The stock SDK lightbox remains the fallback for either intent.
Assistant Markdown rendered by CodexMessageBlock adds a copy control to each fenced code block and shows a check confirmation for two seconds after copying.
Tools and conversation state
CodexToolCall, CodexToolCallTitle, CodexToolIcon, CodexToolGroup, CodexToolConfirmation, CodexToolUserInputRequest, CodexGoal, CodexQueuedPrompt, CodexQueuedPrompts, CodexFollowUps, CodexTurnGitInfo, and CodexAnimatedDiffStat.
CodexToolIcon accepts a toolCall and optional resolved presentation. It uses the same icon chain as stock tool rows: a host icon, a built-in Codex action icon, a stable kind fallback, then the generic tool icon. Only an explicit presentation.icon value of null suppresses the icon. Image generation uses the photo icon and human-readable activity titles by default.
Generic tool titles strip an optional mcp__ prefix and the server namespace through the first __ or . separator, then replace underscores and hyphens with spaces and lowercase the remaining name. They use the existing chat.tool.fallback.running / .completed translations with that readable name, for example Running add comment to pending review / Ran add comment to pending review. Calls with kind: 'command' preserve their literal command text. Explicit host titles take precedence.
CodexScrollToBottom is also rendered by CodexMessageList whenever the transcript is scrolled away from the bottom. It accepts an optional accessible label and emits click; use it directly when composing a custom message layout.
Streaming replies update unfinished Markdown without replacing completed paragraphs and code blocks, preserving selection and code-copy controls as text arrives. Custom text slots still receive the full text block and own its rendering.
Host-rendered fenced blocks
Provide codexCustomBlocksKey (the global symbol Symbol.for('codex.custom-blocks')) with a language-to-Vue-component map:
import { codexCustomBlocksKey } from '@codex-app-sdk/vue'
app.provide(codexCustomBlocksKey, { widget: MyWidget })Assistant Markdown fences named widget render MyWidget with source, language and complete props. While streaming, an unfinished registered fence passes complete: false so the host can show a placeholder instead of source. After the closing fence, complete becomes true. Register lowercase language names. User messages, unfinished fences in stopped messages and unregistered languages retain their normal code rendering. Built-in HTML and Mermaid blocks are reserved. Custom blocks over 100,000 characters or components that throw show their source instead. Surrounding Markdown and assistant work grouping are preserved. The host owns format validation, lazy loading, resource limits, accessible output and interaction; the SDK has no diagram-engine dependency or knowledge of host panes. Registering a renderer does not change provider payloads or persisted conversation data.
Message rendering is incremental by default: CodexMessageList and CodexConversationPane initially mount only the newest batch. Set renderStrategy="eager" when a host needs eager rendering of every supplied message:
<CodexConversationPane
render-strategy="lazy"
:initial-message-batch-size="50"
:message-batch-size="25"
:conversation-key="conversationId"
:surface="surface"
/>initialMessageBatchSize defaults to 50, messageBatchSize defaults to 25, and renderStrategy defaults to lazy. Lazy mode initially mounts the newest batch, prepends one batch when the user scrolls within one viewport of the top, preserves the visible scroll anchor, and keeps bottom-follow behavior for new messages. The current tail, including an active streaming assistant row, is always included; stale historical streaming markers do not expand the window. An unseen conversationKey opens at the newest batch; returning to a previously viewed key restores its mounted window and scroll position. The host still supplies the complete message array; no pagination or backend contract is required.
lazyMessages remains as a deprecated compatibility alias. Use renderStrategy="eager|lazy" in new code.
Configure loadingStrategy on CodexSurfaceOptions to select the data policy; configure renderStrategy on CodexConversationPane to select the DOM policy when the host controls the message array. These are independent, so all four combinations are valid:
lazy(the default) loads the newest page and prefetches older pages when the user scrolls within one viewport of the top;eagerhydrates all pages progressively;renderStrategy="lazy"mounts only the visible message batch;renderStrategy="eager"mounts every supplied message.
Set historyItemsView: 'summary' on the Node surface for summary-first history. The pane shows Done · duration · View details before each completed answer (duration is omitted when unavailable). Selecting View details requests that turn's Working details. A small spinner replaces the chevron while the group stays folded; it expands when content is ready, offers retry on failure, and caches successful reads. Completed historical turns keep their status and collapse control even without a final answer. After loading, a turn with no Working content shows a plain status with no details action. Surface-bound panes wire this automatically. Controlled hosts forward turns through identity state and implement controller.actions.loadTurnHistory(turnId); event-driven hosts handle loadTurnHistory(turnId). Active turns retain full streaming work.
The pane exposes hasOlderHistory and loadingOlderHistory for hosts that own the page request, and emits loadOlderHistory one viewport before the top of the list needs another page. Returning to the bottom collapses lazy rendering back to the newest batch without discarding the loaded messages.
Both components also accept an optional typed transformMessage callback:
type CodexMessageTransform = (
message: Message | SurfaceMessage,
index: number,
) => Message | SurfaceMessage;The callback runs only after lazy slicing and only for mounted messages. It is invoked for every message when renderStrategy is eager. The index is always the original absolute rendering index, and the original message id remains the rendering key. The default behavior is identity.
CodexChatMessage preserves the optional turnId from SurfaceMessage. CodexMessageList projects adjacent messages with that identity into one logical turn. Steering messages remain in chronological order, while all assistant commentary, reasoning-aware tool groups, and generated media share one logical turn. Commentary and tool groups share the Working / Done disclosure. Media parts marked phase: 'commentary', including tool screenshots and image observations recovered from history, belong to the same disclosure. Final-answer and generated media remain visible outside that fold in their chronological position. The latest reasoning summary labels only the currently active tool group; normal assistant text removes that transient label. A transform that returns a CodexChatMessage should retain turnId for that behavior. A tool-only active segment is treated as structured work before the first phased text arrives; unphased messages containing ordinary text retain the flat rendering path. New commentary, reasoning, or tool activity in the same turn supersedes an earlier final answer: its summary is hidden and the disclosure returns to Working until the next final answer. A steer submission alone does not trigger this transition. The original conversation messages remain unchanged.
Pass activeTurnId and turns when controlling the list, or put them in controller.state.identity. Surface-bound panes wire both automatically. Work labels use turns[].startedAt for the live elapsed timer. Surface-bound live turns use the SDK-observed start when Codex omits its start timestamp. Final labels prefer durationMs, falling back to the difference between valid startedAt and completedAt timestamps. Missing, invalid, negative, or subsecond durations leave the label untimed. activeTurnId is authoritative for completed message groups; busy remains the broader conversation-level pending state used by the composer and Thinking placeholder. A real streaming assistant segment reopens its own turn even when the provider has not restored activeTurnId yet, including after an asynchronous question answer resumes a previously completed turn. An active Working disclosure is always expanded and cannot be collapsed.
When a provider-confirmed completed turn has a user message but no assistant message, the list displays Empty response as an acknowledgment. Idle state alone does not create that acknowledgment. Provider messages and turn records remain unchanged, and filtered-out assistant tools do not count as an empty turn.
Pass busy to CodexMessageList (the conversation pane wires this from its surface state) to keep a Thinking shimmer visible while a turn is accepted but the app-server has not yet materialized its first assistant row. When the latest visible message has a turnId, that pending state remains part of the same logical turn so its Working disclosure and steers do not fold during the gap. Lazy batch sizes are approximate: each boundary expands backward to keep the complete turn mounted instead of rendering a partial turn.
Turn mutations are offered on every terminal turn. Delete, Edit, and Retry are available for completed, failed, and interrupted turns; Fork requires successful completion. Completed work-only replies expose their action bar even without answer text; work preceding a final answer keeps its action bar on that answer. The active turn never exposes mutation controls. Historical actions use Codex history-revert semantics for paginated conversations: Delete removes the selected turn and every later turn, while Edit and Retry truncate that suffix before resubmitting the edited or original prompt. Copy and Quote remain message-level actions. While an asynchronous Delete action is pending, the stock action bar keeps the turn visible, replaces Delete with a progress spinner, and disables its other actions until the operation settles.
CodexMessage renders Empty response in muted italic text when a completed assistant message contains no renderable content. Empty streaming messages keep the normal Thinking presentation instead.
File-operation targets in read, edit, and create tool titles are interactive targets when the SDK can resolve an absolute path from the tool input. Clicking a target emits the existing CodexConversationPane openLink event and does not toggle tool details. File links emitted from tool titles include the canonical filepath and the operation action (read, edit, or create) alongside the normal file-link path for compatibility:
openLink: [link: {
href: string;
kind: 'file';
path: string;
filepath?: string;
action?: 'read' | 'edit' | 'create';
turnId?: string;
messageId?: string;
itemId?: string;
diffContent?: { sessionId: string; contentId: string; byteLength: number; changeKind: 'add' | 'update' | 'delete' };
line?: number;
column?: number;
}]When a host uses ConversationContentTransport, nonempty file diffs carry diffContent. Fetch the exact patch through the host's authorized content reader only when that file is selected. Expanding a shortened file row exposes its remaining inline file links. Deleted files use the edit link action to open their historical diff.
Truncated tool rows reveal a small chevron on hover or keyboard focus. Click the text or chevron to expand the full row in place, preserving line breaks; click again to collapse it. Touch devices keep the chevron visible. Hovering a tool icon replaces it with Copy; activating it copies the full row text and briefly shows a checkmark. Shell tools copy their structured command without the status prefix. Visual wrapping never adds newlines to copied text. Tool rows disable text selection; use their Copy action instead. File links remain inline, with no separate Files panel.
Raw tool-call input and output are inaccessible by default: stock tool rows do not place those values in the DOM. Enable access for one component tree with the show-tool-details prop on CodexConversationPane, CodexMessageList, CodexMessage, CodexToolGroup, or CodexToolCall. Applications can set the policy once for a Vue subtree:
import { provideCodexToolCallDetails } from '@codex-app-sdk/vue';
provideCodexToolCallDetails(true);An explicit component prop takes precedence over the provided value.
Configuration contracts
CodexCapabilitiesCodexConversationPresentationand its composer/message/shelf subtypesCodexComposerMentionGroup,CodexComposerMentionItem, andCodexComposerVisibleMentionGroupCodexComposerMenuItemdiscriminated union- model, reasoning, service-tier/Fast mode, skill, plugin, command, context-usage, goal, diff, and client-request view types
CodexChatMessage, block, attachment, media, tool, and status types
Utilities
Theme
applyCodexThemeCodexThemeModeCodexThemeOptions
Native capabilities
getCodexNativeRendererApipickCodexAttachmentsingestCodexAttachments
Rendering and parsing
renderMarkdownrenderCodeBlockandlanguageForFilePathparseAuthoredUserTextfor structured authored content;parseCodexUserTextandhumanizeMentionNamefor explicit provider/legacy markup parsing- conversation-link parsing helpers
- surface-to-chat message adapters
CodexUserText renders saved mentions from its promptContent prop. Plain text stays literal even when a matching catalog exists. Without saved parts, canonical skill/plugin Markdown links render as pills with catalog names or fallback labels. Custom mention:// links retain their label, group, ID, and value without a catalog; the existing mention slot renders them just like authored custom parts. Message pills share the composer's pill styling and default icons. Bare HTTP and HTTPS URLs in user messages render as clickable links and follow the conversation pane's host link handling. Inline code and ordinary Markdown links stay literal. The user-text parsers return link tokens with text and href for these URLs; surrounding punctuation is excluded from the destination. parseCodexUserText accepts a fifth argument of false to disable bare-trigger lookup. CodexComposer creates a mention only when the user accepts a suggestion, and emits the visible text plus options.content for submissions containing mentions. CodexComposerState.content preserves these parts when restoring a draft.
CodexPromptPart and projection/range helpers are exported by SDK core, so native clients can preserve and display the same content without Vue or a skill catalog. Surface-message adapters read metadata.promptContent; direct renderer Message objects use promptContent. Saved labels stay unchanged when catalogs are refreshed. Optional catalogs can supply artwork and descriptions.
Plugin, file, and host-defined mention groups share the @ menu. Their selected identity is stored independently from the visible label. Custom rendering slots receive the saved label and identity; catalogs may enrich the item payload. CodexComposerMentionItem, CodexComposerVisibleMentionGroup, filterComposerMentionGroups, and findComposerMention support host composers.
When the composer is empty, Up recalls submitted prompt text and Down moves forward, returning to an empty prompt after the newest entry. Serialized skill, plugin, and custom mention links return as editable pills, including when their catalog is unavailable. Bare typed references remain literal. Editing a recalled prompt exits history navigation.
Skill suggestions rank IDs, names, display names, and insertion aliases together: exact matches first, then whole words, word prefixes, and substrings. Description-only matches come last; equally scored matches retain catalog order. For example, $cp ranks Commit Push (cp) above sites:sites-mcp.
Customization
provideCodexChatTranslateanduseCodexChatTranslateprovideCodexToolCallDetailsanduseCodexToolCallDetailsprovideCodexToolPresentationanduseCodexToolPresentationCodexToolPresentation,CodexToolPresentationContext, andCodexToolPresentationResolverregisterCodexToolTitlePresenter- capability/presentation resolvers
- composer command, plugin, skill, queue, and mention helpers
CodexMessageToolCall preserves optional kind and metadata fields from the surface tool part. MCP metadata includes server, tool, pluginId, and MCP app resource identity when supplied by app-server.
CodexConversationPane and CodexMessageList accept toolVisibility?: CodexToolVisibility, where CodexToolVisibility = (toolCall: CodexMessageToolCall) => boolean. Return false to omit a tool from rendered messages and work counts; the default is visible. This does not alter snapshots, events, or tool execution.
See the Vue guide, conversation pane integration, composer guide, history guide, message/tool guide, Vue provider guide, and presentation guide.
Bounded image previews
provideCodexHostCapabilities(capabilities, { imagePreviewBudgetBytes }) optionally bounds retained media and attachment previews for that Vue subtree. The budget counts cached original bytes, thumbnail bytes, and decoded preview pixels (four bytes per pixel). Two preview loads run at a time. Data URLs become blob URLs; no base64 strings are retained by the pool. In eager mode, the last consumer releasing an image revokes its owned URLs. Disposing the provider releases the whole pool. Remote image URLs use the browser's own HTTP cache.
This bounds retained preview resources, not total process RSS: provider snapshots, in-flight reads/decodes, browser caching, and a host's separate fullscreen viewer have their own lifetimes. Originals larger than the budget remain available through the host's image-open action. Without the option, hosts retain the existing preview behavior.
Add viewportImageLoading: true alongside the budget to fetch previews only when visible or within 400 CSS pixels of their scroll container. Observers are shared per container; visible requests take priority over prefetches. Inline previews are sized for their rendered width and display density, capped at 1024 pixels wide; height preserves the source aspect ratio. Open, copy and download actions use original bytes. GIF previews retain their animation by displaying the original GIF instead of a still thumbnail; their full pixel dimensions count against the preview budget. Leaving the prefetch region releases decoded previews while retaining compressed originals and thumbnails within the same budget. Returning reuses the cached thumbnail immediately without another host request. Viewport mode also retains up to 128 recently used immutable conversation-image: previews with pool-owned original bytes after their last consumer unmounts, so switching conversations can reuse ready previews. Mutable file references, direct data URLs and borrowed URLs keep last-consumer release behavior. Idle entries remain inside the same byte budget and are evicted before active previews, in least-recently-used order. The full source reference identifies each entry; hosts must dispose the provider when its authorized owner changes, including logout. Least-recently-used originals are evicted when the total cache needs room, before visible images. Optional image width and height reserve the intrinsic aspect ratio before loading. Small conversation images display at their natural size; larger images shrink to fit the conversation and viewport height limits. Decoded dimensions survive cache eviction for images without metadata. Failed previews remain explicitly retryable; eviction does not cause a fetch loop.
Preview blob URLs are borrowed resources: a host that opens an independent image tab must retain its own Blob/object URL before the preview is released, and revoke its own URL when the tab closes. The preview budget does not own that viewer.
Replace the composer
The composer-replacement slot replaces the pane footer's standard composer, shelf, approvals and question controls while keeping the transcript visible. Declare the slot conditionally to restore the standard composer when it is no longer needed. Hosts presenting a stopped or read-only conversation should also disable submission, follow-ups and mutating message actions in their controller; copying and opening existing content can remain available.