Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
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'
import { SUPPORTED_UI_LOCALES } from '../../../src/shared/ui-locale.ts'

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 { useEffect, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { View } from 'react-native'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import { MobileNativeChatQueuedMessages } from './src/session/native-chat/input/MobileNativeChatQueuedMessages'
import { MobileNativeChatComposer } from './src/session/native-chat/composer/MobileNativeChatComposer'
import { mobileQueuedMessageCards } from './src/session/mobile-structured-queued-message-cards'
import { activateMobileUiLocale, translate } from './src/i18n/mobile-i18n'

const [mode, locale] = location.hash.slice(1).split(':')
const texts = ['First queued message', 'Review the mobile transcript and keep every detail. '.repeat(30)]
function Queue() {
const messages = texts.map((text, index) => ({
messageId: 'message-' + index,
position: index + 1,
state: 'waiting',
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] }
}))
return <View style={{ flex: 1, justifyContent: 'flex-end' }}>
<MobileNativeChatQueuedMessages
cards={mobileQueuedMessageCards(messages, [], { agentWorking: true })}
onMove={mode === 'drag' ? async () => true : undefined}
/>
</View>
}
function Editor() {
const [ready, setReady] = useState(false)
useEffect(() => {
void activateMobileUiLocale(locale).then(() => {
window.actionLabels = {
cancel: translate('chat.composer.cancelEditing', 'Cancel editing'),
save: translate('chat.composer.saveEditedMessage', 'Save edited message')
}
setReady(true)
})
}, [])
return ready ? <View style={{ flex: 1, justifyContent: 'flex-end', marginHorizontal: 16 }}>
<MobileNativeChatComposer
value="Edited message"
onChangeText={() => {}}
onSend={async () => true}
editSession={{ cancel: () => {}, refuseCommand: () => false, locked: false }}
sendSurfaceId="editor"
getSendCompletionGeneration={() => 0}
getComposerEditGeneration={() => 0}
onAttachImage={() => {}}
onMicPress={() => {}}
/>
</View> : null
}
createRoot(document.getElementById('root')).render(
<GestureHandlerRootView style={{ flex: 1 }}>{mode === 'editor' ? <Editor /> : <Queue />}</GestureHandlerRootView>
)
`

const bundles = mobileWebAppDependenciesPresent()
const describeLayout = 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', 'queued-messages-'))
const outDir = join(scratch, 'bundle')
await esbuild.build({
...mobileWebAppBuildOptions([]),
entryPoints: undefined,
stdin: { contents: entry, resolveDir: mobileDir, loader: 'tsx', sourcefile: 'queued.tsx' },
splitting: false,
write: true,
outdir: outDir,
entryNames: 'queued',
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="/queued.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, hash, width) {
const page = await browsers.get(engine.name).newPage({ viewport: { width, height: 700 } })
await page.goto(`${origin}/#${hash}`, { waitUntil: 'load' })
return page
}

function editorActionProblems(page) {
return page.evaluate(() => {
const row = document.querySelector('[data-testid="native-chat-composer-actions"]')
const problems = []
const [cancel, save] = ['cancel', 'save'].map((name) => {
const button = row.querySelector(`[aria-label="${window.actionLabels[name]}"]`)
const label = button.querySelector('div[dir]')
const range = document.createRange()
range.selectNodeContents(label)
const text = range.getBoundingClientRect()
const box = button.getBoundingClientRect()
if (label.scrollWidth > label.clientWidth) {
problems.push(`${name} label truncated`)
}
if (text.left < box.left - 0.5 || text.right > box.right + 0.5) {
problems.push(`${name} label outside its button`)
}
return box
})
if (cancel.right > save.left + 0.5) {
problems.push('cancel overlaps save')
}
if (save.right > row.getBoundingClientRect().right + 0.5) {
problems.push('save past the row')
}
return problems
})
}

describeLayout.each(engines)('mobile queued messages in $name', (engine) => {
it.each(['plain', 'drag'])('scrolls only as far as the %s rows reach', async (mode) => {
const page = await openPage(engine, mode, 390)
try {
await page.locator('[data-testid="queued-card-row"]').nth(1).waitFor()
const range = () =>
page.evaluate(() => {
const box = document.querySelector('[data-testid="queued-box"]')
const rows = [...box.querySelectorAll('[data-testid="queued-card-row"]')]
const scroller = [...box.querySelectorAll('*')].find(
(node) => getComputedStyle(node).overflowY === 'auto'
)
const rowsHeight = rows.reduce((sum, row) => sum + row.getBoundingClientRect().height, 0)
return scroller.scrollHeight - rowsHeight
})
await expect.poll(range).toBeLessThanOrEqual(1)
} finally {
await page.close()
}
})

it('fits whole Save and Cancel labels at 360pt in every shipped locale', async () => {
const results = await Promise.all(
SUPPORTED_UI_LOCALES.map(async (locale) => {
const page = await openPage(engine, `editor:${locale}`, 360)
try {
await page.locator('[data-testid="native-chat-composer-actions"]').waitFor()
return { locale, problems: await editorActionProblems(page) }
} finally {
await page.close()
}
})
)
expect(results.filter(({ problems }) => problems.length > 0)).toEqual([])
}, 60_000)
})
28 changes: 25 additions & 3 deletions mobile/src/components/composer-input/composer-input-styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,25 @@ export const FORM_MESSAGE_MIN_HEIGHT = 3 * COMPOSER_LINE_HEIGHT + 2 * MESSAGE_PA
export const MESSAGE_MAX_HEIGHT = 7 * COMPOSER_LINE_HEIGHT
export const FIELD_MIN_HEIGHT = 44

