Keep unsent hand-off messages after restarting Orca (#34933)

* fix: keep unsent hand-off drafts through restart

* test: prune obsolete structured draft clock baseline

* test: give shared launch mocks a portable public type

* fix(chat): preserve published drafts and initial caret

* Preserve published drafts across launch cancellation and fallback

* Keep unsent conversation drafts through launch cancellation

* Consolidate draft retention test imports

* Preserve native draft caret ownership across adoption and close

* Document intentional elapsed-time regression waits

* Document measured proxy property forwarding

* Set workspace identity in draft retirement fixture

* test: complete structured launch guard store fixture

* test: expect ordinary draft retention after launch cancellation

* test: use real tab owners for structured launch fixtures

* test: construct complete launch scenario settings

* Update provisional selection lifetime regression

* Narrow initialized launch fixture settings reads
This commit is contained in:
Brennan Benson
2026-10-30 11:28:40 -07:00
committed by GitHub
parent a1f7f97671
commit cc69f3dda2
41 changed files with 4017 additions and 1213 deletions
-1
View File
@@ -1101,7 +1101,6 @@
1 test-no-wall-clock:src/renderer/src/components/native-chat/NativeChatMessageList.unsent-message.test.tsx
5 test-no-wall-clock:src/renderer/src/components/native-chat/NativeChatResolvedView.turn-status.test.tsx
1 test-no-wall-clock:src/renderer/src/components/native-chat/NativeChatStructuredSession.stopping.test.tsx
2 test-no-wall-clock:src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx
2 test-no-wall-clock:src/renderer/src/components/native-chat/NativeChatStructuredSessionStatus.test.tsx
8 test-no-wall-clock:src/renderer/src/components/native-chat/structured-child-records-switch.test.tsx
2 test-no-wall-clock:src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx
@@ -36,6 +36,7 @@ export type NativeChatComposerFieldProps = {
editSession?: { cancel: () => void }
/** Own draft persistence and native-drop routing by this pane so drops cannot land in another composer. */
draftScopeKey: string
positionTarget?: string
textareaRef: RefObject<NativeChatComposerInput | null>
draft: string
disabled: boolean
@@ -123,6 +124,7 @@ function imeComposedSegment(base: string, settled: string): string {
export function NativeChatComposerField({
editSession,
draftScopeKey,
positionTarget,
textareaRef,
draft,
disabled,
@@ -318,6 +320,7 @@ export function NativeChatComposerField({
<NativeChatPromptEditor
key={draftScopeKey}
scopeKey={draftScopeKey}
positionTarget={positionTarget}
imageRow={imageRow}
inputRef={textareaRef}
initialValue={draft}
@@ -19,10 +19,7 @@ import { useNativeChatSendLifecycle } from './use-native-chat-send-lifecycle'
import { useNativeChatSessionOptions } from './use-native-chat-session-options'
import { useNativeChatDictation } from './use-native-chat-dictation'
import { useNativeChatSessionOptionCommand } from './use-native-chat-session-option-command'
import type {
NativeChatComposerHandle,
NativeChatComposerProps
} from './native-chat-composer-types'
import type * as C from './native-chat-composer-types'
import { useNativeChatPtyComposerSend } from './use-native-chat-pty-composer-send'
import { useNativeChatStructuredComposerSend } from './use-native-chat-structured-composer-send'
import { useImeEnterGestureOwnership } from '@/lib/ime-composition-keyboard-event'
@@ -31,8 +28,10 @@ import { useNativeChatComposerSubmit } from './use-native-chat-composer-submit'
import { useNativeChatComposerCommandPicker } from './use-native-chat-composer-command-picker'
import { useNotificationCardComposerClearance } from '@/lib/notification-card-composer-clearance'
type ComposerHandle = C.NativeChatComposerHandle
/** Send through the chat’s structured transport or verified PTY route, with agent-aware autocomplete and image handling. */
export const NativeChatComposerPane = forwardRef<NativeChatComposerHandle, NativeChatComposerProps>(
export const NativeChatComposerPane = forwardRef<ComposerHandle, C.NativeChatComposerProps>(
function NativeChatComposerPane(
{
terminalTabId,
@@ -191,7 +190,7 @@ export const NativeChatComposerPane = forwardRef<NativeChatComposerHandle, Nativ
setNotice
})
const localHandle = useRef<NativeChatComposerHandle>(null)
const localHandle = useRef<C.NativeChatComposerHandle>(null)
const root = useRef<HTMLDivElement>(null)
useNotificationCardComposerClearance(root, editSession === undefined)
const handlePasteEvent = useNativeChatComposerHandle(localHandle, {
@@ -365,6 +364,7 @@ export const NativeChatComposerPane = forwardRef<NativeChatComposerHandle, Nativ
<div ref={root} data-native-chat-composer-scope={draftScopeKey}>
<NativeChatComposerField
draftScopeKey={draftScopeKey}
positionTarget={editSession ? undefined : terminalTabId}
textareaRef={textareaRef}
draft={draft}
disabled={disabled}
@@ -1,8 +1,9 @@
import { nativeChatDraftPositions } from './native-chat-composer-draft-memory'
import { createNativeChatPastedTextHistory } from './native-chat-pasted-text-history'
import { resolveNativeChatPastedText } from './native-chat-composer-pasted-text-references'
import { NativeChatPastedTextScopeProvider } from './native-chat-pasted-text-state'
import {
readNativeChatDraftDocument,
readNativeChatDraftSnapshot,
writeNativeChatDraftDocument
} from './native-chat-draft-cache'
import {
@@ -11,15 +12,8 @@ import {
} from './native-chat-composer-draft-store'
import { closeHistory } from '@tiptap/pm/history'
import { Slice } from '@tiptap/pm/model'
import {
memo,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
type HTMLAttributes,
type RefObject
} from 'react'
import { TextSelection } from '@tiptap/pm/state'
import { memo, useCallback, useImperativeHandle, useLayoutEffect, useMemo, useRef } from 'react'
import { shallow } from 'zustand/shallow'
import { EditorContent, useEditor } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
@@ -35,23 +29,14 @@ import {
promptTextOffset,
promptTextPosition
} from './native-chat-prompt-document'
import type { NativeChatComposerInput } from './native-chat-composer-input'
import type {
NativeChatComposerInput,
NativeChatPromptEditorProps
} from './native-chat-composer-input'
import { NativeChatImageRowProvider } from './NativeChatImageReferencePill'
import { mountedEditorView } from './native-chat-mounted-editor-view'
import { NativeChatUnkernedRunDecorations } from './native-chat-unkerned-run-decorations'
type Props = Omit<HTMLAttributes<HTMLDivElement>, 'onChange' | 'onSelect'> & {
scopeKey?: string
/** The composer's thumbnail ids, in order, which number its image chips. */
imageRow?: readonly string[]
inputRef: RefObject<NativeChatComposerInput | null>
initialValue: string
disabled: boolean
placeholder: string
onChange: (input: NativeChatComposerInput) => void
onSelect: (input: NativeChatComposerInput) => void
}
const NO_IMAGES: readonly string[] = []
// `initialValue` only seeds the editor at mount; keep the other props referentially stable or this memo stops helping.
@@ -63,6 +48,7 @@ export const NativeChatPromptEditor = memo(
function NativePromptEditor({
scopeKey,
positionTarget,
imageRow = NO_IMAGES,
inputRef,
initialValue,
@@ -72,8 +58,18 @@ function NativePromptEditor({
onSelect,
className,
...events
}: Props): React.JSX.Element {
}: NativeChatPromptEditorProps): React.JSX.Element {
const historyPaths = useMemo(() => createNativeChatPastedTextHistory(scopeKey ?? ''), [scopeKey])
const adopted = useRef(readNativeChatDraftSnapshot(scopeKey, initialValue))
const userOwned = useRef(false)
const appliedPosition = useRef<unknown>(undefined)
const claimSelection = () => {
userOwned.current = true
const position = adopted.current && nativeChatDraftPositions.get(adopted.current)
if (position?.at === 'end' && position.target === positionTarget) {
position.pending = false
}
}
const placeholderRef = useRef(placeholder)
placeholderRef.current = placeholder
const editor = useEditor(
@@ -107,9 +103,7 @@ function NativePromptEditor({
showOnlyWhenEditable: false
})
],
content:
(scopeKey && readNativeChatDraftDocument(scopeKey, initialValue)) ||
promptTextContent(initialValue),
content: adopted.current?.document || promptTextContent(initialValue),
editable: !disabled,
editorProps: {
attributes: {
@@ -143,6 +137,12 @@ function NativePromptEditor({
)
},
onTransaction: ({ editor: current, transaction }) => {
if (
!transaction.getMeta('preventUpdate') &&
(transaction.docChanged || transaction.selectionSet)
) {
claimSelection()
}
const pastedTextFiles = transaction.docChanged
? historyPaths(current.state.doc, transaction.docs)
: undefined
@@ -175,6 +175,46 @@ function NativePromptEditor({
[]
)
const applyPosition = useCallback(
(previousRange?: { from: number; to: number }) => {
const position = adopted.current && nativeChatDraftPositions.get(adopted.current)
if (
!editor ||
!position?.pending ||
appliedPosition.current === position ||
(position.at === 'end' && position.target !== positionTarget)
) {
return
}
if (userOwned.current) {
if (position.at === 'end') {
position.pending = false
} else if (previousRange) {
editor.commands.setTextSelection({
from: promptTextPosition(editor.state.doc, previousRange.from),
to: promptTextPosition(editor.state.doc, previousRange.to)
})
}
return
}
appliedPosition.current = position
editor.view.dispatch(
editor.state.tr
.setSelection(
position.at === 'end'
? TextSelection.atEnd(editor.state.doc)
: TextSelection.atStart(editor.state.doc)
)
.setMeta('preventUpdate', true)
)
if (position.at === 'end') {
position.pending = false
}
},
[editor, positionTarget]
)
useLayoutEffect(() => applyPosition(), [applyPosition])
useLayoutEffect(() => {
if (!editor || !scopeKey) {
return
@@ -208,13 +248,20 @@ function NativePromptEditor({
return
}
// A draft loaded or adopted whole keeps its skill chips: its stored document wins.
const stored = scopeKey ? readNativeChatDraftDocument(scopeKey, value) : undefined
const previousRange = {
from: promptTextOffset(doc, editor.state.selection.from),
to: promptTextOffset(doc, editor.state.selection.to)
}
adopted.current = readNativeChatDraftSnapshot(scopeKey, value)
const stored = adopted.current?.document
if (stored) {
editor.commands.setContent(stored, { emitUpdate: false })
applyPosition(previousRange)
return
}
if (!value) {
editor.commands.setContent(promptTextContent(''), { emitUpdate: false })
applyPosition(previousRange)
return
}
let start = 0
@@ -242,6 +289,7 @@ function NativePromptEditor({
tr.setMeta('preventUpdate', true)
return true
})
applyPosition(previousRange)
},
get disabled() {
return !editor.isEditable
@@ -341,7 +389,7 @@ function NativePromptEditor({
}
}
: null,
[editor, scopeKey]
[editor, scopeKey, applyPosition]
)
useImperativeHandle(inputRef, () => input!, [input])
@@ -351,6 +399,7 @@ function NativePromptEditor({
<EditorContent
editor={editor}
{...events}
onCompositionStartCapture={claimSelection}
data-disabled={disabled || undefined}
className="data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50"
/>
@@ -0,0 +1,121 @@
// @vitest-environment happy-dom
import { act, cleanup, render, screen } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import type { ManagedRuntimeInstallObservation } from '@/runtime/use-managed-runtime-install'
const { mocks, moduleFactories, resetStructuredSessionMocks } = await vi.hoisted(async () =>
(await import('./NativeChatStructuredSession.test-harness')).createStructuredSessionMocks()
)
const install = vi.hoisted((): { observation: ManagedRuntimeInstallObservation } => ({
observation: { kind: 'inactive' }
}))
vi.mock('@/lib/structured-agent-session-launch', () =>
moduleFactories.structuredAgentSessionLaunch()
)
vi.mock('@/lib/structured-agent-session-launch-message', () =>
moduleFactories.structuredAgentSessionLaunchMessage()
)
vi.mock('@/runtime/structured-agent-session-client', () =>
moduleFactories.structuredAgentSessionClient()
)
vi.mock('./use-structured-agent-session', () => moduleFactories.useStructuredAgentSession())
vi.mock('./use-native-chat-font-size', () => moduleFactories.useNativeChatFontSize())
vi.mock('./use-native-chat-file-link-context', () => moduleFactories.useNativeChatFileLinkContext())
vi.mock('./use-native-chat-tab-owner', () => moduleFactories.useNativeChatTabOwner())
vi.mock('./use-native-chat-file-link-click', () => moduleFactories.useNativeChatFileLinkClick())
vi.mock('./NativeChatMessageList', () => moduleFactories.nativeChatMessageList())
vi.mock('./NativeChatEmptyState', () => moduleFactories.nativeChatEmptyState())
vi.mock('./NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard())
vi.mock('./NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard())
vi.mock('@/runtime/use-managed-runtime-install', () => ({
useManagedRuntimeInstall: () => install.observation
}))
import { NativeChatStructuredSession } from './NativeChatStructuredSession'
import {
clearNativeChatComposerDraftsForTests,
hydrateNativeChatComposerDrafts,
readNativeChatComposerDraft,
structuredAgentSessionDraftScopeKey,
updateNativeChatComposerDraft
} from './native-chat-composer-draft-store'
import { TooltipProvider } from '@/components/ui/tooltip'
import { promptEditor } from './native-chat-prompt-editor.test-support'
import { promptTextContent } from './native-chat-prompt-document-text'
import {
createMemoryNativeChatComposerDraftStorage,
setNativeChatComposerDraftStorageForTests
} from './native-chat-composer-draft-storage'
afterEach(() => {
cleanup()
resetStructuredSessionMocks()
clearNativeChatComposerDraftsForTests()
})
it('shows and copies the ordinary source of an unsupported installed launch', async () => {
const text = 'Hand Off context\nwith trailing bytes '
clearNativeChatComposerDraftsForTests()
setNativeChatComposerDraftStorageForTests(createMemoryNativeChatComposerDraftStorage())
await hydrateNativeChatComposerDrafts()
mocks.launchLifecycle = 'failed'
mocks.launchFailure = { kind: 'refused', code: 'structured_agent_session_unsupported' }
mocks.messages = []
install.observation = {
kind: 'active',
subject: { target: { kind: 'local' }, runtimeId: null, agent: 'codex' },
snapshot: {
kind: 'known',
state: {
agent: 'codex',
revision: 1,
available: true,
version: '1.3.0',
installedVersion: '1.3.0',
installedCurrent: true,
downloadBytes: 0,
source: 'external',
operation: null
}
},
removable: false
}
updateNativeChatComposerDraft(
structuredAgentSessionDraftScopeKey('session-1'),
{ text, document: promptTextContent(text) },
'immediate'
)
render(
<TooltipProvider>
<NativeChatStructuredSession
isVisible
isFocusedGroup
tabId="structured-tab-1"
sessionId="session-1"
target={{ kind: 'local' }}
agent="codex"
/>
</TooltipProvider>
)
const field = await screen.findByRole('textbox')
expect(field.getAttribute('contenteditable')).toBe('true')
const editor = promptEditor(field)
act(() => {
editor.commands.selectAll()
})
let copied: string | undefined
editor.view.someProp('clipboardTextSerializer', (serializer) => {
copied = serializer(
editor.state.doc.slice(editor.state.selection.from, editor.state.selection.to),
editor.view
)
return true
})
expect(copied).toBe(text)
expect(editor.state.doc.textBetween(0, editor.state.doc.content.size, '\n')).toBe(text)
expect(readNativeChatComposerDraft(structuredAgentSessionDraftScopeKey('session-1')).text).toBe(
text
)
})
@@ -166,86 +166,23 @@ describe('NativeChatStructuredSession', () => {
})
})
it('routes the launch draft and app-menu paste to the structured composer', () => {
const draft = {
tabId: 'structured-draft-tab',
agent: 'codex' as const,
text: 'PR #19423 — review this change',
createdAt: Date.now()
}
useAppStore.getState().seedNativeChatLaunchDraft(draft)
it('routes app-menu paste to the structured composer', () => {
render(
<NativeChatStructuredSession
isVisible
isFocusedGroup
tabId={draft.tabId}
tabId="draft-tab"
sessionId="draft-session"
target={{ kind: 'local' }}
agent="codex"
/>
)
expect(mocks.composerProps?.launchSeed).toEqual({
launchDraft: draft,
launchDraftResolved: false,
ownsTabWideLaunchDraft: true
})
act(() => useAppStore.getState().clearNativeChatLaunchDraft(draft.tabId))
const composer = screen.getByTestId('structured-composer')
composer.focus()
window.dispatchEvent(new Event('orca-app-menu-paste', { cancelable: true }))
expect(mocks.pasteFromClipboard).toHaveBeenCalledOnce()
})
// Do not baseline launch drafts against the controller’s pre-read idle state; backfill could resolve unseen input.
it('holds the launch draft unresolved until the first journal read settles', () => {
const draft = {
tabId: 'structured-idle-tab',
agent: 'codex' as const,
text: 'PR #19423 — review this change',
createdAt: Date.now()
}
useAppStore.getState().seedNativeChatLaunchDraft(draft)
mocks.status = 'idle'
mocks.messages = [
{
id: 'user-1',
role: 'user',
source: 'transcript',
timestamp: draft.createdAt + 1,
blocks: [{ type: 'text', text: draft.text }]
}
]
const { rerender } = render(
<NativeChatStructuredSession
isVisible
isFocusedGroup
tabId={draft.tabId}
sessionId="idle-session"
target={{ kind: 'local' }}
agent="codex"
/>
)
expect(mocks.composerProps?.launchSeed).toMatchObject({
launchDraft: draft,
launchDraftResolved: false
})
mocks.status = 'ready'
rerender(
<NativeChatStructuredSession
isVisible
isFocusedGroup
tabId={draft.tabId}
sessionId="idle-session"
target={{ kind: 'local' }}
agent="codex"
/>
)
expect(mocks.composerProps?.launchSeed?.launchDraftResolved).toBe(true)
act(() => useAppStore.getState().clearNativeChatLaunchDraft(draft.tabId))
})
it('focuses the chat on a click outside its controls and sends typing there to the composer', () => {
const { container } = render(
<NativeChatStructuredSession
@@ -34,7 +34,6 @@ import { useNativeChatImageRuntimeContext } from './native-chat-image-runtime-co
import { useStructuredNativeChatPaneCommands } from './use-structured-native-chat-pane-commands'
import type { NativeChatStructuredViewProps } from './native-chat-view-types'
import { NativeChatStructuredSessionStatus } from './NativeChatStructuredSessionStatus'
import { useNativeChatLaunchDraftSignal } from './use-native-chat-launch-draft-adoption'
import { useNativeChatInterruptedContinuation } from './NativeChatInterruptedContinue'
import { NativeChatOrcaStopContext } from './native-chat-orca-stop-context'
import { structuredSessionNotices } from './native-chat-structured-session-notices'
@@ -99,13 +98,6 @@ export function NativeChatStructuredSession(
})
useRecheckNativeChatFileLinksWhenTurnEnds(controller.isWorking)
const stopControls = nativeChatStructuredStopControls(controller, hostExecution.stopping)
const launchDraftSignal = useNativeChatLaunchDraftSignal({
terminalTabId: props.tabId,
agent: props.agent,
messages: controller.messages,
// Pre-read idle/loading states cannot establish a launch draft baseline from an empty transcript.
transcriptLoading: controller.status === 'idle' || controller.status === 'loading'
})
const { composerError, reportComposerError } = useNativeChatComposerError(
controller.commandRefusalCauses
)
@@ -399,7 +391,6 @@ export function NativeChatStructuredSession(
unavailableHint={install.unavailableHint}
steerQueued={stopControls.stopping ? undefined : submits.queuedMessages.steerNewest}
structuredTransport={transport}
launchSeed={{ ...launchDraftSignal, ownsTabWideLaunchDraft: true }}
notices={notices}
recallSource={{ messages: session.messages, withoutImageMarkers: true }}
/>
@@ -2,6 +2,7 @@
import {
dirtyScopes,
installNativeChatDraftRecord,
load,
nextSavedAt,
notifyScope,
@@ -78,7 +79,11 @@ function applyLoaded(
}
const { draft, changed } = withAppends(scopeKey, stored, readAtSequence)
reconcileRestoredImageChecks(scopeKey, draft.images, records.get(scopeKey)?.images ?? [])
records.set(scopeKey, draft)
installNativeChatDraftRecord(
scopeKey,
draft,
changed ? undefined : { at: 'start', pending: true }
)
if (changed) {
dirtyScopes.add(scopeKey)
}
@@ -1,3 +1,4 @@
import { sameNativeChatComposerDraftDocument } from './native-chat-composer-draft-comparison'
import type { NativeChatComposerDraftAddition } from './native-chat-composer-draft-addition'
// Memory owns drafts; storage keeps a copy shared by the API and persistence modules.
@@ -17,6 +18,50 @@ export type UnconfirmedDraftChange = {
}
export const records = new Map<string, DraftRecord>()
export type NativeChatDraftPosition = { at: 'start' | 'end'; target?: string; pending: boolean }
export const nativeChatDraftPositions = new WeakMap<
NativeChatComposerDraft,
NativeChatDraftPosition
>()
export function retireNativeChatDraftPosition(
draft: NativeChatComposerDraft | undefined,
target?: string
): void {
const position = draft && nativeChatDraftPositions.get(draft)
if (position && (target === undefined || position.target === target)) {
position.pending = false
}
}
/** Publish UI provenance with its exact value; only metadata-only replacements inherit it. */
export function installNativeChatDraftRecord(
scope: string,
draft?: DraftRecord,
position?: NativeChatDraftPosition
): void {
const previous = records.get(scope)
if (
previous &&
draft &&
previous.text === draft.text &&
sameNativeChatComposerDraftDocument(previous.document, draft.document) &&
!position
) {
position = nativeChatDraftPositions.get(previous)
} else {
retireNativeChatDraftPosition(previous)
}
if (draft) {
if (position) {
nativeChatDraftPositions.set(draft, position)
}
records.set(scope, draft)
} else {
records.delete(scope)
}
}
// Changed in memory with no write issued yet; a refused write comes back here for the next flush.
export const dirtyScopes = new Set<string>()
export const unconfirmed = new Map<string, UnconfirmedDraftChange>()
@@ -112,6 +157,9 @@ export function hasLocalChange(scopeKey: string): boolean {
}
export function clearDraftMemoryForTests(): void {
for (const draft of records.values()) {
retireNativeChatDraftPosition(draft)
}
records.clear()
dirtyScopes.clear()
unconfirmed.clear()
@@ -181,6 +229,6 @@ export function closeNativeChatEditDraft(scopeKey: string): void {
target.active = false
}
ephemeralDrafts.delete(scopeKey)
records.delete(scopeKey)
installNativeChatDraftRecord(scopeKey)
notifyScope(scopeKey)
}
@@ -11,6 +11,7 @@ import {
nextSavedAt,
notifyScope,
records,
installNativeChatDraftRecord,
refusedScopes,
unconfirmed,
reconcileRestoredImageChecks,
@@ -253,9 +254,9 @@ function adoptForeignChange(message: unknown): void {
const draft = parseStoredNativeChatComposerDraft(value)
if (draft) {
reconcileRestoredImageChecks(scopeKey, draft.images, records.get(scopeKey)?.images ?? [])
records.set(scopeKey, draft)
installNativeChatDraftRecord(scopeKey, draft)
} else {
records.delete(scopeKey)
installNativeChatDraftRecord(scopeKey)
reconcileRestoredImageChecks(scopeKey, [])
}
notifyScope(scopeKey)
@@ -14,6 +14,8 @@ import {
import { journalNativeChatComposerDraftAddition } from './native-chat-composer-draft-journal'
import {
clearDraftMemoryForTests,
installNativeChatDraftRecord,
type NativeChatDraftPosition,
dirtyScopes,
hasLocalChange,
load,
@@ -132,7 +134,8 @@ export function updateNativeChatComposerDraft(
scopeKey: string,
change: NativeChatComposerDraftChange,
persist: 'immediate' | 'deferred',
append?: DraftAppend
append?: DraftAppend,
position?: NativeChatDraftPosition
): void {
if (isNativeChatEditDraft(scopeKey) && !ephemeralDrafts.has(scopeKey)) {
return
@@ -160,7 +163,7 @@ export function updateNativeChatComposerDraft(
return
}
if (isEmptyDraft({ text, images })) {
records.delete(scopeKey)
installNativeChatDraftRecord(scopeKey)
reconcileRestoredImageChecks(scopeKey, [])
notifyScope(scopeKey)
if (!isNativeChatEditDraft(scopeKey)) {
@@ -182,7 +185,7 @@ export function updateNativeChatComposerDraft(
...(owner ? { owner } : {}),
...(unsavedText === undefined ? {} : { unsavedText })
}
records.set(scopeKey, record)
installNativeChatDraftRecord(scopeKey, record, position)
reconcileRestoredImageChecks(scopeKey, record.images)
notifyScope(scopeKey)
if (isNativeChatEditDraft(scopeKey)) {
@@ -271,7 +274,7 @@ function deleteDraftsWhere(
for (const scopeKey of new Set([...records.keys(), ...scopeListeners.keys()])) {
const draft = records.get(scopeKey)
if (matches(scopeKey, draft)) {
records.delete(scopeKey)
installNativeChatDraftRecord(scopeKey)
reconcileRestoredImageChecks(scopeKey, [])
notifyScope(scopeKey)
if (draft) {
@@ -1,3 +1,5 @@
import type { HTMLAttributes, RefObject } from 'react'
/** Text coordinates keep transport, attachments, and picker logic independent of the editor. */
export type NativeChatComposerInput = Pick<
HTMLTextAreaElement,
@@ -22,6 +24,22 @@ export type NativeChatComposerInput = Pick<
isCaretOnVisualEdge?: (edge: 'start' | 'end') => boolean
}
export type NativeChatPromptEditorProps = Omit<
HTMLAttributes<HTMLDivElement>,
'onChange' | 'onSelect'
> & {
scopeKey?: string
positionTarget?: string
/** The composer's thumbnail ids, in order, which number its image chips. */
imageRow?: readonly string[]
inputRef: RefObject<NativeChatComposerInput | null>
initialValue: string
disabled: boolean
placeholder: string
onChange: (input: NativeChatComposerInput) => void
onSelect: (input: NativeChatComposerInput) => void
}
export function insertNativeChatPastedText(
input: NativeChatComposerInput | null,
text: string
@@ -1,3 +1,5 @@
import type { Tab } from '../../../../shared/tab-types'
import { retireNativeChatDraftPosition } from './native-chat-composer-draft-memory'
import type { NativeChatComposerImageAttachment } from './NativeChatComposerField'
import type { JSONContent } from '@tiptap/react'
import type {
@@ -10,6 +12,7 @@ import {
appendToNativeChatComposerDraft,
clearNativeChatComposerDraftsForTests,
readNativeChatComposerDraft,
structuredAgentSessionDraftScopeKey,
updateNativeChatComposerDraft
} from './native-chat-composer-draft-store'
import { clearNativeChatPendingAttachmentsForTests } from './native-chat-pending-attachment-cache'
@@ -53,6 +56,11 @@ export function clearNativeChatDraftCacheForTests(): void {
clearNativeChatComposerDraftsForTests()
}
export function readNativeChatDraftSnapshot(scopeKey: string | undefined, text: string) {
const draft = scopeKey ? readNativeChatComposerDraft(scopeKey) : undefined
return draft?.text === text ? draft : undefined
}
export function readNativeChatDraftDocument(
scopeKey: string,
text: string
@@ -104,3 +112,28 @@ export function clearNativeChatAttachmentCacheForTests(): void {
clearNativeChatComposerDraftsForTests()
clearNativeChatPendingAttachmentsForTests()
}
/** A destination's death retires only its unsatisfied UI position, never its ordinary content. */
export function retireRemovedNativeChatDraftPositions(
before: readonly Tab[],
after: readonly Tab[]
): void {
if (before === after) {
return
}
const remaining = new Map(after.map((tab) => [tab.id, tab]))
for (const tab of before) {
const next = remaining.get(tab.id)
if (
tab.contentType === 'agent-session' &&
(next?.contentType !== tab.contentType ||
next.entityId !== tab.entityId ||
next.executionHostId !== tab.executionHostId)
) {
retireNativeChatDraftPosition(
readNativeChatComposerDraft(structuredAgentSessionDraftScopeKey(tab.entityId)),
tab.id
)
}
}
}
@@ -0,0 +1,86 @@
// @vitest-environment happy-dom
import { afterEach, expect, it, vi } from 'vitest'
import {
clearNativeChatComposerDraftsForTests,
hydrateNativeChatComposerDrafts,
nativeChatComposerDraftWritesSettled,
readNativeChatComposerDraft,
subscribeToNativeChatComposerDraft
} from './native-chat-composer-draft-store'
import {
createMemoryNativeChatComposerDraftStorage,
setNativeChatComposerDraftStorageForTests,
type StoredNativeChatComposerDraft
} from './native-chat-composer-draft-storage'
import { records } from './native-chat-composer-draft-memory'
import { deleteWorkspaceChatDrafts } from '@/store/slices/worktrees/teardown/removed-worktree-chat-drafts'
afterEach(() => {
vi.restoreAllMocks()
clearNativeChatComposerDraftsForTests()
})
it('hydrates and explicitly deletes retained closed drafts with linear saved-record work at N and 10N', async () => {
for (const count of [100, 1000]) {
clearNativeChatComposerDraftsForTests()
localStorage.clear()
const storage = createMemoryNativeChatComposerDraftStorage()
for (let i = 0; i < count; i++) {
storage.drafts.set(`agent-session:closed-${i}`, {
text: `retained context ${i}\n${'text '.repeat(40)}`,
images: [],
owner: {
workspaceId: 'folder-workspace:kept',
executionHostId: i % 2 ? 'ssh:other' : 'local'
},
savedAt: i + 1
})
}
let visits = 0
class SavedRecords extends Map<string, StoredNativeChatComposerDraft> {
override *[Symbol.iterator](): Generator<
[string, StoredNativeChatComposerDraft],
undefined,
unknown
> {
for (const entry of super[Symbol.iterator]()) {
visits++
yield entry
}
return undefined
}
}
const load = vi.fn(async () => new SavedRecords(storage.drafts))
const write = vi.fn(storage.write)
const remove = vi.fn(storage.remove)
setNativeChatComposerDraftStorageForTests({ ...storage, loadAll: load, write, remove })
await hydrateNativeChatComposerDrafts()
expect(load).toHaveBeenCalledOnce()
expect(visits).toBe(count)
expect(records.size).toBe(count)
const gets = vi.spyOn(records, 'get')
const affected = vi.fn(),
otherHost = vi.fn()
const off = subscribeToNativeChatComposerDraft('agent-session:closed-0', affected)
const offOther = subscribeToNativeChatComposerDraft('agent-session:closed-1', otherHost)
deleteWorkspaceChatDrafts({
owners: [{ workspaceId: 'folder-workspace:kept', executionHostId: 'local' }],
conversations: [],
terminalTabIds: []
})
// Owner selection reads each saved record once; persistence may read the selected keys again.
expect(gets.mock.calls.length).toBeLessThanOrEqual(count * 2)
await nativeChatComposerDraftWritesSettled()
expect(records.size).toBe(count / 2)
expect(storage.drafts.size).toBe(count / 2)
expect(remove.mock.calls.flatMap(([keys]) => keys)).toHaveLength(count / 2)
expect(write).not.toHaveBeenCalled()
expect(affected).toHaveBeenCalledOnce()
expect(otherHost).not.toHaveBeenCalled()
expect(readNativeChatComposerDraft('agent-session:closed-1').text).toBe(
`retained context 1\n${'text '.repeat(40)}`
)
off()
offOther()
gets.mockRestore()
}
})
@@ -1,39 +1,35 @@
// @vitest-environment happy-dom
import { act, createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest'
import type { AppState } from '@/store/types'
import type { StructuredAgentLaunchSettlement } from '@/lib/structured-agent-launch-settlement'
const mocks = vi.hoisted(() => {
const answers: ((support: unknown) => void)[] = []
return {
gate: vi.fn(),
createTab: vi.fn(),
createUnifiedTab: vi.fn(),
begin: vi.fn(),
select: (selector: (state: { pendingWorktreeCreations: Record<string, never> }) => unknown) =>
selector({ pendingWorktreeCreations: {} }),
createUnifiedTab: vi.fn<AppState['createUnifiedTab']>(),
begin: vi.fn<AgentSessionLaunchPlan['begin']>(),
answers
}
})
vi.mock('@/store', () => ({
useAppStore: Object.assign(mocks.select, {
getState: () => ({
activeWorktreeId: 'wt-1',
tabsByWorktree: {},
closedTerminalTabTombstonesByTabId: {},
unifiedTabsByWorktree: {},
groupsByWorktree: {},
layoutByWorktree: {},
activeGroupIdByWorktree: {},
// A switch-on chat open places the tab in the workspace's root group.
ensureWorktreeRootGroup: () => 'group-1',
createUnifiedTab: mocks.createUnifiedTab,
readLocalAgentInventory: () => ({ ids: null, state: 'pending' }),
setActiveTabType: vi.fn()
})
})
const owner = vi.hoisted((): { store: ReturnType<typeof createTestStore> | null } => ({
store: null
}))
vi.mock('@/store', async () => {
const module = (await import('@/lib/launch-parity-renderer.test-fixture')).launchStoreModuleMock(
owner
)
return {
useAppStore: Object.assign(
(selector: (state: AppState) => unknown) => owner.store!(selector),
module.useAppStore
)
}
})
vi.mock('@/lib/worktree-agent-activation-gate', () => ({ gateWorktreeAgentActivation: mocks.gate }))
vi.mock('@/lib/resume-sleeping-agent-session', () => ({
resumeSleepingAgentSessionsForWorktree: vi.fn()
@@ -50,7 +46,13 @@ vi.mock('../terminal-pane/terminal-parked-tab-watchers', () => ({
vi.mock('@/runtime/structured-agent-session-client', () => ({
callStructuredAgentSession: (_target: unknown, method: string) =>
method === 'agentSession.createSupport'
? new Promise((resolve) => mocks.answers.push(resolve))
? new Promise((resolve) => {
const answer = (support: unknown) => {
mocks.answers.splice(mocks.answers.indexOf(answer), 1)
resolve(support)
}
mocks.answers.push(answer)
})
: new Promise(() => undefined)
}))
@@ -61,25 +63,109 @@ vi.mock('@/runtime/runtime-rpc-client', async (importOriginal) =>
).runtimeRpcClientWithLayoutApply(await importOriginal())
)
vi.mock('@/runtime/runtime-layout-client', async (importOriginal) =>
(
await import('@/runtime/layout-apply-test-transport.test-fixture')
).runtimeLayoutClientWithTestFrames(await importOriginal())
)
import { createTestStore, makeWorktree, seedStore } from '@/store/slices/store-test-helpers'
import {
drawTabsFromMain,
type TabsDrawnFromMain
} from '@/store/slices/tabs-drawn-from-main.test-fixture'
import { isPendingTab } from '@/runtime/layout-owner-pending-tabs'
import { useTerminalWatcherEffects } from '../use-terminal-watcher-effects'
import { beginStructuredAgentSessionProvisionalLaunch } from '@/lib/agent-session/structured-agent-session-provisional-tab'
import { isEmptyWorkspaceDefaultSurfacePending } from '@/lib/empty-workspace-default-surface-claims'
import type { AgentSessionLaunchPlan } from '@/lib/agent-session-launch-plan'
import type { Tab } from '../../../../shared/tab-types'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch'
import { layoutApplyTestTransport } from '@/runtime/layout-apply-test-transport.test-fixture'
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
let root: Root | undefined
let main: TabsDrawnFromMain
let warnings: MockInstance<typeof console.warn>
const owned: {
launch: NonNullable<ReturnType<typeof beginStructuredAgentSessionProvisionalLaunch>>
done: boolean
}[] = []
const begins: { finish: () => void; cancel: ReturnType<typeof vi.fn> }[] = []
beforeEach(async () => {
vi.resetAllMocks()
owner.store = createTestStore()
seedStore(owner.store, {
worktreesByRepo: { repo: [makeWorktree({ id: 'wt-1', repoId: 'repo' })] },
activeWorktreeId: 'wt-1'
})
mocks.createUnifiedTab.mockImplementation(owner.store.getState().createUnifiedTab)
owner.store.setState({ createUnifiedTab: mocks.createUnifiedTab })
expect(owner.store.getState().readLocalAgentInventory('wt-1')).toEqual({
ids: null,
state: 'pending'
})
main = await drawTabsFromMain(owner.store)
warnings = vi.spyOn(console, 'warn')
})
afterEach(async () => {
await act(async () => root?.unmount())
root = undefined
mocks.answers.length = 0
vi.clearAllMocks()
layoutApplyTestTransport.reset()
for (const entry of owned) {
if (!entry.done) {
entry.launch.cancel()
}
}
while (mocks.answers.length) {
mocks.answers[0]!({ supported: false })
}
for (const begin of begins.splice(0)) {
begin.finish()
}
await Promise.all(owned.splice(0).map(({ launch }) => launch.settlement))
await main.settle()
expect(mocks.answers).toEqual([])
expect(begins).toEqual([])
expect(layoutApplyTestTransport.pendingCount).toBe(0)
expect(
warnings.mock.calls.filter(
([message]) => message === '[layout-owner] pending tab waiter threw:'
)
).toEqual([])
main.close()
vi.restoreAllMocks()
owner.store = null
})
function launchChat(args: Parameters<typeof beginStructuredAgentSessionProvisionalLaunch>[0]) {
const launch = beginStructuredAgentSessionProvisionalLaunch(args)
if (!launch) {
throw new Error('Expected admitted launch handle')
}
const entry = { launch, done: false }
owned.push(entry)
void launch.settlement.then(() => {
entry.done = true
})
return launch
}
async function finishChat(launch: NonNullable<ReturnType<typeof launchChat>>): Promise<void> {
const begin = begins.pop()!
begin.finish()
await expect(launch.settlement).resolves.toEqual({ kind: 'structured', sessionId: 'claude_1' })
await main.settle()
expect(begin.cancel).not.toHaveBeenCalled()
const tab = owner
.store!.getState()
.unifiedTabsByWorktree['wt-1']?.find((row) => row.entityId === 'claude_1')
expect(tab).toBeDefined()
expect(owner.store!.getState().getTab(tab!.id)).toBe(tab)
expect(isPendingTab(tab!.id)).toBe(false)
expect(isEmptyWorkspaceDefaultSurfacePending('wt-1')).toBe(false)
}
/** No shell created here or (switch-on) asked of main. */
function expectNoShell(): void {
expect(mocks.createTab).not.toHaveBeenCalled()
@@ -98,7 +184,7 @@ async function expectShellCreatedOnce(): Promise<void> {
expect(mocks.createTab).toHaveBeenCalledOnce()
}
/** The chat opened: drawn here, or (switch-on) its open sent to main, whose frame draws it. */
/** Observe the original create/open request count; finishChat verifies the actual drawn row. */
async function expectChatOpenedOnce(): Promise<void> {
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
await layoutApplyTestTransport.settle()
@@ -147,19 +233,15 @@ function Watcher(): null {
}
function localChatPlan(): AgentSessionLaunchPlan {
mocks.begin.mockReturnValue({
sessionId: 'claude_1',
executionHostId: 'local',
settlement: new Promise(() => undefined),
cancel: vi.fn()
})
mocks.createUnifiedTab.mockImplementation(
(worktreeId: string, _type: string, tab: Partial<Tab>) => ({
...tab,
worktreeId
mocks.begin.mockImplementation(() => {
const result = Promise.withResolvers<StructuredAgentLaunchSettlement>()
const cancel = vi.fn()
begins.push({
finish: () => result.resolve({ kind: 'structured', sessionId: 'claude_1' }),
cancel
})
)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: begin() is the only member this path calls.
return { sessionId: 'claude_1', executionHostId: 'local', settlement: result.promise, cancel }
})
return {
route: 'structured-native-chat',
requestId: 'request-1',
@@ -168,7 +250,7 @@ function localChatPlan(): AgentSessionLaunchPlan {
executionHostId: 'local',
begin: mocks.begin,
launch: vi.fn()
} as unknown as AgentSessionLaunchPlan
}
}
function gateAnsweredLater(): {
@@ -199,7 +281,7 @@ describe('a local chat launch waiting on its host', () => {
it('keeps a watched create free of a stray shell until its chat opens', async () => {
const { finish } = gateAnsweredLater()
beginStructuredAgentSessionProvisionalLaunch({
const launch = launchChat({
plan: localChatPlan(),
hooks: {},
beforeOpen: () => true
@@ -214,13 +296,12 @@ describe('a local chat launch waiting on its host', () => {
await act(async () => mocks.answers[0]?.({ supported: true }))
await expectChatOpenedOnce()
expectNoShell()
await finishChat(launch)
})
it("keeps an empty workspace's default chat free of a shell seeded by the shared gate", async () => {
const { gate, finish } = gateAnsweredLater()
void gate.then(() =>
beginStructuredAgentSessionProvisionalLaunch({ plan: localChatPlan(), hooks: {} })
)
const pendingLaunch = gate.then(() => launchChat({ plan: localChatPlan(), hooks: {} }))
root = createRoot(document.createElement('div'))
await act(async () => root?.render(createElement(Watcher)))
await act(async () => finish())
@@ -230,11 +311,12 @@ describe('a local chat launch waiting on its host', () => {
await act(async () => mocks.answers[0]?.({ supported: true }))
await expectChatOpenedOnce()
expectNoShell()
await finishChat(await pendingLaunch)
})
it('stops owning the surface once the host has answered and its surface opened', async () => {
const onHostDeclined = vi.fn(() => ({ opened: true }))
const launch = beginStructuredAgentSessionProvisionalLaunch({
const launch = launchChat({
plan: localChatPlan(),
hooks: {},
onHostDeclined
@@ -0,0 +1,98 @@
import { retireStructuredAgentSessionReadOwner } from '@/components/native-chat/structured-agent-session-read-owner-registry'
import { structuredAgentSessionTargetForHost } from '@/runtime/structured-agent-session-owner'
import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../../shared/execution-host'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch'
import { markStructuredAgentLaunchCancellation } from '../../launch-cancel-tombstones-compat/structured-agent-session-launch-cancellation'
import { cancelStructuredAgentLaunchOnLocalHost } from '../../structured-agent-session-local-launch-cancel'
import { forgetStructuredSessionSelection } from '../../structured-agent-session-selection-controller'
import { hasStructuredAgentLaunchCancellationTombstonePersisted } from './structured-agent-session-launch-persistence'
import {
removeStructuredLaunchSlot,
type StructuredLaunchSlotOwner
} from './structured-agent-session-launch-slot'
import {
deleteStructuredLaunchStateIfCurrent,
getPersistedStructuredAgentLaunchRecord,
getStructuredLaunchStateBySessionId,
notifyStructuredLaunchListeners
} from './structured-agent-session-launch-registry'
function markStructuredAgentSessionLaunchCancelledInternal(
worktreeId: string,
sessionId: string,
executionHostId: ExecutionHostId,
owner: StructuredLaunchSlotOwner | undefined
): boolean {
const alreadyCancelled = hasStructuredAgentLaunchCancellationTombstonePersisted(sessionId)
const state = getStructuredLaunchStateBySessionId(sessionId)
const record = getPersistedStructuredAgentLaunchRecord(sessionId)
const surfaceAddress = state?.intent.surfaceAddress ?? record?.surfaceAddress
const matchingState = state?.intent.worktreeId === worktreeId ? state : undefined
const host = matchingState?.intent.executionHostId ?? record?.executionHostId ?? executionHostId
const target = matchingState?.intent.target ?? structuredAgentSessionTargetForHost(host)
if (state?.intent.worktreeId === worktreeId) {
// The launch's own owner outranks the caller's: it is the host the create was sent to.
if (ORCA_LAYOUT_OWNER_IS_MAIN && state.intent.executionHostId === LOCAL_EXECUTION_HOST_ID) {
cancelStructuredAgentLaunchOnLocalHost(worktreeId, sessionId)
} else {
markStructuredAgentLaunchCancellation(
sessionId,
state.intent.executionHostId,
alreadyCancelled,
state.promise
)
}
state.cancelled = true
forgetStructuredSessionSelection(sessionId, state.intent.target)
state.callers.outcome = 'cancelled'
// Tombstones remain durable authority; drop in-memory dead promises so bulk closes cannot retain them all session.
deleteStructuredLaunchStateIfCurrent(state)
} else if (
ORCA_LAYOUT_OWNER_IS_MAIN &&
!alreadyCancelled &&
executionHostId === LOCAL_EXECUTION_HOST_ID
) {
cancelStructuredAgentLaunchOnLocalHost(worktreeId, sessionId)
} else if (!alreadyCancelled) {
markStructuredAgentLaunchCancellation(sessionId, executionHostId, alreadyCancelled)
}
if ((!state || matchingState) && (!surfaceAddress || surfaceAddress.worktreeId === worktreeId)) {
retireStructuredAgentSessionReadOwner(sessionId, target, host)
}
if (owner && surfaceAddress) {
removeStructuredLaunchSlot(owner, worktreeId, sessionId)
}
if (!alreadyCancelled && owner) {
notifyStructuredLaunchListeners()
}
return !alreadyCancelled
}
/** `executionHostId` owns the chat; a launch still in memory names its own. */
export function markStructuredAgentSessionLaunchCancelled(
worktreeId: string,
sessionId: string,
executionHostId: ExecutionHostId,
owner: StructuredLaunchSlotOwner
): boolean {
return markStructuredAgentSessionLaunchCancelledInternal(
worktreeId,
sessionId,
executionHostId,
owner
)
}
/** Bulk workspace purges run inside a store updater; persist cancellation without notifying React. */
export function markStructuredAgentSessionLaunchCancelledSilently(
worktreeId: string,
sessionId: string,
executionHostId: ExecutionHostId
): boolean {
return markStructuredAgentSessionLaunchCancelledInternal(
worktreeId,
sessionId,
executionHostId,
undefined
)
}
@@ -79,6 +79,7 @@ export function trackLaunchSettlement(
if (state.cancelled) {
return
}
state.visibilityUnknown = false
materializeStructuredLaunchSurface(state.intent)
if (!state.hostListed) {
const { worktreeId, sessionId, executionHostId } = state.intent
@@ -1,5 +1,3 @@
import { retireStructuredAgentSessionReadOwner } from '@/components/native-chat/structured-agent-session-read-owner-registry'
import { structuredAgentSessionTargetForHost } from '@/runtime/structured-agent-session-owner'
import { launchStateLifecycle } from '../../structured-agent-session-launch-lifecycle'
export { launchStateLifecycle } from '../../structured-agent-session-launch-lifecycle'
import { forgetStructuredSessionSelection } from '../../structured-agent-session-selection-controller'
@@ -23,20 +21,11 @@ import {
import type { StructuredAgentLaunchPersistedRecord } from './structured-agent-session-launch-record'
import { structuredAgentLaunchRecordFor } from './structured-agent-session-launch-record'
import {
removeStructuredLaunchSlot,
type StructuredLaunchSlotOwner
} from './structured-agent-session-launch-slot'
import {
markStructuredAgentLaunchCancellation,
resetStructuredAgentLaunchCancellationForTests,
retireAbsentStructuredAgentLaunchCancellations,
retireStructuredAgentLaunchCancellation
} from '../../launch-cancel-tombstones-compat/structured-agent-session-launch-cancellation'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch'
import {
cancelStructuredAgentLaunchOnLocalHost,
resetStructuredAgentLocalLaunchCancelsForTests
} from '../../structured-agent-session-local-launch-cancel'
import { resetStructuredAgentLocalLaunchCancelsForTests } from '../../structured-agent-session-local-launch-cancel'
export type StructuredLaunchState = StructuredLaunchRecoveryState & {
identity: string
@@ -214,86 +203,6 @@ export function shouldRetainStructuredAgentSessionLaunchTab(
return lifecycle === 'pending' || lifecycle === 'visibility-unknown' || lifecycle === 'failed'
}
function markStructuredAgentSessionLaunchCancelledInternal(
worktreeId: string,
sessionId: string,
executionHostId: ExecutionHostId,
owner: StructuredLaunchSlotOwner | undefined
): boolean {
const alreadyCancelled = hasStructuredAgentLaunchCancellationTombstonePersisted(sessionId)
const state = getStructuredLaunchStateBySessionId(sessionId)
const record = getPersistedStructuredAgentLaunchRecord(sessionId)
const surfaceAddress = state?.intent.surfaceAddress ?? record?.surfaceAddress
const matchingState = state?.intent.worktreeId === worktreeId ? state : undefined
const host = matchingState?.intent.executionHostId ?? record?.executionHostId ?? executionHostId
const target = matchingState?.intent.target ?? structuredAgentSessionTargetForHost(host)
if (state?.intent.worktreeId === worktreeId) {
// The launch's own owner outranks the caller's: it is the host the create was sent to.
if (ORCA_LAYOUT_OWNER_IS_MAIN && state.intent.executionHostId === LOCAL_EXECUTION_HOST_ID) {
cancelStructuredAgentLaunchOnLocalHost(worktreeId, sessionId)
} else {
markStructuredAgentLaunchCancellation(
sessionId,
state.intent.executionHostId,
alreadyCancelled,
state.promise
)
}
state.cancelled = true
forgetStructuredSessionSelection(sessionId, state.intent.target)
state.callers.outcome = 'cancelled'
// Tombstones remain durable authority; drop in-memory dead promises so bulk closes cannot retain them all session.
deleteStructuredLaunchStateIfCurrent(state)
} else if (
ORCA_LAYOUT_OWNER_IS_MAIN &&
!alreadyCancelled &&
executionHostId === LOCAL_EXECUTION_HOST_ID
) {
cancelStructuredAgentLaunchOnLocalHost(worktreeId, sessionId)
} else if (!alreadyCancelled) {
markStructuredAgentLaunchCancellation(sessionId, executionHostId, alreadyCancelled)
}
if ((!state || matchingState) && (!surfaceAddress || surfaceAddress.worktreeId === worktreeId)) {
retireStructuredAgentSessionReadOwner(sessionId, target, host)
}
if (owner && surfaceAddress) {
removeStructuredLaunchSlot(owner, worktreeId, sessionId)
}
if (!alreadyCancelled && owner) {
notifyStructuredLaunchListeners()
}
return !alreadyCancelled
}
/** `executionHostId` owns the chat; a launch still in memory names its own. */
export function markStructuredAgentSessionLaunchCancelled(
worktreeId: string,
sessionId: string,
executionHostId: ExecutionHostId,
owner: StructuredLaunchSlotOwner
): boolean {
return markStructuredAgentSessionLaunchCancelledInternal(
worktreeId,
sessionId,
executionHostId,
owner
)
}
/** Bulk workspace purges run inside a store updater; persist cancellation without notifying React. */
export function markStructuredAgentSessionLaunchCancelledSilently(
worktreeId: string,
sessionId: string,
executionHostId: ExecutionHostId
): boolean {
return markStructuredAgentSessionLaunchCancelledInternal(
worktreeId,
sessionId,
executionHostId,
undefined
)
}
export function hasStructuredAgentSessionLaunchCancellationTombstone(
_worktreeId: string,
sessionId: string
@@ -328,3 +237,8 @@ export function retireAbsentStructuredAgentSessionLaunchCancellationTombstones(
}
return changed
}
export {
markStructuredAgentSessionLaunchCancelled,
markStructuredAgentSessionLaunchCancelledSilently
} from './structured-agent-session-launch-cancel'
@@ -0,0 +1,467 @@
// @vitest-environment happy-dom
import {
main,
rpc,
storage,
POSITION_TEXT,
openPositionDraft,
PositionField,
positionInventory,
startPositionMain
} from './structured-agent-session-draft-position.test-fixture'
import * as draftCache from '@/components/native-chat/native-chat-draft-cache'
import * as draftMemory from '@/components/native-chat/native-chat-composer-draft-memory'
import { seedStructuredAgentLaunchDraft } from '../structured-agent-session-launch-draft'
import { publishedLayoutsOf } from '@/runtime/main-loaded-layout-frames.test-fixture'
import { applyStructuredSessionTabSnapshots } from '@/runtime/local-structured-session-tabs-sync/snapshot-apply'
import { layoutApplyTestTransport } from '@/runtime/layout-apply-test-transport.test-fixture'
import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-types'
import { render, within } from '@testing-library/react'
import { createRef, StrictMode } from 'react'
import type { NativeChatComposerInput } from '@/components/native-chat/native-chat-composer-input'
import { promptEditor } from '@/components/native-chat/native-chat-prompt-editor.test-support'
import { expect, it, vi } from 'vitest'
import { useAppStore } from '@/store/index'
import { getStructuredLaunchStateBySessionId } from './launch/structured-agent-session-launch-registry'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch'
import {
clearNativeChatComposerDraftsForTests,
hydrateNativeChatComposerDrafts,
readNativeChatComposerDraft,
structuredAgentSessionDraftScopeKey,
updateNativeChatComposerDraft
} from '@/components/native-chat/native-chat-composer-draft-store'
import { setNativeChatComposerDraftStorageForTests } from '@/components/native-chat/native-chat-composer-draft-storage'
import { promptTextContent } from '@/components/native-chat/native-chat-prompt-document-text'
import { openStructuredAgentSessionProvisionalTab } from '../structured-agent-session-launch-surface'
it
.runIf(ORCA_LAYOUT_OWNER_IS_MAIN)
.each(['discarded-inventory', 'refused-close', 'excluded-close'] as const)(
'keeps fresh END on the actually drawn destination after %s, then retires on accepted removal',
async (schedule) => {
const handle = openPositionDraft(),
scope = structuredAgentSessionDraftScopeKey(handle.sessionId)
await main.settle()
await vi.waitFor(() =>
expect(rpc.call.mock.calls.some(([, method]) => method === 'agentSession.create')).toBe(true)
)
await handle.finish()
applyStructuredSessionTabSnapshots([positionInventory(handle.sessionId, 1)])
const original = readNativeChatComposerDraft(scope)
if (schedule === 'discarded-inventory') {
applyStructuredSessionTabSnapshots([positionInventory(null, 2)])
} else {
layoutApplyTestTransport.answerWith((command) =>
command.type === 'closeTabs'
? schedule === 'refused-close'
? { ok: false, code: 'tab_not_found' }
: { ok: true, result: { closed: [], refused: [] } }
: 'apply'
)
useAppStore.getState().closeUnifiedTab(handle.tab.id)
await main.settle()
layoutApplyTestTransport.answerWith('apply')
}
expect(useAppStore.getState().getTab(handle.tab.id)?.entityId).toBe(handle.sessionId)
const input = createRef<NativeChatComposerInput>()
const mount = () =>
render(
<StrictMode>
<PositionField scope={scope} tabId={handle.tab.id} input={input} />
</StrictMode>
)
const first = mount()
expect(input.current!.selectionStart).toBe(POSITION_TEXT.length)
first.unmount()
useAppStore.getState().closeUnifiedTab(handle.tab.id)
await main.settle()
expect(useAppStore.getState().getTab(handle.tab.id)).toBeNull()
openStructuredAgentSessionProvisionalTab({
worktreeId: 'wt-1',
executionHostId: 'local',
sessionId: handle.sessionId,
agent: 'claude'
})
await main.settle()
const reopened = mount()
expect(input.current!.selectionStart).toBe(0)
expect(input.current!.value).toBe(POSITION_TEXT)
expect(readNativeChatComposerDraft(scope)).toBe(original)
reopened.unmount()
}
)
it.runIf(ORCA_LAYOUT_OWNER_IS_MAIN).each(['fresh', 'restored', 'newer-seed'] as const)(
'settles actual no-surface open without retiring another occurrence: %s',
async (kind) => {
const uuid = '11111111-2222-4333-8444-555555555555'
vi.spyOn(crypto, 'randomUUID').mockReturnValue(uuid)
const id = `claude_${uuid.replaceAll('-', '_')}`,
scope = structuredAgentSessionDraftScopeKey(id)
if (kind === 'restored') {
await storage.write(scope, {
text: POSITION_TEXT,
document: promptTextContent(POSITION_TEXT),
images: [],
savedAt: 1
})
clearNativeChatComposerDraftsForTests()
setNativeChatComposerDraftStorageForTests(storage)
await hydrateNativeChatComposerDrafts()
}
layoutApplyTestTransport.answerWith('pending')
const handle = openPositionDraft()
await vi.waitFor(() => expect(layoutApplyTestTransport.pendingCount).toBeGreaterThan(0))
const original = readNativeChatComposerDraft(scope)
if (kind === 'newer-seed') {
updateNativeChatComposerDraft(scope, { text: '', document: undefined }, 'immediate')
const state = getStructuredLaunchStateBySessionId(id)
if (!state) {
throw new Error('Expected live initializer owner')
}
seedStructuredAgentLaunchDraft(state, {
requestId: 'newer-accepted-seed',
prompt: POSITION_TEXT,
promptDelivery: 'draft'
})
}
layoutApplyTestTransport.answerPending({ ok: false, code: 'tab_not_found' })
layoutApplyTestTransport.answerWith('apply')
await handle.finish()
expect(useAppStore.getState().getTab(handle.tab.id)).toBeNull()
const input = createRef<NativeChatComposerInput>()
const mount = () =>
render(
<StrictMode>
<PositionField scope={scope} tabId={handle.tab.id} input={input} />
</StrictMode>
)
const first = mount()
expect(input.current!.value).toBe(POSITION_TEXT)
expect(input.current!.selectionStart).toBe(kind === 'newer-seed' ? POSITION_TEXT.length : 0)
if (kind !== 'newer-seed') {
expect(readNativeChatComposerDraft(scope)).toBe(original)
}
first.unmount()
const second = mount()
expect(input.current!.selectionStart).toBe(0)
second.unmount()
}
)
it.each(['remove', 'replace', 'final-retained'] as const)(
'retires at actual final accepted topology, preserving ordinary bytes: %s',
async (kind) => {
const handle = openPositionDraft(),
scope = structuredAgentSessionDraftScopeKey(handle.sessionId)
await handle.finish()
applyStructuredSessionTabSnapshots([positionInventory(handle.sessionId, 1)])
const original = readNativeChatComposerDraft(scope)
const observedInput = createRef<NativeChatComposerInput>()
let observed: ReturnType<typeof render> | undefined
const unsubscribe = useAppStore.subscribe((state) => {
if (
kind !== 'final-retained' &&
state.getTab(handle.tab.id)?.entityId !== handle.sessionId &&
!observed
) {
observed = render(
<PositionField scope={scope} tabId={handle.tab.id} input={observedInput} />
)
expect(observedInput.current!.selectionStart).toBe(0)
}
})
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
const model = layoutApplyTestTransport.mainModel
if (!model) {
throw new Error('Expected main model')
}
const layout = publishedLayoutsOf(model)['wt-1']!
if (kind === 'replace') {
const changed = structuredClone(layout)
changed.tabs.find((tab) => tab.id === handle.tab.id)!.entityId = 'replacement-session'
layoutApplyTestTransport.emitFrame({ type: 'workspace', key: 'wt-1', layout: changed })
} else if (kind === 'remove') {
const changed = {
...layout,
tabs: layout.tabs.filter((tab) => tab.id !== handle.tab.id),
groups: layout.groups.map((group) => ({
...group,
tabIds: group.tabIds.filter((id) => id !== handle.tab.id)
}))
}
layoutApplyTestTransport.emitFrame({ type: 'workspace', key: 'wt-1', layout: changed })
} else {
// Proposed removal and restoration are one accepted final batch.
layoutApplyTestTransport.emitFrame({
type: 'workspace',
key: 'wt-1',
layout: { ...layout, tabs: [], groups: [] }
})
layoutApplyTestTransport.emitFrame({ type: 'workspace', key: 'wt-1', layout })
}
await main.settle()
} else {
if (kind === 'replace') {
const inventory = positionInventory(handle.sessionId, 2)
inventory.tabs = inventory.tabs.map((tab) =>
tab.type === 'agent-session' ? { ...tab, sessionId: 'replacement-session' } : tab
)
applyStructuredSessionTabSnapshots([inventory])
} else {
applyStructuredSessionTabSnapshots(
kind === 'remove'
? [positionInventory(null, 2)]
: [positionInventory(null, 2), positionInventory(handle.sessionId, 3)]
)
}
}
unsubscribe()
if (kind !== 'final-retained') {
expect(observedInput.current!.selectionStart).toBe(0)
}
observed?.unmount()
expect(readNativeChatComposerDraft(scope)).toBe(original)
if (kind !== 'final-retained') {
// Reopen the retained ordinary conversation through the existing API.
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
layoutApplyTestTransport.emitFrame({
type: 'workspace',
key: 'wt-1',
layout: publishedLayoutsOf(layoutApplyTestTransport.mainModel!)['wt-1']!
})
await main.settle()
} else {
openStructuredAgentSessionProvisionalTab({
worktreeId: 'wt-1',
executionHostId: 'local',
sessionId: handle.sessionId,
agent: 'claude'
})
}
await main.settle()
}
const input = createRef<NativeChatComposerInput>()
const view = render(
<StrictMode>
<PositionField scope={scope} tabId={handle.tab.id} input={input} />
</StrictMode>
)
expect(input.current!.value).toBe(POSITION_TEXT)
expect(input.current!.selectionStart).toBe(kind === 'final-retained' ? POSITION_TEXT.length : 0)
expect(promptEditor(within(view.container).getByRole('textbox')).getJSON()).toEqual(
original.document
)
view.unmount()
}
)
it.each([10, 100])(
'bounds actual affected-workspace retirement at %i tabs without scanning unrelated drafts',
async (n) => {
const handle = openPositionDraft()
await handle.finish()
const row = useAppStore.getState().getTab(handle.tab.id)
if (!row) {
throw new Error('Expected drawn source')
}
main.close()
const rows = Array.from({ length: n }, (_, i) => ({
...row,
id: `scale-${i}`,
entityId: `scale-session-${i}`
}))
useAppStore.setState({
unifiedTabsByWorktree: {
'wt-1': rows,
unrelated: [{ ...row, id: 'do-not-visit', worktreeId: 'unrelated' }]
},
groupsByWorktree: {
'wt-1': [
{
id: row.groupId,
worktreeId: 'wt-1',
tabOrder: rows.map((tab) => tab.id),
activeTabId: rows[0]!.id,
recentTabIds: []
}
],
unrelated: []
}
})
await startPositionMain()
const visits = { before: 0, after: 0, entries: 0, maps: 0, retire: 0, calls: 0 }
const realRetire = draftCache.retireRemovedNativeChatDraftPositions,
RealMap = Map,
mapped = new WeakSet<object>()
const retire = vi.spyOn(draftMemory, 'retireNativeChatDraftPosition')
const compare = vi
.spyOn(draftCache, 'retireRemovedNativeChatDraftPositions')
.mockImplementation((before, after) => {
visits.calls++
if (before === after) {
realRetire(before, after)
return
}
expect(before.every((tab) => tab.worktreeId === 'wt-1')).toBe(true)
realRetire(
new Proxy(before, {
get(target, key, receiver) {
if (key === Symbol.iterator) {
return function* () {
for (const tab of target) {
visits.before++
yield tab
}
}
}
// oxlint-disable-next-line anti-slop/no-reflect-get -- Test-only Proxy forwards unmeasured string/symbol keys with the original receiver.
return Reflect.get(target, key, receiver)
}
}),
new Proxy(after, {
get(target, key, receiver) {
if (key === 'map') {
return (callback: (tab: typeof row, index: number) => unknown) => {
const entries = target.map((tab, index) => {
visits.after++
visits.entries++
return callback(tab, index)
})
mapped.add(entries)
return entries
}
}
// oxlint-disable-next-line anti-slop/no-reflect-get -- Test-only Proxy forwards unmeasured string/symbol keys with the original receiver.
return Reflect.get(target, key, receiver)
}
})
)
})
class MeasuredMap<K, V> extends RealMap<K, V> {
constructor(entries?: Iterable<readonly [K, V]> | null) {
super(entries)
if (entries && mapped.has(entries)) {
visits.maps++
}
}
}
const measure = async (action: () => void) => {
Object.assign(visits, { before: 0, after: 0, entries: 0, maps: 0, retire: 0, calls: 0 })
retire.mockClear()
globalThis.Map = MeasuredMap
try {
action()
await main.settle()
} finally {
globalThis.Map = RealMap
}
visits.retire = retire.mock.calls.length
expect(visits.before).toBeLessThanOrEqual(n)
expect(visits.after).toBeLessThanOrEqual(n)
expect(visits.entries).toBe(visits.after)
expect(visits.maps).toBeLessThanOrEqual(1)
expect(visits.calls).toBeLessThanOrEqual(1)
return { ...visits }
}
const inventories = (title = 'Chat', omit = false): RuntimeMobileSessionTabsResult => ({
...positionInventory(null, 1),
tabs: omit
? []
: rows.map((tab) => ({
type: 'agent-session',
id: tab.id,
sessionId: tab.entityId,
agent: 'claude',
title,
isActive: false
}))
})
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
const layout = publishedLayoutsOf(layoutApplyTestTransport.mainModel!)['wt-1']!
const emit = (next: typeof layout) =>
layoutApplyTestTransport.emitFrame({ type: 'workspace', key: 'wt-1', layout: next })
const identical = await measure(() => emit(layout))
expect(identical.retire).toBe(0)
const titled = {
...layout,
tabs: layout.tabs.map((tab) => ({ ...tab, customTitle: 'title' }))
}
const titles = await measure(() => emit(titled))
expect(titles.retire).toBe(0)
const removed = { ...titled, tabs: [], groups: [] }
const removal = await measure(() => emit(removed))
expect(removal).toMatchObject({ before: n, after: 0, maps: 1, retire: n })
const duplicate = await measure(() => emit(removed))
expect(duplicate.retire).toBe(0)
} else {
let version = 1
const publish = (snapshot: RuntimeMobileSessionTabsResult) =>
applyStructuredSessionTabSnapshots([{ ...snapshot, snapshotVersion: version++ }])
const first = await measure(() => publish(inventories()))
expect(first.retire).toBe(0)
const identical = await measure(() => publish(inventories()))
expect(identical.retire).toBe(0)
const titles = await measure(() => publish(inventories('title')))
expect(titles.retire).toBe(0)
const removal = await measure(() => publish(inventories('title', true)))
expect(removal).toMatchObject({ before: n, after: 0, maps: 1, retire: n })
const duplicate = await measure(() => publish(inventories('title', true)))
expect(duplicate.retire).toBe(0)
}
compare.mockRestore()
retire.mockRestore()
}
)
it.runIf(ORCA_LAYOUT_OWNER_IS_MAIN)(
'parks a live fresh destination across group/title changes and cache unpublish until actual attachment',
async () => {
const handle = openPositionDraft(),
scope = structuredAgentSessionDraftScopeKey(handle.sessionId)
await handle.finish()
const original = readNativeChatComposerDraft(scope)
const layout = publishedLayoutsOf(layoutApplyTestTransport.mainModel!)['wt-1']!
const moved = {
...layout,
groupLayout: undefined,
groups: [{ id: 'moved-group', tabIds: layout.tabs.map((tab) => tab.id) }],
tabs: layout.tabs.map((tab) => ({ ...tab, customTitle: 'renamed' }))
}
layoutApplyTestTransport.emitFrame({ type: 'workspace', key: 'wt-1', layout: moved })
await main.settle()
expect(useAppStore.getState().getTab(handle.tab.id)?.groupId).toBe('moved-group')
layoutApplyTestTransport.emitFrame({ type: 'removed', key: 'wt-1' })
await main.settle()
expect(useAppStore.getState().getTab(handle.tab.id)?.entityId).toBe(handle.sessionId)
// ast-grep-ignore: test-no-real-time-wait-tsx -- Attach the still-live destination after the former 1s expiry.
await new Promise((resolve) => setTimeout(resolve, 1050))
const input = createRef<NativeChatComposerInput>()
const view = render(
<StrictMode>
<PositionField scope={scope} tabId={handle.tab.id} input={input} />
</StrictMode>
)
expect(input.current!.selectionStart).toBe(POSITION_TEXT.length)
expect(input.current!.value).toBe(POSITION_TEXT)
expect(readNativeChatComposerDraft(scope)).toBe(original)
view.unmount()
}
)
it.runIf(!ORCA_LAYOUT_OWNER_IS_MAIN)(
'uses one addressed retirement for actual local close and makes a duplicate close inert',
async () => {
const handle = openPositionDraft()
await handle.finish()
const compare = vi.spyOn(draftCache, 'retireRemovedNativeChatDraftPositions')
useAppStore.getState().closeUnifiedTab(handle.tab.id)
expect(compare.mock.calls.map(([before, after]) => [before.length, after.length])).toEqual([
[1, 0]
])
compare.mockClear()
expect(useAppStore.getState().closeUnifiedTab(handle.tab.id)).toBeNull()
expect(compare).not.toHaveBeenCalled()
}
)
@@ -0,0 +1,211 @@
import { resetLocalStructuredSessionVersionForTests } from '@/runtime/local-structured-session-tabs-sync/inventory-generation-fence'
import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-types'
import type { createRef } from 'react'
import {
NativeChatComposerField,
type NativeChatComposerFieldProps
} from '@/components/native-chat/NativeChatComposerField'
import type { NativeChatComposerInput } from '@/components/native-chat/native-chat-composer-input'
import { useImeEnterGestureOwnership } from '@/lib/ime-composition-keyboard-event'
import { TooltipProvider } from '@/components/ui/tooltip'
import { afterEach, beforeEach, vi } from 'vitest'
import { useAppStore } from '@/store/index'
import type * as structuredSessionClient from '@/runtime/structured-agent-session-client'
import { adoptAgentSessionLaunchVerdict } from '../agent-session-launch-plan'
import { beginStructuredAgentSessionProvisionalLaunch } from './structured-agent-session-provisional-tab'
import { resetStructuredAgentLaunchRegistryForTests } from './launch/structured-agent-session-launch-registry'
import {
drawTabsFromMain,
type TabsDrawnFromMain
} from '@/store/slices/tabs-drawn-from-main.test-fixture'
import {
clearNativeChatComposerDraftsForTests,
hydrateNativeChatComposerDrafts
} from '@/components/native-chat/native-chat-composer-draft-store'
import {
createMemoryNativeChatComposerDraftStorage,
setNativeChatComposerDraftStorageForTests
} from '@/components/native-chat/native-chat-composer-draft-storage'
import { clearNativeChatPendingAttachmentsForTests } from '@/components/native-chat/native-chat-pending-attachment-cache'
import { useNativeChatDraft } from '@/components/native-chat/use-native-chat-draft'
const rpcMock = vi.hoisted(() => ({
call: vi.fn<(target: unknown, method: string, params: unknown) => Promise<unknown>>()
}))
export const rpc = rpcMock
vi.mock('@/runtime/runtime-rpc-client', async (original) =>
(
await import('@/runtime/layout-apply-test-transport.test-fixture')
).runtimeRpcClientWithLayoutApply(await original())
)
vi.mock('@/runtime/runtime-layout-client', async (original) =>
(
await import('@/runtime/layout-apply-test-transport.test-fixture')
).runtimeLayoutClientWithTestFrames(await original())
)
vi.mock('@/runtime/structured-agent-session-client', async (original) => ({
...(await original<typeof structuredSessionClient>()),
callStructuredAgentSession: rpcMock.call,
supportsStructuredAgentSessionCreateMessage: async () => false
}))
vi.mock('@/runtime/structured-session-tab-inventory', () => ({
readStructuredSessionTabInventory: async () => []
}))
vi.mock('sonner', () => ({ toast: { info: vi.fn(), error: vi.fn() } }))
export let main: TabsDrawnFromMain
export let storage: ReturnType<typeof createMemoryNativeChatComposerDraftStorage>
beforeEach(async () => {
vi.clearAllMocks()
localStorage.clear()
clearNativeChatComposerDraftsForTests()
clearNativeChatPendingAttachmentsForTests()
resetStructuredAgentLaunchRegistryForTests()
resetLocalStructuredSessionVersionForTests()
storage = createMemoryNativeChatComposerDraftStorage()
setNativeChatComposerDraftStorageForTests(storage)
await hydrateNativeChatComposerDrafts()
useAppStore.setState({
activeWorktreeId: 'wt-1',
unifiedTabsByWorktree: {},
groupsByWorktree: {},
activeGroupIdByWorktree: {},
tabsByWorktree: {},
tabBarOrderByWorktree: {}
})
main = await drawTabsFromMain(useAppStore)
})
const pendingPositions: { cancel(): void; finish(): Promise<void> }[] = []
afterEach(async () => {
for (const pending of pendingPositions.splice(0)) {
pending.cancel()
await pending.finish()
}
vi.restoreAllMocks()
main.close()
})
export const POSITION_TEXT = 'Hand Off\ncontext '
export function openPositionDraft() {
const creation = Promise.withResolvers<unknown>()
rpc.call.mockImplementation((_target, method) =>
method === 'agentSession.create'
? creation.promise
: Promise.resolve({ ok: true, supported: true })
)
const plan = adoptAgentSessionLaunchVerdict({
requestId: 'position',
route: 'structured-native-chat',
agent: 'claude',
worktreeId: 'wt-1',
executionHostId: 'local',
prompt: POSITION_TEXT,
promptDelivery: 'draft'
})
const handle = beginStructuredAgentSessionProvisionalLaunch({
plan,
hooks: {},
focusIntent: { request: vi.fn(), cancel: vi.fn() }
})
if (!handle?.tab) {
throw new Error('Expected destination')
}
const finish = async () => {
creation.resolve({
ok: true,
value: { sessionId: handle.sessionId, fence: 1, page: { submissions: [] } }
})
await handle.settlement
await main.settle()
}
pendingPositions.push({ cancel: handle.cancel, finish })
return { ...handle, finish }
}
export function PositionField({
scope,
input,
tabId = 'ordinary',
disabled = false
}: {
scope: string
input: ReturnType<typeof createRef<NativeChatComposerInput>>
tabId?: string
disabled?: boolean
}) {
const ime = useImeEnterGestureOwnership()
const draft = useNativeChatDraft(scope, ime.isComposing)
const noop = () => {}
const props: NativeChatComposerFieldProps = {
draftScopeKey: scope,
textareaRef: input,
draft: draft.draft,
disabled,
hasPty: false,
canSend: false,
autocomplete: { mode: 'none' },
mentionFiles: { files: [], loading: false, failed: false },
activeSuggestion: 0,
notices: [],
imageAttachments: [],
sendButtonDisabled: true,
isWorking: false,
attachDisabled: true,
dictationDisabled: true,
isDictating: false,
isDictationHoldMode: false,
imeEnterGesture: ime,
onDraftChange: (value) => draft.setDraft(value),
onTextareaSelect: noop,
onKeyDown: noop,
onImeSettled: (element) => {
draft.setDraft(element.value)
draft.flushDraftAppends()
},
onPaste: noop,
pickerListboxId: 'position',
onChoosePickerItem: noop,
onRetrySkills: noop,
onChooseMentionFile: noop,
onRemoveImageAttachment: noop,
onAttach: noop,
onDictationToggle: noop,
onDictationHoldStart: noop,
onDictationHoldEnd: noop,
onSend: noop,
sessionOptionsSurface: null,
sessionOptionsSnapshot: []
}
return (
<TooltipProvider>
<NativeChatComposerField {...props} positionTarget={tabId} />
</TooltipProvider>
)
}
export function positionInventory(
sessionId: string | null,
version: number
): RuntimeMobileSessionTabsResult {
return {
worktree: 'wt-1',
publicationEpoch: 'position-epoch',
snapshotVersion: version,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: sessionId
? [
{
type: 'agent-session',
id: `agent-session:${sessionId}`,
sessionId,
agent: 'claude',
title: 'Chat',
isActive: false
}
]
: []
}
}
export async function startPositionMain() {
main = await drawTabsFromMain(useAppStore)
}
@@ -0,0 +1,606 @@
// @vitest-environment happy-dom
import {
rpc,
main,
storage,
POSITION_TEXT,
openPositionDraft,
PositionField
} from './structured-agent-session-draft-position.test-fixture'
import { act, render, renderHook, within, fireEvent } from '@testing-library/react'
import { createRef, StrictMode } from 'react'
import type { NativeChatComposerInput } from '@/components/native-chat/native-chat-composer-input'
import { promptEditor } from '@/components/native-chat/native-chat-prompt-editor.test-support'
import { appendNativeChatDraftCache } from '@/components/native-chat/native-chat-draft-cache'
import { expect, it, vi } from 'vitest'
import { useAppStore } from '@/store/index'
import { adoptAgentSessionLaunchVerdict } from '../agent-session-launch-plan'
import { beginStructuredAgentSessionProvisionalLaunch } from './structured-agent-session-provisional-tab'
import {
getStructuredLaunchStateBySessionId,
hasStructuredAgentSessionLaunchCancellationTombstone
} from './launch/structured-agent-session-launch-registry'
import { hasStagedStructuredLaunchPrompt } from '../structured-agent-session-launch-prompt'
import { wasStructuredAgentLaunchClosedByLocalCancel } from '../structured-agent-session-local-launch-cancel'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch'
import {
clearNativeChatComposerDraftsForTests,
flushNativeChatComposerDrafts,
hydrateNativeChatComposerDrafts,
nativeChatComposerDraftWritesSettled,
readNativeChatComposerDraft,
structuredAgentSessionDraftScopeKey,
updateNativeChatComposerDraft
} from '@/components/native-chat/native-chat-composer-draft-store'
import { setNativeChatComposerDraftStorageForTests } from '@/components/native-chat/native-chat-composer-draft-storage'
import {
addNativeChatPendingAttachment,
nativeChatPendingAttachmentSnapshot
} from '@/components/native-chat/native-chat-pending-attachment-cache'
import { promptTextContent } from '@/components/native-chat/native-chat-prompt-document-text'
import { useNativeChatDraft } from '@/components/native-chat/use-native-chat-draft'
import { openStructuredAgentSessionProvisionalTab } from '../structured-agent-session-launch-surface'
import { structuredAgentSessionTabId } from '../../../../shared/structured-agent-session-projection'
import {
handBackStructuredAgentSessionMessage,
returnMessageToComposer
} from '@/components/native-chat/structured-agent-session-message-hand-back'
import { CreateIntentParams } from '../../../../shared/rpc-contract/structured-agent-session-params'
it.each(['close', 'cancel', 'abort', 'edited-close'] as const)(
'keeps a nonresume Hand Off through actual %s and late create settlement',
async (action) => {
const creation = Promise.withResolvers<unknown>()
rpc.call.mockImplementation((_target, method) => {
if (method === 'agentSession.create') {
return creation.promise
}
if (method === 'agentSession.createSupport') {
return Promise.resolve({ supported: true })
}
if (method === 'agentSession.close') {
return Promise.resolve({ ok: true })
}
throw new Error(`Unexpected provider operation ${method}`)
})
const controller = new AbortController()
const text = 'Hand Off context\nwith exact trailing bytes '
const plan = adoptAgentSessionLaunchVerdict({
requestId: `early-${action}`,
route: 'structured-native-chat',
agent: 'claude',
worktreeId: 'wt-1',
executionHostId: 'local',
prompt: text,
promptDelivery: 'draft'
})
const handle = beginStructuredAgentSessionProvisionalLaunch({
plan,
hooks: { signal: controller.signal },
focusIntent: { request: vi.fn(), cancel: vi.fn() }
})
if (!handle?.tab) {
throw new Error('Expected a provisional source')
}
const { tab } = handle
const scope = structuredAgentSessionDraftScopeKey(handle.sessionId)
await main.settle()
await vi.waitFor(() =>
expect(rpc.call.mock.calls.some(([, method]) => method === 'agentSession.create')).toBe(true)
)
const params = CreateIntentParams.parse(
rpc.call.mock.calls.find(([, method]) => method === 'agentSession.create')?.[2]
)
expect(params.resumeFrom).toBeUndefined()
expect(params.firstMessage).toBeUndefined()
expect(hasStagedStructuredLaunchPrompt(handle.sessionId)).toBe(false)
expect(readNativeChatComposerDraft(scope)).toMatchObject({
text,
document: promptTextContent(text),
owner: { workspaceId: 'wt-1', executionHostId: 'local' }
})
const edited = action === 'edited-close'
const expectedText = edited ? 'my later text' : text
const expectedDocument = edited
? { ...promptTextContent(expectedText), attrs: { edited: true } }
: promptTextContent(text)
if (edited) {
updateNativeChatComposerDraft(
scope,
{
text: expectedText,
document: expectedDocument,
images: [{ id: 'kept', path: '/repo/kept.png' }]
},
'immediate'
)
addNativeChatPendingAttachment(scope, { id: 'pending', path: '', pending: true })
}
if (action === 'cancel') {
handle.cancel()
} else if (action === 'abort') {
controller.abort()
} else {
useAppStore.getState().closeUnifiedTab(tab.id)
}
await main.settle()
const remainingIds = (useAppStore.getState().unifiedTabsByWorktree['wt-1'] ?? []).map(
(row) => row.id
)
expect(readNativeChatComposerDraft(scope).text).toBe(expectedText)
expect(readNativeChatComposerDraft(scope).document).toEqual(expectedDocument)
expect(
ORCA_LAYOUT_OWNER_IS_MAIN
? wasStructuredAgentLaunchClosedByLocalCancel(handle.sessionId)
: hasStructuredAgentSessionLaunchCancellationTombstone('wt-1', handle.sessionId)
).toBe(true)
creation.resolve({
ok: true,
value: { sessionId: handle.sessionId, fence: 1, page: { submissions: [] } }
})
expect((await handle.settlement).kind).not.toBe('structured')
await main.settle()
expect(getStructuredLaunchStateBySessionId(handle.sessionId)).toBeUndefined()
expect(
(useAppStore.getState().unifiedTabsByWorktree['wt-1'] ?? []).map((row) => row.id)
).toEqual(remainingIds)
if (action.endsWith('close')) {
expect(useAppStore.getState().getTab(tab.id)).toBeNull()
}
expect(
rpc.call.mock.calls.filter(([, method]) => method === 'agentSession.create')
).toHaveLength(1)
expect(
rpc.call.mock.calls.every(
([, method]) =>
method === 'agentSession.create' ||
method === 'agentSession.close' ||
method === 'agentSession.createSupport'
)
).toBe(true)
if (edited) {
expect(nativeChatPendingAttachmentSnapshot(scope)).toHaveLength(1)
}
await nativeChatComposerDraftWritesSettled()
expect(storage.drafts.get(scope)).toMatchObject({
text: expectedText,
document: expectedDocument,
owner: { workspaceId: 'wt-1', executionHostId: 'local' }
})
clearNativeChatComposerDraftsForTests()
setNativeChatComposerDraftStorageForTests(storage)
await hydrateNativeChatComposerDrafts()
const reader = renderHook(() => useNativeChatDraft(scope, () => false))
expect(reader.result.current.draft).toBe(expectedText)
expect(readNativeChatComposerDraft(scope).document).toEqual(expectedDocument)
if (edited) {
expect(readNativeChatComposerDraft(scope).images).toEqual([
{ id: 'kept', path: '/repo/kept.png' }
])
}
reader.unmount()
await act(async () => {})
}
)
it.each(['before', 'mounted', 'delayed-disabled', 'metadata', 'ordinary', 'replaced'] as const)(
'installs the exact production draft and native position under StrictMode: %s',
async (schedule) => {
const input = createRef<NativeChatComposerInput>()
let scope = 'agent-session:ordinary-position',
tabId = 'ordinary'
let view: ReturnType<typeof render> | undefined
const mount = () =>
render(
<StrictMode>
<div hidden={schedule === 'delayed-disabled'}>
<PositionField
scope={scope}
input={input}
tabId={tabId}
disabled={schedule === 'delayed-disabled'}
/>
</div>
</StrictMode>
)
if (schedule === 'mounted') {
const uuid = '11111111-2222-4333-8444-555555555555'
vi.spyOn(crypto, 'randomUUID').mockReturnValue(uuid)
const id = `claude_${uuid.replaceAll('-', '_')}`
scope = structuredAgentSessionDraftScopeKey(id)
tabId = structuredAgentSessionTabId(id)
view = mount()
await act(async () => {
openPositionDraft()
await main.settle()
})
} else if (schedule === 'ordinary') {
updateNativeChatComposerDraft(
scope,
{ text: POSITION_TEXT, document: promptTextContent(POSITION_TEXT) },
'immediate'
)
} else {
const handle = openPositionDraft()
scope = structuredAgentSessionDraftScopeKey(handle.sessionId)
tabId = handle.tab.id
if (schedule === 'metadata') {
updateNativeChatComposerDraft(
scope,
{ images: [{ id: 'image', path: '/image.png' }] },
'immediate'
)
}
if (schedule === 'replaced') {
updateNativeChatComposerDraft(
scope,
{ text: `${POSITION_TEXT}changed`, document: undefined },
'immediate'
)
}
if (schedule === 'delayed-disabled') {
// ast-grep-ignore: test-no-real-time-wait-tsx -- Cross the former 1s expiry before hidden/disabled attachment.
await new Promise((resolve) => setTimeout(resolve, 1050))
}
}
view ??= mount()
const expected = schedule === 'replaced' ? `${POSITION_TEXT}changed` : POSITION_TEXT
const end = !['ordinary', 'replaced'].includes(schedule)
expect(input.current!.value).toBe(expected)
expect([input.current!.selectionStart, input.current!.selectionEnd]).toEqual(
end ? [expected.length, expected.length] : [0, 0]
)
const editor = promptEditor(within(view.container).getByRole('textbox', { hidden: true }))
expect(editor.state.selection.from).toBe(end ? editor.state.doc.content.size - 1 : 1)
if (schedule !== 'delayed-disabled') {
act(() => input.current!.insertText!('!'))
expect(input.current!.value).toBe(end ? `${expected}!` : `!${expected}`)
}
act(() => input.current!.setSelectionRange(2, 5))
view.rerender(
<StrictMode>
<div>
<PositionField scope={scope} input={input} tabId={tabId} />
</div>
</StrictMode>
)
act(() => input.current!.focus())
expect([input.current!.selectionStart, input.current!.selectionEnd]).toEqual([2, 5])
view.unmount()
}
)
it.each(['plain', 'rich', 'append'] as const)(
'delivers a genuinely late saved load without taking newer ownership: %s',
async (kind) => {
const scope = 'agent-session:late-position',
input = createRef<NativeChatComposerInput>()
clearNativeChatComposerDraftsForTests()
const loaded = Promise.withResolvers<ReadonlyMap<string, unknown>>()
setNativeChatComposerDraftStorageForTests({ ...storage, loadAll: () => loaded.promise })
const loading = hydrateNativeChatComposerDrafts()
const view = render(
<StrictMode>
<PositionField scope={scope} input={input} />
</StrictMode>
)
const field = within(view.container).getByRole('textbox')
if (kind === 'append') {
act(() => appendNativeChatDraftCache(scope, 'newer'))
}
// ast-grep-ignore: test-no-real-time-wait-tsx -- Release the actual saved load after the 1500ms startup wait.
await new Promise((resolve) => setTimeout(resolve, 1550))
const document =
kind === 'rich'
? {
type: 'doc',
content: [
{
type: 'paragraph',
content: [
{ type: 'nativeChatSkill', attrs: { token: '$review', path: '/review' } },
{ type: 'text', text: ' context ' }
]
}
]
}
: undefined
const text =
kind === 'rich'
? '$review context '
: kind === 'append'
? 'Hand Off\ncontext'
: POSITION_TEXT
await act(async () => {
loaded.resolve(
new Map([[scope, { text, images: [], savedAt: 1, ...(document ? { document } : {}) }]])
)
await loading
})
if (kind === 'plain' || kind === 'rich') {
expect(input.current!.value).toBe(text)
expect([input.current!.selectionStart, input.current!.selectionEnd]).toEqual([0, 0])
if (document) {
expect(promptEditor(field).getJSON()).toEqual(document)
}
} else if (kind === 'append') {
expect(input.current!.value).toBe(`${text}\n\nnewer`)
expect(input.current!.selectionStart).toBeGreaterThan(0)
}
view.unmount()
}
)
it.each(['close-before-attach', 'consumed-remount', 'sibling-first'] as const)(
'uses the actual destination lifetime without changing its ordinary draft: %s',
async (schedule) => {
const handle = openPositionDraft(),
scope = structuredAgentSessionDraftScopeKey(handle.sessionId)
await main.settle()
await vi.waitFor(() =>
expect(rpc.call.mock.calls.some(([, method]) => method === 'agentSession.create')).toBe(true)
)
await handle.finish()
const original = readNativeChatComposerDraft(scope)
const input = createRef<NativeChatComposerInput>()
const mount = (tabId = handle.tab.id) =>
render(
<StrictMode>
<PositionField scope={scope} input={input} tabId={tabId} />
</StrictMode>
)
if (schedule === 'close-before-attach') {
useAppStore.getState().closeUnifiedTab(handle.tab.id)
await main.settle()
openStructuredAgentSessionProvisionalTab({
worktreeId: 'wt-1',
executionHostId: 'local',
sessionId: handle.sessionId,
agent: 'claude'
})
await main.settle()
expect(useAppStore.getState().getTab(handle.tab.id)?.entityId).toBe(handle.sessionId)
} else if (schedule === 'consumed-remount') {
const first = mount()
expect(input.current!.selectionStart).toBe(POSITION_TEXT.length)
first.unmount()
} else {
const sibling = mount('other-tab')
expect(input.current!.selectionStart).toBe(0)
sibling.unmount()
}
const view = mount()
expect(input.current!.value).toBe(POSITION_TEXT)
expect(input.current!.selectionStart).toBe(
schedule === 'sibling-first' ? POSITION_TEXT.length : 0
)
expect(readNativeChatComposerDraft(scope)).toBe(original)
view.unmount()
}
)
it.each(['range', 'edit', 'ime'] as const)(
'keeps substantive native %s ahead of a held saved load and permits another restored editor',
async (kind) => {
const scope = 'agent-session:user-before-load',
input = createRef<NativeChatComposerInput>(),
other = createRef<NativeChatComposerInput>()
clearNativeChatComposerDraftsForTests()
const loaded = Promise.withResolvers<ReadonlyMap<string, unknown>>()
setNativeChatComposerDraftStorageForTests({ ...storage, loadAll: () => loaded.promise })
const loading = hydrateNativeChatComposerDrafts()
const first = render(
<StrictMode>
<PositionField scope={scope} input={input} />
</StrictMode>
)
const field = within(first.container).getByRole('textbox')
await storage.write(scope, { text: 'typed before load', images: [], savedAt: 1 })
const channel = new BroadcastChannel('orca-native-chat-composer-drafts')
channel.postMessage({ scopeKey: scope })
await act(async () => {
await vi.waitFor(() => expect(input.current!.value).toBe('typed before load'))
})
channel.close()
if (kind !== 'range') {
act(() => {
input.current!.setSelectionRange(0, 0)
input.current!.insertText!('!')
})
}
act(() => input.current!.setSelectionRange(2, 5))
const before = promptEditor(field).getJSON()
const saved = {
text: POSITION_TEXT,
images: [],
savedAt: 1,
document: promptTextContent(POSITION_TEXT)
}
await act(async () => {
loaded.resolve(
new Map([
[scope, saved],
['agent-session:eligible', saved]
])
)
await loading
})
if (kind === 'ime') {
fireEvent.compositionEnd(field, { data: 'typed' })
}
expect(input.current!.value).toBe(kind === 'range' ? POSITION_TEXT : '!typed before load')
expect(promptEditor(field).getJSON()).toEqual(
kind === 'range' ? promptTextContent(POSITION_TEXT) : before
)
expect([input.current!.selectionStart, input.current!.selectionEnd]).toEqual([2, 5])
first.unmount()
const eligible = render(
<StrictMode>
<PositionField scope="agent-session:eligible" input={input} />
<PositionField scope="agent-session:eligible" input={other} />
</StrictMode>
)
expect([input.current!.selectionStart, other.current!.selectionStart]).toEqual([0, 0])
act(() => input.current!.setSelectionRange(2, 5))
expect([input.current!.selectionStart, input.current!.selectionEnd]).toEqual([2, 5])
expect(other.current!.selectionStart).toBe(0)
eligible.unmount()
const remount = render(<PositionField scope={scope} input={input} />)
expect(input.current!.value).toBe(kind === 'range' ? POSITION_TEXT : '!typed before load')
expect(input.current!.selectionStart).toBe(0)
remount.unmount()
}
)
it('uses actual no-focus Hand Off host admission, seed, open and create settlement without reauthoring on repeat', async () => {
const creation = Promise.withResolvers<unknown>()
rpc.call.mockImplementation((_target, method) =>
Promise.resolve(
method === 'agentSession.createSupport'
? { supported: true }
: method === 'agentSession.create'
? creation.promise
: { ok: true }
)
)
const plan = adoptAgentSessionLaunchVerdict({
requestId: 'no-focus',
route: 'structured-native-chat',
agent: 'claude',
worktreeId: 'wt-1',
executionHostId: 'local',
prompt: POSITION_TEXT,
promptDelivery: 'draft'
})
const launch = beginStructuredAgentSessionProvisionalLaunch({ plan, hooks: {} })
if (!launch) {
throw new Error('Expected admission')
}
expect(launch.tab).toBeNull()
await vi.waitFor(() =>
expect(rpc.call.mock.calls.some(([, method]) => method === 'agentSession.create')).toBe(true)
)
const params = CreateIntentParams.parse(
rpc.call.mock.calls.find(([, method]) => method === 'agentSession.create')?.[2]
)
expect(params.firstMessage).toBeUndefined()
const tab = (useAppStore.getState().unifiedTabsByWorktree['wt-1'] ?? []).find(
(tab) => tab.contentType === 'agent-session'
)
if (!tab) {
throw new Error('Expected admitted tab')
}
creation.resolve({
ok: true,
value: { sessionId: tab.entityId, fence: 1, page: { submissions: [] } }
})
await launch.settlement
await main.settle()
const scope = structuredAgentSessionDraftScopeKey(tab.entityId),
original = readNativeChatComposerDraft(scope),
input = createRef<NativeChatComposerInput>()
const mount = () =>
render(
<StrictMode>
<PositionField scope={scope} tabId={tab.id} input={input} />
</StrictMode>
)
const first = mount()
expect(input.current!.value).toBe(POSITION_TEXT)
expect(input.current!.selectionStart).toBe(POSITION_TEXT.length)
act(() => input.current!.setSelectionRange(2, 5))
openStructuredAgentSessionProvisionalTab({
worktreeId: 'wt-1',
executionHostId: 'local',
sessionId: tab.entityId,
agent: 'claude'
})
await main.settle()
expect(readNativeChatComposerDraft(scope)).toBe(original)
expect([input.current!.selectionStart, input.current!.selectionEnd]).toEqual([2, 5])
first.unmount()
const second = mount()
expect(input.current!.selectionStart).toBe(0)
second.unmount()
expect(
rpc.call.mock.calls.filter(([, method]) => method === 'agentSession.createSupport')
).toHaveLength(2)
})
it('keeps genuine handback and foreign adoption on their ordinary native mapping', async () => {
const scope = 'agent-session:controls',
input = createRef<NativeChatComposerInput>()
updateNativeChatComposerDraft(scope, { text: 'original' }, 'immediate')
const view = render(
<StrictMode>
<PositionField scope={scope} input={input} />
</StrictMode>
)
act(() => input.current!.setSelectionRange(2, 5))
act(() =>
expect(
handBackStructuredAgentSessionMessage('controls', 'one', {
kind: 'message',
role: 'user',
blocks: [{ type: 'text', text: 'returned' }]
})
).toBe(true)
)
expect(input.current!.value).toBe('original\n\nreturned')
expect([input.current!.selectionStart, input.current!.selectionEnd]).toEqual([2, 5])
act(() =>
expect(returnMessageToComposer(scope, 'two', [{ type: 'text', text: 'second' }])).toBe(true)
)
expect(input.current!.value).toBe('original\n\nreturned\n\nsecond')
expect([input.current!.selectionStart, input.current!.selectionEnd]).toEqual([26, 26])
await nativeChatComposerDraftWritesSettled()
flushNativeChatComposerDrafts()
await nativeChatComposerDraftWritesSettled()
await storage.write(scope, { text: 'foreign replacement', images: [], savedAt: 100 })
const channel = new BroadcastChannel('orca-native-chat-composer-drafts')
channel.postMessage({ scopeKey: scope })
await act(async () => {
await vi.waitFor(() => expect(input.current!.value).toBe('foreign replacement'))
})
expect([input.current!.selectionStart, input.current!.selectionEnd]).toEqual([19, 19])
channel.close()
view.unmount()
})
it.each(['edit', 'ime'] as const)(
'lets genuine native %s win between accepted seed and actual adoption, without replay on remount',
async (kind) => {
const uuid = '11111111-2222-4333-8444-555555555555'
vi.spyOn(crypto, 'randomUUID').mockReturnValue(uuid)
const id = `claude_${uuid.replaceAll('-', '_')}`,
scope = structuredAgentSessionDraftScopeKey(id),
input = createRef<NativeChatComposerInput>()
const mount = () =>
render(
<StrictMode>
<PositionField scope={scope} tabId={structuredAgentSessionTabId(id)} input={input} />
</StrictMode>
)
const first = mount(),
field = within(first.container).getByRole('textbox')
await act(async () => {
openPositionDraft()
if (kind === 'ime') {
fireEvent.compositionStart(field)
}
input.current!.insertText!('native wins ')
input.current!.setSelectionRange(2, 5)
if (kind === 'ime') {
fireEvent.compositionEnd(field, { data: 'native wins ' })
}
await main.settle()
})
expect(input.current!.value).toBe('native wins ')
expect([input.current!.selectionStart, input.current!.selectionEnd]).toEqual([2, 5])
expect(promptEditor(field).getJSON()).toEqual(promptTextContent('native wins '))
first.unmount()
const second = mount()
expect(input.current!.value).toBe('native wins ')
expect(input.current!.selectionStart).toBe(0)
second.unmount()
}
)
@@ -0,0 +1,247 @@
import { expect, vi } from 'vitest'
import { useAppStore } from '@/store/index'
import type * as launchModule from '../structured-agent-session-launch-create-call'
import type { StructuredAgentLaunchHandle } from '../structured-agent-launch-settlement'
import type { OpenedAgentSessionTab } from '../structured-agent-session-tab-open-through-layout-owner'
import type { TabsDrawnFromMain } from '@/store/slices/tabs-drawn-from-main.test-fixture'
import { getStructuredLaunchStateBySessionId } from './launch/structured-agent-session-launch-registry'
import {
nativeChatComposerDraftWritesSettled,
readNativeChatComposerDraft,
structuredAgentSessionDraftScopeKey
} from '@/components/native-chat/native-chat-composer-draft-store'
import { promptTextContent } from '@/components/native-chat/native-chat-prompt-document-text'
import {
startStructuredAgentLaunch,
retryStructuredAgentSessionLaunch
} from '../structured-agent-session-launch'
import { trackStructuredLaunchConfirmationDeadline } from './launch/structured-agent-session-launch-prompt-outcome'
import { holdStructuredAgentSessionLaunchOption } from '../structured-agent-session-launch-options'
import * as sessionClient from '@/runtime/structured-agent-session-client'
import * as runtimeRpc from '@/runtime/runtime-rpc-client'
import { structuredSessionSelectionController } from '../structured-agent-session-selection-controller'
import type { SelectionOperation } from '../../../../shared/structured-agent-session-selection-operations'
import { structuredAgentSessionPayloadFingerprint } from '../../../../shared/structured-agent-session-mutation'
export async function assertProvisionalSelectionLifetime({
launch,
chat,
main,
accept,
launchCall
}: {
launch: Pick<StructuredAgentLaunchHandle, 'executionHostId' | 'settlement'>
chat: OpenedAgentSessionTab
main: Pick<TabsDrawnFromMain, 'settle'>
accept: (receipt: Awaited<ReturnType<typeof launchModule.launchStructuredAgentSession>>) => void
launchCall: ReturnType<typeof vi.fn>
}): Promise<void> {
const optionResponse = Promise.withResolvers<unknown>()
const optionCall = vi
.spyOn(sessionClient, 'callStructuredAgentSession')
.mockReturnValueOnce(optionResponse.promise)
const rpcCall = vi.spyOn(runtimeRpc, 'callRuntimeRpc')
const pending = getStructuredLaunchStateBySessionId(chat.entityId)
let controller: ReturnType<typeof structuredSessionSelectionController> | undefined
let operation: SelectionOperation | undefined
let pick: ReturnType<typeof holdStructuredAgentSessionLaunchOption> = null
let joined: ReturnType<typeof startStructuredAgentLaunch> | undefined
let optionAnswered = false
void optionResponse.promise.then(() => {
optionAnswered = true
})
const scope = structuredAgentSessionDraftScopeKey(chat.entityId)
const lateReply = { ok: true, value: { options: { model: 'picked' } } }
try {
await main.settle()
expect(useAppStore.getState().getTab(chat.id)?.entityId).toBe(chat.entityId)
if (!pending) {
throw new Error('Missing original pending launch')
}
const intent = pending.intent
const originalResult = pending.promise
pending.intent.createMessageSupport = true
controller = structuredSessionSelectionController(intent.target, chat.entityId, intent.agent)
pick = holdStructuredAgentSessionLaunchOption(chat.entityId, 'model', 'picked')
operation = controller.current('model')
if (!operation || !pick) {
throw new Error('Missing original held selection')
}
expect(operation.result).toBe(pick)
expect(operation).toMatchObject({
key: 'model',
value: 'picked',
model: 'picked',
transmitted: false
})
expect(operation.request).toBeUndefined()
expect(operation.outcome).toBeUndefined()
expect(controller.isCurrent()).toBe(true)
expect(controller.pending()).toEqual([operation])
expect(controller.isPending('model')).toBe(true)
expect(controller.pendingId()).toBe('model')
expect(controller.overlay()).toEqual({ model: 'picked' })
expect(optionAnswered).toBe(false)
joined = startStructuredAgentLaunch('wt-1', 'claude', {
requestId: 'after-success',
prompt: 'hand-off context',
promptDelivery: 'draft',
resumeFrom: { providerSessionId: 'prior-chat' }
})
expect(joined.joined).toBe(true)
expect(joined.sessionId).toBe(chat.entityId)
expect(joined.executionHostId).toBe(launch.executionHostId)
expect(joined.launchResult).toBe(originalResult)
expect(pending.intent).toBe(intent)
expect(getStructuredLaunchStateBySessionId(chat.entityId)).toBe(pending)
expect(launchCall).toHaveBeenCalledOnce()
expect(readNativeChatComposerDraft(scope).text).toBe('hand-off context')
expect(readNativeChatComposerDraft(scope).document).toEqual(
promptTextContent('hand-off context')
)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
trackStructuredLaunchConfirmationDeadline(pending, originalResult)
await vi.advanceTimersByTimeAsync(30_000)
expect(pending.visibilityUnknown).toBe(true)
expect(pending.callers.outcome).toBe('unknown')
expect(controller.current('model')).toBe(operation)
expect(controller.overlay()).toEqual({ model: 'picked' })
expect(operation.transmitted).toBe(false)
expect(operation.outcome).toBeUndefined()
expect(optionAnswered).toBe(false)
vi.useRealTimers()
accept({ sessionId: chat.entityId, fence: 1 })
expect(await launch.settlement).toMatchObject({
kind: 'structured',
sessionId: chat.entityId
})
expect(await originalResult).toEqual({ sessionId: chat.entityId, fence: 1 })
expect(await joined.launchResult).toEqual({ sessionId: chat.entityId, fence: 1 })
await main.settle()
expect(pending.visibilityUnknown).toBe(false)
expect(pending.callers.outcome).toBe('published')
expect(pending.hostListed).toBeUndefined()
expect(getStructuredLaunchStateBySessionId(chat.entityId)).toBeUndefined()
expect(controller.isCurrent()).toBe(true)
expect(controller.current('model')).toBe(operation)
expect(operation.result).toBe(pick)
expect(controller.pending()).toEqual([operation])
expect(controller.overlay()).toEqual({ model: 'picked' })
expect(operation.transmitted).toBe(true)
expect(operation.outcome).toBeUndefined()
const request = operation.request
if (!request) {
throw new Error('Original selection request was not dispatched')
}
const writes = optionCall.mock.calls.filter(([, method]) => method === 'agentSession.setOption')
expect(writes).toEqual([
[
{ kind: 'local' },
'agentSession.setOption',
{
envelope: {
sessionId: chat.entityId,
clientOperationId: expect.stringMatching(/^\d{13}-[0-9a-f]{32}$/),
expectedRuntimeFence: 1,
payloadFingerprint: structuredAgentSessionPayloadFingerprint({
method: 'agentSession.setOption',
sessionId: chat.entityId,
fields: { key: 'model', value: 'picked' }
})
},
key: 'model',
value: 'picked'
},
{}
]
])
expect(optionCall.mock.results[0]?.value).toBe(optionResponse.promise)
expect(retryStructuredAgentSessionLaunch('wt-1', chat.entityId)).toBe(false)
expect(getStructuredLaunchStateBySessionId(chat.entityId)).toBeUndefined()
expect(launchCall).toHaveBeenCalledOnce()
expect(controller.isCurrent()).toBe(true)
expect(controller.current('model')).toBe(operation)
expect(controller.overlay()).toEqual({ model: 'picked' })
useAppStore.getState().closeUnifiedTab(chat.id)
await main.settle()
expect(useAppStore.getState().getTab(chat.id)).toBeNull()
expect(controller.isCurrent()).toBe(false)
expect(await pick).toEqual({ kind: 'superseded' })
expect(operation.outcome).toEqual({ kind: 'superseded' })
await controller.drain()
expect(optionAnswered).toBe(false)
expect(controller.current('model')).toBeUndefined()
expect(controller.pending()).toEqual([])
expect(controller.isPending('model')).toBe(false)
expect(controller.pendingId()).toBeNull()
expect(controller.overlay()).toEqual({})
expect(controller.captureRead()).toEqual([])
expect(readNativeChatComposerDraft(scope).text).toBe('hand-off context')
expect(readNativeChatComposerDraft(scope).document).toEqual(
promptTextContent('hand-off context')
)
expect(operation.request).toBe(request)
optionResponse.resolve(lateReply)
await expect(request).rejects.toEqual(new Error('Conversation selection owner retired.'))
await optionResponse.promise
await pick
await controller.drain()
await Promise.allSettled(
[...optionCall.mock.results, ...rpcCall.mock.results].flatMap((result) =>
result.type === 'return' ? [result.value] : []
)
)
await main.settle()
await nativeChatComposerDraftWritesSettled()
expect(controller.isCurrent()).toBe(false)
expect(operation.outcome).toEqual({ kind: 'superseded' })
expect(controller.current('model')).toBeUndefined()
expect(controller.pending()).toEqual([])
expect(controller.overlay()).toEqual({})
expect(controller.captureRead()).toEqual([])
expect(useAppStore.getState().getTab(chat.id)).toBeNull()
expect(getStructuredLaunchStateBySessionId(chat.entityId)).toBeUndefined()
expect(launchCall).toHaveBeenCalledOnce()
expect(readNativeChatComposerDraft(scope).text).toBe('hand-off context')
expect(readNativeChatComposerDraft(scope).document).toEqual(
promptTextContent('hand-off context')
)
} finally {
vi.useRealTimers()
try {
try {
accept({ sessionId: chat.entityId, fence: 1 })
await Promise.allSettled([launch.settlement, pending?.promise, joined?.launchResult])
await main.settle()
} finally {
try {
if (useAppStore.getState().getTab(chat.id)) {
useAppStore.getState().closeUnifiedTab(chat.id)
}
await main.settle()
} finally {
optionResponse.resolve(lateReply)
await Promise.allSettled([
optionResponse.promise,
operation?.request,
operation?.result,
pick,
controller?.drain()
])
await Promise.allSettled(
[...optionCall.mock.results, ...rpcCall.mock.results].flatMap((result) =>
result.type === 'return' ? [result.value] : []
)
)
await main.settle()
await nativeChatComposerDraftWritesSettled()
}
}
} finally {
rpcCall.mockRestore()
optionCall.mockRestore()
}
}
}
@@ -10,13 +10,16 @@ import { act, renderHook } from '@testing-library/react'
import { useNativeChatProvisionalLaunch } from '@/components/native-chat/use-native-chat-provisional-launch'
import {
getStructuredAgentSessionLaunchFailure,
getStructuredLaunchStateBySessionId,
hasStructuredAgentSessionLaunchCancellationTombstone,
resetStructuredAgentLaunchRegistryForTests
} from './launch/structured-agent-session-launch-registry'
import { structuredSessionNotices } from '@/components/native-chat/native-chat-structured-session-notices'
import type { AgentTerminalLaunchCompletion } from '../structured-agent-session-launch-admission'
import {
addNativeChatPendingAttachment,
clearNativeChatPendingAttachmentsForTests
clearNativeChatPendingAttachmentsForTests,
nativeChatPendingAttachmentSnapshot
} from '@/components/native-chat/native-chat-pending-attachment-cache'
import { applyStructuredSessionTabSnapshots } from '@/runtime/local-structured-session-tabs-sync/snapshot-apply'
import { makeEmptyHostSnapshot } from '@/runtime/host-session-mirror-frame-fixtures'
@@ -42,18 +45,37 @@ vi.mock('@/runtime/runtime-layout-client', async (importOriginal) =>
).runtimeLayoutClientWithTestFrames(await importOriginal())
)
const mocks = vi.hoisted(() => ({ text: '', focus: vi.fn(), toast: vi.fn(), launch: vi.fn() }))
const mocks = vi.hoisted(() => ({ focus: vi.fn(), toast: vi.fn(), launch: vi.fn() }))
vi.mock('../structured-agent-session-launch-create-call', async (original) => ({
...(await original<typeof launchModule>()),
launchStructuredAgentSession: mocks.launch
}))
vi.mock('sonner', () => ({ toast: { info: mocks.toast, error: vi.fn() } }))
vi.mock('../focus-terminal-tab-surface', () => ({ focusTerminalTabSurface: vi.fn() }))
vi.mock('@/components/native-chat/native-chat-composer-draft-store', () => ({
readNativeChatComposerDraft: () => ({ text: mocks.text, images: [] }),
resolveNativeChatComposerDraftOwner: () => undefined,
structuredAgentSessionDraftScopeKey: (id: string) => `agent-session:${id}`
}))
import {
clearNativeChatComposerDraftsForTests,
hydrateNativeChatComposerDrafts,
nativeChatComposerDraftWritesSettled,
readNativeChatComposerDraft,
structuredAgentSessionDraftScopeKey,
updateNativeChatComposerDraft
} from '@/components/native-chat/native-chat-composer-draft-store'
import {
createMemoryNativeChatComposerDraftStorage,
setNativeChatComposerDraftStorageForTests
} from '@/components/native-chat/native-chat-composer-draft-storage'
import { restorePersistedStructuredLaunchState } from './launch/structured-agent-session-launch-reload'
import { promptTextContent } from '@/components/native-chat/native-chat-prompt-document-text'
import { useNativeChatDraft } from '@/components/native-chat/use-native-chat-draft'
import { wasStructuredAgentLaunchClosedByLocalCancel } from '../structured-agent-session-local-launch-cancel'
import {
startStructuredAgentLaunch,
retryStructuredAgentSessionLaunch
} from '../structured-agent-session-launch'
import { assertProvisionalSelectionLifetime } from './structured-agent-session-provisional-selection-lifetime.test-fixture'
import { layoutApplyTestTransport } from '@/runtime/layout-apply-test-transport.test-fixture'
import { openStructuredAgentSessionProvisionalTab } from '../structured-agent-session-launch-surface'
import { markStructuredAgentSessionLaunchPublished } from './launch/structured-agent-session-launch-publication'
function terminalRecord(id: string): TerminalTab {
return {
@@ -69,26 +91,41 @@ function terminalRecord(id: string): TerminalTab {
}
let refuse = (): void => {}
let accept: (receipt: Awaited<ReturnType<typeof launchModule.launchStructuredAgentSession>>) => void
function planSettlingAs(error: StructuredAgentSessionCreateRefusalError): AgentSessionLaunchPlan {
const refusal = new Promise<never>((_, reject) => {
function planSettlingAs(
error: StructuredAgentSessionCreateRefusalError,
prompt = 'hand-off context',
resume = false
): AgentSessionLaunchPlan {
const creation = new Promise<
Awaited<ReturnType<typeof launchModule.launchStructuredAgentSession>>
>((resolve, reject) => {
refuse = () => reject(error)
accept = resolve
})
mocks.launch.mockReturnValue(refusal)
mocks.launch.mockReturnValue(creation)
return adoptAgentSessionLaunchVerdict({
requestId: 'action',
route: 'structured-native-chat',
agent: 'claude',
worktreeId: 'wt-1',
executionHostId: 'local'
executionHostId: 'local',
prompt,
...(resume ? { resumeFrom: { providerSessionId: 'prior-chat' } } : {}),
promptDelivery: 'draft'
})
}
let main: TabsDrawnFromMain
let draftStorage: ReturnType<typeof createMemoryNativeChatComposerDraftStorage>
beforeEach(async () => {
vi.clearAllMocks()
mocks.text = ''
clearNativeChatComposerDraftsForTests()
draftStorage = createMemoryNativeChatComposerDraftStorage()
setNativeChatComposerDraftStorageForTests(draftStorage)
await hydrateNativeChatComposerDrafts()
resetStructuredAgentLaunchRegistryForTests()
clearNativeChatPendingAttachmentsForTests()
useAppStore.setState({
@@ -145,21 +182,38 @@ function groupOf(tabId: string): string {
return groupId
}
function openChat(requestedSurface?: 'chat') {
function openChat(
requestedSurface?: 'chat',
signal?: AbortSignal,
prompt = 'hand-off context',
resume = false
) {
let complete!: (value: AgentTerminalLaunchCompletion) => void
const completion = new Promise<AgentTerminalLaunchCompletion>((resolve) => {
complete = resolve
})
const fallback = vi.fn(() => ({ opened: true, completion }))
const launch = beginStructuredAgentSessionProvisionalLaunch({
plan: {
...planSettlingAs(new StructuredAgentSessionCreateRefusalError('no')),
requestedSurface
},
hooks: {},
focusIntent: { request: mocks.focus, cancel: vi.fn() },
onHostDeclined: fallback
})
const plan = {
...planSettlingAs(new StructuredAgentSessionCreateRefusalError('no'), prompt, resume),
requestedSurface
}
const resumed = resume ? plan.begin({ signal }) : null
const launch = resumed
? {
...resumed,
tab: openStructuredAgentSessionProvisionalTab({
worktreeId: 'wt-1',
executionHostId: resumed.executionHostId,
sessionId: resumed.sessionId,
agent: 'claude'
})
}
: beginStructuredAgentSessionProvisionalLaunch({
plan,
hooks: { signal },
focusIntent: { request: mocks.focus, cancel: vi.fn() },
onHostDeclined: fallback
})
const chat = launch?.tab
if (!chat) {
throw new Error('No immediate chat')
@@ -168,10 +222,257 @@ function openChat(requestedSurface?: 'chat') {
}
describe('a provisional structured chat tab', () => {
it.each(['before', 'after'] as const)(
'retains a draft initialized %s host publication through close and reopen',
async (order) => {
const { launch, chat } = openChat(
'chat',
undefined,
order === 'after' ? '' : 'hand-off context',
order === 'after'
)
await main.settle()
const scope = structuredAgentSessionDraftScopeKey(chat.entityId)
const pending = getStructuredLaunchStateBySessionId(chat.entityId)
expect(markStructuredAgentSessionLaunchPublished('wt-1', chat.entityId, 'ssh:other')).toBe(
false
)
expect(pending?.hostListed).not.toBe(true)
applyStructuredSessionTabSnapshots([
{
...makeEmptyHostSnapshot('wt-1'),
publicationEpoch: chat.entityId,
tabs: [
{
type: 'agent-session',
id: structuredAgentSessionTabId(chat.entityId),
sessionId: chat.entityId,
agent: 'claude',
title: 'Chat',
isActive: true
}
]
}
])
await main.settle()
expect(pending?.hostListed).toBe(true)
expect(pending?.callers.outcome).toBe('pending')
expect(useAppStore.getState().getTab(chat.id)).not.toBeNull()
const joined =
order === 'after'
? startStructuredAgentLaunch('wt-1', 'claude', {
requestId: 'later-action',
prompt: 'hand-off context',
promptDelivery: 'draft',
resumeFrom: { providerSessionId: 'prior-chat' }
})
: undefined
expect(joined?.joined ?? true).toBe(true)
expect(readNativeChatComposerDraft(scope).text).toBe('hand-off context')
useAppStore.getState().closeUnifiedTab(chat.id)
await main.settle()
expect(
ORCA_LAYOUT_OWNER_IS_MAIN
? wasStructuredAgentLaunchClosedByLocalCancel(chat.entityId)
: hasStructuredAgentSessionLaunchCancellationTombstone('wt-1', chat.entityId)
).toBe(true)
accept({ sessionId: chat.entityId, fence: 1 })
expect(pending?.cancelled).toBe(true)
expect((await launch.settlement).kind).not.toBe('structured')
await Promise.allSettled(joined ? [joined.launchResult] : [])
await main.settle()
expect(useAppStore.getState().getTab(chat.id)).toBeNull()
expect(getStructuredLaunchStateBySessionId(chat.entityId)).toBeUndefined()
await nativeChatComposerDraftWritesSettled()
expect(draftStorage.drafts.get(scope)?.text).toBe('hand-off context')
expect(draftStorage.drafts.get(scope)?.document).toEqual(
promptTextContent('hand-off context')
)
clearNativeChatComposerDraftsForTests()
setNativeChatComposerDraftStorageForTests(draftStorage)
await hydrateNativeChatComposerDrafts()
const reopened = useAppStore.getState().createUnifiedTab('wt-1', 'agent-session', {
entityId: chat.entityId
})
await main.settle()
const composer = renderHook(() =>
useNativeChatDraft(structuredAgentSessionDraftScopeKey(reopened.entityId), () => false)
)
expect(composer.result.current.draft).toBe('hand-off context')
composer.unmount()
}
)
it('joins pending launch before uncertainty, then normalizes own success with held picks, Retry and close', async () => {
const { launch, chat } = openChat('chat', undefined, '', true)
await assertProvisionalSelectionLifetime({
launch,
chat,
main,
accept,
launchCall: mocks.launch
})
})
it.each(['cancel', 'abort', 'close', 'reloaded-close', 'silent'] as const)(
'retains ordinary draft content during %s',
async (action) => {
const controller = new AbortController()
const { launch, chat } = openChat('chat', controller.signal)
await main.settle()
const scope = structuredAgentSessionDraftScopeKey(chat.entityId)
const text = action === 'cancel' ? 'new thought' : 'hand-off context'
const document =
action === 'close'
? { ...promptTextContent(text), attrs: { edited: true } }
: promptTextContent(text)
updateNativeChatComposerDraft(
scope,
{ text, document, images: [{ id: 'image', path: '/repo/image.png' }] },
'immediate'
)
addNativeChatPendingAttachment(scope, { id: 'pending', path: '', pending: true })
if (action === 'reloaded-close') {
await nativeChatComposerDraftWritesSettled()
clearNativeChatComposerDraftsForTests()
setNativeChatComposerDraftStorageForTests(draftStorage)
await hydrateNativeChatComposerDrafts()
resetStructuredAgentLaunchRegistryForTests()
expect(restorePersistedStructuredLaunchState('wt-1', chat.entityId)).toBeDefined()
}
if (action === 'cancel') {
launch.cancel()
} else if (action === 'abort') {
controller.abort()
} else if (action === 'silent') {
buildFullWorktreePurgeState(useAppStore.getState(), [{ id: 'wt-1' }])
} else {
useAppStore.getState().closeUnifiedTab(chat.id)
}
await main.settle()
expect(readNativeChatComposerDraft(scope)).toMatchObject({
text,
images: [{ id: 'image' }]
})
expect(readNativeChatComposerDraft(scope).document).toEqual(document)
expect(nativeChatPendingAttachmentSnapshot(scope)).toHaveLength(1)
refuse()
await launch.settlement
}
)
it
.skipIf(!ORCA_LAYOUT_OWNER_IS_MAIN)
.each([
'initializer',
'published',
'text',
'document',
'image',
'pending',
'pre-removed',
'retry',
'abort',
'source-closed',
'replacement-closed',
'unplaced'
])('revalidates terminal takeover after main placement: %s', async (change) => {
const controller = new AbortController()
const { launch, chat, fallback, complete } = openChat(
undefined,
controller.signal,
change === 'initializer' ? 'hand-off context' : ''
)
await main.settle()
const scope = structuredAgentSessionDraftScopeKey(chat.entityId)
if (change === 'pre-removed') {
updateNativeChatComposerDraft(scope, { text: 'keep before' }, 'immediate')
}
refuse()
await vi.waitFor(() => expect(fallback).toHaveBeenCalledOnce())
const terminal = useAppStore.getState().createUnifiedTab('wt-1', 'terminal', {
id: 'replacement',
activate: false,
split: { sourceGroupId: groupOf(chat.id), splitDirection: 'right', activate: false }
})
useAppStore.setState({ tabsByWorktree: { 'wt-1': [terminalRecord(terminal.entityId)] } })
await mainLoadsStoreLayout()
layoutApplyTestTransport.answerWith((command) =>
command.type === 'moveTab' ? 'pending' : 'apply'
)
complete({ outcome: { status: 'created' }, tabId: terminal.id })
await vi.waitFor(() => expect(layoutApplyTestTransport.pendingCount).toBe(1))
if (change === 'published') {
markStructuredAgentSessionLaunchPublished('wt-1', chat.entityId, 'local')
}
if (change === 'text') {
updateNativeChatComposerDraft(scope, { text: 'keep after', document: undefined }, 'immediate')
}
if (change === 'document') {
updateNativeChatComposerDraft(
scope,
{
text: 'hand-off context',
document: { ...promptTextContent('hand-off context'), attrs: { edited: true } }
},
'immediate'
)
}
if (change === 'image') {
updateNativeChatComposerDraft(
scope,
{ images: [{ id: 'image', path: '/repo/image.png' }] },
'immediate'
)
}
if (change === 'pending') {
addNativeChatPendingAttachment(scope, { id: 'pending', path: '', pending: true })
}
if (change === 'pre-removed') {
updateNativeChatComposerDraft(scope, { text: '', document: undefined }, 'immediate')
}
if (change === 'retry') {
expect(retryStructuredAgentSessionLaunch('wt-1', chat.entityId)).toBe(true)
}
if (change === 'abort') {
controller.abort()
}
if (change === 'source-closed') {
useAppStore.getState().closeUnifiedTab(chat.id)
}
if (change === 'replacement-closed') {
useAppStore.getState().closeUnifiedTab(terminal.id)
}
layoutApplyTestTransport.answerWith(
change === 'unplaced' ? { refuse: 'tab_not_found' } : 'apply'
)
layoutApplyTestTransport.answerPending()
const result = await launch.settlement
await main.settle()
expect(result.kind).not.toBe('terminal')
expect(readNativeChatComposerDraft(scope).text).toBe(
change === 'pre-removed'
? ''
: change === 'text'
? 'keep after'
: ['initializer', 'document'].includes(change)
? 'hand-off context'
: ''
)
if (change !== 'source-closed' && change !== 'abort') {
expect(useAppStore.getState().getTab(chat.id)).not.toBeNull()
}
})
it.each([
'empty',
'typed-before',
'typed-during',
'initializer',
'published-during',
'image-during',
'pending-chip',
'failed',
'unreconciled',
@@ -181,12 +482,15 @@ describe('a provisional structured chat tab', () => {
'away-during',
'closed-during'
])('owns the destination through terminal completion: %s', async (scenario) => {
if (scenario === 'typed-before') {
mocks.text = 'keep this'
}
const { launch, chat, fallback, complete } = openChat(
scenario === 'explicit' ? 'chat' : undefined
scenario === 'explicit' ? 'chat' : undefined,
undefined,
scenario === 'initializer' || scenario === 'explicit' ? 'hand-off context' : ''
)
const scope = structuredAgentSessionDraftScopeKey(chat.entityId)
if (scenario === 'typed-before') {
updateNativeChatComposerDraft(scope, { text: 'keep this', document: undefined }, 'immediate')
}
await main.settle()
expect(mocks.focus).toHaveBeenCalledWith(chat.id)
const view = renderHook(() => {
@@ -234,7 +538,7 @@ describe('a provisional structured chat tab', () => {
ORCA_LAYOUT_OWNER_IS_MAIN ? [terminalRecord(sibling.entityId)] : []
useAppStore.setState({ tabsByWorktree: { 'wt-1': siblingRecords() } })
await mainLoadsStoreLayout()
const pinnedSource = scenario === 'empty' || scenario === 'typed-during'
const pinnedSource = ['empty', 'typed-during', 'initializer'].includes(scenario)
if (pinnedSource) {
pinAsUser(chat.id)
pinAsUser(sibling.id)
@@ -243,7 +547,21 @@ describe('a provisional structured chat tab', () => {
useAppStore.getState().moveUnifiedTabToGroup(chat.id, groupId)
useAppStore.getState().reorderUnifiedTabs(groupId, [chat.id, sibling.id])
if (scenario === 'typed-during') {
mocks.text = 'new thought'
updateNativeChatComposerDraft(
scope,
{ text: 'new thought', document: undefined },
'immediate'
)
}
if (scenario === 'published-during') {
markStructuredAgentSessionLaunchPublished('wt-1', chat.entityId, 'local')
}
if (scenario === 'image-during') {
updateNativeChatComposerDraft(
scope,
{ images: [{ id: 'image', path: '/repo/image.png' }] },
'immediate'
)
}
if (scenario === 'pending-chip') {
addNativeChatPendingAttachment(`agent-session:${chat.entityId}`, {
@@ -291,6 +609,19 @@ describe('a provisional structured chat tab', () => {
await launch?.settlement
await main.settle()
})
if (scenario !== 'closed-during') {
expect(readNativeChatComposerDraft(scope).text).toBe(
['empty', 'away-before', 'away-during'].includes(scenario)
? ''
: scenario === 'typed-before'
? 'keep this'
: scenario === 'typed-during'
? 'new thought'
: scenario === 'initializer'
? 'hand-off context'
: ''
)
}
expect(interaction).not.toHaveBeenCalled()
const state = useAppStore.getState()
const tabs = state.unifiedTabsByWorktree['wt-1'] ?? []
@@ -300,11 +631,13 @@ describe('a provisional structured chat tab', () => {
if (terminal) {
const order = state.groupsByWorktree['wt-1']?.find((g) => g.id === groupId)?.tabOrder
expect(order).toEqual(
scenario === 'closed-during'
? [sibling.id, terminal.id]
: ['empty', 'away-before', 'away-during'].includes(scenario)
? [terminal.id, sibling.id]
: [chat.id, terminal.id, sibling.id]
scenario === 'published-during'
? [chat.id, sibling.id, terminal.id]
: scenario === 'closed-during'
? [sibling.id, terminal.id]
: ['empty', 'away-before', 'away-during'].includes(scenario)
? [terminal.id, sibling.id]
: [chat.id, terminal.id, sibling.id]
)
expect(mocks.toast).toHaveBeenCalledOnce()
expect(state.getTab(terminal.id)?.isPinned ?? false).toBe(pinnedSource)
@@ -355,7 +688,7 @@ describe('a provisional structured chat tab', () => {
// Hidden launch slots exist only in window order; count terminal position among tabs both window and main draw.
it("places a declined chat's terminal right after the chat past a hidden launch slot", async () => {
const { launch, chat, fallback, complete } = openChat()
const { launch, chat, fallback, complete } = openChat(undefined, undefined, '')
await main.settle()
refuse()
await vi.waitFor(() => expect(fallback).toHaveBeenCalled())
@@ -1,3 +1,10 @@
import {
readNativeChatComposerDraft,
structuredAgentSessionDraftScopeKey
} from '@/components/native-chat/native-chat-composer-draft-store'
import { nativeChatDraftPositions } from '@/components/native-chat/native-chat-composer-draft-memory'
import { structuredAgentSessionTabId } from '../../../../shared/structured-agent-session-projection'
import { afterPendingTab } from '@/runtime/layout-owner-pending-tabs'
import type { NativeChatComposerFocusIntent } from '@/components/native-chat/use-native-chat-composer-reveal-focus'
import type {
AgentSessionLaunchPlan,
@@ -192,8 +199,16 @@ function beginLocalProvisionalLaunch(
if (!worktreeId) {
throw new Error('A provisional structured launch needs its workspace.')
}
const draft = readNativeChatComposerDraft(structuredAgentSessionDraftScopeKey(handle.sessionId))
const position = nativeChatDraftPositions.get(draft)
const retirePosition = (target = structuredAgentSessionTabId(handle.sessionId)) => {
if (position?.at === 'end' && position.target === target) {
position.pending = false
}
}
try {
if (args.beforeOpen?.(handle.sessionId) === false) {
retirePosition()
handle.cancel()
return null
}
@@ -206,8 +221,14 @@ function beginLocalProvisionalLaunch(
...(args.afterTabId ? { afterTabId: args.afterTabId } : {}),
...(args.activate !== undefined ? { activate: args.activate } : {})
})
afterPendingTab(tab.id, (shown) => {
if (!shown || !useAppStore.getState().getTab(shown)) {
retirePosition(tab.id)
}
})
return { ...handle, tab }
} catch (error) {
retirePosition()
// Why: a launch without its owning surface would strand a late publication.
handle.cancel()
throw error
@@ -2,7 +2,6 @@
import {
mockCreateTab,
mockCreateUnifiedTab,
mockWaitForAgentReady,
mockPasteDraftWhenAgentReady,
mockCreateStructuredCodexSessionLaunchIntent,
@@ -13,304 +12,140 @@ import {
mockCallStructuredAgentSession,
mockCreateSupport,
structuredLaunchIntent,
store,
structuredLaunchErrorMocks,
setHostCapabilities
liveStore,
main
} from './launch-agent-structured-chat-test-fixture'
import type * as PickerMenu from '@/components/agent/AgentLaunchPickerMenu'
import type * as Dropdown from '@/components/ui/dropdown-menu'
import type * as Tooltip from '@/components/ui/tooltip'
import type * as QuickLaunch from '@/components/tab-bar/QuickLaunchButton'
import { createElement } from 'react'
import { cleanup, fireEvent, render } from '@testing-library/react'
import { buildNewTabAgentMenuRows } from '../../../shared/agent-launch-picker-rows'
import type * as StructuredLaunch from './launch-structured-agent-session'
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AppState } from '@/store/types'
import type { GlobalSettings } from '../../../shared/global-settings-types'
import { createGlobalSettingsFixture } from '../../../shared/global-settings-test-fixture'
import type { launchAgentInNewTab } from './launch-agent-in-new-tab'
import { makeUnifiedTab } from '@/store/slices/store-test-helpers'
import { layoutApplyTestTransport } from '@/runtime/layout-apply-test-transport.test-fixture'
import { isPendingTab } from '@/runtime/layout-owner-pending-tabs'
import {
resetStructuredAgentLaunchRegistryForTests,
getStructuredLaunchStateBySessionId
} from './agent-session/launch/structured-agent-session-launch-registry'
import { resetStructuredAgentLaunchPersistenceForTests } from './agent-session/launch/structured-agent-session-launch-persistence'
import * as capabilities from '@/runtime/local-runtime-capabilities'
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest'
const launchErrorMocks = structuredLaunchErrorMocks()
const mockCreateUnifiedTab = vi.fn<AppState['createUnifiedTab']>()
const mockSetTabViewMode = vi.fn<AppState['setTabViewMode']>()
const mockMarkNativeChatLaunchPromptFailed = vi.fn<AppState['markNativeChatLaunchPromptFailed']>()
const STRUCTURED_HOST_CAPABILITIES = ['agent-session.structured.v1'] as const
let hostCapabilities: ReturnType<typeof capabilities.readLocalRuntimeCapabilitiesOrUnknown> =
STRUCTURED_HOST_CAPABILITIES
const state = () => liveStore().getState()
function launchScenarioSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings {
return createGlobalSettingsFixture({
agentCmdOverrides: {},
agentDefaultArgs: {},
agentDefaultEnv: {},
activeRuntimeEnvironmentId: null,
experimentalNativeChat: true,
nativeChatSessionOptions: undefined,
agentPermissionDefault: undefined,
agentPermissionOverrides: undefined,
...overrides
})
}
let warnings: MockInstance<typeof console.warn>
const owned: ReturnType<typeof launchAgentInNewTab>[] = []
const lateCreates: (() => void)[] = []
// No initial chat mode proves availability rejection preceded terminal-tab adoption.
describe('structured chat adoption guard on the launch path', () => {
let restoreCatalogStore: (() => void) | undefined
beforeEach(async () => {
const { registerStructuredSelectionCatalogStore } =
await import('./structured-agent-session-selection-controller')
restoreCatalogStore = registerStructuredSelectionCatalogStore({
read: () => ({ ...store, runtimeEnvironmentCatalogHydrated: true }),
subscribe: () => () => {}
localStorage.clear()
resetStructuredAgentLaunchRegistryForTests()
resetStructuredAgentLaunchPersistenceForTests()
liveStore().setState({ settings: launchScenarioSettings() })
mockCreateUnifiedTab.mockImplementation(state().createUnifiedTab)
liveStore().setState({
createUnifiedTab: mockCreateUnifiedTab,
setTabViewMode: mockSetTabViewMode,
markNativeChatLaunchPromptFailed: mockMarkNativeChatLaunchPromptFailed
})
vi.spyOn(capabilities, 'readLocalRuntimeCapabilitiesOrUnknown').mockImplementation(
() => hostCapabilities
)
vi.spyOn(capabilities, 'ensureLocalRuntimeCapabilities').mockImplementation(
async () => hostCapabilities
)
warnings = vi.spyOn(console, 'warn')
mockWaitForAgentReady.mockResolvedValue({ ready: true, reason: 'foreground-match' })
mockPasteDraftWhenAgentReady.mockResolvedValue(true)
mockCreateStructuredCodexSessionLaunchIntent.mockImplementation((worktreeId: string) =>
structuredLaunchIntent(worktreeId)
)
mockRetryStructuredAgentSessionLaunchIntent.mockImplementation((intent) => ({
...intent,
params: {
...intent.params,
envelope: {
...intent.params.envelope,
clientOperationId: `${intent.params.envelope.clientOperationId}-retry`
}
}
}))
mockLaunchStructuredCodexSession.mockResolvedValue({
sessionId: 'codex-session-1',
fence: 1
})
mockCallStructuredAgentSession.mockResolvedValue({
ok: true,
page: { fence: 1 },
value: { submission: { dispatchState: 'accepted' } }
})
mockRefreshLocalStructuredSessionTabs.mockResolvedValue([
{
worktree: 'wt-1',
tabs: [{ type: 'agent-session', sessionId: 'codex-session-1' }]
}
])
mockCreateSupport.mockResolvedValue({ supported: true })
hostCapabilities = STRUCTURED_HOST_CAPABILITIES
const module = await import('./launch-agent-in-new-tab')
const launch = module.launchAgentInNewTab
vi.spyOn(module, 'launchAgentInNewTab').mockImplementation((args) => {
const result = launch(args)
owned.push(result)
return result
})
})
afterEach(async () => {
cleanup()
vi.restoreAllMocks()
const { cancelStructuredAgentLaunch, retireStructuredAgentSessionLaunchCancellationTombstone } =
await import('./structured-agent-session-launch')
const pending = ['codex-session-1', 'codex-session-2'].flatMap((id) => {
const launch = getStructuredLaunchStateBySessionId(id)
return launch ? [launch.promise] : []
})
for (const sessionId of ['codex-session-1', 'codex-session-2']) {
cancelStructuredAgentLaunch('wt-1', sessionId)
retireStructuredAgentSessionLaunchCancellationTombstone('wt-1', sessionId)
}
restoreCatalogStore?.()
})
let pickerMenu: typeof PickerMenu
let dropdown: typeof Dropdown
let tooltip: typeof Tooltip
let quickLaunch: typeof QuickLaunch
let actual: typeof StructuredLaunch
beforeAll(async () => {
actual = await vi.importActual<typeof StructuredLaunch>('./launch-structured-agent-session')
;[pickerMenu, dropdown, tooltip, quickLaunch] = await Promise.all([
import('@/components/agent/AgentLaunchPickerMenu'),
import('@/components/ui/dropdown-menu'),
import('@/components/ui/tooltip'),
import('@/components/tab-bar/QuickLaunchButton')
])
})
it.each(
(['local', 'runtime:web-runtime'] as const).flatMap((host) =>
(
[
['claude', 'success'],
['claude', 'refusal'],
['claude', 'failure'],
['codex', 'success'],
['codex', 'refusal'],
['codex', 'failure']
] as const
).map(([agent, outcome]) => ({ host, agent, outcome }))
)
)(
'keeps ordinary and picker $agent Chat inputs and $outcome endpoint outcomes equivalent on $host',
async ({ host, agent, outcome }) => {
store.settings.activeRuntimeEnvironmentId = host === 'local' ? null : 'web-runtime'
const { captureNativeChatComposerFocusIntent } =
await import('@/components/native-chat/use-native-chat-composer-reveal-focus')
const { AgentLaunchPickerMenu } = pickerMenu
const { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } = dropdown
const { TooltipProvider } = tooltip
const { useTabAgentMenuLaunch } = quickLaunch
const launcher = await import('./launch-agent-in-new-tab')
const dispatch = vi.spyOn(launcher, 'launchAgentInNewTab')
const { launchAgentInNewTab } = launcher
const { resetStructuredAgentLaunchRegistryForTests } =
await import('./agent-session/launch/structured-agent-session-launch-registry')
const { resetStructuredAgentLaunchPersistenceForTests } =
await import('./agent-session/launch/structured-agent-session-launch-persistence')
const { agentPickerChoiceSeeds, agentPickerEntriesFromRows } =
await import('../../../shared/agent-launch-picker')
store.settings.nativeChatSessionOptions = {
[agent]: {
model: 'saved-unknown-model',
valuesByModel: { 'saved-unknown-model': { effort: 'high' } }
}
}
store.settings.nativeChatProviders = { [agent]: false }
const rows = buildNewTabAgentMenuRows({
settings: store.settings,
detectedOnHost: [agent],
chatAgents: [agent],
hostChatAnswer: () => 'yes',
chatProgram: () => 'available'
}).map((row) => ({ ...row, executionHostId: host }))
expect(rows).toEqual([{ agent, kind: 'cli', chat: true, executionHostId: host }])
const entry = agentPickerEntriesFromRows(
rows,
[agent],
(selected) => agentPickerChoiceSeeds(selected, store.settings),
(selected) => selected
)[0]
expect(entry.defaultSurface).toBe('terminal')
expect(entry.surfaces).toEqual(['chat', 'terminal'])
Object.assign(entry, {
defaultsPending: true,
structuredDefaultsPending: true,
arguments: undefined,
terminal: {},
structured: {}
})
// The searched setup matches the saved choices so endpoint parity includes search intent.
entry.catalog = {
origin: 'probe',
fetchedAt: 1,
models: [
{
id: 'saved-unknown-model',
label: 'Saved model',
isDefault: true,
efforts: [{ value: 'high', label: 'High' }]
}
]
}
function Menu() {
const runLaunch = useTabAgentMenuLaunch({
worktreeId: 'wt-1',
groupId: 'group-1',
onFocusTerminal: () => {}
})
return createElement(
TooltipProvider,
null,
createElement(
DropdownMenu,
{ defaultOpen: true, modal: false },
createElement(DropdownMenuTrigger, null, 'New tab'),
createElement(
DropdownMenuContent,
null,
createElement(AgentLaunchPickerMenu, {
entries: [entry],
runLaunch
})
)
)
)
}
mockCreateStructuredCodexSessionLaunchIntent.mockImplementation(
(worktreeId, selectedAgent, host, resume, seed) => {
const intent = actual.createStructuredAgentSessionLaunchIntent(
worktreeId,
selectedAgent,
host,
resume,
seed,
false
)
return {
...intent,
sessionId: 'codex-session-1',
params: {
...intent.params,
envelope: structuredLaunchIntent(worktreeId).params.envelope
}
}
}
)
const error =
outcome === 'refusal'
? new launchErrorMocks.StructuredAgentSessionCreateRefusalError('provider unavailable')
: new Error('connection failed')
const perform = async (picker: false | 'ordinary' | 'searched') => {
resetStructuredAgentLaunchRegistryForTests()
resetStructuredAgentLaunchPersistenceForTests()
mockLaunchStructuredCodexSession.mockClear()
mockCreateTab.mockClear()
mockToastError.mockClear()
if (outcome === 'failure') {
store.unifiedTabsByWorktree = {}
mockRefreshLocalStructuredSessionTabs.mockResolvedValue([])
}
const preparationErrors: unknown[] = []
mockLaunchStructuredCodexSession.mockImplementation(async (intent) => {
await Promise.resolve()
intent.createMessageSupport = true
try {
expect(intent.prepareCreate).toBeTypeOf('function')
intent.prepareCreate!(false)
expect(intent.createPrepared).toBe(true)
} catch (error) {
preparationErrors.push(error instanceof Error ? error.stack : error)
throw error
}
if (outcome !== 'success') {
throw error
}
return { sessionId: intent.sessionId, fence: 1 }
})
dispatch.mockClear()
if (picker) {
const view = render(createElement(Menu))
if (picker === 'searched') {
fireEvent.change(view.getByPlaceholderText('Search agents and setups…'), {
target: { value: 'saved-unknown-model high' }
})
}
fireEvent.click(
document.querySelector<HTMLButtonElement>(`button[aria-label="Configure ${agent}"]`)!
)
expect(mockLaunchStructuredCodexSession).not.toHaveBeenCalled()
expect(document.querySelector('textarea')).toHaveProperty('disabled', true)
expect(document.body.textContent).toContain('Launch terminal')
expect(
[...document.querySelectorAll('button')].find(
(button) => button.textContent === 'Launch terminal'
)?.className
).toContain('bg-primary')
fireEvent.click(
[...document.querySelectorAll('button')].find(
(button) => button.textContent === 'Launch chat'
)!
)
} else {
launchAgentInNewTab({
requestId: `equivalent-${agent}-${outcome}`,
agent,
worktreeId: 'wt-1',
groupId: 'group-1',
requestedSurface: 'chat',
selectedExecutionHostId: host,
focusIntent: captureNativeChatComposerFocusIntent()
})
}
const call = dispatch.mock.results.at(-1)
const result = call?.type === 'return' ? call.value : undefined
const settlement = await result?.structuredSettlement
cleanup()
expect(preparationErrors).toEqual([])
const intent = mockLaunchStructuredCodexSession.mock.calls[0]?.[0]
return {
surface: result?.surface,
settlement,
target: intent?.target,
params: intent?.params,
seed: intent?.seedOptions,
explicit: intent?.explicitLaunchOptions,
terminalCalls: mockCreateTab.mock.calls,
errors: mockToastError.mock.calls
}
}
const ordinary = await perform(false)
const picker = await perform('ordinary')
expect(picker).toEqual(ordinary)
const searched = await perform('searched')
expect(searched).toMatchObject({
surface: ordinary.surface,
settlement: ordinary.settlement,
target: ordinary.target,
errors: ordinary.errors,
terminalCalls: []
})
expect(searched.params).toMatchObject({
agent,
worktree: 'id:wt-1',
options: { model: 'saved-unknown-model', effort: 'high' }
})
expect(searched.explicit).toMatchObject({ model: 'saved-unknown-model', effort: 'high' })
dispatch.mockRestore()
expect(picker.target).toEqual(
host === 'local' ? { kind: 'local' } : { kind: 'environment', environmentId: 'web-runtime' }
)
expect(picker.params).toMatchObject({
agent,
worktree: 'id:wt-1'
})
expect(picker.params).not.toHaveProperty('options')
expect(picker.explicit).toBeUndefined()
if (host === 'local') {
expect(picker.seed).toMatchObject({ model: 'saved-unknown-model', effort: 'high' })
} else {
expect(picker.seed).toBeUndefined()
}
expect(picker.terminalCalls).toEqual([])
expect(picker.settlement?.kind).toBe(
outcome === 'success'
? 'structured'
: outcome === 'refusal'
? 'failed'
: 'visibility-unknown'
)
for (const finish of lateCreates.splice(0)) {
finish()
}
)
await Promise.allSettled(pending)
await Promise.all(owned.splice(0).map((result) => result?.structuredSettlement))
await main.settle()
expect(lateCreates).toEqual([])
expect(layoutApplyTestTransport.pendingCount).toBe(0)
for (const tab of state().unifiedTabsByWorktree['wt-1'] ?? []) {
expect(isPendingTab(tab.id)).toBe(false)
}
expect(
warnings.mock.calls.filter(
([message]) => message === '[layout-owner] pending tab waiter threw:'
)
).toEqual([])
for (const id of ['codex-session-1', 'codex-session-2']) {
retireStructuredAgentSessionLaunchCancellationTombstone('wt-1', id)
}
})
it('takes the structured path when the chat-default view is selected', async () => {
const { launchAgentInNewTab, shouldQueueTerminalFocusAfterMenuClose } =
@@ -351,12 +186,13 @@ describe('structured chat adoption guard on the launch path', () => {
})
it('takes the structured path when a Codex model and effort are already saved', async () => {
store.settings.nativeChatSessionOptions = {
codex: {
model: 'gpt-5.6-sol',
valuesByModel: { 'gpt-5.6-sol': { effort: 'medium' } }
}
}
liveStore().setState({
settings: launchScenarioSettings({
nativeChatSessionOptions: {
codex: { model: 'gpt-5.6-sol', valuesByModel: { 'gpt-5.6-sol': { effort: 'medium' } } }
}
})
})
const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab')
const result = launchAgentInNewTab({
@@ -402,7 +238,7 @@ describe('structured chat adoption guard on the launch path', () => {
// WSL-bound Claude accounts must decline before opening a chat that could only fail Retry.
it('opens the terminal, and no chat, when this machine declines the chat', async () => {
store.unifiedTabsByWorktree = {}
liveStore().setState({ unifiedTabsByWorktree: {} })
mockCreateSupport.mockResolvedValue({ supported: false, reason: 'wsl' })
const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab')
@@ -444,7 +280,7 @@ describe('structured chat adoption guard on the launch path', () => {
it.each([[], null])(
'preserves terminal-backed launches with capability answer %s',
async (capabilities) => {
setHostCapabilities(capabilities)
hostCapabilities = capabilities
const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab')
const launches = [
@@ -461,7 +297,7 @@ describe('structured chat adoption guard on the launch path', () => {
// Recheck persisted opt-in against current default view; the hidden toggle can remain enabled under Terminal chat.
it('ignores a stale structured opt-in while the default view is Terminal chat', async () => {
store.settings.experimentalNativeChat = false
liveStore().setState({ settings: launchScenarioSettings({ experimentalNativeChat: false }) })
const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab')
const result = launchAgentInNewTab({
@@ -502,7 +338,7 @@ describe('structured chat adoption guard on the launch path', () => {
error: refusal
})
expect(mockCreateTab).not.toHaveBeenCalled()
expect(store.unifiedTabsByWorktree['wt-1']).toContainEqual(
expect(state().unifiedTabsByWorktree['wt-1']).toContainEqual(
expect.objectContaining({ contentType: 'agent-session', entityId: 'codex-session-1' })
)
await new Promise((resolve) => setTimeout(resolve, 0))
@@ -540,7 +376,10 @@ describe('structured chat adoption guard on the launch path', () => {
let resolveLaunch!: (receipt: { sessionId: string; fence: number }) => void
mockLaunchStructuredCodexSession.mockImplementationOnce(
() =>
new Promise<{ sessionId: string; fence: number }>((resolve) => (resolveLaunch = resolve))
new Promise<{ sessionId: string; fence: number }>((resolve) => {
resolveLaunch = resolve
lateCreates.push(() => resolve({ sessionId: 'codex-session-1', fence: 1 }))
})
)
const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab')
@@ -566,7 +405,8 @@ describe('structured chat adoption guard on the launch path', () => {
})
it('settles a successful create and opens its chat without an inventory refresh', async () => {
store.unifiedTabsByWorktree = {}
liveStore().setState({ unifiedTabsByWorktree: {} })
expect(state().getTab('structured-agent-session-codex-session-1')).toBeNull()
mockRefreshLocalStructuredSessionTabs.mockRejectedValue(new Error('inventory unavailable'))
const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab')
@@ -580,15 +420,20 @@ describe('structured chat adoption guard on the launch path', () => {
kind: 'structured',
sessionId: 'codex-session-1'
})
expect(store.unifiedTabsByWorktree['wt-1']).toContainEqual(
expect(state().unifiedTabsByWorktree['wt-1']).toContainEqual(
expect.objectContaining({ contentType: 'agent-session', entityId: 'codex-session-1' })
)
await main.settle()
const tab = state().unifiedTabsByWorktree['wt-1']!.find(
(row) => row.entityId === 'codex-session-1'
)!
expect(state().getTab(tab.id)).toBe(tab)
expect(mockRefreshLocalStructuredSessionTabs).not.toHaveBeenCalled()
expect(mockToastError).not.toHaveBeenCalled()
})
it('re-checks a chat whose visibility proof is unknown through its own Retry, with its own intent', async () => {
store.unifiedTabsByWorktree = {}
liveStore().setState({ unifiedTabsByWorktree: {} })
const firstIntent = structuredLaunchIntent('wt-1', 'codex-session-1')
const secondIntent = structuredLaunchIntent('wt-1', 'codex-session-2')
mockCreateStructuredCodexSessionLaunchIntent
@@ -602,15 +447,19 @@ describe('structured chat adoption guard on the launch path', () => {
.mockRejectedValueOnce(new Error('inventory unavailable'))
.mockResolvedValueOnce([])
.mockImplementationOnce(() => {
store.unifiedTabsByWorktree['wt-1'] = [
{
id: `structured-agent-session-${firstIntent.sessionId}`,
contentType: 'agent-session',
entityId: firstIntent.sessionId,
worktreeId: 'wt-1',
groupId: 'group-1'
liveStore().setState({
unifiedTabsByWorktree: {
'wt-1': [
makeUnifiedTab({
id: `structured-agent-session-${firstIntent.sessionId}`,
contentType: 'agent-session',
entityId: firstIntent.sessionId,
worktreeId: 'wt-1',
groupId: 'group-1'
})
]
}
]
})
return Promise.resolve([
{ worktree: 'wt-1', tabs: [{ type: 'agent-session', sessionId: firstIntent.sessionId }] }
])
@@ -665,9 +514,15 @@ describe('structured chat adoption guard on the launch path', () => {
expect(mockCreateStructuredCodexSessionLaunchIntent).toHaveBeenCalledTimes(2)
expect(mockLaunchStructuredCodexSession).toHaveBeenCalledTimes(3)
expect(mockLaunchStructuredCodexSession.mock.calls[2]?.[0]).toBe(secondIntent)
expect(store.unifiedTabsByWorktree['wt-1']?.map((tab) => tab.entityId)).toEqual(
expect(state().unifiedTabsByWorktree['wt-1']?.map((tab) => tab.entityId)).toEqual(
expect.arrayContaining([firstIntent.sessionId, secondIntent.sessionId])
)
const replacement = state().unifiedTabsByWorktree['wt-1']!.find(
(row) => row.entityId === secondIntent.sessionId
)!
liveStore().setState({ unifiedTabsByWorktree: { 'wt-1': [replacement] } })
expect(state().getTab(`structured-agent-session-${firstIntent.sessionId}`)).toBeNull()
expect(state().getTab(replacement.id)).toBe(replacement)
})
it('routes an auto-submitted Codex prompt through the structured outbox', async () => {
@@ -712,7 +567,7 @@ describe('structured chat adoption guard on the launch path', () => {
})
it('keeps an SSH Codex tab on the bridge', async () => {
store.repos = [{ id: 'repo-1', connectionId: 'ssh-a', path: '/repo' }]
liveStore().setState({ repos: [{ ...state().repos[0]!, connectionId: 'ssh-a' }] })
const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab')
launchAgentInNewTab({ requestId: 'request-18', agent: 'codex', worktreeId: 'wt-1' })
@@ -728,7 +583,7 @@ describe('structured chat adoption guard on the launch path', () => {
})
it('keeps a runtime-paired Codex tab on the bridge', async () => {
store.repos = [{ id: 'repo-1', connectionId: 'runtime-ssh-a', path: '/repo' }]
liveStore().setState({ repos: [{ ...state().repos[0]!, connectionId: 'runtime-ssh-a' }] })
const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab')
launchAgentInNewTab({ requestId: 'request-19', agent: 'codex', worktreeId: 'wt-1' })
@@ -0,0 +1,519 @@
// @vitest-environment happy-dom
import {
mockCreateTab,
mockCreateStructuredCodexSessionLaunchIntent,
mockLaunchStructuredCodexSession,
mockRefreshLocalStructuredSessionTabs,
mockToastError,
structuredLaunchIntent,
liveStore,
currentLaunchSettings,
main,
mockCallStructuredAgentSession,
mockCreateSupport,
launchErrorMocks,
mockWaitForAgentReady,
mockPasteDraftWhenAgentReady,
mockRetryStructuredAgentSessionLaunchIntent
} from './launch-agent-structured-chat-test-fixture'
import type * as PickerMenu from '@/components/agent/AgentLaunchPickerMenu'
import type * as Dropdown from '@/components/ui/dropdown-menu'
import type * as Tooltip from '@/components/ui/tooltip'
import type * as QuickLaunch from '@/components/tab-bar/QuickLaunchButton'
import { createElement } from 'react'
import { cleanup, fireEvent, render } from '@testing-library/react'
import { buildNewTabAgentMenuRows } from '../../../shared/agent-launch-picker-rows'
import type * as StructuredLaunch from './launch-structured-agent-session'
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import * as registry from './agent-session/launch/structured-agent-session-launch-registry'
import { cancelStructuredAgentLaunch } from './structured-agent-session-launch'
import { structuredLaunchSelectionController } from './structured-agent-session-launch-options'
import { forgetStructuredSessionSelection } from './structured-agent-session-selection-controller'
import * as rpc from '@/runtime/runtime-rpc-client'
import { isPendingTab } from '@/runtime/layout-owner-pending-tabs'
import { layoutApplyTestTransport } from '@/runtime/layout-apply-test-transport.test-fixture'
import { nativeChatComposerDraftWritesSettled } from '@/components/native-chat/native-chat-composer-draft-persistence'
import type { SelectionOperation } from '../../../shared/structured-agent-session-selection-operations'
// No initial chat mode proves availability rejection preceded terminal-tab adoption.
describe('structured chat adoption guard on the launch path', () => {
beforeEach(() => {
const originalRow = liveStore().getState().getTab('structured-agent-session-codex-session-1')
expect(originalRow).not.toHaveProperty('executionHostId')
expect(originalRow).not.toHaveProperty('agentSessionAgent')
mockWaitForAgentReady.mockResolvedValue({ ready: true, reason: 'foreground-match' })
mockPasteDraftWhenAgentReady.mockResolvedValue(true)
mockCreateStructuredCodexSessionLaunchIntent.mockImplementation((worktreeId: string) =>
structuredLaunchIntent(worktreeId)
)
mockRetryStructuredAgentSessionLaunchIntent.mockImplementation((intent) => ({
...intent,
params: {
...intent.params,
envelope: {
...intent.params.envelope,
clientOperationId: `${intent.params.envelope.clientOperationId}-retry`
}
}
}))
mockLaunchStructuredCodexSession.mockResolvedValue({
sessionId: 'codex-session-1',
fence: 1
})
mockCallStructuredAgentSession.mockResolvedValue({
ok: true,
page: { fence: 1 },
value: { submission: { dispatchState: 'accepted' } }
})
mockRefreshLocalStructuredSessionTabs.mockResolvedValue([
{
worktree: 'wt-1',
tabs: [{ type: 'agent-session', sessionId: 'codex-session-1' }]
}
])
mockCreateSupport.mockResolvedValue({ supported: true })
})
let pickerMenu: typeof PickerMenu
let dropdown: typeof Dropdown
let tooltip: typeof Tooltip
let quickLaunch: typeof QuickLaunch
let actual: typeof StructuredLaunch
beforeAll(async () => {
actual = await vi.importActual<typeof StructuredLaunch>('./launch-structured-agent-session')
;[pickerMenu, dropdown, tooltip, quickLaunch] = await Promise.all([
import('@/components/agent/AgentLaunchPickerMenu'),
import('@/components/ui/dropdown-menu'),
import('@/components/ui/tooltip'),
import('@/components/tab-bar/QuickLaunchButton')
])
})
it.each(
(['local', 'runtime:web-runtime'] as const).flatMap((host) =>
(
[
['claude', 'success'],
['claude', 'refusal'],
['claude', 'failure'],
['codex', 'success'],
['codex', 'refusal'],
['codex', 'failure']
] as const
).map(([agent, outcome]) => ({ host, agent, outcome }))
)
)(
'keeps ordinary and picker $agent Chat inputs and $outcome endpoint outcomes equivalent on $host',
async ({ host, agent, outcome }) => {
const store = liveStore()
store.setState({
settings: {
...currentLaunchSettings(),
activeRuntimeEnvironmentId: host === 'local' ? null : 'web-runtime'
}
})
const { captureNativeChatComposerFocusIntent } =
await import('@/components/native-chat/use-native-chat-composer-reveal-focus')
const { AgentLaunchPickerMenu } = pickerMenu
const { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } = dropdown
const { TooltipProvider } = tooltip
const { useTabAgentMenuLaunch } = quickLaunch
const launcher = await import('./launch-agent-in-new-tab')
const owned: ReturnType<typeof launcher.launchAgentInNewTab>[] = []
const originalLaunch = launcher.launchAgentInNewTab
const dispatch = vi.spyOn(launcher, 'launchAgentInNewTab').mockImplementation((args) => {
const result = originalLaunch(args)
owned.push(result)
return result
})
const warnings = vi.spyOn(console, 'warn')
const rawRpc = vi.spyOn(rpc, 'callRuntimeRpc')
const states = new Set<registry.StructuredLaunchState>()
const promises = new Set<registry.StructuredLaunchState['promise']>()
const settled = new Set<registry.StructuredLaunchState['promise']>()
const controllers = new Map<
ReturnType<typeof structuredLaunchSelectionController>,
registry.StructuredLaunchState['intent']
>()
const optionWork = new Set<SelectionOperation>()
const install = registry.setStructuredLaunchState
vi.spyOn(registry, 'setStructuredLaunchState').mockImplementation((state) => {
states.add(state)
const promise = state.promise
promises.add(promise)
void promise.then(
() => settled.add(promise),
() => settled.add(promise)
)
controllers.set(structuredLaunchSelectionController(state), state.intent)
install(state)
})
let activeCreates = 0
const drain = async () => {
await Promise.allSettled(promises)
await Promise.allSettled(
owned.flatMap((result) => [result?.structuredSettlement, result?.promptDeliveryResult])
)
await Promise.allSettled(
[...states].flatMap((state) => [...state.callers.promptDeliveryResults])
)
for (const controller of controllers.keys()) {
for (const operation of controller.pending()) {
optionWork.add(operation)
}
}
await Promise.allSettled(
[...optionWork].flatMap((operation) => [operation.result, operation.request])
)
await Promise.all([...controllers.keys()].map((controller) => controller.drain()))
const raw = [
mockCreateSupport,
mockLaunchStructuredCodexSession,
mockRefreshLocalStructuredSessionTabs,
mockCallStructuredAgentSession,
rawRpc
].flatMap<unknown>((mock) =>
mock.mock.results.flatMap<unknown>((result) =>
result.type === 'return' ? [result.value] : []
)
)
const pendingRaw = new Set(
raw.filter((value): value is Promise<unknown> => value instanceof Promise)
)
for (const request of pendingRaw) {
void request.then(
() => pendingRaw.delete(request),
() => pendingRaw.delete(request)
)
}
await Promise.allSettled(pendingRaw)
expect(pendingRaw.size).toBe(0)
await main.settle()
await nativeChatComposerDraftWritesSettled()
expect(activeCreates).toBe(0)
expect(layoutApplyTestTransport.pendingCount).toBe(0)
expect(isPendingTab('structured-agent-session-codex-session-1')).toBe(false)
expect(
warnings.mock.calls.filter(
([message]) => message === '[layout-owner] pending tab waiter threw:'
)
).toEqual([])
}
const finish = async () => {
try {
for (const state of states) {
if (
!settled.has(state.promise) &&
registry.getStructuredLaunchStateBySessionId(state.intent.sessionId) === state
) {
expect(state.intent.worktreeId).toBe('wt-1')
expect(state.intent.executionHostId).toBe(host)
cancelStructuredAgentLaunch('wt-1', state.intent.sessionId)
}
}
} finally {
try {
await drain()
} finally {
try {
cleanup()
} finally {
for (const state of states) {
if (registry.deleteStructuredLaunchStateIfCurrent(state)) {
registry.notifyStructuredLaunchListeners()
}
}
try {
await drain()
} finally {
registry.retireStructuredAgentSessionLaunchCancellationTombstone(
'wt-1',
'codex-session-1'
)
await drain()
}
}
}
}
expect(registry.getStructuredLaunchStateBySessionId('codex-session-1')).toBeUndefined()
expect(registry.getPersistedStructuredAgentLaunchRecord('codex-session-1')).toBeUndefined()
expect(
registry.hasStructuredAgentSessionLaunchCancellationTombstone('wt-1', 'codex-session-1')
).toBe(false)
}
const { launchAgentInNewTab } = launcher
const { resetStructuredAgentLaunchRegistryForTests } =
await import('./agent-session/launch/structured-agent-session-launch-registry')
const { resetStructuredAgentLaunchPersistenceForTests } =
await import('./agent-session/launch/structured-agent-session-launch-persistence')
const { agentPickerChoiceSeeds, agentPickerEntriesFromRows } =
await import('../../../shared/agent-launch-picker')
store.setState({
settings: {
...currentLaunchSettings(),
nativeChatSessionOptions: {
[agent]: {
model: 'saved-unknown-model',
valuesByModel: { 'saved-unknown-model': { effort: 'high' } }
}
},
nativeChatProviders: { [agent]: false }
}
})
const rows = buildNewTabAgentMenuRows({
settings: store.getState().settings,
detectedOnHost: [agent],
chatAgents: [agent],
hostChatAnswer: () => 'yes',
chatProgram: () => 'available'
}).map((row) => ({ ...row, executionHostId: host }))
expect(rows).toEqual([{ agent, kind: 'cli', chat: true, executionHostId: host }])
const entry = agentPickerEntriesFromRows(
rows,
[agent],
(selected) => agentPickerChoiceSeeds(selected, store.getState().settings),
(selected) => selected
)[0]
expect(entry.defaultSurface).toBe('terminal')
expect(entry.surfaces).toEqual(['chat', 'terminal'])
Object.assign(entry, {
defaultsPending: true,
structuredDefaultsPending: true,
arguments: undefined,
terminal: {},
structured: {}
})
// The searched setup matches the saved choices so endpoint parity includes search intent.
entry.catalog = {
origin: 'probe',
fetchedAt: 1,
models: [
{
id: 'saved-unknown-model',
label: 'Saved model',
isDefault: true,
efforts: [{ value: 'high', label: 'High' }]
}
]
}
function Menu() {
const runLaunch = useTabAgentMenuLaunch({
worktreeId: 'wt-1',
groupId: 'group-1',
onFocusTerminal: () => {}
})
return createElement(
TooltipProvider,
null,
createElement(
DropdownMenu,
{ defaultOpen: true, modal: false },
createElement(DropdownMenuTrigger, null, 'New tab'),
createElement(
DropdownMenuContent,
null,
createElement(AgentLaunchPickerMenu, {
entries: [entry],
runLaunch
})
)
)
)
}
mockCreateStructuredCodexSessionLaunchIntent.mockImplementation(
(worktreeId, selectedAgent, host, resume, seed) => {
const intent = actual.createStructuredAgentSessionLaunchIntent(
worktreeId,
selectedAgent,
host,
resume,
seed,
false
)
return {
...intent,
sessionId: 'codex-session-1',
params: {
...intent.params,
envelope: structuredLaunchIntent(worktreeId).params.envelope
}
}
}
)
const error =
outcome === 'refusal'
? new launchErrorMocks.StructuredAgentSessionCreateRefusalError('provider unavailable')
: new Error('connection failed')
const perform = async (picker: false | 'ordinary' | 'searched') => {
resetStructuredAgentLaunchRegistryForTests()
resetStructuredAgentLaunchPersistenceForTests()
mockLaunchStructuredCodexSession.mockClear()
mockCreateTab.mockClear()
mockToastError.mockClear()
if (outcome === 'failure') {
store.setState({
unifiedTabsByWorktree: {},
groupsByWorktree: {},
layoutByWorktree: {},
activeGroupIdByWorktree: {}
})
expect(store.getState().getTab('structured-agent-session-codex-session-1')).toBeNull()
mockRefreshLocalStructuredSessionTabs.mockResolvedValue([])
}
const preparationErrors: unknown[] = []
mockLaunchStructuredCodexSession.mockImplementation(async (intent) => {
activeCreates++
try {
await Promise.resolve()
intent.createMessageSupport = true
try {
expect(intent.prepareCreate).toBeTypeOf('function')
intent.prepareCreate!(false)
expect(intent.createPrepared).toBe(true)
} catch (error) {
preparationErrors.push(error instanceof Error ? error.stack : error)
throw error
}
if (outcome !== 'success') {
throw error
}
return { sessionId: intent.sessionId, fence: 1 }
} finally {
activeCreates--
}
})
dispatch.mockClear()
try {
if (picker) {
const view = render(createElement(Menu))
if (picker === 'searched') {
fireEvent.change(view.getByPlaceholderText('Search agents and setups…'), {
target: { value: 'saved-unknown-model high' }
})
}
fireEvent.click(
document.querySelector<HTMLButtonElement>(`button[aria-label="Configure ${agent}"]`)!
)
expect(mockLaunchStructuredCodexSession).not.toHaveBeenCalled()
expect(document.querySelector('textarea')).toHaveProperty('disabled', true)
expect(document.body.textContent).toContain('Launch terminal')
expect(
[...document.querySelectorAll('button')].find(
(button) => button.textContent === 'Launch terminal'
)?.className
).toContain('bg-primary')
fireEvent.click(
[...document.querySelectorAll('button')].find(
(button) => button.textContent === 'Launch chat'
)!
)
} else {
launchAgentInNewTab({
requestId: `equivalent-${agent}-${outcome}`,
agent,
worktreeId: 'wt-1',
groupId: 'group-1',
requestedSurface: 'chat',
selectedExecutionHostId: host,
focusIntent: captureNativeChatComposerFocusIntent()
})
}
const call = dispatch.mock.results.at(-1)
const result = call?.type === 'return' ? call.value : undefined
const settlement = await result?.structuredSettlement
expect(states.size).toBeGreaterThan(0)
await main.settle()
expect(preparationErrors).toEqual([])
const intent = mockLaunchStructuredCodexSession.mock.calls[0]?.[0]
if (outcome === 'success') {
for (const controller of controllers.keys()) {
expect(controller.isCurrent()).toBe(true)
}
}
expect(store.getState().getTab('structured-agent-session-codex-session-1')).toMatchObject(
{
id: 'structured-agent-session-codex-session-1',
entityId: 'codex-session-1',
contentType: 'agent-session',
worktreeId: 'wt-1'
}
)
return {
surface: result?.surface,
settlement,
target: intent?.target,
params: intent?.params,
seed: intent?.seedOptions,
explicit: intent?.explicitLaunchOptions,
terminalCalls: mockCreateTab.mock.calls.map((args) => [...args]),
errors: mockToastError.mock.calls.map((args) => [...args])
}
} finally {
await finish()
}
}
try {
const ordinary = await perform(false)
const picker = await perform('ordinary')
expect(picker).toEqual(ordinary)
const searched = await perform('searched')
expect(searched).toMatchObject({
surface: ordinary.surface,
settlement: ordinary.settlement,
target: ordinary.target,
errors: ordinary.errors,
terminalCalls: []
})
expect(searched.params).toMatchObject({
agent,
worktree: 'id:wt-1',
options: { model: 'saved-unknown-model', effort: 'high' }
})
expect(searched.explicit).toMatchObject({ model: 'saved-unknown-model', effort: 'high' })
dispatch.mockRestore()
expect(picker.target).toEqual(
host === 'local'
? { kind: 'local' }
: { kind: 'environment', environmentId: 'web-runtime' }
)
expect(picker.params).toMatchObject({
agent,
worktree: 'id:wt-1'
})
expect(picker.params).not.toHaveProperty('options')
expect(picker.explicit).toBeUndefined()
if (host === 'local') {
expect(picker.seed).toMatchObject({ model: 'saved-unknown-model', effort: 'high' })
} else {
expect(picker.seed).toBeUndefined()
}
expect(picker.terminalCalls).toEqual([])
expect(picker.settlement?.kind).toBe(
outcome === 'success'
? 'structured'
: outcome === 'refusal'
? 'failed'
: 'visibility-unknown'
)
} finally {
try {
await finish()
} finally {
try {
for (const [controller, intent] of controllers) {
for (const operation of controller.pending()) {
optionWork.add(operation)
}
forgetStructuredSessionSelection(intent.sessionId, intent.target)
}
} finally {
await drain()
}
for (const controller of controllers.keys()) {
expect(controller.isCurrent()).toBe(false)
}
}
}
}
)
})
@@ -1,77 +1,82 @@
import { beforeEach, vi } from 'vitest'
import { afterEach, beforeEach, expect, vi } from 'vitest'
import {
createTestStore,
makeWorktree,
makeTab,
makeUnifiedTab,
makeTabGroup,
seedStore,
TEST_REPO
} from '@/store/slices/store-test-helpers'
import { drawTabsFromMain } from '@/store/slices/tabs-drawn-from-main.test-fixture'
import type * as Frames from '@/store/slices/tabs-drawn-from-main.test-fixture'
import { createGlobalSettingsFixture } from '../../../shared/global-settings-test-fixture'
import type { GlobalSettings } from '../../../shared/global-settings-types'
import { registerStructuredSelectionCatalogStore } from './structured-agent-session-selection-controller'
import type { AppState } from '@/store/types'
import type { pasteDraftWhenAgentReady } from './agent-paste-draft'
import type { waitForAgentReady } from './agent-ready-wait'
import type { createStructuredAgentSessionLaunchIntent as createIntent } from './launch-structured-agent-session'
import type { launchStructuredAgentSession } from './structured-agent-session-launch-create-call'
import type { createStructuredAgentSessionLaunchIntent as create } from './launch-structured-agent-session'
import type { launchStructuredAgentSession as launch } from './structured-agent-session-launch-create-call'
import type { refreshLocalStructuredSessionTabs as refreshTabs } from '@/runtime/local-structured-session-tabs-sync/inventory-refresh'
import type { toast } from 'sonner'
import type * as LaunchErrors from '@/lib/structured-agent-session-launch-errors'
export const mockCreateTab = vi.fn<(...args: Parameters<AppState['createTab']>) => { id: string }>()
export const mockCreateUnifiedTab = vi.fn<
(
worktreeId: string,
contentType: string,
init: Pick<UnifiedTabFixture, 'id' | 'entityId' | 'agentSessionAgent' | 'label'> & {
targetGroupId?: string
}
) => UnifiedTabFixture
>()
const mockSetTabViewMode = vi.fn<AppState['setTabViewMode']>()
export const mockWaitForAgentReady = vi.fn<typeof waitForAgentReady>()
export const mockPasteDraftWhenAgentReady = vi.fn<typeof pasteDraftWhenAgentReady>()
const mockMarkNativeChatLaunchPromptFailed = vi.fn<AppState['markNativeChatLaunchPromptFailed']>()
export const mockCreateStructuredCodexSessionLaunchIntent =
vi.fn<
(...args: Parameters<typeof createIntent>) => Omit<ReturnType<typeof createIntent>, 'agent'>
>()
const mockAbandonStructuredAgentSessionLaunchIntent = vi.fn()
export const mockRetryStructuredAgentSessionLaunchIntent =
vi.fn<
(intent: ReturnType<typeof structuredLaunchIntent>) => ReturnType<typeof structuredLaunchIntent>
>()
export const mockLaunchStructuredCodexSession = vi.fn<typeof launchStructuredAgentSession>()
const mockCreateTab = vi.hoisted(() => vi.fn<AppState['createTab']>())
const mockWaitForAgentReady = vi.hoisted(() => vi.fn<typeof waitForAgentReady>())
const mockPasteDraftWhenAgentReady = vi.hoisted(() => vi.fn<typeof pasteDraftWhenAgentReady>())
const mockCreateStructuredCodexSessionLaunchIntent = vi.hoisted(() =>
vi.fn<(...args: Parameters<typeof create>) => Omit<ReturnType<typeof create>, 'agent'>>()
)
type LaunchIntent = ReturnType<typeof structuredLaunchIntent>
const mockRetryStructuredAgentSessionLaunchIntent = vi.hoisted(() =>
vi.fn<(intent: LaunchIntent) => LaunchIntent>()
)
const mockLaunchStructuredCodexSession = vi.hoisted(() => vi.fn<typeof launch>())
type TabSnapshotFixture = { worktree: string; tabs: { type: 'agent-session'; sessionId: string }[] }
export const mockRefreshLocalStructuredSessionTabs =
const mockRefreshLocalStructuredSessionTabs = vi.hoisted(() =>
vi.fn<(...args: Parameters<typeof refreshTabs>) => Promise<TabSnapshotFixture[]>>()
export const mockToastError = vi.fn<typeof toast.error>()
export const mockCallStructuredAgentSession =
)
const mockToastError = vi.hoisted(() => vi.fn<typeof toast.error>())
const mockCallStructuredAgentSession = vi.hoisted(() =>
vi.fn<(target: unknown, method: string, params: unknown) => Promise<unknown>>()
export const mockCreateSupport = vi.fn<() => Promise<{ supported: boolean; reason?: string }>>()
)
const mockCreateSupport = vi.hoisted(() =>
vi.fn<() => Promise<{ supported: boolean; reason?: string }>>()
)
const STRUCTURED_HOST_CAPABILITIES = ['agent-session.structured.v1']
let hostCapabilities: readonly string[] | null = STRUCTURED_HOST_CAPABILITIES
type UnifiedTabFixture = {
id: string
contentType: string
entityId: string
worktreeId: string
groupId: string
agentSessionAgent?: string
label?: string
const owner = vi.hoisted((): { store: ReturnType<typeof createTestStore> | null } => ({
store: null
}))
export function liveStore() {
if (!owner.store) {
throw new Error('structured launch store not seeded')
}
return owner.store
}
const emptyUnifiedTabsByWorktree: Record<string, UnifiedTabFixture[]> = {}
type StructuredLaunchFixtureSettings = {
agentCmdOverrides: Record<string, string>
agentDefaultArgs: Record<string, string>
agentDefaultEnv: Record<string, Record<string, string>>
activeRuntimeEnvironmentId: string | null
experimentalNativeChat: boolean
nativeChatProviders: Record<string, boolean>
nativeChatSessionOptions?: Record<
string,
{ model?: string; valuesByModel?: Record<string, Record<string, string | boolean>> }
>
const state = () => liveStore().getState()
export function currentLaunchSettings(): GlobalSettings {
const settings = state().settings
if (settings === null) {
throw new Error('structured launch settings not seeded')
}
return settings
}
const settings: StructuredLaunchFixtureSettings = {
agentCmdOverrides: {},
agentDefaultArgs: {},
agentDefaultEnv: {},
activeRuntimeEnvironmentId: null,
experimentalNativeChat: true,
nativeChatProviders: {},
nativeChatSessionOptions: undefined
export let main: Frames.TabsDrawnFromMain
let restoreCatalog: (() => void) | undefined
function launchScenarioSettings(): GlobalSettings {
return createGlobalSettingsFixture({
agentCmdOverrides: {},
agentDefaultArgs: {},
agentDefaultEnv: {},
activeRuntimeEnvironmentId: null,
experimentalNativeChat: true,
nativeChatProviders: {},
nativeChatSessionOptions: undefined,
agentPermissionDefault: undefined,
agentPermissionOverrides: undefined
})
}
export function structuredLaunchIntent(worktreeId: string, sessionId = 'codex-session-1') {
@@ -93,60 +98,20 @@ export function structuredLaunchIntent(worktreeId: string, sessionId = 'codex-se
}
}
export const store = {
clearNativeChatLaunchDraft: vi.fn<AppState['clearNativeChatLaunchDraft']>(),
readLocalAgentInventory: () => ({ ids: null, state: 'pending' }),
activeRepoId: 'repo-1',
activeWorktreeId: 'wt-1',
settings,
projects: [{ id: 'repo-1', localWindowsRuntimePreference: { kind: 'inherit-global' as const } }],
repos: [{ id: 'repo-1', connectionId: null as string | null, path: '/repo' }],
sshConnectionStates: new Map([
['ssh-a', { status: 'connected', remotePlatform: 'linux' }],
['runtime-ssh-a', { status: 'connected', remotePlatform: 'linux' }]
]),
sshStateByEnvironment: new Map(),
runtimeStatusByEnvironmentId: new Map([
[
'web-runtime',
{ status: { hostPlatform: 'linux', capabilities: STRUCTURED_HOST_CAPABILITIES } }
]
]),
transientClearedAgentStatusConnectionIds: {},
worktreesByRepo: {
'repo-1': [{ id: 'wt-1', repoId: 'repo-1', projectId: 'repo-1', path: '/repo/worktree' }]
},
detectedWorktreesByRepo: {},
allWorktrees: vi.fn<() => { id: string; repoId: string; projectId: string; path: string }[]>(
() => store.worktreesByRepo['repo-1']
),
tabsByWorktree: { 'wt-1': [{ id: 'tab-1' }] },
unifiedTabsByWorktree: emptyUnifiedTabsByWorktree,
groupsByWorktree: {},
layoutByWorktree: {},
activeGroupIdByWorktree: {},
openFiles: [] as { id: string; worktreeId: string }[],
browserTabsByWorktree: {} as Record<string, { id: string }[]>,
tabBarOrderByWorktree: {} as Record<string, string[]>,
terminalLayoutsByTabId: {},
ptyIdsByTabId: {},
createTab: mockCreateTab,
createUnifiedTab: mockCreateUnifiedTab,
closeTab: vi.fn<AppState['closeTab']>(),
queueTabStartupCommand: vi.fn<AppState['queueTabStartupCommand']>(),
setActiveTabType: vi.fn<AppState['setActiveTabType']>(),
focusGroup: vi.fn<AppState['focusGroup']>(),
activateTab: vi.fn<AppState['activateTab']>(),
setTabViewMode: mockSetTabViewMode,
setTabBarOrder: vi.fn<AppState['setTabBarOrder']>(),
setAgentStatus: vi.fn<AppState['setAgentStatus']>(),
seedNativeChatLaunchPrompt: vi.fn<AppState['seedNativeChatLaunchPrompt']>(),
seedNativeChatLaunchDraft: vi.fn<AppState['seedNativeChatLaunchDraft']>(),
markNativeChatLaunchPromptFailed: mockMarkNativeChatLaunchPromptFailed
}
vi.mock('@/hooks/useShortcutLabel', () => ({ useOptionalShortcutLabel: () => null }))
vi.mock('@/store', () => ({ useAppStore: { getState: () => store } }))
vi.mock('@/store', async () =>
(await import('./launch-parity-renderer.test-fixture')).launchStoreModuleMock(owner)
)
vi.mock('@/runtime/runtime-rpc-client', async (original) =>
(
await import('@/runtime/layout-apply-test-transport.test-fixture')
).runtimeRpcClientWithLayoutApply(await original())
)
vi.mock('@/runtime/runtime-layout-client', async (original) =>
(
await import('@/runtime/layout-apply-test-transport.test-fixture')
).runtimeLayoutClientWithTestFrames(await original())
)
vi.mock('sonner', () => ({ toast: { message: vi.fn(), error: mockToastError } }))
vi.mock('@/components/tab-bar/reconcile-order', () => ({ reconcileTabOrder: vi.fn(() => []) }))
vi.mock('@/lib/agent-paste-draft', () => ({
@@ -192,17 +157,10 @@ vi.mock('@/lib/structured-agent-session-launch-create-call', () => ({
vi.mock('@/lib/launch-structured-agent-session', () => {
return {
createStructuredAgentSessionLaunchIntent: mockCreateStructuredCodexSessionLaunchIntent,
abandonStructuredAgentSessionLaunchIntent: mockAbandonStructuredAgentSessionLaunchIntent,
abandonStructuredAgentSessionLaunchIntent: vi.fn(),
retryStructuredAgentSessionLaunchIntent: mockRetryStructuredAgentSessionLaunchIntent,
launchStructuredAgentSession: mockLaunchStructuredCodexSession,
StructuredAgentSessionCreateRefusalError:
launchErrorMocks.StructuredAgentSessionCreateRefusalError,
StructuredAgentSessionHostDeclinedError:
launchErrorMocks.StructuredAgentSessionHostDeclinedError,
StructuredAgentSessionHostUnreachableError:
launchErrorMocks.StructuredAgentSessionHostUnreachableError,
StructuredAgentSessionOwnerUnresolvedError:
launchErrorMocks.StructuredAgentSessionOwnerUnresolvedError
...launchErrorMocks
}
})
vi.mock('@/runtime/local-structured-session-tabs-sync/inventory-refresh', () => ({
@@ -212,16 +170,16 @@ vi.mock('@/runtime/local-structured-session-owner', () => ({
LOCAL_STRUCTURED_SESSION_OWNER: 'local-structured-session'
}))
vi.mock('@/runtime/local-runtime-capabilities', () => ({
readLocalRuntimeCapabilitiesOrUnknown: () => hostCapabilities,
ensureLocalRuntimeCapabilities: async () => hostCapabilities,
readLocalRuntimeCapabilitiesOrUnknown: () => STRUCTURED_HOST_CAPABILITIES,
ensureLocalRuntimeCapabilities: async () => STRUCTURED_HOST_CAPABILITIES,
awaitLocalRuntimeCapabilities: () => ({ known: Promise.resolve([]), stop: () => {} })
}))
vi.mock('@/lib/worktree-runtime-owner', () => ({
getExecutionHostIdForWorktree: () =>
store.repos[0]?.connectionId
? `ssh:${store.repos[0].connectionId}`
: store.settings.activeRuntimeEnvironmentId
? `runtime:${store.settings.activeRuntimeEnvironmentId}`
state().repos[0]?.connectionId
? `ssh:${state().repos[0].connectionId}`
: currentLaunchSettings().activeRuntimeEnvironmentId
? `runtime:${currentLaunchSettings().activeRuntimeEnvironmentId}`
: 'local',
runtimeEnvironmentIdOrLocalUnlessTwin: () => null
}))
@@ -232,80 +190,121 @@ vi.mock('@/runtime/structured-agent-session-client', () => ({
: mockCallStructuredAgentSession(target, method, params)
}))
beforeEach(() => {
beforeEach(async () => {
vi.resetAllMocks()
store.unifiedTabsByWorktree = {
'wt-1': [
owner.store = createTestStore()
const chat = makeUnifiedTab({
id: 'structured-agent-session-codex-session-1',
contentType: 'agent-session',
entityId: 'codex-session-1',
worktreeId: 'wt-1',
groupId: 'group-1'
})
seedStore(owner.store, {
activeRepoId: 'repo-1',
activeWorktreeId: 'wt-1',
settings: launchScenarioSettings(),
projects: [
{
id: 'structured-agent-session-codex-session-1',
contentType: 'agent-session',
entityId: 'codex-session-1',
worktreeId: 'wt-1',
groupId: 'group-1'
id: 'repo-1',
displayName: 'repo',
badgeColor: '',
sourceRepoIds: ['repo-1'],
createdAt: 0,
updatedAt: 0,
localWindowsRuntimePreference: { kind: 'inherit-global' }
}
]
}
store.repos = [{ id: 'repo-1', connectionId: null, path: '/repo' }]
store.projects = [{ id: 'repo-1', localWindowsRuntimePreference: { kind: 'inherit-global' } }]
mockCreateTab.mockReturnValue({ id: 'tab-1' })
mockCreateUnifiedTab.mockImplementation((worktreeId, contentType, init) => {
const tab = {
id: init.id,
entityId: init.entityId,
contentType,
worktreeId,
groupId: init.targetGroupId ?? 'group-1',
...(init.agentSessionAgent ? { agentSessionAgent: init.agentSessionAgent } : {}),
...(init.label ? { label: init.label } : {})
}
store.unifiedTabsByWorktree[worktreeId] = [
...(store.unifiedTabsByWorktree[worktreeId] ?? []),
tab
]
return tab
],
repos: [{ ...TEST_REPO, id: 'repo-1', connectionId: null, path: '/repo' }],
sshConnectionStates: new Map(
['ssh-a', 'runtime-ssh-a'].map((targetId) => [
targetId,
{
targetId,
status: 'connected' as const,
error: null,
reconnectAttempt: 0,
remotePlatform: 'linux' as const
}
])
),
runtimeStatusByEnvironmentId: new Map([
[
'web-runtime',
{
checkedAt: 0,
status: {
hostPlatform: 'linux',
runtimeId: 'web-runtime',
rendererGraphEpoch: 0,
graphStatus: 'ready',
authoritativeWindowId: null,
liveTabCount: 0,
liveLeafCount: 0,
runtimeProtocolVersion: 3,
minCompatibleRuntimeClientVersion: 3,
capabilities: STRUCTURED_HOST_CAPABILITIES
}
}
]
]),
worktreesByRepo: {
'repo-1': [
makeWorktree({
id: 'wt-1',
repoId: 'repo-1',
path: '/repo/worktree',
projectId: 'repo-1'
})
]
},
tabsByWorktree: { 'wt-1': [makeTab({ id: 'tab-1', worktreeId: 'wt-1' })] },
unifiedTabsByWorktree: { 'wt-1': [chat] },
groupsByWorktree: {
'wt-1': [
makeTabGroup({
id: 'group-1',
worktreeId: 'wt-1',
tabOrder: [chat.id],
activeTabId: chat.id
})
]
},
layoutByWorktree: { 'wt-1': { type: 'leaf', groupId: 'group-1' } },
activeGroupIdByWorktree: { 'wt-1': 'group-1' }
})
mockWaitForAgentReady.mockResolvedValue({ ready: true, reason: 'foreground-match' })
mockPasteDraftWhenAgentReady.mockResolvedValue(true)
mockCreateStructuredCodexSessionLaunchIntent.mockImplementation((worktreeId: string) =>
structuredLaunchIntent(worktreeId)
)
mockRetryStructuredAgentSessionLaunchIntent.mockImplementation((intent) => ({
...intent,
params: {
...intent.params,
envelope: {
...intent.params.envelope,
clientOperationId: `${intent.params.envelope.clientOperationId}-retry`
}
}
}))
mockLaunchStructuredCodexSession.mockResolvedValue({
sessionId: 'codex-session-1',
fence: 1
liveStore().setState({ createTab: mockCreateTab, runtimeEnvironmentCatalogHydrated: true })
mockCreateTab.mockReturnValue(makeTab({ id: 'tab-1', worktreeId: 'wt-1' }))
expect(state().getTab('missing')).toBeNull()
expect(state().getTab(chat.id)).toBe(chat)
expect(state().readLocalAgentInventory()).toEqual({ ids: null, state: 'pending' })
restoreCatalog = registerStructuredSelectionCatalogStore({
read: state,
subscribe: (listener) => liveStore().subscribe(listener)
})
mockCallStructuredAgentSession.mockResolvedValue({
ok: true,
page: { fence: 1 },
value: { submission: { dispatchState: 'accepted' } }
})
mockRefreshLocalStructuredSessionTabs.mockResolvedValue([
{
worktree: 'wt-1',
tabs: [{ type: 'agent-session', sessionId: 'codex-session-1' }]
}
])
mockCreateSupport.mockResolvedValue({ supported: true })
hostCapabilities = STRUCTURED_HOST_CAPABILITIES
store.settings.activeRuntimeEnvironmentId = null
store.settings.nativeChatProviders = {}
store.settings.experimentalNativeChat = true
store.settings.nativeChatSessionOptions = undefined
main = await drawTabsFromMain(liveStore())
})
export function setHostCapabilities(value: readonly string[] | null) {
hostCapabilities = value
}
afterEach(() => {
try {
restoreCatalog?.()
main.close()
} finally {
vi.restoreAllMocks()
owner.store = null
}
})
export function structuredLaunchErrorMocks() {
return launchErrorMocks
export {
mockCreateTab,
mockWaitForAgentReady,
mockPasteDraftWhenAgentReady,
mockCreateStructuredCodexSessionLaunchIntent,
mockRetryStructuredAgentSessionLaunchIntent,
mockLaunchStructuredCodexSession,
mockRefreshLocalStructuredSessionTabs,
mockToastError,
mockCallStructuredAgentSession,
launchErrorMocks,
mockCreateSupport
}
@@ -99,17 +99,17 @@ export async function openTerminalForDeclinedChat(
return settlement
}
const state = useAppStore.getState()
const current = source()
const replacement = (state.unifiedTabsByWorktree[worktreeId] ?? []).find(
let current = source()
let replacement = (state.unifiedTabsByWorktree[worktreeId] ?? []).find(
(candidate) => candidate.id === completed.tabId
)
const ownsFailure =
const ownsFailure = () =>
launchState &&
getStructuredLaunchStateBySessionId(tab.entityId) === launchState &&
launchState.callers === attempt &&
attempt?.outcome === 'failed' &&
!launchState.cancelled
if (current && ownsFailure) {
if (current && launchState && ownsFailure()) {
launchState.failure = {
...(launchState.failure?.code === 'structured_agent_session_unsupported'
? launchState.failure
@@ -133,10 +133,11 @@ export async function openTerminalForDeclinedChat(
if (!replacement) {
return settlement
}
if (!current || args.hooks.signal?.aborted || (launchState && !ownsFailure)) {
if (!current || args.hooks.signal?.aborted || !ownsFailure()) {
notifyHostDeclined(args.plan.agent)
return settlement
}
const replacementEntityId = replacement.entityId
// Switch point: main places and pins the tab in one step; a pin sent alone would re-sort it.
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
await placeReplacementThroughMain(worktreeId, replacement, current)
@@ -144,9 +145,18 @@ export async function openTerminalForDeclinedChat(
placeReplacementAfterSource(worktreeId, replacement, current)
}
const placed = useAppStore.getState()
const group = (placed.groupsByWorktree[worktreeId] ?? []).find((g) => g.id === current.groupId)
current = source()
replacement = (placed.unifiedTabsByWorktree[worktreeId] ?? []).find(
(candidate) => candidate.id === completed.tabId && candidate.entityId === replacementEntityId
)
const group = (placed.groupsByWorktree[worktreeId] ?? []).find((g) => g.id === current?.groupId)
if (
!current ||
!replacement ||
!ownsFailure() ||
args.hooks.signal?.aborted ||
!group ||
!group.tabOrder.includes(current.id) ||
group.tabOrder.indexOf(replacement.id) !== group.tabOrder.indexOf(current.id) + 1 ||
typed ||
nativeChatComposerHasUserContent(scopeKey)
@@ -1,5 +1,10 @@
// @vitest-environment happy-dom
import {
readNativeChatComposerDraft,
structuredAgentSessionDraftScopeKey,
updateNativeChatComposerDraft
} from '@/components/native-chat/native-chat-composer-draft-store'
import type * as LaunchErrors from '@/lib/structured-agent-session-launch-errors'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-session-contracts'
@@ -85,7 +90,6 @@ import {
clearNativeChatDraftCacheForTests,
readNativeChatDraftCache
} from '@/components/native-chat/native-chat-draft-cache'
import { structuredAgentSessionDraftScopeKey } from '@/components/native-chat/native-chat-composer-draft-store'
import { StructuredAgentSessionCreateRefusalError } from '@/lib/launch-structured-agent-session'
import {
getStructuredAgentSessionLaunchLifecycle,
@@ -374,6 +378,9 @@ describe('one action delivered twice while its chat is still starting', () => {
prompt: 'PR context',
promptDelivery: 'draft'
})
const scope = structuredAgentSessionDraftScopeKey(click.sessionId)
expect(readNativeChatComposerDraft(scope).text).toBe('PR context')
updateNativeChatComposerDraft(scope, { text: '', document: undefined }, 'immediate')
const repeat = startStructuredAgentLaunch(WORKTREE_ID, 'codex', {
requestId: 'continue-click',
prompt: 'PR context',
@@ -381,7 +388,7 @@ describe('one action delivered twice while its chat is still starting', () => {
})
expect(repeat.sessionId).toBe(click.sessionId)
expect(mocks.seedDraft).toHaveBeenCalledOnce()
expect(readNativeChatComposerDraft(scope).text).toBe('')
})
it('opens a new chat for a click after the start failed', async () => {
@@ -0,0 +1,108 @@
// @vitest-environment happy-dom
import {
mocks,
launchIntent,
sends,
composerDraft
} from './structured-agent-session-launch.test-fixture'
import { describe, expect, it, vi } from 'vitest'
import { startStructuredAgentLaunch } from './structured-agent-session-launch'
import { hasStagedStructuredLaunchPrompt } from './structured-agent-session-launch-prompt'
import {
clearNativeChatComposerDraftsForTests,
hydrateNativeChatComposerDrafts,
nativeChatComposerDraftWritesSettled,
readNativeChatComposerDraft,
structuredAgentSessionDraftScopeKey,
updateNativeChatComposerDraft
} from '@/components/native-chat/native-chat-composer-draft-store'
import {
createMemoryNativeChatComposerDraftStorage,
setNativeChatComposerDraftStorageForTests
} from '@/components/native-chat/native-chat-composer-draft-storage'
import { resetStructuredAgentLaunchRegistryForTests } from './agent-session/launch/structured-agent-session-launch-registry'
import { act, renderHook } from '@testing-library/react'
import { useNativeChatDraft } from '@/components/native-chat/use-native-chat-draft'
import { useNativeChatStructuredComposerSend } from '@/components/native-chat/use-native-chat-structured-composer-send'
describe('structured launch draft persistence', () => {
it.each(['claude', 'codex'] as const)(
'restores an unmounted %s hand-off, then keeps Send/clear empty',
async (agent) => {
const storage = createMemoryNativeChatComposerDraftStorage()
setNativeChatComposerDraftStorageForTests(storage)
const intent = {
...launchIntent('folder-draft', 'draft-session'),
agent,
executionHostId: 'ssh:remote' as const
}
mocks.createIntent.mockReturnValueOnce(intent)
mocks.launch.mockResolvedValue({ sessionId: intent.sessionId, fence: 1 })
const text = Array.from({ length: 60 }, (_, i) => `line ${i + 1}`).join('\n')
const launch = startStructuredAgentLaunch(intent.worktreeId, agent, {
requestId: 'request-1',
prompt: text,
promptDelivery: 'draft'
})
const scope = structuredAgentSessionDraftScopeKey(launch.sessionId)
expect(readNativeChatComposerDraft(scope)).toMatchObject({
text,
owner: { workspaceId: 'folder-draft', executionHostId: 'ssh:remote' }
})
await launch.launchResult
expect(hasStagedStructuredLaunchPrompt(launch.sessionId)).toBe(false)
expect(launch.promptDeliveryResult).toBeUndefined()
expect(sends()).toHaveLength(0)
await nativeChatComposerDraftWritesSettled()
expect(storage.drafts.get(scope)?.text).toBe(text)
const restart = async () => {
clearNativeChatComposerDraftsForTests()
resetStructuredAgentLaunchRegistryForTests()
setNativeChatComposerDraftStorageForTests(storage)
await hydrateNativeChatComposerDrafts()
}
await restart()
expect(composerDraft(launch.sessionId)).toBe(text)
const send = vi.fn(() => true)
const composer = renderHook(() => {
const draft = useNativeChatDraft(scope, () => false)
return useNativeChatStructuredComposerSend({
agent,
draftScopeKey: scope,
imageAttachments: [],
isComposing: () => false,
setDraft: draft.setDraft,
setCaret: vi.fn(),
clearSkillOrigin: vi.fn(),
structuredTransport: {
sessionId: launch.sessionId,
runtime: 'remote',
runtimeEnvironmentId: 'remote',
capturePresentation: () => () => true,
send,
onError: vi.fn(),
optionSnapshot: [],
dispatchCommand: async () => ({ handled: false, accepted: false, error: null }),
optionsSurface: {
getSnapshot: () => [],
setOption: vi.fn(),
invokeAction: vi.fn(),
subscribe: () => () => {}
}
}
})
})
await act(() => composer.result.current(text))
expect(send).toHaveBeenCalledExactlyOnceWith(text, [])
composer.unmount()
await nativeChatComposerDraftWritesSettled()
await restart()
expect(composerDraft(launch.sessionId)).toBe('')
updateNativeChatComposerDraft(scope, { text }, 'immediate')
updateNativeChatComposerDraft(scope, { text: '', document: undefined }, 'immediate')
await nativeChatComposerDraftWritesSettled()
await restart()
expect(composerDraft(launch.sessionId)).toBe('')
}
)
})
@@ -1,25 +1,37 @@
import type { TuiAgent } from '../../../shared/tui-agent'
import { structuredAgentSessionTabId } from '../../../shared/structured-agent-session-projection'
import { useAppStore } from '@/store'
import { findStructuredLaunchTab } from './structured-agent-session-launch-surface'
import {
readNativeChatComposerDraft,
structuredAgentSessionDraftScopeKey,
updateNativeChatComposerDraft
} from '@/components/native-chat/native-chat-composer-draft-store'
import { promptTextContent } from '@/components/native-chat/native-chat-prompt-document-text'
import type { StructuredAgentLaunchOptions } from './structured-agent-session-launch-callers'
import type { StructuredLaunchState } from './agent-session/launch/structured-agent-session-launch-registry'
/** Structured chats have no TUI mirror; the legacy forty-line cap would drop prompts instead of protecting TUI clearing. */
export function seedStructuredAgentLaunchDraft(
sessionId: string,
agent: TuiAgent,
state: StructuredLaunchState,
options: StructuredAgentLaunchOptions
): void {
if (options.promptDelivery !== 'draft' || !options.prompt) {
return
}
useAppStore.getState().seedNativeChatLaunchDraft({
tabId: structuredAgentSessionTabId(sessionId),
agent,
text: options.prompt,
createdAt: Date.now()
})
}
export function clearStructuredAgentLaunchDraft(sessionId: string): void {
useAppStore.getState().clearNativeChatLaunchDraft(structuredAgentSessionTabId(sessionId))
const { sessionId, worktreeId, executionHostId } = state.intent
const scopeKey = structuredAgentSessionDraftScopeKey(sessionId)
const current = readNativeChatComposerDraft(scopeKey)
if (current.text !== '' || current.document) {
return
}
const document = promptTextContent(options.prompt)
updateNativeChatComposerDraft(
scopeKey,
{ text: options.prompt, document, owner: { workspaceId: worktreeId, executionHostId } },
'immediate',
undefined,
{
at: 'end',
target: findStructuredLaunchTab(state.intent)?.id ?? structuredAgentSessionTabId(sessionId),
pending: true
}
)
}
@@ -1,4 +1,8 @@
// @vitest-environment happy-dom
import {
readNativeChatComposerDraft,
structuredAgentSessionDraftScopeKey
} from '@/components/native-chat/native-chat-composer-draft-store'
import type * as LaunchErrors from '@/lib/structured-agent-session-launch-errors'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -203,11 +207,8 @@ describe('coalesced launch delivery mode', () => {
expect(mocks.callRuntimeRpc.mock.calls.some((call) => call[1] === 'agentSession.send')).toBe(
false
)
expect(mocks.seedDraft).toHaveBeenLastCalledWith(
expect.objectContaining({
tabId: 'structured-agent-session-unset-delivery-session',
text: 'PR context'
})
)
expect(
readNativeChatComposerDraft(structuredAgentSessionDraftScopeKey(intent.sessionId)).text
).toBe('PR context')
})
})
@@ -0,0 +1,260 @@
// @vitest-environment happy-dom
import type * as LaunchErrors from '@/lib/structured-agent-session-launch-errors'
import { afterEach, beforeEach, vi, type Mock } from 'vitest'
import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-session-contracts'
import type * as RecoveryModule from '@/lib/agent-session/launch/structured-agent-session-launch-recovery'
import type { StructuredAgentSessionLaunchIntent } from '@/lib/launch-structured-agent-session'
type LaunchMocks = Record<
| 'abandonIntent'
| 'callStructuredAgentSession'
| 'callRuntimeRpc'
| 'createIntent'
| 'retryIntent'
| 'restoreIntent'
| 'launch'
| 'seedDraft'
| 'clearDraft',
Mock
> & {
rendererTabs: Record<string, unknown[]>
listeners: Set<(state: { unifiedTabsByWorktree: Record<string, unknown[]> }) => void>
}
const mocks: LaunchMocks = vi.hoisted(() => ({
abandonIntent: vi.fn(),
callStructuredAgentSession: vi.fn(),
callRuntimeRpc: vi.fn(),
createIntent: vi.fn(),
retryIntent: vi.fn(),
restoreIntent: vi.fn(),
launch: vi.fn(),
seedDraft: vi.fn(),
clearDraft: vi.fn(),
rendererTabs: {} as Record<string, unknown[]>,
listeners: new Set<(state: { unifiedTabsByWorktree: Record<string, unknown[]> }) => void>()
}))
vi.mock('sonner', () => ({
toast: {
error: vi.fn(),
message: vi.fn()
}
}))
const launchErrorMocks = vi.hoisted(() => {
class StructuredAgentSessionCreateRefusalError extends Error {}
return { StructuredAgentSessionCreateRefusalError }
})
vi.mock('@/lib/structured-agent-session-launch-errors', async () => ({
...(await vi.importActual<typeof LaunchErrors>('@/lib/structured-agent-session-launch-errors')),
...launchErrorMocks
}))
vi.mock('@/lib/structured-agent-session-launch-create-call', () => ({
launchStructuredAgentSession: mocks.launch
}))
vi.mock('@/lib/launch-structured-agent-session', () => {
return {
createStructuredAgentSessionLaunchIntent: mocks.createIntent,
retryStructuredAgentSessionLaunchIntent: mocks.retryIntent,
restoreStructuredAgentSessionLaunchIntent: mocks.restoreIntent,
abandonStructuredAgentSessionLaunchIntent: mocks.abandonIntent,
launchStructuredAgentSession: mocks.launch,
StructuredAgentSessionCreateRefusalError:
launchErrorMocks.StructuredAgentSessionCreateRefusalError
}
})
vi.mock('@/lib/agent-session/launch/structured-agent-session-launch-recovery', async () => {
const actual = await vi.importActual<typeof RecoveryModule>(
'@/lib/agent-session/launch/structured-agent-session-launch-recovery'
)
return { ...actual, launchAndReconcile: vi.fn(actual.launchAndReconcile) }
})
vi.mock('@/runtime/local-structured-session-tabs-sync/inventory-refresh', () => ({
refreshLocalStructuredSessionTabs: vi.fn()
}))
vi.mock('@/runtime/structured-agent-session-client', () => ({
// Sends reach the runtime RPC through this wrapper, as in the app; reads stay on this mock.
callStructuredAgentSession: (target: unknown, method: string, params?: unknown) =>
method === 'agentSession.send'
? mocks.callRuntimeRpc(target, method, params)
: mocks.callStructuredAgentSession(target, method, params)
}))
vi.mock('@/runtime/runtime-rpc-client', () => ({
callRuntimeRpc: mocks.callRuntimeRpc,
ensureRuntimeEnvironmentCompatible: vi.fn(async () => undefined)
}))
vi.mock('@/store', () => ({
useAppStore: {
getState: () => ({
runtimeEnvironmentCatalogHydrated: true,
unifiedTabsByWorktree: mocks.rendererTabs,
seedNativeChatLaunchDraft: mocks.seedDraft,
clearNativeChatLaunchDraft: mocks.clearDraft
}),
subscribe: (
listener: (state: { unifiedTabsByWorktree: Record<string, unknown[]> }) => void
) => {
mocks.listeners.add(listener)
return () => mocks.listeners.delete(listener)
}
}
}))
vi.mock('@/i18n/i18n', () => ({
translate: (_key: string, fallback: string, options?: { value0?: string }) =>
fallback.replace('{{value0}}', options?.value0 ?? '')
}))
vi.mock('@/lib/agent-catalog', () => ({
getAgentLabel: (agent: string) => (agent === 'codex' ? 'Codex' : 'Claude'),
getAgentCatalog: () => [
{ id: 'claude', label: 'Claude' },
{ id: 'codex', label: 'Codex' }
]
}))
import { resetStructuredAgentSessionSendsForTests } from '@/components/native-chat/structured-agent-session-message-sender'
import { refreshLocalStructuredSessionTabs } from '@/runtime/local-structured-session-tabs-sync/inventory-refresh'
import {
clearNativeChatDraftCacheForTests,
readNativeChatDraftCache
} from '@/components/native-chat/native-chat-draft-cache'
import { structuredAgentSessionDraftScopeKey } from '@/components/native-chat/native-chat-composer-draft-store'
import { resetStructuredAgentLaunchPersistenceForTests } from './agent-session/launch/structured-agent-session-launch-persistence'
import { resetStructuredAgentLaunchRegistryForTests } from './agent-session/launch/structured-agent-session-launch-registry'
import { useAppStore } from '@/store'
import { registerStructuredSelectionCatalogStore } from './structured-agent-session-selection-controller'
import { replaceRuntimeEnvironmentRevisions } from '@/runtime/runtime-environment-revision'
vi.mock('@/lib/native-chat-telemetry', () => ({ emitNativeChatMessageSent: vi.fn() }))
vi.mock('@/lib/worker-terminal-takeover-report', () => ({
reportStructuredSessionUserInput: vi.fn()
}))
function launchIntent(
worktreeId: string,
sessionId = `session-${worktreeId}`
): StructuredAgentSessionLaunchIntent {
return {
worktreeId,
executionHostId: 'local',
target: { kind: 'local' },
sessionId,
agent: 'codex',
params: {
envelope: {
sessionId,
clientOperationId: `operation-${sessionId}`,
expectedRuntimeFence: null,
payloadFingerprint: `fingerprint-${sessionId}`
},
worktree: `id:${worktreeId}`,
agent: 'codex'
}
}
}
function publishedSnapshot(worktreeId: string, sessionId: string): RuntimeMobileSessionTabsResult {
return {
worktree: worktreeId,
publicationEpoch: 'epoch-1',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: [
{
type: 'agent-session',
id: 'tab-1',
title: 'Codex',
sessionId,
agent: 'codex',
isActive: true
}
]
}
}
function publishIntent(intent: StructuredAgentSessionLaunchIntent): void {
vi.mocked(refreshLocalStructuredSessionTabs).mockResolvedValue([
publishedSnapshot(intent.worktreeId, intent.sessionId)
])
}
function sends(): unknown[][] {
return mocks.callRuntimeRpc.mock.calls.filter((call) => call[1] === 'agentSession.send')
}
function composerDraft(sessionId: string): string {
return readNativeChatDraftCache(structuredAgentSessionDraftScopeKey(sessionId))
}
async function flushLaunchSettlement(): Promise<void> {
for (let i = 0; i < 20; i += 1) {
await Promise.resolve()
}
}
let restoreCatalog: () => void
afterEach(() => {
resetStructuredAgentLaunchRegistryForTests()
replaceRuntimeEnvironmentRevisions([])
restoreCatalog()
})
beforeEach(() => {
vi.resetAllMocks()
restoreCatalog = registerStructuredSelectionCatalogStore({
read: useAppStore.getState,
subscribe: useAppStore.subscribe
})
replaceRuntimeEnvironmentRevisions([{ id: 'server-1', createdAt: 1, pairingRevision: 1 }])
localStorage.clear()
resetStructuredAgentLaunchPersistenceForTests()
resetStructuredAgentLaunchRegistryForTests()
resetStructuredAgentSessionSendsForTests()
clearNativeChatDraftCacheForTests()
mocks.rendererTabs = {}
mocks.listeners.clear()
mocks.createIntent.mockImplementation((worktreeId: string, agent: 'claude' | 'codex') => {
const intent = launchIntent(worktreeId, `${agent}-session-${worktreeId}`)
return { ...intent, agent, params: { ...intent.params, agent } }
})
mocks.retryIntent.mockImplementation((intent: StructuredAgentSessionLaunchIntent) => ({
...intent,
params: {
...intent.params,
envelope: {
...intent.params.envelope,
clientOperationId: `${intent.params.envelope.clientOperationId}-retry`
}
}
}))
mocks.callStructuredAgentSession.mockResolvedValue({
ok: true,
page: { fence: 1 }
})
mocks.callRuntimeRpc.mockResolvedValue({
ok: true,
value: { submission: { dispatchState: 'accepted' } }
})
})
export {
mocks,
launchIntent,
publishedSnapshot,
publishIntent,
sends,
composerDraft,
flushLaunchSettlement
}
@@ -1,113 +1,16 @@
// @vitest-environment happy-dom
import type * as LaunchErrors from '@/lib/structured-agent-session-launch-errors'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
mocks,
launchIntent,
publishedSnapshot,
publishIntent,
sends,
composerDraft,
flushLaunchSettlement
} from './structured-agent-session-launch.test-fixture'
import { describe, expect, it, vi } from 'vitest'
import { toast } from 'sonner'
import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-session-contracts'
import type * as RecoveryModule from '@/lib/agent-session/launch/structured-agent-session-launch-recovery'
import type { StructuredAgentSessionLaunchIntent } from '@/lib/launch-structured-agent-session'
const mocks = vi.hoisted(() => ({
abandonIntent: vi.fn(),
callStructuredAgentSession: vi.fn(),
callRuntimeRpc: vi.fn(),
createIntent: vi.fn(),
retryIntent: vi.fn(),
restoreIntent: vi.fn(),
launch: vi.fn(),
seedDraft: vi.fn(),
clearDraft: vi.fn(),
rendererTabs: {} as Record<string, unknown[]>,
listeners: new Set<(state: { unifiedTabsByWorktree: Record<string, unknown[]> }) => void>()
}))
vi.mock('sonner', () => ({
toast: {
error: vi.fn(),
message: vi.fn()
}
}))
const launchErrorMocks = vi.hoisted(() => {
class StructuredAgentSessionCreateRefusalError extends Error {}
return { StructuredAgentSessionCreateRefusalError }
})
vi.mock('@/lib/structured-agent-session-launch-errors', async () => ({
...(await vi.importActual<typeof LaunchErrors>('@/lib/structured-agent-session-launch-errors')),
...launchErrorMocks
}))
vi.mock('@/lib/structured-agent-session-launch-create-call', () => ({
launchStructuredAgentSession: mocks.launch
}))
vi.mock('@/lib/launch-structured-agent-session', () => {
return {
createStructuredAgentSessionLaunchIntent: mocks.createIntent,
retryStructuredAgentSessionLaunchIntent: mocks.retryIntent,
restoreStructuredAgentSessionLaunchIntent: mocks.restoreIntent,
abandonStructuredAgentSessionLaunchIntent: mocks.abandonIntent,
launchStructuredAgentSession: mocks.launch,
StructuredAgentSessionCreateRefusalError:
launchErrorMocks.StructuredAgentSessionCreateRefusalError
}
})
vi.mock('@/lib/agent-session/launch/structured-agent-session-launch-recovery', async () => {
const actual = await vi.importActual<typeof RecoveryModule>(
'@/lib/agent-session/launch/structured-agent-session-launch-recovery'
)
return { ...actual, launchAndReconcile: vi.fn(actual.launchAndReconcile) }
})
vi.mock('@/runtime/local-structured-session-tabs-sync/inventory-refresh', () => ({
refreshLocalStructuredSessionTabs: vi.fn()
}))
vi.mock('@/runtime/structured-agent-session-client', () => ({
// Sends reach the runtime RPC through this wrapper, as in the app; reads stay on this mock.
callStructuredAgentSession: (target: unknown, method: string, params?: unknown) =>
method === 'agentSession.send'
? mocks.callRuntimeRpc(target, method, params)
: mocks.callStructuredAgentSession(target, method, params)
}))
vi.mock('@/runtime/runtime-rpc-client', () => ({
callRuntimeRpc: mocks.callRuntimeRpc,
ensureRuntimeEnvironmentCompatible: vi.fn(async () => undefined)
}))
vi.mock('@/store', () => ({
useAppStore: {
getState: () => ({
runtimeEnvironmentCatalogHydrated: true,
unifiedTabsByWorktree: mocks.rendererTabs,
seedNativeChatLaunchDraft: mocks.seedDraft,
clearNativeChatLaunchDraft: mocks.clearDraft
}),
subscribe: (
listener: (state: { unifiedTabsByWorktree: Record<string, unknown[]> }) => void
) => {
mocks.listeners.add(listener)
return () => mocks.listeners.delete(listener)
}
}
}))
vi.mock('@/i18n/i18n', () => ({
translate: (_key: string, fallback: string, options?: { value0?: string }) =>
fallback.replace('{{value0}}', options?.value0 ?? '')
}))
vi.mock('@/lib/agent-catalog', () => ({
getAgentLabel: (agent: string) => (agent === 'codex' ? 'Codex' : 'Claude'),
getAgentCatalog: () => [
{ id: 'claude', label: 'Claude' },
{ id: 'codex', label: 'Codex' }
]
}))
import { StructuredAgentSessionCreateRefusalError } from '@/lib/launch-structured-agent-session'
import { refreshLocalStructuredSessionTabs } from '@/runtime/local-structured-session-tabs-sync/inventory-refresh'
import { launchAndReconcile } from '@/lib/agent-session/launch/structured-agent-session-launch-recovery'
@@ -117,180 +20,10 @@ import {
retryStructuredAgentSessionLaunch,
startStructuredAgentLaunch
} from './structured-agent-session-launch'
import { resetStructuredAgentSessionSendsForTests } from '@/components/native-chat/structured-agent-session-message-sender'
import {
clearNativeChatDraftCacheForTests,
readNativeChatDraftCache
} from '@/components/native-chat/native-chat-draft-cache'
import { structuredAgentSessionDraftScopeKey } from '@/components/native-chat/native-chat-composer-draft-store'
import { hasStagedStructuredLaunchPrompt } from './structured-agent-session-launch-prompt'
import { resetStructuredAgentLaunchPersistenceForTests } from './agent-session/launch/structured-agent-session-launch-persistence'
import { resetStructuredAgentLaunchRegistryForTests } from './agent-session/launch/structured-agent-session-launch-registry'
import { getStructuredAgentSessionLaunchSelection } from './structured-agent-session-launch-options'
import { useAppStore } from '@/store'
import { registerStructuredSelectionCatalogStore } from './structured-agent-session-selection-controller'
import { replaceRuntimeEnvironmentRevisions } from '@/runtime/runtime-environment-revision'
let restoreCatalog: () => void
afterEach(() => {
resetStructuredAgentLaunchRegistryForTests()
replaceRuntimeEnvironmentRevisions([])
restoreCatalog()
})
function launchIntent(
worktreeId: string,
sessionId = `session-${worktreeId}`
): StructuredAgentSessionLaunchIntent {
return {
worktreeId,
executionHostId: 'local',
target: { kind: 'local' },
sessionId,
agent: 'codex',
params: {
envelope: {
sessionId,
clientOperationId: `operation-${sessionId}`,
expectedRuntimeFence: null,
payloadFingerprint: `fingerprint-${sessionId}`
},
worktree: `id:${worktreeId}`,
agent: 'codex'
}
}
}
function publishedSnapshot(worktreeId: string, sessionId: string): RuntimeMobileSessionTabsResult {
return {
worktree: worktreeId,
publicationEpoch: 'epoch-1',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: [
{
type: 'agent-session',
id: 'tab-1',
title: 'Codex',
sessionId,
agent: 'codex',
isActive: true
}
]
}
}
function publishIntent(intent: StructuredAgentSessionLaunchIntent): void {
vi.mocked(refreshLocalStructuredSessionTabs).mockResolvedValue([
publishedSnapshot(intent.worktreeId, intent.sessionId)
])
}
function sends(): unknown[][] {
return mocks.callRuntimeRpc.mock.calls.filter((call) => call[1] === 'agentSession.send')
}
function composerDraft(sessionId: string): string {
return readNativeChatDraftCache(structuredAgentSessionDraftScopeKey(sessionId))
}
async function flushLaunchSettlement(): Promise<void> {
for (let i = 0; i < 20; i += 1) {
await Promise.resolve()
}
}
describe('startStructuredAgentLaunch', () => {
beforeEach(() => {
vi.resetAllMocks()
restoreCatalog = registerStructuredSelectionCatalogStore({
read: useAppStore.getState,
subscribe: useAppStore.subscribe
})
replaceRuntimeEnvironmentRevisions([{ id: 'server-1', createdAt: 1, pairingRevision: 1 }])
localStorage.clear()
resetStructuredAgentLaunchPersistenceForTests()
resetStructuredAgentLaunchRegistryForTests()
resetStructuredAgentSessionSendsForTests()
clearNativeChatDraftCacheForTests()
mocks.rendererTabs = {}
mocks.listeners.clear()
mocks.createIntent.mockImplementation((worktreeId: string, agent: 'claude' | 'codex') => {
const intent = launchIntent(worktreeId, `${agent}-session-${worktreeId}`)
return { ...intent, agent, params: { ...intent.params, agent } }
})
mocks.retryIntent.mockImplementation((intent: StructuredAgentSessionLaunchIntent) => ({
...intent,
params: {
...intent.params,
envelope: {
...intent.params.envelope,
clientOperationId: `${intent.params.envelope.clientOperationId}-retry`
}
}
}))
mocks.callStructuredAgentSession.mockResolvedValue({
ok: true,
page: { fence: 1 }
})
mocks.callRuntimeRpc.mockResolvedValue({
ok: true,
value: { submission: { dispatchState: 'accepted' } }
})
})
it('keeps launch drafts in the composer without staging or sending a turn', async () => {
const worktreeId = 'wt-draft'
const intent = launchIntent(worktreeId, 'draft-session')
mocks.createIntent.mockReturnValueOnce(intent)
mocks.launch.mockResolvedValue({ sessionId: intent.sessionId, fence: 1 })
publishIntent(intent)
const launch = startStructuredAgentLaunch(worktreeId, 'codex', {
requestId: 'request-1',
prompt: 'PR #19423 — review this change',
promptDelivery: 'draft'
})
await launch.launchResult
expect(mocks.seedDraft).toHaveBeenCalledWith({
tabId: 'structured-agent-session-draft-session',
agent: 'codex',
text: 'PR #19423 — review this change',
createdAt: expect.any(Number)
})
expect(hasStagedStructuredLaunchPrompt(intent.sessionId)).toBe(false)
expect(launch.promptDeliveryResult).toBeUndefined()
expect(sends()).toHaveLength(0)
})
it('seeds a draft longer than the terminal mirror cap under the projected tab id', async () => {
const worktreeId = 'wt-long-draft'
const intent = launchIntent(worktreeId, 'long-draft-session')
mocks.createIntent.mockReturnValueOnce(intent)
mocks.launch.mockResolvedValue({ sessionId: intent.sessionId, fence: 1 })
publishIntent(intent)
const sixtyLineDraft = Array.from({ length: 60 }, (_, i) => `line ${i + 1}`).join('\n')
const launch = startStructuredAgentLaunch(worktreeId, 'codex', {
requestId: 'request-2',
prompt: sixtyLineDraft,
promptDelivery: 'draft'
})
await launch.launchResult
expect(mocks.seedDraft).toHaveBeenCalledWith({
tabId: 'structured-agent-session-long-draft-session',
agent: 'codex',
text: sixtyLineDraft,
createdAt: expect.any(Number)
})
expect(hasStagedStructuredLaunchPrompt(intent.sessionId)).toBe(false)
})
it('preserves the draft seed when the launch is definitively refused', async () => {
const worktreeId = 'wt-draft-refused'
const intent = launchIntent(worktreeId, 'refused-draft-session')
@@ -307,8 +40,7 @@ describe('startStructuredAgentLaunch', () => {
)
await flushLaunchSettlement()
expect(mocks.seedDraft).toHaveBeenCalledOnce()
expect(mocks.clearDraft).not.toHaveBeenCalled()
expect(composerDraft(intent.sessionId)).toBe('review this')
expect(getStructuredAgentSessionLaunchLifecycle(worktreeId, intent.sessionId)).toBe('failed')
})
@@ -327,12 +59,11 @@ describe('startStructuredAgentLaunch', () => {
await expect(launch.launchResult).rejects.toThrow()
await flushLaunchSettlement()
expect(mocks.seedDraft).toHaveBeenCalledOnce()
expect(mocks.clearDraft).not.toHaveBeenCalled()
expect(composerDraft(intent.sessionId)).toBe('review this')
expect(getStructuredAgentSessionLaunchLifecycle(worktreeId, intent.sessionId)).toBe('failed')
})
it('clears the draft seed when the launch is cancelled', async () => {
it('preserves the ordinary draft seed when the launch is cancelled', async () => {
const worktreeId = 'wt-draft-cancelled'
const intent = launchIntent(worktreeId, 'cancelled-draft-session')
const create = Promise.withResolvers<{ sessionId: string; fence: number }>()
@@ -350,9 +81,7 @@ describe('startStructuredAgentLaunch', () => {
await expect(launch.launchResult).rejects.toThrow('structured session launch cancelled')
await flushLaunchSettlement()
expect(mocks.clearDraft).toHaveBeenCalledWith(
'structured-agent-session-cancelled-draft-session'
)
expect(composerDraft(intent.sessionId)).toBe('review this')
})
it('opens the chat without an informational progress toast', async () => {
@@ -899,12 +628,6 @@ describe('startStructuredAgentLaunch', () => {
expect(sends().map((call) => call[2])).toEqual([
expect.objectContaining({ envelope: expect.objectContaining({ sessionId: sent.sessionId }) })
])
expect(mocks.seedDraft).toHaveBeenCalledOnce()
expect(mocks.seedDraft).toHaveBeenCalledWith(
expect.objectContaining({
tabId: 'structured-agent-session-coalesced-delivery-session',
text: 'PR #1 context'
})
)
expect(composerDraft(drafted.sessionId)).toBe('PR #1 context')
})
})
@@ -165,7 +165,6 @@ function promptOwner(options: StructuredAgentLaunchOptions): { callerKeepsText?:
function joinStructuredLaunchState(
existing: StructuredLaunchState,
agent: TuiAgent,
options: StructuredAgentLaunchOptions
): StructuredLaunchStateResult | undefined {
// A re-delivery of the same action shares the text it staged, so it is sent once.
@@ -183,7 +182,7 @@ function joinStructuredLaunchState(
releaseStructuredLaunchSource(existing)
}
if (!retrying && !repeat) {
launchDraft.seedStructuredAgentLaunchDraft(existing.intent.sessionId, agent, joined)
launchDraft.seedStructuredAgentLaunchDraft(existing, joined)
}
// A re-delivery waits on the text its action staged, if any, and never stages its own.
const { prompt: _retryPrompt, ...joinedWithoutPrompt } = joined
@@ -206,7 +205,7 @@ function structuredAgentLaunchState(
): StructuredLaunchStateResult {
const identity = structuredLaunchIdentity(worktreeId, agent, options)
const existing = getJoinableStructuredLaunchState(identity, options.requestId)
const joined = existing && joinStructuredLaunchState(existing, agent, options)
const joined = existing && joinStructuredLaunchState(existing, options)
if (joined) {
return joined
}
@@ -226,7 +225,6 @@ function structuredAgentLaunchState(
const stagedPrompt = text
? stageStructuredLaunchPrompt(intent.sessionId, text, promptOwner(options))
: null
launchDraft.seedStructuredAgentLaunchDraft(intent.sessionId, agent, options)
const callers = createStructuredLaunchCallerGroup({
kind: 'first',
requestId: options.requestId,
@@ -243,6 +241,7 @@ function structuredAgentLaunchState(
callers,
selection: initialStructuredLaunchSelection(intent)
}
launchDraft.seedStructuredAgentLaunchDraft(state, options)
state.onHostSeed = (seedOptions) => adoptPairedHostSeed(state, seedOptions)
callers.onSettled = () => maybeCleanupLaunchState(state)
structuredLaunchSelectionController(state)
@@ -275,7 +274,6 @@ export function cancelStructuredAgentLaunch(worktreeId: string, sessionId: strin
useAppStore.getState()
)
discardStructuredAgentSessionChatSends(state.intent.sessionId)
launchDraft.clearStructuredAgentLaunchDraft(state.intent.sessionId)
abandonStructuredAgentSessionLaunchIntent(state.intent)
notifyStructuredLaunchListeners()
return true
@@ -1,14 +1,13 @@
// @vitest-environment happy-dom
import type * as LaunchErrors from '@/lib/structured-agent-session-launch-errors'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest'
import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-session-contracts'
import type { Tab, TabGroup, TabGroupLayoutNode } from '../../../shared/tab-types'
import type { AgentSessionStatusSummary } from '../../../shared/agent-session-wire'
import type { StructuredAgentSessionLaunchIntent } from '@/lib/launch-structured-agent-session'
import type * as LaunchAdmissionModule from './structured-agent-session-launch-admission'
import type * as RpcClientModule from '@/runtime/runtime-rpc-client'
import type { AppState } from '@/store/types'
const mocks = vi.hoisted(() => ({
createIntent: vi.fn(),
@@ -51,13 +50,9 @@ function emptyStoreState(): StoreState {
nativeChatLaunchDraftByTabId: {}
}
}
const store = vi.hoisted((): { state: StoreState } => ({ state: emptyStoreState() }))
type DrawnStore = {
getState: () => AppState
subscribe: (listener: (state: AppState, previous: AppState) => void) => () => void
}
/** Switch on: a real store drawn from main's frames stands in for `store`. */
const drawn = vi.hoisted((): { store: DrawnStore | null } => ({ store: null }))
const owner = vi.hoisted((): { store: ReturnType<typeof createTestStore> | null } => ({
store: null
}))
vi.mock('sonner', () => ({ toast: { error: vi.fn(), info: vi.fn(), message: vi.fn() } }))
vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback }))
@@ -130,46 +125,9 @@ vi.mock('@/runtime/structured-agent-session-status-feed', () => ({
)
})
}))
vi.mock('@/store', () => ({
useAppStore: {
getState: () =>
drawn.store
? {
...drawn.store.getState(),
activateTab: mocks.activateTab,
focusGroup: mocks.focusGroup
}
: standInState(),
subscribe: (listener: (state: AppState, previous: AppState) => void) =>
drawn.store?.subscribe(listener) ?? (() => undefined)
}
}))
function standInState() {
return {
...store.state,
createUnifiedTab: (
worktreeId: string,
contentType: Tab['contentType'],
init: { targetGroupId?: string }
) => {
const groupId =
init.targetGroupId ?? store.state.activeGroupIdByWorktree[worktreeId] ?? 'group-left'
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the launch passes the agent-session fields a structured tab carries.
const tab = { ...init, contentType, worktreeId, groupId, createdAt: 1 } as Tab
store.state.unifiedTabsByWorktree[worktreeId] = [
...(store.state.unifiedTabsByWorktree[worktreeId] ?? []),
tab
]
return tab
},
activateTab: mocks.activateTab,
focusGroup: mocks.focusGroup,
setActiveTabType: vi.fn(),
seedNativeChatLaunchDraft: vi.fn(),
clearNativeChatLaunchDraft: vi.fn()
}
}
vi.mock('@/store', async () =>
(await import('./launch-parity-renderer.test-fixture')).launchStoreModuleMock(owner)
)
import { resetStructuredAgentSessionSendsForTests } from '@/components/native-chat/structured-agent-session-message-sender'
import { clearNativeChatDraftCacheForTests } from '@/components/native-chat/native-chat-draft-cache'
@@ -185,6 +143,8 @@ import {
} from './structured-agent-session-launch-prompt'
import { resetStructuredAgentLaunchPersistenceForTests } from './agent-session/launch/structured-agent-session-launch-persistence'
import { resetStructuredAgentLaunchRegistryForTests } from './agent-session/launch/structured-agent-session-launch-registry'
import { layoutApplyTestTransport } from '@/runtime/layout-apply-test-transport.test-fixture'
import { isPendingTab } from '@/runtime/layout-owner-pending-tabs'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch'
import { createTestStore, makeWorktree, seedStore } from '@/store/slices/store-test-helpers'
import {
@@ -237,9 +197,10 @@ function published(...sessionIds: string[]): RuntimeMobileSessionTabsResult[] {
}
let main: TabsDrawnFromMain | null = null
let warnings: MockInstance<typeof console.warn>
// Frame-drawn split workspace: each side needs a terminal because main drops empty groups.
async function drawSplitFromMain(): Promise<void> {
async function seedSplit(): Promise<void> {
const real = createTestStore()
const side = (groupId: string): Tab => ({
id: `terminal-${groupId}`,
@@ -258,37 +219,67 @@ async function drawSplitFromMain(): Promise<void> {
worktreesByRepo: { repo: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo' })] },
activeWorktreeId: WORKTREE_ID,
tabsByWorktree: {
[WORKTREE_ID]: ['group-left', 'group-right'].map((groupId, index) => ({
id: `terminal-${groupId}`,
ptyId: null,
worktreeId: WORKTREE_ID,
title: 'Terminal',
customTitle: null,
color: null,
sortOrder: index,
createdAt: 1
}))
[WORKTREE_ID]: (ORCA_LAYOUT_OWNER_IS_MAIN ? ['group-left', 'group-right'] : []).map(
(groupId, index) => ({
id: `terminal-${groupId}`,
ptyId: null,
worktreeId: WORKTREE_ID,
title: 'Terminal',
customTitle: null,
color: null,
sortOrder: index,
createdAt: 1
})
)
},
unifiedTabsByWorktree: {
[WORKTREE_ID]: ORCA_LAYOUT_OWNER_IS_MAIN ? [side('group-left'), side('group-right')] : []
},
unifiedTabsByWorktree: { [WORKTREE_ID]: [side('group-left'), side('group-right')] },
groupsByWorktree: {
[WORKTREE_ID]: seeded.groupsByWorktree[WORKTREE_ID]!.map((group) => ({
...group,
activeTabId: `terminal-${group.id}`,
tabOrder: [`terminal-${group.id}`]
activeTabId: ORCA_LAYOUT_OWNER_IS_MAIN ? `terminal-${group.id}` : null,
tabOrder: ORCA_LAYOUT_OWNER_IS_MAIN ? [`terminal-${group.id}`] : []
}))
},
layoutByWorktree: seeded.layoutByWorktree,
activeGroupIdByWorktree: seeded.activeGroupIdByWorktree
})
owner.store = real
const { activateTab, focusGroup } = real.getState()
real.setState({
activateTab: mocks.activateTab.mockImplementation(activateTab),
focusGroup: mocks.focusGroup.mockImplementation(focusGroup)
})
main = await drawTabsFromMain(real)
drawn.store = real
}
/** The chat tabs the workspace shows: switch-on, as main's frames drew them. */
async function openedChats(): Promise<Tab[]> {
await main?.settle()
const tabs = (drawn.store?.getState() ?? store.state).unifiedTabsByWorktree[WORKTREE_ID] ?? []
return tabs.filter((tab) => tab.contentType === 'agent-session')
const tabs = owner.store!.getState().unifiedTabsByWorktree[WORKTREE_ID] ?? []
const chats = tabs.filter((tab) => tab.contentType === 'agent-session')
for (const tab of chats) {
expect(owner.store!.getState().getTab(tab.id)).toBe(tab)
}
return chats
}
const owned: {
handle: Exclude<StructuredAgentSessionProvisionalLaunch, { sessionId: null }>
done: boolean
}[] = []
const heldCreates: {
intent: StructuredAgentSessionLaunchIntent
resolve: (receipt: { sessionId: string; fence: number }) => void
}[] = []
function holdCreates(): void {
mocks.launch.mockImplementation(
(intent: StructuredAgentSessionLaunchIntent) =>
new Promise<{ sessionId: string; fence: number }>((resolve) =>
heldCreates.push({ intent, resolve })
)
)
}
const first = launchIntent('session-first')
@@ -321,6 +312,11 @@ function pick(
if (!launch || launch.sessionId === null) {
throw new Error('expected a local chat')
}
const pending = { handle: launch, done: false }
owned.push(pending)
void launch.settlement.then(() => {
pending.done = true
})
return launch
}
@@ -350,7 +346,6 @@ beforeEach(() => {
}
mocks.statusBySession.clear()
mocks.liveSessions.clear()
store.state = emptyStoreState()
mocks.createIntent
.mockReturnValueOnce(first)
.mockReturnValueOnce(second)
@@ -366,20 +361,41 @@ beforeEach(() => {
})
beforeEach(async () => {
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
await drawSplitFromMain()
}
await seedSplit()
warnings = vi.spyOn(console, 'warn')
expect(owner.store!.getState().getTab('structured-agent-session-session-first')).toBeNull()
})
afterEach(() => {
afterEach(async () => {
for (const pending of owned) {
if (!pending.done) {
pending.handle.cancel()
}
}
for (const { intent, resolve } of heldCreates.splice(0)) {
resolve({ sessionId: intent.sessionId, fence: 1 })
}
await Promise.all(owned.splice(0).map(({ handle }) => handle.settlement))
await main?.settle()
expect(heldCreates).toEqual([])
expect(layoutApplyTestTransport.pendingCount).toBe(0)
for (const tab of owner.store!.getState().unifiedTabsByWorktree[WORKTREE_ID] ?? []) {
expect(isPendingTab(tab.id)).toBe(false)
}
expect(
warnings.mock.calls.filter(
([message]) => message === '[layout-owner] pending tab waiter threw:'
)
).toEqual([])
main?.close()
vi.restoreAllMocks()
main = null
drawn.store = null
owner.store = null
})
describe('a second "new chat" with no text', () => {
it('opens a second chat while the first empty one is still starting', async () => {
mocks.launch.mockImplementation(() => new Promise(() => undefined))
holdCreates()
const firstPick = pick('plus-pick-1')
const secondPick = pick('plus-pick-2')
@@ -403,7 +419,7 @@ describe('a second "new chat" with no text', () => {
})
it('opens one chat when the same pick is delivered twice', () => {
mocks.launch.mockImplementation(() => new Promise(() => undefined))
holdCreates()
const firstPick = pick('plus-pick-1')
expect(pick('plus-pick-1').sessionId).toBe(firstPick.sessionId)
@@ -426,7 +442,7 @@ describe('a "new chat" with text', () => {
})
it('opens its own chat beside an empty one still starting', async () => {
mocks.launch.mockImplementation(() => new Promise(() => undefined))
holdCreates()
const blank = pick('plus-pick-1')
const notes = pick('notes-send', { prompt: 'review notes' })
@@ -438,7 +454,7 @@ describe('a "new chat" with text', () => {
})
it('opens its own chat in the split it was sent from', async () => {
mocks.launch.mockImplementation(() => new Promise(() => undefined))
holdCreates()
pick('plus-pick-1', { group: 'group-left' })
const notes = pick('notes-send', { prompt: 'review notes', group: 'group-right' })
@@ -88,7 +88,10 @@ export function applyStructuredSessionTabSnapshots(
},
changedAgentPaneKeys
),
{ frames: [] }
{ frames: [] },
undefined,
false,
snapshots.map(({ worktree }) => worktree)
)
settleStructuredSessionMirror()
const { setTabLabel } = useAppStore.getState()
@@ -1,3 +1,4 @@
import { retireRemovedNativeChatDraftPositions } from '@/components/native-chat/native-chat-draft-cache'
import {
markStructuredAgentSessionLaunchesPublished,
publishedStructuredSessions
@@ -37,7 +38,10 @@ export function applyWebSessionTabsStorePatch(
) => WebSessionTabsSyncState | Partial<WebSessionTabsSyncState>,
hostMirrorVerdict: HostSessionMirrorPatchVerdict,
agentStatusSnapshots?: RuntimeMobileSessionTabsResult | readonly RuntimeMobileSessionTabsResult[],
allowCompletionNotification = false
allowCompletionNotification = false,
affectedWorkspaces = hostMirrorVerdict.frames
.filter(({ decision }) => decision.apply)
.map(({ worktreeId }) => worktreeId)
): HostSessionMirrorSettle {
let mirroredAgentStatusChanged = false
// Zustand commits before notifying subscribers, so a completed producer has landed even if a subscriber throws.
@@ -181,6 +185,12 @@ export function applyWebSessionTabsStorePatch(
}
}
}
for (const key of new Set(affectedWorkspaces)) {
retireRemovedNativeChatDraftPositions(
state.unifiedTabsByWorktree[key] ?? [],
(patch.unifiedTabsByWorktree ?? state.unifiedTabsByWorktree)[key] ?? []
)
}
patchCommitted = true
return patch
}
@@ -88,8 +88,8 @@ export function openWorkspaceLayoutFrameSync(
/** The moved tabs' selections this flush's writes took. */
let selectionsTaken: MovedTabSelection[] = []
const show = (patch: LayoutFrameBuildPatch): void => {
selectionsTaken.push(...showFramePatch(store, patch))
const show = (patch: LayoutFrameBuildPatch, rebuiltWorkspaces?: readonly string[]): void => {
selectionsTaken.push(...showFramePatch(store, patch, rebuiltWorkspaces))
}
// Each change against the cache's copy it applies to, before the frame replaces it.
@@ -189,16 +189,14 @@ export function openWorkspaceLayoutFrameSync(
// One update: a move's or rename's content rekeys with the frame that shows it.
const rekeyed = shownContentRekeyPatch(state, cache)
const base: AppState = { ...state, ...rekeyed }
show({
...rekeyed,
...layoutFrameFlushPatch(base, cache, { fullBuilt, workspaceBuilt, rebound }, holds)
})
const builtKeys = [...fullBuilt, ...workspaceBuilt]
const patch = layoutFrameFlushPatch(base, cache, { fullBuilt, workspaceBuilt, rebound }, holds)
show({ ...rekeyed, ...patch }, builtKeys)
if (titleUpdates.length > 0) {
store.getState().updateTabTitles(titleUpdates)
}
showFramePaneStarts(store, changed, cache, paneStartsShown)
// Run after the apply check: the focus is the user's selection, not the frame's.
const builtKeys = [...fullBuilt, ...workspaceBuilt]
const followHeldTabs = heldTabGroupFocus(base, store, builtKeys, holds.held)
for (const key of builtKeys) {
shown.add(key)
@@ -1,3 +1,4 @@
import { retireRemovedNativeChatDraftPositions } from '@/components/native-chat/native-chat-draft-cache'
// Select moved tabs with the frame showing the move (L120); a later reply may already be superseded by another drag.
import type { AppState } from '../../types'
@@ -85,12 +86,20 @@ export function withMovedTabsSelected(
/** Writes a frame's patch, with the selection of each moved tab it shows; returns those moves. */
export function showFramePatch(
store: { getState: () => AppState; setState: (patch: Partial<AppState>) => void },
patch: Partial<AppState>
patch: Partial<AppState>,
rebuiltWorkspaces: readonly string[] = []
): MovedTabSelection[] {
if (Object.keys(patch).length === 0) {
return []
}
const shown = withMovedTabSelections(store.getState(), patch)
const before = store.getState()
const shown = withMovedTabSelections(before, patch)
for (const key of rebuiltWorkspaces) {
retireRemovedNativeChatDraftPositions(
before.unifiedTabsByWorktree[key] ?? [],
(shown.patch.unifiedTabsByWorktree ?? before.unifiedTabsByWorktree)[key] ?? []
)
}
store.setState(shown.patch)
return shown.taken
}
@@ -1,3 +1,4 @@
import { retireRemovedNativeChatDraftPositions } from '@/components/native-chat/native-chat-draft-cache'
import { retireStructuredAgentSessionReadOwner } from '@/components/native-chat/structured-agent-session-read-owner-registry'
import type { TabsSlice, TabsSliceGet, TabsSliceSet } from './tabs-slice-contract'
import { collapseGroupLayout } from '../../../../../shared/workspace-layout/tab-group-layout-tree'
@@ -14,7 +15,6 @@ import {
hasStructuredAgentSessionLaunchCancellationTombstone,
shouldRetainStructuredAgentSessionLaunchTab
} from '@/lib/agent-session/launch/structured-agent-session-launch-registry'
import { structuredAgentSessionTabId } from '../../../../../shared/structured-agent-session-projection'
import { clearWebSessionFocusIntentIfMatches } from '@/runtime/web-session-focus-intent'
import { ownsGlobalSelection } from '../../global-selection-owner'
import {
@@ -98,7 +98,6 @@ export function createTabsCloseActions(
// Closing still removes the tab; no host can be named to stop its chat on.
console.warn('[structured-agent-session] close found no owning host', tab.entityId)
}
get().clearNativeChatLaunchDraft(structuredAgentSessionTabId(tab.entityId))
// The unsent draft stays: it belongs to the conversation, which can be reopened from history.
}
const nextActiveTabId =
@@ -121,9 +120,12 @@ export function createTabsCloseActions(
const closeHere = (): void =>
settleAttentionRemovedBy(set, get, () =>
set((current) => {
const nextTabs = (current.unifiedTabsByWorktree[worktreeId] ?? []).filter(
(item) => item.id !== tabId
)
const nextTabs = (current.unifiedTabsByWorktree[worktreeId] ?? []).filter((item) => {
if (item.id === tabId) {
retireRemovedNativeChatDraftPositions([item], [])
}
return item.id !== tabId
})
// Bulk closes bypass terminals.closeTab, so clear entity-keyed unread markers here too.
const nextUnreadTerminalTabs = terminalEntityId
? omitRecordKeys(current.unreadTerminalTabs, [terminalEntityId])