Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.
TypeScript adeagent-ideai-agentsautomationbotclaude-codecodexghosttygrok-bothermes-agentmobile-appmuseopenclawopencodeorchestrationpiruntimeterminalworktreesyc-backed
fix(mobile): grow chat composer with its draft (#36083)
Kelvin Amoaba5ecfa8d5f531
diff --git a/config/scripts/mobile-web-app/mobile-web-app-composer-sizing-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-composer-sizing-render.test.mjsnew file mode 100644index 00000000000..e9c9efc69d7--- /dev/null+++ b/config/scripts/mobile-web-app/mobile-web-app-composer-sizing-render.test.mjs@@ -0,0 +1,248 @@+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import * as esbuild from 'esbuild'+import { chromium, webkit } from 'playwright-core'+import {+ MOBILE_WEB_APP_NATIVE_PARITY_STYLE,+ MOBILE_WEB_APP_ROOT_RESET,+ mobileWebAppBuildOptions+} from '../build-mobile-web-app-bundle.mjs'+import { mobileWebAppDependenciesPresent } from './mobile-web-app-bundle-dependencies.mjs'+import { createBundleServer, readShellCsp } from './preview/mobile-web-app-render-harness.mjs'++const mobileDir = fileURLToPath(new URL('../../../mobile', import.meta.url))+const engines = [+ {+ name: 'chromium',+ launch: () => {+ const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER+ return chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })+ }+ },+ { name: 'webkit', launch: () => webkit.launch({ headless: true }) }+]++const entry = `+import { useState } from 'react'+import { createRoot } from 'react-dom/client'+import { View } from 'react-native'+import { MobileNativeChatComposerField } from './src/session/native-chat/composer/MobileNativeChatComposerField.web'+import { publishShellKeyboardSource } from './src/platform/keyboard-occlusion'++let keyboardHeight = 0+const listeners = new Set()+if (location.hash !== '#browser') {+ publishShellKeyboardSource({+ read: () => keyboardHeight,+ subscribe: (listener) => {+ listeners.add(listener)+ return () => listeners.delete(listener)+ }+ })+}+window.setShellKeyboard = (height) => {+ keyboardHeight = height+ listeners.forEach((listener) => listener(height))+}+function Composer() {+ const [state, setState] = useState({ value: '', placeholder: 'Message', dictationPreview: null })+ window.updateComposer = (patch) => setState((previous) => ({ ...previous, ...patch }))+ return <View style={{ flex: 1, padding: 12 }}>+ <MobileNativeChatComposerField+ {...state}+ skillToken={null}+ multiline+ scrollEnabled+ accessibilityLabel="Message"+ onChangeText={(value) => setState((previous) => ({ ...previous, value }))}+ />+ </View>+}+createRoot(document.getElementById('root')).render(<Composer />)+`++const bundles = mobileWebAppDependenciesPresent()+const describeSizing = bundles ? describe : describe.skip+const browsers = new Map()+let scratch+let server+let origin++beforeAll(async () => {+ if (!bundles) {+ return+ }+ await mkdir(join(mobileDir, '.tmp'), { recursive: true })+ scratch = await mkdtemp(join(mobileDir, '.tmp', 'composer-sizing-'))+ const outDir = join(scratch, 'bundle')+ await esbuild.build({+ ...mobileWebAppBuildOptions([]),+ entryPoints: undefined,+ stdin: { contents: entry, resolveDir: mobileDir, loader: 'tsx', sourcefile: 'composer.tsx' },+ splitting: false,+ write: true,+ outdir: outDir,+ entryNames: 'composer',+ metafile: false+ })+ await writeFile(+ join(outDir, 'index.html'),+ `<!doctype html><html><head><meta charset="utf-8">${MOBILE_WEB_APP_ROOT_RESET}` ++ `${MOBILE_WEB_APP_NATIVE_PARITY_STYLE}</head><body><div id="root"></div>` ++ '<script type="module" src="/composer.js"></script></body></html>'+ )+ const served = await createBundleServer({ outDir, cspHeader: await readShellCsp() })+ server = served.server+ origin = served.origin+ for (const engine of engines) {+ browsers.set(engine.name, await engine.launch())+ }+}, 180_000)++afterAll(async () => {+ for (const browser of browsers.values()) {+ await browser.close()+ }+ server?.close()+ if (scratch) {+ await rm(scratch, { recursive: true, force: true })+ }+})++async function openPage(engine, mode = 'shell') {+ const page = await browsers.get(engine.name).newPage({ viewport: { width: 390, height: 844 } })+ if (mode === 'browser') {+ // Model iOS's shrinking visual viewport; RN Web and our keyboard subscription read it independently.+ await page.addInitScript(() => {+ let keyboard = 0+ const viewport = window.visualViewport+ Object.defineProperty(viewport, 'height', { get: () => window.innerHeight - keyboard })+ window.setVisualKeyboard = (height) => {+ keyboard = height+ viewport.dispatchEvent(new Event('resize'))+ }+ })+ }+ await page.goto(`${origin}/#${mode}`, { waitUntil: 'load' })+ const field = page.getByRole('textbox', { name: 'Message' })+ await field.waitFor({ state: 'visible' })+ return { page, field }+}++function height(field) {+ return field.evaluate((input) => input.getBoundingClientRect().height)+}++const longDraft = Array.from({ length: 30 }, (_, index) => `Line ${index + 1}`).join('\n')++describeSizing.each(engines)('web composer sizing in $name', (engine) => {+ it('grows for newlines and wrapping, remeasures width, and shrinks without losing focus', async () => {+ const { page, field } = await openPage(engine)+ try {+ await field.fill('Short draft')+ const compact = await height(field)+ await field.fill('First line\nSecond line\nThird line')+ await expect.poll(() => height(field)).toBeGreaterThan(compact)+ expect(await field.evaluate((input) => input.scrollHeight <= input.clientHeight)).toBe(true)++ await field.fill('Review the mobile composer and keep all draft text visible. '.repeat(4))+ await expect.poll(() => height(field)).toBeGreaterThan(compact * 2)+ const narrow = await height(field)+ await page.setViewportSize({ width: 844, height: 844 })+ await expect.poll(() => height(field)).toBeLessThan(narrow)+ await expect+ .poll(() => field.evaluate((input) => input.scrollHeight - input.clientHeight))+ .toBeLessThanOrEqual(1)+ expect(await field.evaluate((input) => document.activeElement === input)).toBe(true)++ await field.fill('Short draft')+ await expect.poll(() => height(field)).toBe(compact)+ } finally {+ await page.close()+ }+ })++ it('fits a wrapping placeholder as fully as the same text entered as a draft', async () => {+ const { page, field } = await openPage(engine)+ try {+ await page.setViewportSize({ width: 320, height: 568 })+ const compact = await height(field)+ const placeholder = 'Describe the changes you want to make to the mobile composer input.'+ await page.evaluate((placeholder) => window.updateComposer({ placeholder }), placeholder)+ await expect.poll(() => height(field)).toBeGreaterThan(compact)+ const placeholderHeight = await height(field)+ await field.fill(placeholder)+ await expect.poll(() => height(field)).toBe(placeholderHeight)+ expect(await field.evaluate((input) => input.scrollHeight <= input.clientHeight)).toBe(true)+ await field.fill('')+ await expect.poll(() => height(field)).toBe(placeholderHeight)+ await page.evaluate(() => window.updateComposer({ placeholder: 'Message' }))+ await expect.poll(() => height(field)).toBe(compact)+ } finally {+ await page.close()+ }+ })++ it('grows for dictation without changing the draft or remounting the focused field', async () => {+ const { page, field } = await openPage(engine)+ try {+ await field.fill('Existing draft')+ const compact = await height(field)+ await page.evaluate(() =>+ window.updateComposer({+ dictationPreview: {+ before: 'Existing draft ',+ text: 'Heard words '.repeat(12),+ after: ''+ }+ })+ )+ await expect.poll(() => height(field)).toBeGreaterThan(compact)+ expect(await field.inputValue()).toBe('Existing draft')+ expect(await field.evaluate((input) => document.activeElement === input)).toBe(true)+ await page.evaluate(() => window.updateComposer({ dictationPreview: null }))+ await expect.poll(() => height(field)).toBe(compact)+ } finally {+ await page.close()+ }+ })++ it.each(['shell', 'browser'])(+ 'caps and scrolls a long draft as the %s keyboard opens and rotates',+ async (mode) => {+ const { page, field } = await openPage(engine, mode)+ const setKeyboard = (height) =>+ page.evaluate(+ ({ mode, height }) => {+ if (mode === 'shell') {+ window.setShellKeyboard(height)+ } else {+ window.setVisualKeyboard(height)+ }+ },+ { mode, height }+ )+ try {+ await field.fill(longDraft)+ await expect.poll(() => height(field)).toBeCloseTo(295, 0)+ expect(await field.evaluate((input) => input.scrollHeight > input.clientHeight)).toBe(true)+ await setKeyboard(340)+ await expect.poll(() => height(field)).toBeCloseTo(176, 0)+ await field.press('ControlOrMeta+End')+ await field.pressSequentially(' Last word')+ await expect.poll(() => field.evaluate((input) => input.scrollTop)).toBeGreaterThan(0)++ await page.setViewportSize({ width: 844, height: 390 })+ await setKeyboard(250)+ await expect.poll(() => height(field)).toBeCloseTo(49, 0)+ await setKeyboard(0)+ await expect.poll(() => height(field)).toBeCloseTo(137, 0)+ expect(await field.evaluate((input) => document.activeElement === input)).toBe(true)+ } finally {+ await page.close()+ }+ }+ )+})diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposerField.web.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposerField.web.tsxindex bfae1da8f0b..1f9c8f893a2 100644--- a/mobile/src/session/native-chat/composer/MobileNativeChatComposerField.web.tsx+++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposerField.web.tsx@@ -1,11 +1,16 @@-import { useState } from 'react'-import { StyleSheet, TextInput, View } from 'react-native'+import { useRef, useState } from 'react'+import { StyleSheet, TextInput, View, useWindowDimensions } from 'react-native'+import { useKeyboardOcclusion } from '../../../platform/keyboard-occlusion'+import { useTextInputContentHeight } from '../../../platform/text-input-content-height'import { colors } from '../../../theme/mobile-theme'import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme'import { mobileNativeChatInputStyles as inputStyles } from './mobile-native-chat-input-styles'import type { MobileNativeChatComposerFieldProps } from './mobile-native-chat-composer-field-skill'import { MobileNativeChatComposerFieldCopy } from './MobileNativeChatComposerFieldCopy'+// Share of the space above the keyboard the field may grow into before it scrolls.+const MAX_HEIGHT_SHARE = 0.35+// Textareas cannot style tokens: hide their text under a styled copy while preserving the caret. RN types omit caretColor.function clearText() {return { field: { color: 'transparent', caretColor: colors.textPrimary } }@@ -35,6 +40,20 @@ export function MobileNativeChatComposerField({useMobileColorScheme()const [scrollTop, setScrollTop] = useState(0)const [fieldHeight, setFieldHeight] = useState(0)+ const ownRef = useRef<TextInput>(null)+ const input = ref ?? ownRef+ const shown = dictationPreview+ ? `${dictationPreview.before}${dictationPreview.text}${dictationPreview.after}`+ : value || placeholder || ''+ const contentHeight = useTextInputContentHeight(input, shown)+ const windowHeight = useWindowDimensions().height+ const keyboardHeight = useKeyboardOcclusion()+ // RN Web already shrinks browser dimensions; shell WebViews report the keyboard separately.+ const visibleHeight = Math.min(windowHeight, window.innerHeight - keyboardHeight)+ const sizing = {+ height: contentHeight,+ maxHeight: Math.max(inputStyles.input.minHeight, Math.round(visibleHeight * MAX_HEIGHT_SHARE))+ }const copied = Boolean(skillToken || dictationPreview)// Keep one tree so adding/removing a skill or dictation cannot remount the field and drop focus.return (@@ -52,9 +71,9 @@ export function MobileNativeChatComposerField({/>) : null}<TextInput- ref={ref}+ ref={input}value={value}- style={copied ? [inputStyles.input, clearText().field] : inputStyles.input}+ style={[inputStyles.input, sizing, copied ? clearText().field : null]}onScroll={skillToken ? (event) => setScrollTop(scrollTopOf(event)) : undefined}placeholder={dictationPreview ? undefined : placeholder}{...props}diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-composer-field-skill.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-composer-field-skill.tsindex e22a694b629..38145b1f375 100644--- a/mobile/src/session/native-chat/composer/mobile-native-chat-composer-field-skill.ts+++ b/mobile/src/session/native-chat/composer/mobile-native-chat-composer-field-skill.ts@@ -1,3 +1,4 @@+import type { RefObject } from 'react'import type { TextInput, TextInputProps } from 'react-native'import { colors } from '../../../theme/mobile-theme'import { themedStyleSheet } from '../../../theme/themed-styles'@@ -10,7 +11,7 @@ export type MobileNativeChatComposerFieldProps = Omit<skillToken: string | null// Dictation heard so far, shown between the draft's halves without becoming part of its value.dictationPreview?: { before: string; text: string; after: string } | null- ref?: React.Ref<TextInput>+ ref?: RefObject<TextInput | null>}// Use the field’s exact font so the web overlay and transparent textarea occupy identical space.diff --git a/mobile/web-entry/web-overrides.json b/mobile/web-entry/web-overrides.jsonindex 683e23ad345..f6d1965b888 100644--- a/mobile/web-entry/web-overrides.json+++ b/mobile/web-entry/web-overrides.json@@ -47,7 +47,7 @@},{"file": "src/platform/text-input-content-height.web.ts",- "reason": "react-native-web renders a multiline TextInput as a <textarea> that keeps the browser's default two rows whatever it holds, where a native multiline input grows between its min and max heights by itself. The web file measures the text in a hidden copy of the textarea and returns that height, so the queued-message edit field grows from one line to four; the native file returns nothing to measure. Resizing the live field to measure it was rejected: WebKit clamps the scroll position of the list around it, so the queue jumped while typing."+ "reason": "react-native-web renders a multiline TextInput as a <textarea> that keeps the browser's default two rows whatever it holds, where a native multiline input grows between its min and max heights by itself. The web file measures the text in a hidden copy of the textarea and returns that height, so the chat composer grows with its draft, placeholder, and dictation preview; the native file returns nothing to measure. Resizing the live field to measure it was rejected: WebKit clamps the scroll position of the list around it, so the queue jumped while typing."},{"file": "src/platform/haptics.web.ts",@@ -119,7 +119,7 @@},{"file": "src/session/native-chat/composer/MobileNativeChatComposerField.web.tsx",- "reason": "A picked skill leads the composer's draft and is drawn highlighted in place. Natively that is a styled span of the TextInput's own text, but react-native-web renders TextInput as a textarea, which cannot style part of its text and ignores Text children. This one draws a copy of the draft behind the field with the skill highlighted, clears the field's own text while keeping its caret, and moves the copy with the field's scroll."+ "reason": "A picked skill leads the composer's draft and is drawn highlighted in place. Natively that is a styled span of the TextInput's own text, but react-native-web renders TextInput as a textarea, which cannot style part of its text and ignores Text children. This one draws a copy of the draft behind the field with the skill highlighted, clears the field's own text while keeping its caret, and moves the copy with the field's scroll. It also measures the shown text to grow the textarea, whose default two rows do not grow with content, and caps it to the space above the keyboard."},{"file": "src/session/native-chat/composer/mobile-native-chat-input-styles.web.ts",diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-page-types.ts b/src/renderer/src/components/browser-pane/describe-page/browser-page-types.tsindex 6e335704197..8bb7d4f8df3 100644--- a/src/renderer/src/components/browser-pane/describe-page/browser-page-types.ts+++ b/src/renderer/src/components/browser-pane/describe-page/browser-page-types.ts@@ -113,25 +113,3 @@ export type ClientHostedBrowserPagePaneProps = {onUpdatePageState: (tabId: string, updates: BrowserTabPageState) => voidonSetUrl: BrowserPageUrlSetter}--export type BrowserPageGrabAnnotations = {- grabIntent: GrabIntent- startGrabIntent: (nextIntent: GrabIntent) => void- pendingAnnotationPayload: BrowserGrabPayload | null- setPendingAnnotationPayload: Dispatch<SetStateAction<BrowserGrabPayload | null>>- grabToast: BrowserPageGrabToastState | null- setGrabToast: Dispatch<SetStateAction<BrowserPageGrabToastState | null>>- grabToastTimerRef: MutableRefObject<ReturnType<typeof setTimeout> | undefined>- dismissGrabToast: () => void- handleGrabCopy: () => void- handleGrabCopyScreenshot: () => void- grabMenuActionTakenRef: MutableRefObject<boolean>- handleAddBrowserAnnotation: (- comment: string,- intent: BrowserAnnotationIntent,- imagePaths?: string[]- ) => void- handleCancelPendingBrowserAnnotation: () => void- cancelPendingBrowserCapture: () => void- handleGrabActionShortcut: (key: 'c' | 's') => void-}diff --git a/src/renderer/src/components/native-chat/native-chat-subscriptions.performance.test.tsx b/src/renderer/src/components/native-chat/native-chat-subscriptions.performance.test.tsxindex 6472a823d06..a01b0eca5de 100644--- a/src/renderer/src/components/native-chat/native-chat-subscriptions.performance.test.tsx+++ b/src/renderer/src/components/native-chat/native-chat-subscriptions.performance.test.tsx@@ -2,11 +2,7 @@import { act, cleanup, render, waitFor } from '@testing-library/react'import { afterEach, describe, expect, it, vi } from 'vitest'-import { createStructuredSessionSelectionController } from '../../../../shared/structured-agent-session-selection-operations'-import { useStructuredSessionSelectionReads } from './use-structured-session-selection-reads'-import { useStructuredAgentSessionOptionStamp } from './structured-agent-session-status-hooks'import { useAppStore } from '@/store'-import { replaceRuntimeEnvironmentRevisions } from '@/runtime/runtime-environment-revision'import type { AppState } from '@/store/types'import type { NativeChatSkillDiscovery } from './use-native-chat-skills'import {@@ -613,254 +609,3 @@ describe('native chat store subscription performance', () => {console.info('native-chat-dense-subscription-work', JSON.stringify(results))})})--it('bounds the actual pick/read/overlay path at 10 and 100 delayed writes without whole-drain joins', async () => {- const measurements: {- count: number- sends: number- renders: number- visits: number- memberships: number- }[] = []- const target = { kind: 'local' } as const- for (const count of [10, 100]) {- const controller = createStructuredSessionSelectionController(vi.fn())- const replies = Array.from({ length: count }, () =>- Promise.withResolvers<{- kind: 'accepted'- options: Record<string, string>- }>()- )- const reread = vi.fn()- const capture = vi.spyOn(controller, 'captureRead')- let renders = 0- let visits = 0- let sends = 0- let memberships = 0- const all = Promise.all.bind(Promise)- const join = vi.spyOn(Promise, 'all').mockImplementation((values) => {- const entries = Array.from(values)- memberships += entries.length- return all(entries)- })- function Probe() {- useStructuredSessionSelectionReads({- controller,- target,- authority: 'local',- hostOptionStamp: '',- turnId: null,- rereadOptions: reread- })- controller.overlay()- controller.isPending('model')- controller.pendingId()- renders++- return null- }- const view = render(<Probe />)- const baseline = renders- for (let index = 0; index < count; index++) {- act(() => {- const operation = controller.issue('model', index % 2 ? 'sonnet' : 'opus', null)- for (const key of ['identity', 'key', 'transmitted', 'outcome'] as const) {- let value = operation[key]- Object.defineProperty(operation, key, {- configurable: true,- get() {- visits++- return value- },- set(next) {- value = next- }- })- }- controller.flush(() => {- sends++- return replies[index].promise- })- })- }- join.mockRestore()- expect(sends).toBe(count)- expect(renders - baseline).toBe(count)- expect(memberships).toBe(0)- expect(visits).toBeLessThanOrEqual(40 * count)- expect(capture).not.toHaveBeenCalled()- expect(reread).not.toHaveBeenCalled()- measurements.push({ count, sends, renders: renders - baseline, visits, memberships })- await act(async () =>- replies[count - 1].resolve({ kind: 'accepted', options: { model: 'sonnet' } })- )- expect(reread).toHaveBeenCalledTimes(1)- const captured = controller.captureRead()- await act(async () => replies[1].resolve({ kind: 'accepted', options: { model: 'sonnet' } }))- expect(reread).toHaveBeenCalledTimes(2)- act(() => controller.retire(captured))- expect(controller.captureRead()).toEqual([2])- expect(controller.overlay()).toEqual({})- const draining = controller.drain()- act(() => controller.abandon())- await draining- for (const reply of replies) {- reply.resolve({ kind: 'accepted', options: { model: 'opus' } })- }- await act(async () => {- await Promise.resolve()- })- expect(controller.overlay()).toEqual({})- view.unmount()- }- expect(measurements[1].visits).toBeLessThanOrEqual(measurements[0].visits * 11)- console.info('selection-pick-upstream-work', JSON.stringify(measurements))-})--it('keeps unrelated store, same-host status and other-host consumers quiet at N and 10N', async () => {- for (const count of [10, 100]) {- const emits = new Map<string, (event: AgentSessionStatusEvent) => void>()- handOffTransport.subscribe.mockImplementation(async (target, emit) => {- emits.set(target.kind === 'local' ? 'local' : target.environmentId, emit)- return { unsubscribe: vi.fn() }- })- const target = { kind: 'local' } as const- const feed = getStructuredAgentSessionStatusFeed(target)- const snapshot = vi.spyOn(feed, 'getSnapshot')- const other = getStructuredAgentSessionStatusFeed({- kind: 'environment',- environmentId: 'other'- })- const controllers = Array.from({ length: count }, () =>- createStructuredSessionSelectionController(vi.fn())- )- const renders = Array.from({ length: count }, () => 0)- const rereads = controllers.map(() => vi.fn())- function Probe({ index }: { index: number }) {- const stamp = useStructuredAgentSessionOptionStamp(`session-${index}`, target)- useStructuredSessionSelectionReads({- controller: controllers[index],- target,- authority: 'local',- hostOptionStamp: stamp,- turnId: null,- rereadOptions: rereads[index]- })- renders[index]++- return null- }- const view = render(controllers.map((_, index) => <Probe key={index} index={index} />))- let stop = () => {}- await act(async () => {- stop = other.activate()- })- const baseline = [...renders]- const publish = (host: string, sessionId: string, model: string) => {- const emit = emits.get(host)- if (!emit) {- throw new Error('Missing test status transport')- }- act(() =>- emit({- type: 'snapshot',- sessions: [- {- sessionId,- workspaceId: 'wt-1',- agent: 'codex',- status: 'idle',- latestPrompt: 'hello',- updatedAt: 1,- effort: model- }- ]- })- )- }- snapshot.mockClear()- act(() => useAppStore.setState({ lastTerminalInputAtByPaneKey: { other: 1 } }))- expect(snapshot).not.toHaveBeenCalled()- publish('other', 'session-0', 'other-model')- expect(snapshot).not.toHaveBeenCalled()- publish('local', 'unmounted', 'unrelated-model')- const upstreamReads = snapshot.mock.calls.length- expect(upstreamReads).toBeGreaterThanOrEqual(count)- expect(upstreamReads).toBeLessThanOrEqual(count * 3)- expect(renders).toEqual(baseline)- publish('local', 'session-0', 'sonnet')- expect(renders).toEqual(baseline.map((value, index) => value + (index === 0 ? 1 : 0)))- expect(rereads[0]).toHaveBeenCalledTimes(1)- const beforePick = [...renders]- act(() => controllers[1].issue('model', 'opus', null))- expect(renders).toEqual(beforePick.map((value, index) => value + (index === 1 ? 1 : 0)))- console.info(- 'selection-status-upstream-work',- JSON.stringify({ count, upstreamReads, unrelatedRenders: 0 })- )- view.unmount()- stop()- snapshot.mockRestore()- resetStructuredAgentSessionStatusFeedsForTests()- }-})--it('bounds selected continuity wakes and keeps other-host consumers quiet at N and 10N', () => {- for (const count of [10, 100]) {- const targets = Array.from({ length: count }, (_, index) => ({- kind: 'environment' as const,- environmentId: index % 2 ? 'continuity-other' : 'continuity-selected'- }))- const controllers = targets.map(() => createStructuredSessionSelectionController(vi.fn()))- const reads = targets.map(() => vi.fn())- const renders = targets.map(() => 0)- function Probe({ index }: { index: number }) {- useStructuredSessionSelectionReads({- controller: controllers[index],- target: targets[index],- authority: '',- hostOptionStamp: '',- turnId: null,- rereadOptions: reads[index]- })- renders[index]++- return null- }- const environments = targets- .slice(0, 2)- .map((target) => ({ id: target.environmentId, createdAt: 1, pairingRevision: 2 }))- replaceRuntimeEnvironmentRevisions(environments, {- retired: [],- sameHost: [],- pending: [{ id: 'continuity-selected', fromRevision: 1 }]- })- const view = render(targets.map((_, index) => <Probe key={index} index={index} />))- const baseline = [...renders]- const projectionReads = vi.spyOn(useAppStore.getState().runtimeStatusByEnvironmentId, 'get')- act(() => useAppStore.setState({ lastTerminalInputAtByPaneKey: { other: count } }))- expect(projectionReads).not.toHaveBeenCalled()- const publishCatalog = () =>- useAppStore.setState({ runtimeEnvironments: [...useAppStore.getState().runtimeEnvironments] })- act(publishCatalog)- expect(renders).toEqual(baseline)- expect(projectionReads.mock.calls.length).toBeLessThanOrEqual(2 * count)- replaceRuntimeEnvironmentRevisions(environments, {- retired: [],- sameHost: [{ id: 'continuity-selected', fromRevision: 1, toRevision: 2 }]- })- act(publishCatalog)- expect(renders).toEqual(baseline.map((value, index) => value + (index % 2 ? 0 : 1)))- expect(reads.map((read) => read.mock.calls.length)).toEqual(- targets.map((_, index) => (index % 2 ? 0 : 1))- )- console.info(- 'selection-continuity-work',- JSON.stringify({- count,- projectionReads: projectionReads.mock.calls.length,- otherHostRenders: 0- })- )- view.unmount()- projectionReads.mockRestore()- }- replaceRuntimeEnvironmentRevisions([])-})diff --git a/src/renderer/src/components/native-chat/use-structured-session-selection-reads.performance.test.tsx b/src/renderer/src/components/native-chat/use-structured-session-selection-reads.performance.test.tsxnew file mode 100644index 00000000000..1bbdd46ee83--- /dev/null+++ b/src/renderer/src/components/native-chat/use-structured-session-selection-reads.performance.test.tsx@@ -0,0 +1,287 @@+// @vitest-environment happy-dom++import { act, cleanup, render } from '@testing-library/react'+import { afterEach, expect, it, vi } from 'vitest'+import { createStructuredSessionSelectionController } from '../../../../shared/structured-agent-session-selection-operations'+import { useStructuredSessionSelectionReads } from './use-structured-session-selection-reads'+import { useStructuredAgentSessionOptionStamp } from './structured-agent-session-status-hooks'+import { useAppStore } from '@/store'+import { replaceRuntimeEnvironmentRevisions } from '@/runtime/runtime-environment-revision'+import type * as StructuredClient from '@/runtime/structured-agent-session-client'+import type { AgentSessionStatusEvent } from '../../../../shared/agent-session-wire'+import {+ getStructuredAgentSessionStatusFeed,+ resetStructuredAgentSessionStatusFeedsForTests+} from '@/runtime/structured-agent-session-status-feed'++const rpc = vi.hoisted(() => vi.fn())+vi.mock('@/runtime/runtime-rpc-client', () => ({+ callRuntimeRpc: rpc,+ runtimeEnvironmentSupportsCapability: vi.fn(async () => true)+}))+const handOffTransport = vi.hoisted(() => ({ subscribe: vi.fn() }))+vi.mock('@/runtime/structured-agent-session-client', async (importOriginal) => ({+ ...(await importOriginal<typeof StructuredClient>()),+ subscribeStructuredAgentSessionStatus: handOffTransport.subscribe,+ supportsStructuredAgentSessionContinuationContext: vi.fn(async () => false)+}))++const initialState = useAppStore.getState()+afterEach(() => {+ cleanup()+ useAppStore.setState(initialState, true)+ resetStructuredAgentSessionStatusFeedsForTests()+ handOffTransport.subscribe.mockReset()+ rpc.mockReset()+})++it('bounds the actual pick/read/overlay path at 10 and 100 delayed writes without whole-drain joins', async () => {+ const measurements: {+ count: number+ sends: number+ renders: number+ visits: number+ memberships: number+ }[] = []+ const target = { kind: 'local' } as const+ for (const count of [10, 100]) {+ const controller = createStructuredSessionSelectionController(vi.fn())+ const replies = Array.from({ length: count }, () =>+ Promise.withResolvers<{+ kind: 'accepted'+ options: Record<string, string>+ }>()+ )+ const reread = vi.fn()+ const capture = vi.spyOn(controller, 'captureRead')+ let renders = 0+ let visits = 0+ let sends = 0+ let memberships = 0+ const all = Promise.all.bind(Promise)+ const join = vi.spyOn(Promise, 'all').mockImplementation((values) => {+ const entries = Array.from(values)+ memberships += entries.length+ return all(entries)+ })+ function Probe() {+ useStructuredSessionSelectionReads({+ controller,+ target,+ authority: 'local',+ hostOptionStamp: '',+ turnId: null,+ rereadOptions: reread+ })+ controller.overlay()+ controller.isPending('model')+ controller.pendingId()+ renders+++ return null+ }+ const view = render(<Probe />)+ const baseline = renders+ for (let index = 0; index < count; index++) {+ act(() => {+ const operation = controller.issue('model', index % 2 ? 'sonnet' : 'opus', null)+ for (const key of ['identity', 'key', 'transmitted', 'outcome'] as const) {+ let value = operation[key]+ Object.defineProperty(operation, key, {+ configurable: true,+ get() {+ visits+++ return value+ },+ set(next) {+ value = next+ }+ })+ }+ controller.flush(() => {+ sends+++ return replies[index].promise+ })+ })+ }+ join.mockRestore()+ expect(sends).toBe(count)+ expect(renders - baseline).toBe(count)+ expect(memberships).toBe(0)+ expect(visits).toBeLessThanOrEqual(40 * count)+ expect(capture).not.toHaveBeenCalled()+ expect(reread).not.toHaveBeenCalled()+ measurements.push({ count, sends, renders: renders - baseline, visits, memberships })+ await act(async () =>+ replies[count - 1].resolve({ kind: 'accepted', options: { model: 'sonnet' } })+ )+ expect(reread).toHaveBeenCalledTimes(1)+ const captured = controller.captureRead()+ await act(async () => replies[1].resolve({ kind: 'accepted', options: { model: 'sonnet' } }))+ expect(reread).toHaveBeenCalledTimes(2)+ act(() => controller.retire(captured))+ expect(controller.captureRead()).toEqual([2])+ expect(controller.overlay()).toEqual({})+ const draining = controller.drain()+ act(() => controller.abandon())+ await draining+ for (const reply of replies) {+ reply.resolve({ kind: 'accepted', options: { model: 'opus' } })+ }+ await act(async () => {+ await Promise.resolve()+ })+ expect(controller.overlay()).toEqual({})+ view.unmount()+ }+ expect(measurements[1].visits).toBeLessThanOrEqual(measurements[0].visits * 11)+ console.info('selection-pick-upstream-work', JSON.stringify(measurements))+})++it('keeps unrelated store, same-host status and other-host consumers quiet at N and 10N', async () => {+ for (const count of [10, 100]) {+ const emits = new Map<string, (event: AgentSessionStatusEvent) => void>()+ handOffTransport.subscribe.mockImplementation(async (target, emit) => {+ emits.set(target.kind === 'local' ? 'local' : target.environmentId, emit)+ return { unsubscribe: vi.fn() }+ })+ const target = { kind: 'local' } as const+ const feed = getStructuredAgentSessionStatusFeed(target)+ const snapshot = vi.spyOn(feed, 'getSnapshot')+ const other = getStructuredAgentSessionStatusFeed({+ kind: 'environment',+ environmentId: 'other'+ })+ const controllers = Array.from({ length: count }, () =>+ createStructuredSessionSelectionController(vi.fn())+ )+ const renders = Array.from({ length: count }, () => 0)+ const rereads = controllers.map(() => vi.fn())+ function Probe({ index }: { index: number }) {+ const stamp = useStructuredAgentSessionOptionStamp(`session-${index}`, target)+ useStructuredSessionSelectionReads({+ controller: controllers[index],+ target,+ authority: 'local',+ hostOptionStamp: stamp,+ turnId: null,+ rereadOptions: rereads[index]+ })+ renders[index]+++ return null+ }+ const view = render(controllers.map((_, index) => <Probe key={index} index={index} />))+ let stop = () => {}+ await act(async () => {+ stop = other.activate()+ })+ const baseline = [...renders]+ const publish = (host: string, sessionId: string, model: string) => {+ const emit = emits.get(host)+ if (!emit) {+ throw new Error('Missing test status transport')+ }+ act(() =>+ emit({+ type: 'snapshot',+ sessions: [+ {+ sessionId,+ workspaceId: 'wt-1',+ agent: 'codex',+ status: 'idle',+ latestPrompt: 'hello',+ updatedAt: 1,+ effort: model+ }+ ]+ })+ )+ }+ snapshot.mockClear()+ act(() => useAppStore.setState({ lastTerminalInputAtByPaneKey: { other: 1 } }))+ expect(snapshot).not.toHaveBeenCalled()+ publish('other', 'session-0', 'other-model')+ expect(snapshot).not.toHaveBeenCalled()+ publish('local', 'unmounted', 'unrelated-model')+ const upstreamReads = snapshot.mock.calls.length+ expect(upstreamReads).toBeGreaterThanOrEqual(count)+ expect(upstreamReads).toBeLessThanOrEqual(count * 3)+ expect(renders).toEqual(baseline)+ publish('local', 'session-0', 'sonnet')+ expect(renders).toEqual(baseline.map((value, index) => value + (index === 0 ? 1 : 0)))+ expect(rereads[0]).toHaveBeenCalledTimes(1)+ const beforePick = [...renders]+ act(() => controllers[1].issue('model', 'opus', null))+ expect(renders).toEqual(beforePick.map((value, index) => value + (index === 1 ? 1 : 0)))+ console.info(+ 'selection-status-upstream-work',+ JSON.stringify({ count, upstreamReads, unrelatedRenders: 0 })+ )+ view.unmount()+ stop()+ snapshot.mockRestore()+ resetStructuredAgentSessionStatusFeedsForTests()+ }+})++it('bounds selected continuity wakes and keeps other-host consumers quiet at N and 10N', () => {+ for (const count of [10, 100]) {+ const targets = Array.from({ length: count }, (_, index) => ({+ kind: 'environment' as const,+ environmentId: index % 2 ? 'continuity-other' : 'continuity-selected'+ }))+ const controllers = targets.map(() => createStructuredSessionSelectionController(vi.fn()))+ const reads = targets.map(() => vi.fn())+ const renders = targets.map(() => 0)+ function Probe({ index }: { index: number }) {+ useStructuredSessionSelectionReads({+ controller: controllers[index],+ target: targets[index],+ authority: '',+ hostOptionStamp: '',+ turnId: null,+ rereadOptions: reads[index]+ })+ renders[index]+++ return null+ }+ const environments = targets+ .slice(0, 2)+ .map((target) => ({ id: target.environmentId, createdAt: 1, pairingRevision: 2 }))+ replaceRuntimeEnvironmentRevisions(environments, {+ retired: [],+ sameHost: [],+ pending: [{ id: 'continuity-selected', fromRevision: 1 }]+ })+ const view = render(targets.map((_, index) => <Probe key={index} index={index} />))+ const baseline = [...renders]+ const projectionReads = vi.spyOn(useAppStore.getState().runtimeStatusByEnvironmentId, 'get')+ act(() => useAppStore.setState({ lastTerminalInputAtByPaneKey: { other: count } }))+ expect(projectionReads).not.toHaveBeenCalled()+ const publishCatalog = () =>+ useAppStore.setState({ runtimeEnvironments: [...useAppStore.getState().runtimeEnvironments] })+ act(publishCatalog)+ expect(renders).toEqual(baseline)+ expect(projectionReads.mock.calls.length).toBeLessThanOrEqual(2 * count)+ replaceRuntimeEnvironmentRevisions(environments, {+ retired: [],+ sameHost: [{ id: 'continuity-selected', fromRevision: 1, toRevision: 2 }]+ })+ act(publishCatalog)+ expect(renders).toEqual(baseline.map((value, index) => value + (index % 2 ? 0 : 1)))+ expect(reads.map((read) => read.mock.calls.length)).toEqual(+ targets.map((_, index) => (index % 2 ? 0 : 1))+ )+ console.info(+ 'selection-continuity-work',+ JSON.stringify({+ count,+ projectionReads: projectionReads.mock.calls.length,+ otherHostRenders: 0+ })+ )+ view.unmount()+ projectionReads.mockRestore()+ }+ replaceRuntimeEnvironmentRevisions([])+})