const roundControl = {
width: COMPOSER_CONTROL_SIZE,
height: COMPOSER_CONTROL_SIZE,
const pillControl = {
borderRadius: radii.pill,
alignItems: 'center',
justifyContent: 'center'
} as const

const roundControl = {
...pillControl,
width: COMPOSER_CONTROL_SIZE,
height: COMPOSER_CONTROL_SIZE
} as const

const labelControl = {
...pillControl,
flexShrink: 1,
minWidth: COMPOSER_CONTROL_SIZE,
minHeight: COMPOSER_CONTROL_SIZE
} as const

const surface = () =>
({
borderWidth: StyleSheet.hairlineWidth,
Expand Down Expand Up @@ -86,6 +97,17 @@ export const composerInputStyles = themedStyleSheet(() => ({
sendButtonDisabled: {
backgroundColor: colors.composerControl
},
// Save and Cancel hug their translated label and truncate only when the row runs out.
sendLabelButton: {
...labelControl,
paddingHorizontal: spacing.md,
backgroundColor: colors.surfaceBright
},
// Unframed, so a small inset is enough and leaves a long label more room.
ghostLabelButton: {
...labelControl,
paddingHorizontal: spacing.xs
},
pressed: {
opacity: feedback.pressedOpacity
},
Expand Down
8 changes: 6 additions & 2 deletions mobile/src/session/MobileQueuedCardText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function MobileQueuedCardText({
)
if (!clipped && !expanded) {
return (
<View>
<View style={styles.probeBounds}>
{measure}
<Text style={queuedMessageStyles.bodyText} numberOfLines={2}>
{text}
Expand Down Expand Up @@ -66,14 +66,18 @@ export function MobileQueuedCardText({
</Pressable>
)
return (
<View>
<View style={styles.probeBounds}>
{expanded ? null : measure}
{toggle}
</View>
)
}

const styles = themedStyleSheet(() => ({
// Clip the full-text probe so it cannot stretch the queue's scroll range.
probeBounds: {
overflow: 'hidden'
},
measure: {
position: 'absolute',
left: 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
} from './mobile-native-chat-draft-inputs'
import type { NativeChatSkillDiscoverySnapshot } from '../../../../../src/shared/native-chat/input/native-chat-picker-items'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { ActivityIndicator, Keyboard, Pressable, type TextInput, Text, View } from 'react-native'
import { ActivityIndicator, Keyboard, Pressable, type TextInput, View } from 'react-native'
import { Plus } from 'lucide-react-native'
import { colors } from '../../../theme/mobile-theme'
import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme'
Expand Down Expand Up @@ -39,6 +39,7 @@ import {
composerInputStyles as inputStyles
} from '../../../components/composer-input/composer-input-styles'
import { MobileNativeChatSendButton } from './MobileNativeChatSendButton'
import { MobileNativeChatEditActions } from './MobileNativeChatEditActions'
import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send'
import {
MobileNativeChatComposerMic,
Expand Down Expand Up @@ -361,46 +362,25 @@ export function MobileNativeChatComposer({
/>
) : null}
{editSession ? (
<Pressable
accessibilityRole="button"
accessibilityLabel={t('chat.composer.cancelEditing', 'Cancel editing')}
style={({ pressed }) => [inputStyles.ghostButton, pressed && inputStyles.pressed]}
onPress={editSession.cancel}
hitSlop={COMPOSER_CONTROL_HIT_SLOP}
>
<Text style={{ color: colors.textSecondary }}>{t('common.cancel', 'Cancel')}</Text>
</Pressable>
) : null}
<MobileNativeChatControlSwap
swapKey={showsStop && stop ? 'stop' : editSession ? 'save' : 'send'}
>
{showsStop && stop ? (
// Only this phone's own request holds Stop: a repeat is how a stuck stop escalates.
<MobileNativeChatStopButton onStop={stop.onStop} held={stop.held} />
) : editSession ? (
<Pressable
accessibilityLabel={t('chat.composer.saveEditedMessage', 'Save edited message')}
style={({ pressed }) => [
inputStyles.sendButton,
!canSend && inputStyles.sendButtonDisabled,
pressed && canSend && inputStyles.pressed
]}
onPress={() => void handleSend()}
disabled={!canSend}
hitSlop={COMPOSER_CONTROL_HIT_SLOP}
>
<Text style={{ color: canSend ? colors.bgBase : colors.textMuted }}>
{t('common.save', 'Save')}
</Text>
</Pressable>
) : (
<MobileNativeChatSendButton
canSend={canSend}
sendFollowUp={sendFollowUp}
onSend={(intent) => void handleSend(intent)}
/>
)}
</MobileNativeChatControlSwap>
<MobileNativeChatEditActions
canSave={canSend}
onCancel={editSession.cancel}
onSave={() => void handleSend()}
/>
) : (
<MobileNativeChatControlSwap swapKey={showsStop && stop ? 'stop' : 'send'}>
{showsStop && stop ? (
// Only this phone's own request holds Stop: a repeat is how a stuck stop escalates.
<MobileNativeChatStopButton onStop={stop.onStop} held={stop.held} />
) : (
<MobileNativeChatSendButton
canSend={canSend}
sendFollowUp={sendFollowUp}
onSend={(intent) => void handleSend(intent)}
/>
)}
</MobileNativeChatControlSwap>
)}
</View>
</View>
</View>
Expand Down
Loading
Loading