From 2fefde5f5dc9836c79d177ccef06f1c130ee2839 Mon Sep 17 00:00:00 2001 From: Takeshi Matsumoto Date: Sun, 25 Oct 2026 01:37:59 +0900 Subject: [PATCH 1/2] feat(mobile): add independent split panes and preserve session state --- .../scripts/build-mobile-web-app-bundle.mjs | 3 +- config/scripts/mobile-web-page-routes.mjs | 4 +- .../scripts/mobile-web-page-routes.test.mjs | 32 ++ mobile/app/h/[hostId]/index.web.tsx | 5 +- .../mobile-web-shell/MobileWebShellScreen.tsx | 8 +- .../src/mobile-web-shell/bridge-host-back.ts | 2 + mobile/src/mobile-web-shell/bridge-host.ts | 12 +- .../bridge/bridge-back-round-trip.test.ts | 2 +- .../bridge/bridge-client-init-handshake.ts | 11 +- .../bridge/bridge-envelope.ts | 9 +- .../bridge/bridge-rpc-client-frames.test.ts | 6 +- .../host-area-layout-class-change.test.tsx | 30 +- .../host-area-leave-session.test.tsx | 11 + .../host-area-session.test.ts | 15 + .../host-area-sidebar-matrix.test.tsx | 6 +- .../host-root-responsive-content.test.tsx | 43 +++ .../src/mobile-web-shell/page-route-policy.ts | 15 +- .../page-storage-keys-negotiation.test.ts | 124 +++++++ .../src/mobile-web-shell/page-storage-keys.ts | 32 +- .../route-handoff-host-area.web.test.tsx | 24 +- .../session/MobileSessionActiveContent.tsx | 45 ++- .../session/MobileSessionTabStrip.test.tsx | 7 +- mobile/src/session/MobileSessionTabStrip.tsx | 80 ++++- mobile/src/session/TerminalPaneView.test.tsx | 83 +++++ mobile/src/session/TerminalPaneView.tsx | 127 +++++-- ...ile-session-terminal-frame-layout.test.tsx | 53 +++ .../mobile-terminal-layout-choice.test.tsx | 327 ++++++++++++++++++ .../mobile-terminal-pane-layout.test.ts | 46 +++ .../session/mobile-terminal-pane-layout.ts | 74 ++++ .../mobile-terminal-split-gestures.test.tsx | 317 +++++++++++++++++ .../mobile-terminal-split-input.test.tsx | 110 ++++++ .../session/use-mobile-session-controller.ts | 7 + ...use-mobile-session-keyboard-state.test.tsx | 2 + .../use-mobile-session-keyboard-state.ts | 6 + .../session/use-mobile-session-lifecycle.ts | 3 + .../use-mobile-session-presentation.ts | 8 +- .../use-mobile-session-screen-state.ts | 3 + .../src/session/use-mobile-session-startup.ts | 6 + .../use-mobile-session-tab-application.ts | 14 +- .../use-mobile-session-tab-switching.ts | 27 +- .../use-mobile-session-terminal-runtime.ts | 25 ++ ...-mobile-session-terminal-stream-display.ts | 4 +- ...ile-session-terminal-subscription.test.tsx | 116 ++++++- ...se-mobile-session-terminal-subscription.ts | 6 +- .../use-mobile-session-terminal-webview.ts | 153 ++++++-- .../use-terminal-split-layout.test.tsx | 45 +++ .../src/session/use-terminal-split-layout.ts | 37 ++ mobile/src/storage/preferences.ts | 20 ++ .../src/terminal/document/mouse-click-drag.ts | 1 + .../document/surface-touch-gestures.ts | 1 + mobile/src/terminal/document/wheel-scroll.ts | 10 + .../terminal/terminal-cell-box-refit.test.tsx | 52 ++- .../terminal-foreground-recovery.test.ts | 20 ++ .../terminal/terminal-foreground-recovery.ts | 34 +- .../terminal-viewport-refit-options.ts | 28 ++ .../src/terminal/terminal-viewport-refit.ts | 211 ++++++----- .../src/terminal/terminal-webview-contract.ts | 1 + .../terminal-webview-notification-dispatch.ts | 2 + .../use-terminal-webview-controller.ts | 3 + .../mobile-web-bundle-reply-schemas.test.ts | 20 ++ .../mobile-web-bundle-reply-schemas.ts | 3 +- .../manifest-contract.test.ts | 9 + .../mobile-web-bundle/manifest-contract.ts | 4 +- 63 files changed, 2291 insertions(+), 253 deletions(-) create mode 100644 mobile/src/mobile-web-shell/host-root-responsive-content.test.tsx create mode 100644 mobile/src/mobile-web-shell/page-storage-keys-negotiation.test.ts create mode 100644 mobile/src/session/TerminalPaneView.test.tsx create mode 100644 mobile/src/session/mobile-terminal-layout-choice.test.tsx create mode 100644 mobile/src/session/mobile-terminal-pane-layout.test.ts create mode 100644 mobile/src/session/mobile-terminal-pane-layout.ts create mode 100644 mobile/src/session/mobile-terminal-split-gestures.test.tsx create mode 100644 mobile/src/session/mobile-terminal-split-input.test.tsx create mode 100644 mobile/src/session/use-terminal-split-layout.test.tsx create mode 100644 mobile/src/session/use-terminal-split-layout.ts create mode 100644 mobile/src/terminal/terminal-viewport-refit-options.ts diff --git a/config/scripts/build-mobile-web-app-bundle.mjs b/config/scripts/build-mobile-web-app-bundle.mjs index 66462468d2d6..751154d94959 100644 --- a/config/scripts/build-mobile-web-app-bundle.mjs +++ b/config/scripts/build-mobile-web-app-bundle.mjs @@ -594,7 +594,8 @@ export function resolveMobileWebPageRoutes(routeKeys, declared = MOBILE_WEB_PAGE ...(route.optionalGrants === undefined || route.optionalGrants.length === 0 ? {} : { optionalGrants: [...route.optionalGrants] }), - ...(route.canOwnHostArea === true ? { canOwnHostArea: true } : {}) + ...(route.canOwnHostArea === true ? { canOwnHostArea: true } : {}), + ...(route.canOwnHostAreaAcrossLayouts === true ? { canOwnHostAreaAcrossLayouts: true } : {}) })) } diff --git a/config/scripts/mobile-web-page-routes.mjs b/config/scripts/mobile-web-page-routes.mjs index 0a7665e29371..6de411027b19 100644 --- a/config/scripts/mobile-web-page-routes.mjs +++ b/config/scripts/mobile-web-page-routes.mjs @@ -31,10 +31,12 @@ export const MOBILE_WEB_PAGE_ROUTES = [ // every `/h` route in `HostProtocolGate`, so without the grant the wall's Update Orca tap posts a // notify the shell refuses, with nothing on screen to say why. // `canOwnHostArea`: on wide layouts it draws the sidebar itself, given `ownsHostArea` in `init`. + // `canOwnHostAreaAcrossLayouts`: it also renders the narrow host area, so ownership survives rotation. { pathname: '/h/[hostId]', grants: ['navigate', 'storage', 'externalLink', 'haptics'], - canOwnHostArea: true + canOwnHostArea: true, + canOwnHostAreaAcrossLayouts: true }, // Agent session history. `navigate` because a resumed session opens the session screen, which is // native, and because the list above now reaches this one without leaving the page. `storage` diff --git a/config/scripts/mobile-web-page-routes.test.mjs b/config/scripts/mobile-web-page-routes.test.mjs index 298683435f85..6c4efe5c9127 100644 --- a/config/scripts/mobile-web-page-routes.test.mjs +++ b/config/scripts/mobile-web-page-routes.test.mjs @@ -71,6 +71,38 @@ describe('the page routes the manifest declares', () => { ]) }) + it('serializes cross-layout ownership only for opted-in routes and declares it only on the host root', () => { + const routes = resolveMobileWebPageRoutes( + ['./h/[hostId]/index.tsx', './h/[hostId]/tasks.tsx'], + [ + { + pathname: '/h/[hostId]', + grants: ['navigate'], + canOwnHostArea: true, + canOwnHostAreaAcrossLayouts: true + }, + { pathname: '/h/[hostId]/tasks', grants: ['navigate'], canOwnHostArea: true } + ] + ) + expect(JSON.parse(JSON.stringify(routes))).toEqual([ + { + pathname: '/h/[hostId]', + grants: ['navigate'], + canOwnHostArea: true, + canOwnHostAreaAcrossLayouts: true + }, + { pathname: '/h/[hostId]/tasks', grants: ['navigate'], canOwnHostArea: true } + ]) + expect( + MOBILE_WEB_PAGE_ROUTES.filter((route) => route.canOwnHostAreaAcrossLayouts).map( + (route) => route.pathname + ) + ).toEqual(['/h/[hostId]']) + for (const route of routes) { + expect(MobileWebBundleRouteSchema.safeParse(route).success).toBe(true) + } + }) + /** * The wide iPad's host-area session is granted every served route's list, so its in-page hops * stay in the page. Bounded by the per-route ceiling too, so that grant never outgrows one route's. diff --git a/mobile/app/h/[hostId]/index.web.tsx b/mobile/app/h/[hostId]/index.web.tsx index 1bbec9fb6cb1..2c8f5dda7067 100644 --- a/mobile/app/h/[hostId]/index.web.tsx +++ b/mobile/app/h/[hostId]/index.web.tsx @@ -1,5 +1,6 @@ import { WorkspaceDetailPlaceholder } from '../../../src/components/WorkspaceDetailPlaceholder' import { HostScreen } from '../../../src/host-screen/HostScreen' +import { useResponsiveLayout } from '../../../src/layout/responsive-layout' import { usePageOwnsHostArea } from '../../../src/mobile-web-shell/page-owns-host-area' /** @@ -8,5 +9,7 @@ import { usePageOwnsHostArea } from '../../../src/mobile-web-shell/page-owns-hos */ export default function HostWorktreeRoute() { // The placeholder only beside the page's own sidebar: without the host area this is the list. - return usePageOwnsHostArea() ? : + const ownsHostArea = usePageOwnsHostArea() + const { isWideLayout } = useResponsiveLayout() + return ownsHostArea && isWideLayout ? : } diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx index e3793e64b084..a32d66597394 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx @@ -277,10 +277,10 @@ export function MobileWebShellScreen({ }) return } - // Wide, this host's route is the area-owning session even when it is not on the stack as - // asked: `dismissTo` pops to it by name with the href's params, or replaces this one after a - // cold deep link, so it is never a second on top. - if (isWideLayout && isHostRouteOf(href, hostId)) { + // This host's route is the area-owning session at either width, even when it is not on the + // stack as asked: `dismissTo` pops to it by name with the href's params, or replaces this one + // after a cold deep link, so it is never a second on top. + if (isHostRouteOf(href, hostId)) { router.dismissTo(href) return } diff --git a/mobile/src/mobile-web-shell/bridge-host-back.ts b/mobile/src/mobile-web-shell/bridge-host-back.ts index a835be0e3549..cae83a47930a 100644 --- a/mobile/src/mobile-web-shell/bridge-host-back.ts +++ b/mobile/src/mobile-web-shell/bridge-host-back.ts @@ -11,6 +11,8 @@ import { BRIDGE_BACK_FRAME } from './bridge/bridge-page-back' */ export type BridgeSessionBack = { readonly claimed: boolean + /** The negotiated storage keys the page's `ready` named; absent for a page that named none. */ + readonly storageKeys?: readonly string[] } /** diff --git a/mobile/src/mobile-web-shell/bridge-host.ts b/mobile/src/mobile-web-shell/bridge-host.ts index fbf177b7be09..c58e75b2e96d 100644 --- a/mobile/src/mobile-web-shell/bridge-host.ts +++ b/mobile/src/mobile-web-shell/bridge-host.ts @@ -20,6 +20,7 @@ import { createBridgeHostFrames } from './bridge-host-frames' import { createBridgeHostBack, type BridgeSessionBack } from './bridge-host-back' import { createBridgeNotifyForwarder } from './bridge-host-notify' import { createBridgeHostRoute } from './bridge-host-route' +import { pageStorageForReader } from './page-storage-keys' import type { BridgeSafeAreaInsets } from './bridge/bridge-safe-area-insets' import type { BridgeHostOptions } from './bridge-host-contract' @@ -108,6 +109,9 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { // Seeded from the session rather than started false: this host may be a rebuild taking over a // session that handshook with the one before it. let initSent = options.sessionEstablished + // What the page's init reader accepts, carried across a rebuild because the page does not + // re-handshake. Null is a page older than `storageKeys`, which gets the legacy keys only. + let pageStorageKeys: readonly string[] | null = options.sessionBack?.storageKeys ?? null const frames = createBridgeHostFrames({ post: options.post, @@ -178,7 +182,7 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { granted, host, ownsHostArea: options.ownsHostArea === true, - ...options.readStorage() + ...pageStorageForReader(options.readStorage(), pageStorageKeys) }) ) ) @@ -257,6 +261,7 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { // re-asked `ready` from the document already being served is answered the same way. if (message.type === 'ready') { serving = true + pageStorageKeys = message.storageKeys ?? null back.readReady() // Every time it is asked, not once: the page re-asks on a backoff, and each ask is answered // with the route the shell holds now. That is the whole repair path for a frame that never @@ -345,7 +350,10 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { routes.publishKeyboardInset(next, deliverable()) }, sendBack: back.send, - readSessionBack: back.read, + readSessionBack: () => ({ + ...back.read(), + ...(pageStorageKeys === null ? {} : { storageKeys: pageStorageKeys }) + }), dispose } } diff --git a/mobile/src/mobile-web-shell/bridge/bridge-back-round-trip.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-back-round-trip.test.ts index 2f66377d51ad..169c1d3ef851 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-back-round-trip.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-back-round-trip.test.ts @@ -52,7 +52,7 @@ describe('a Back press crossing from the shell to the page', () => { expect(pair.host.sendBack()).toBe(true) await pair.flush() expect(took).toHaveBeenCalledTimes(1) - expect(pair.readToShell().find((frame) => frame.type === 'ready')).toEqual({ + expect(pair.readToShell().find((frame) => frame.type === 'ready')).toMatchObject({ v: 1, type: 'ready' }) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts index 24060668e24b..c0b696c9cdae 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts @@ -1,4 +1,5 @@ import { BRIDGE_PROTOCOL_VERSION, type BridgeClientMessage } from './bridge-envelope' +import { NEGOTIATED_PAGE_STORAGE_KEYS } from '../page-storage-keys' /** The page asks again until the shell answers; a session has no other way to start. */ export const BRIDGE_READY_RETRY_MIN_MS = 50 @@ -49,8 +50,12 @@ export function createBridgeInitHandshake(ask: () => void): BridgeInitHandshake } } -/** What the page says on every ask. It declares nothing: the shell serves no page older than its - * floor, so every page it talks to takes everything the shell sends. */ +/** What the page says on every ask. Pages and shells update independently, so it names the + * negotiated storage keys its `init` reader accepts; an older shell ignores the member. */ export function createPageReadyFrame(): Extract { - return { v: BRIDGE_PROTOCOL_VERSION, type: 'ready' } + return { + v: BRIDGE_PROTOCOL_VERSION, + type: 'ready', + storageKeys: [...NEGOTIATED_PAGE_STORAGE_KEYS] + } } diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts index fd79f1c5a01b..c125a7df2047 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts @@ -171,7 +171,14 @@ const replyPartSchema = z.object({ const BridgeClientMessageSchema = z.discriminatedUnion('type', [ z.object({ v: versionSchema, - type: z.literal('ready') + type: z.literal('ready'), + // Negotiated keys this page's `init` reader accepts. A malformed list reads as none, so the + // page gets the legacy keys rather than no session. + storageKeys: z + .array(z.string().min(1).max(PAGE_STORAGE_MAX_KEY_CHARS)) + .max(PAGE_STORAGE_MAX_ENTRIES) + .optional() + .catch(undefined) }), z.object({ v: versionSchema, diff --git a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts index 0138feea23e2..35f4e06b9fe8 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts @@ -36,9 +36,11 @@ afterEach(() => { }) describe('bridge client handshake', () => { - it('asks for a session as soon as it exists, declaring nothing', () => { + it('asks for a session immediately and declares the storage keys it can read', () => { const page = createPageClient() - expect(page.frames()).toEqual([{ v: BRIDGE_PROTOCOL_VERSION, type: 'ready' }]) + expect(page.frames()).toEqual([ + { v: BRIDGE_PROTOCOL_VERSION, type: 'ready', storageKeys: ['orca:terminalSplitLayout'] } + ]) }) it('keeps asking on a widening backoff until init answers', () => { diff --git a/mobile/src/mobile-web-shell/host-area-layout-class-change.test.tsx b/mobile/src/mobile-web-shell/host-area-layout-class-change.test.tsx index 88f171ca187d..eb63ed9e3db4 100644 --- a/mobile/src/mobile-web-shell/host-area-layout-class-change.test.tsx +++ b/mobile/src/mobile-web-shell/host-area-layout-class-change.test.tsx @@ -3,8 +3,7 @@ * * Off a wide layout a detail route is served as before; on one it is served only by a page that * declares `canOwnHostArea`, because an older page would draw its own sidebar beside the native - * one, so an older one is walled. The session rebuilds on the change, so the page's in-page stack - * does not survive it. + * one, so an older one is walled. A declaring page keeps its session and in-page stack across the change. */ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { describe, expect, it, vi } from 'vitest' @@ -95,12 +94,13 @@ const store: GenerationStore = { forgetHostUpdateFailures: async () => undefined } -function routes(declares: boolean): MobileWebBundleManifestRead['routes'] { +function routes(declares: boolean, acrossLayouts = true): MobileWebBundleManifestRead['routes'] { return [ { pathname: '/h/[hostId]', grants: ['navigate'], - ...(declares ? { canOwnHostArea: true } : {}) + ...(declares ? { canOwnHostArea: true } : {}), + ...(declares && acrossLayouts ? { canOwnHostAreaAcrossLayouts: true } : {}) }, { pathname: '/h/[hostId]/session/[worktreeId]', grants: ['navigate'] } ] @@ -109,9 +109,10 @@ function routes(declares: boolean): MobileWebBundleManifestRead['routes'] { async function settledKinds( declares: boolean, widths: readonly boolean[], - routePathname = '/h/host-1/session/wt-1' + routePathname = '/h/host-1/session/wt-1', + acrossLayouts = true ) { - doubles.routes = routes(declares) + doubles.routes = routes(declares, acrossLayouts) doubles.manifestReads = 0 doubles.gates.hostCapabilities = [MOBILE_WEB_BUNDLE_CAPABILITY] const seen: MobileWebShellSessionState[] = [] @@ -150,9 +151,16 @@ async function settledKinds( } describe('a detail session across a layout-class change', () => { - // Once per flip: the wide session may not keep the host-route hop the narrow one could. - it('restarts an open page once per flip under a declaring bundle', async () => { + // Ownership and route grants belong to the document, not its changing viewport. + it('preserves the open page across rotation under a declaring bundle', async () => { expect(await settledKinds(true, [false, true, false])).toEqual({ + kinds: ['ready session-1', 'ready session-1', 'ready session-1'], + manifestReads: 1 + }) + }) + + it('keeps legacy declaring pages usable under their original layout-specific sessions', async () => { + expect(await settledKinds(true, [false, true, false], '/h/host-1', false)).toEqual({ kinds: ['ready session-1', 'ready session-2', 'ready session-3'], manifestReads: 3 }) @@ -165,9 +173,9 @@ describe('a detail session across a layout-class change', () => { }) }) - it('rebuilds the host route, whose wide session owns the area under other grants', async () => { - const { kinds } = await settledKinds(true, [false, true], '/h/host-1') - expect(kinds).toEqual(['ready session-1', 'ready session-2']) + it('preserves the host-area document and its in-page workspace across rotation', async () => { + const { kinds } = await settledKinds(true, [false, true, false], '/h/host-1') + expect(kinds).toEqual(['ready session-1', 'ready session-1', 'ready session-1']) }) }) diff --git a/mobile/src/mobile-web-shell/host-area-leave-session.test.tsx b/mobile/src/mobile-web-shell/host-area-leave-session.test.tsx index e6372993c957..b82f096f6138 100644 --- a/mobile/src/mobile-web-shell/host-area-leave-session.test.tsx +++ b/mobile/src/mobile-web-shell/host-area-leave-session.test.tsx @@ -158,6 +158,17 @@ describe('leaving a wide detail session for its host route', () => { }) describe('the same hop on a phone', () => { + it.each([HOST, BOUNCE])('replaces a cold detail session with %s', async (href) => { + await hopFromSession(PHONE, [DETAIL], href) + expect(applied([DETAIL])).toEqual([href]) + expect(dependencies.push).not.toHaveBeenCalled() + }) + + it('updates the existing host notice without retaining the exited detail session', async () => { + await hopFromSession(PHONE, [HOST, DETAIL], BOUNCE) + expect(applied([HOST, DETAIL])).toEqual([BOUNCE]) + }) + it('returns to the host route below rather than stacking a second one', async () => { await hopFromSession(PHONE, [HOST, DETAIL], HOST) expect(device.dismissTo).not.toHaveBeenCalled() diff --git a/mobile/src/mobile-web-shell/host-area-session.test.ts b/mobile/src/mobile-web-shell/host-area-session.test.ts index 4c1bc354d444..fea6db70a5b5 100644 --- a/mobile/src/mobile-web-shell/host-area-session.test.ts +++ b/mobile/src/mobile-web-shell/host-area-session.test.ts @@ -102,6 +102,21 @@ describe('the page declaring it can own the host area', () => { const unserved = [{ ...desktopRoutes(true)[0]!, grants: ['native.teleport.start'] }] expect(routeViewOf(unserved, HOST_ROUTE, true).ownsHostArea).toBe(false) }) + + it('keeps the area at either width only for a page that declares it across layouts', () => { + const [host, ...rest] = desktopRoutes(true) + const routes = [{ ...host!, canOwnHostAreaAcrossLayouts: true }, ...rest] + expect(routeViewOf(routes, HOST_ROUTE, true).ownsHostArea).toBe(true) + expect(routeViewOf(routes, HOST_ROUTE, false).ownsHostArea).toBe(true) + // A narrow detail session hands a hop to the host route back to the shell, like a wide one. + expect( + routeViewOf(routes, '/h/host-1/session/wt-1', false).pageRouteGrants.map((p) => p.pathname) + ).not.toContain('/h/[hostId]') + // Without `canOwnHostArea` the across-layouts flag claims nothing. + const flagOnly = [{ ...desktopRoutes(false)[0]!, canOwnHostAreaAcrossLayouts: true }] + expect(routeViewOf(flagOnly, HOST_ROUTE, false).ownsHostArea).toBe(false) + expect(routeViewOf(flagOnly, HOST_ROUTE, true).ownsHostArea).toBe(false) + }) }) describe('the wide host-area session', () => { diff --git a/mobile/src/mobile-web-shell/host-area-sidebar-matrix.test.tsx b/mobile/src/mobile-web-shell/host-area-sidebar-matrix.test.tsx index 08f74e239762..28490f3fcc53 100644 --- a/mobile/src/mobile-web-shell/host-area-sidebar-matrix.test.tsx +++ b/mobile/src/mobile-web-shell/host-area-sidebar-matrix.test.tsx @@ -186,7 +186,7 @@ function pageRoutes(page: Page): MobileWebPageRoute[] | null { { pathname: '/h/[hostId]', grants: ['navigate'], - ...(page === 'declared' ? { canOwnHostArea: true } : {}) + ...(page === 'declared' ? { canOwnHostArea: true, canOwnHostAreaAcrossLayouts: true } : {}) }, { pathname: '/h/[hostId]/session/[worktreeId]', grants: ['navigate'] } ] @@ -368,11 +368,11 @@ describe('the page sidebar rule', () => { }) describe('a phone', () => { - it('reports nothing to the layout from a served host route', async () => { + it('reports host ownership without drawing a sidebar on a narrow viewport', async () => { const hostSession = sessionFor('declared', HOST, false) expect(hostSession.state.kind).toBe('activating') env.reports.length = 0 expect(await sidebarsIn('native', PHONE, { hostSession })).toBe(0) - expect(env.reports).toEqual([]) + expect(env.reports).toEqual([true, false]) }) }) diff --git a/mobile/src/mobile-web-shell/host-root-responsive-content.test.tsx b/mobile/src/mobile-web-shell/host-root-responsive-content.test.tsx new file mode 100644 index 000000000000..ccbfd1b96c60 --- /dev/null +++ b/mobile/src/mobile-web-shell/host-root-responsive-content.test.tsx @@ -0,0 +1,43 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { describe, expect, it, vi } from 'vitest' + +const viewport = vi.hoisted(() => ({ width: 669, height: 951, ownsHostArea: true })) +vi.mock('react-native', () => ({ useWindowDimensions: () => viewport })) +vi.mock('./page-owns-host-area', () => ({ usePageOwnsHostArea: () => viewport.ownsHostArea })) +vi.mock('../host-screen/HostScreen', () => ({ HostScreen: () => createElement('WorkspacePicker') })) +vi.mock('../components/WorkspaceDetailPlaceholder', () => ({ + WorkspaceDetailPlaceholder: () => createElement('WorkspacePlaceholder') +})) + +import HostWorktreeRoute from '../../app/h/[hostId]/index.web' + +describe('host root content across layouts', () => { + it.each([ + { width: 390, height: 844, ownsHostArea: true, expected: 'WorkspacePicker' }, + { width: 669, height: 951, ownsHostArea: true, expected: 'WorkspacePicker' }, + { width: 951, height: 669, ownsHostArea: true, expected: 'WorkspacePlaceholder' }, + { width: 951, height: 669, ownsHostArea: false, expected: 'WorkspacePicker' } + ])('renders $expected at $width with ownership $ownsHostArea', (state) => { + Object.assign(viewport, state) + let tree: ReactTestRenderer | undefined + act(() => { + tree = create(createElement(HostWorktreeRoute)) + }) + expect(tree?.toJSON()).toMatchObject({ type: state.expected }) + act(() => tree?.unmount()) + }) + + it('returns the picker after rotating a host root from landscape to portrait', () => { + Object.assign(viewport, { width: 951, height: 669, ownsHostArea: true }) + let tree: ReactTestRenderer | undefined + act(() => { + tree = create(createElement(HostWorktreeRoute)) + }) + expect(tree?.toJSON()).toMatchObject({ type: 'WorkspacePlaceholder' }) + Object.assign(viewport, { width: 669, height: 951 }) + act(() => tree?.update(createElement(HostWorktreeRoute))) + expect(tree?.toJSON()).toMatchObject({ type: 'WorkspacePicker' }) + act(() => tree?.unmount()) + }) +}) diff --git a/mobile/src/mobile-web-shell/page-route-policy.ts b/mobile/src/mobile-web-shell/page-route-policy.ts index 3de345d1bd5d..7ca37e987067 100644 --- a/mobile/src/mobile-web-shell/page-route-policy.ts +++ b/mobile/src/mobile-web-shell/page-route-policy.ts @@ -203,11 +203,20 @@ export function routeViewOf( if (!servesWideLayout(entries, pathname, wide)) { return { pageRoutes: [], pageRouteGrants: [], routeGrants: [], ownsHostArea: false } } - const ownsHostArea = wide && pathname === root - // No pair for the host route in a wide detail session, so a hop there goes to the shell, which + const canOwnHostArea = + root !== null && + pageCanOwnHostArea(entries, root) && + (wide || + entries.some( + (route) => + route.canOwnHostAreaAcrossLayouts === true && matchesRoutePattern(root, route.pathname) + )) + // New pages keep ownership across rotation; legacy pages require the wide-only contract. + const ownsHostArea = canOwnHostArea && pathname === root + // No pair for the host route in an owned detail session, so a hop there goes to the shell, which // opens it owning the area rather than as a second host list in this pane. const paired = - wide && !ownsHostArea && root !== null + canOwnHostArea && !ownsHostArea && root !== null ? entries.filter((route) => !matchesRoutePattern(root, route.pathname)) : entries return { diff --git a/mobile/src/mobile-web-shell/page-storage-keys-negotiation.test.ts b/mobile/src/mobile-web-shell/page-storage-keys-negotiation.test.ts new file mode 100644 index 000000000000..88ce4572b4dc --- /dev/null +++ b/mobile/src/mobile-web-shell/page-storage-keys-negotiation.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it } from 'vitest' +import { z } from 'zod' +import { harness } from './bridge-host-test-harness' +import { clientFrame } from './bridge-host-test-fakes' +import { createPageReadyFrame } from './bridge/bridge-client-init-handshake' +import { versionSchema } from './bridge/bridge-frame-fields' +import { NEGOTIATED_PAGE_STORAGE_KEYS, PAGE_STORAGE_EXACT_KEYS } from './page-storage-keys' + +/** The exact keys every page shipped before `storageKeys` refines `init` storage against. */ +const LEGACY_EXACT_KEYS = [ + 'orca:last-visited-worktree', + 'orca:hostSidebarWidth', + 'orca:hostDockWidth', + 'orca:terminal-accessory-layout', + 'orca:custom-accessory-keys', + 'orca:defaultSessionView', + 'orca:mobileStructuredSendOperations:v1', + 'orca:terminalTextScale', + 'orca:terminalAutocompleteEnabled', + 'orca:terminalLinkOpenMode' +] +const LEGACY_PREFIXES = [ + 'orca:pins:', + 'orca:nativeChatTabs:', + 'orca:terminalLiveInputDisabled:', + 'orca:terminalDrafts:' +] +const legacyIsPageStorageKey = (key: string): boolean => + key.length <= 256 && + (LEGACY_EXACT_KEYS.includes(key) || + LEGACY_PREFIXES.some((prefix) => key.startsWith(prefix) && key.length > prefix.length)) +// The older page's `init` storage members, as `BridgeInitStorageSchema` and `storageOversize` read them. +const LegacyInitStorageSchema = z.object({ + storage: z + .record(z.string().min(1).max(256).refine(legacyIsPageStorageKey), z.string().max(16 * 1024)) + .refine((entries) => Object.keys(entries).length <= 32) + .optional(), + storageOversize: z.array(z.string().refine(legacyIsPageStorageKey)).max(32).optional() +}) +// The `ready` reader every shell shipped before `storageKeys`. +const LegacyReadySchema = z.object({ v: versionSchema, type: z.literal('ready') }) + +const SPLIT_KEY = 'orca:terminalSplitLayout' +const STORAGE = { [SPLIT_KEY]: 'stacked', 'orca:pins:host-a': '["wt-1"]' } + +function lastInit(posted: readonly string[]): Record { + const init = posted + .map((json): unknown => JSON.parse(json)) + .findLast( + (frame): frame is Record => + z.object({ type: z.literal('init') }).safeParse(frame).success + ) + if (init === undefined) { + throw new Error('no init was posted') + } + return init +} + +describe('negotiated page storage keys across page and shell versions', () => { + it('names every key added after the legacy allowlist as negotiated', () => { + expect(PAGE_STORAGE_EXACT_KEYS.filter((key) => !LEGACY_EXACT_KEYS.includes(key))).toEqual([ + ...NEGOTIATED_PAGE_STORAGE_KEYS + ]) + }) + + it('keeps the split layout out of an older page init, which that page then accepts', () => { + const bridge = harness({ storage: STORAGE }) + bridge.host.receive(clientFrame({ type: 'ready' })) + + const init = lastInit(bridge.posted) + expect(LegacyInitStorageSchema.safeParse(init).success).toBe(true) + expect(init.storage).toEqual({ 'orca:pins:host-a': '["wt-1"]' }) + }) + + it('keeps an oversize split layout out of an older page init too', () => { + const bridge = harness({ + readStorage: () => ({ storage: {}, storageOversize: [SPLIT_KEY] }) + }) + bridge.host.receive(clientFrame({ type: 'ready' })) + + expect(LegacyInitStorageSchema.safeParse(lastInit(bridge.posted)).success).toBe(true) + }) + + it('hands the split layout to a page whose ready names it', () => { + const bridge = harness({ storage: STORAGE }) + bridge.host.receive(JSON.stringify(createPageReadyFrame())) + + expect(lastInit(bridge.posted).storage).toEqual(STORAGE) + expect(bridge.frames().some((frame) => frame.type === 'init')).toBe(true) + }) + + it('sends a ready an older shell still reads', () => { + const ready: unknown = JSON.parse(JSON.stringify(createPageReadyFrame())) + expect(LegacyReadySchema.safeParse(ready).success).toBe(true) + }) + + it('reads a malformed storageKeys list as none rather than refusing the ready', () => { + const bridge = harness({ storage: STORAGE }) + bridge.host.receive(clientFrame({ type: 'ready', storageKeys: [SPLIT_KEY, 7] })) + + expect(bridge.pageReadyCount()).toBe(1) + expect(lastInit(bridge.posted).storage).toEqual({ 'orca:pins:host-a': '["wt-1"]' }) + }) + + it('keeps what the page declared across a host rebuild under the same document', () => { + const first = harness({ storage: STORAGE }) + first.host.receive(JSON.stringify(createPageReadyFrame())) + const carried = first.host.readSessionBack() + + const rebuilt = harness({ storage: STORAGE, sessionEstablished: true, sessionBack: carried }) + rebuilt.host.publishKeyboardInset(120) + expect(lastInit(rebuilt.posted).storage).toEqual(STORAGE) + }) + + it('drops the declaration when the next document says ready without one', () => { + const bridge = harness({ storage: STORAGE }) + bridge.host.receive(JSON.stringify(createPageReadyFrame())) + bridge.host.receive(clientFrame({ type: 'close' })) + bridge.host.receive(clientFrame({ type: 'ready' })) + + expect(lastInit(bridge.posted).storage).toEqual({ 'orca:pins:host-a': '["wt-1"]' }) + expect(bridge.host.readSessionBack()).toEqual({ claimed: false }) + }) +}) diff --git a/mobile/src/mobile-web-shell/page-storage-keys.ts b/mobile/src/mobile-web-shell/page-storage-keys.ts index c9e1bbbaf427..f001c02fc90f 100644 --- a/mobile/src/mobile-web-shell/page-storage-keys.ts +++ b/mobile/src/mobile-web-shell/page-storage-keys.ts @@ -36,9 +36,39 @@ export const PAGE_STORAGE_EXACT_KEYS = [ /** Whether the terminal's command inputs offer autocorrect. */ 'orca:terminalAutocompleteEnabled', /** Whether a terminal link opens in Orca's browser or the phone's. */ - 'orca:terminalLinkOpenMode' + 'orca:terminalLinkOpenMode', + /** The split terminal's chosen direction. */ + 'orca:terminalSplitLayout' ] as const +/** + * Keys added after pages stopped sharing one allowlist with every host. An older page's `init` + * reader refines each key against its own list and refuses the whole frame on one it lacks, so + * the host sends these only to a page whose `ready` named them in `storageKeys`. + */ +export const NEGOTIATED_PAGE_STORAGE_KEYS = ['orca:terminalSplitLayout'] as const + +/** Whether a page that declared `storageKeys` (null: declared nothing) reads this key in `init`. */ +export function pageReadsStorageKey(key: string, declared: readonly string[] | null): boolean { + return ( + !NEGOTIATED_PAGE_STORAGE_KEYS.some((negotiated) => negotiated === key) || + (declared?.includes(key) ?? false) + ) +} + +/** The part of `init` storage the page on the other side can read. */ +export function pageStorageForReader( + held: PageStorageForInit, + declared: readonly string[] | null +): PageStorageForInit { + return { + storage: Object.fromEntries( + Object.entries(held.storage).filter(([key]) => pageReadsStorageKey(key, declared)) + ), + storageOversize: held.storageOversize.filter((key) => pageReadsStorageKey(key, declared)) + } +} + export const PAGE_STORAGE_KEY_PREFIXES = [ /** `orca:pins:`: the pinned worktrees of the host whose list the page is showing. */ 'orca:pins:', diff --git a/mobile/src/navigation/route-handoff-host-area.web.test.tsx b/mobile/src/navigation/route-handoff-host-area.web.test.tsx index 6084a109e73b..ad8e98c0b265 100644 --- a/mobile/src/navigation/route-handoff-host-area.web.test.tsx +++ b/mobile/src/navigation/route-handoff-host-area.web.test.tsx @@ -40,7 +40,8 @@ const ROUTES: MobileWebPageRoute[] = [ { pathname: '/h/[hostId]', grants: ['navigate', 'storage', 'externalLink', 'haptics'], - canOwnHostArea: true + canOwnHostArea: true, + canOwnHostAreaAcrossLayouts: true }, { pathname: '/h/[hostId]/tasks', @@ -165,18 +166,11 @@ describe('a worktree row in the host-area page', () => { expect(page.navigations()).toEqual([]) }) - it('is still handed to the shell from a phone host page, whose grants do not cover it', () => { + it('keeps a workspace in the same declaring host document on a narrow viewport too', () => { const page = mountPage('/h/host-1', false) page.handoff.push('/h/host-1/session/wt-1') - expect(router.push).not.toHaveBeenCalled() - expect(page.navigations()).toEqual([ - { - v: BRIDGE_PROTOCOL_VERSION, - type: 'notify', - name: 'navigate', - href: '/h/host-1/session/wt-1' - } - ]) + expect(router.push).toHaveBeenCalledWith('/h/host-1/session/wt-1', undefined) + expect(page.navigations()).toEqual([]) }) }) @@ -194,10 +188,12 @@ describe('a session page opened on its own, leaving for the host route', () => { expect(routeViewOf(ROUTES, '/h/host-1', true).ownsHostArea).toBe(true) }) - it('keeps it in this document on a phone, as before', () => { + it('returns a narrow detail document to the same shell-owned host area', () => { const page = mountPage('/h/host-1/session/wt-1', false) page.handoff.replace(hop) - expect(router.replace).toHaveBeenCalledWith(hop, undefined) - expect(page.navigations()).toEqual([]) + expect(router.replace).not.toHaveBeenCalled() + expect(page.navigations()).toEqual([ + { v: BRIDGE_PROTOCOL_VERSION, type: 'notify', name: 'navigate', href: hop } + ]) }) }) diff --git a/mobile/src/session/MobileSessionActiveContent.tsx b/mobile/src/session/MobileSessionActiveContent.tsx index 053e84f960ed..3b97e92c50e5 100644 --- a/mobile/src/session/MobileSessionActiveContent.tsx +++ b/mobile/src/session/MobileSessionActiveContent.tsx @@ -1,3 +1,6 @@ +import { useState } from 'react' +import { computeActiveTerminalKeyboardLift } from '../terminal/terminal-keyboard-avoidance-lift' +import { terminalPaneDirection, terminalPaneKeyboardLayout } from './mobile-terminal-pane-layout' import { Animated, View, Text, Pressable, ActivityIndicator } from 'react-native' import { saveTerminalTextScale } from '../storage/preferences' import { MobileBrowserPane } from '../browser/MobileBrowserPane' @@ -17,6 +20,8 @@ export function MobileSessionActiveContent({ controller: MobileSessionController }) { const executionHost = useWorkspaceExecutionHost() + const [paneFrame, setPaneFrame] = useState({ width: 0, height: 0 }) + const paneDirection = terminalPaneDirection(paneFrame, controller.terminalSplitLayout) const { hostId, worktreeId, @@ -28,6 +33,9 @@ export function MobileSessionActiveContent({ setTerminalTextScale, terminalTextScaleRevisionRef, activeHandle, + terminalSplitActive, + visibleTerminalHandles, + notifyTerminalPaneFrame, markdownDocs, fileDocs, diffComments, @@ -38,6 +46,7 @@ export function MobileSessionActiveContent({ dictationMode, dictationEnabled, toastMessage, + handleTerminalInteraction, handleTerminalTap, browserScreencastSupported, showToast, @@ -211,7 +220,37 @@ export function MobileSessionActiveContent({ key={terminal.handle} handle={terminal.handle} active={terminal.handle === activeHandle} - keyboardLift={terminal.handle === activeHandle ? activeTerminalKeyboardLift : 0} + visible={ + visibleTerminalHandles?.includes(terminal.handle) ?? terminal.handle === activeHandle + } + splitIndex={ + terminalSplitActive && visibleTerminalHandles.includes(terminal.handle) + ? visibleTerminalHandles.indexOf(terminal.handle) + : undefined + } + splitDirection={paneDirection} + splitFrame={paneFrame} + keyboardInset={keyboardLift} + title={terminal.title} + onFrame={notifyTerminalPaneFrame} + keyboardLift={ + terminal.handle !== activeHandle + ? 0 + : terminalSplitActive + ? computeActiveTerminalKeyboardLift({ + keyboardLift: terminalPaneKeyboardLayout( + paneFrame, + paneDirection, + visibleTerminalHandles.indexOf(terminal.handle), + keyboardLift + ).occlusion, + metrics: controller.terminalKeyboardMetrics.get(terminal.handle), + terminalFrameHeight: + controller.getTerminalPaneViewport(terminal.handle).terminalFrameRef.current + ?.height ?? 0 + }) + : activeTerminalKeyboardLift + } terminalTheme={terminal.terminalTheme} textScale={terminalTextScale} onTextScaleChange={(scale) => { @@ -232,6 +271,7 @@ export function MobileSessionActiveContent({ onHaptic={handleHaptic} onTerminalInput={handleTerminalInput} onTerminalQueryReply={handleTerminalQueryReply} + onTerminalInteraction={handleTerminalInteraction} onTerminalTap={handleTerminalTap} onFileTap={handleFileTap} onOpenUrl={handleTerminalOpenUrl} @@ -270,6 +310,9 @@ export function MobileSessionActiveContent({ onLayout={(e) => { const { width, height } = e.nativeEvent.layout notifyTerminalFrame({ width, height }) + setPaneFrame((previous) => + previous.width === width && previous.height === height ? previous : { width, height } + ) }} > {content} diff --git a/mobile/src/session/MobileSessionTabStrip.test.tsx b/mobile/src/session/MobileSessionTabStrip.test.tsx index bc7ebdb030da..ad9ae0d4386f 100644 --- a/mobile/src/session/MobileSessionTabStrip.test.tsx +++ b/mobile/src/session/MobileSessionTabStrip.test.tsx @@ -14,10 +14,15 @@ vi.mock('lucide-react-native', () => ({ FileText: 'Icon', Globe: 'Icon', Plus: 'Icon', - SquareTerminal: 'Icon' + SquareTerminal: 'Icon', + Columns2: 'Icon', + Rows2: 'Icon', + Check: 'Icon', + LayoutGrid: 'Icon' })) vi.mock('../platform/haptics', () => ({ triggerMediumImpact: () => {} })) vi.mock('../hooks/use-now', () => ({ useNow: () => 0 })) +vi.mock('../components/ActionSheetModal', () => ({ ActionSheetModal: () => null })) vi.mock('../components/MobileAgentIcon', () => ({ MobileAgentIcon: () => null })) vi.mock('../components/AgentStateDot', () => ({ AgentStateDot: () => null })) vi.mock('./MobileSessionHeaderIconButton', () => ({ MobileSessionHeaderIconButton: () => null })) diff --git a/mobile/src/session/MobileSessionTabStrip.tsx b/mobile/src/session/MobileSessionTabStrip.tsx index 482ab59b942e..485f18516f69 100644 --- a/mobile/src/session/MobileSessionTabStrip.tsx +++ b/mobile/src/session/MobileSessionTabStrip.tsx @@ -1,6 +1,18 @@ +import { ActionSheetModal } from '../components/ActionSheetModal' +import type { TerminalSplitLayout } from '../storage/preferences' import { useCallback, useMemo, useRef, useState } from 'react' import { View, Text, ScrollView, Pressable } from 'react-native' -import { File, FileText, Globe, Plus, SquareTerminal } from 'lucide-react-native' +import { + File, + FileText, + Globe, + Plus, + SquareTerminal, + Columns2, + Rows2, + Check, + LayoutGrid +} from 'lucide-react-native' import { triggerMediumImpact } from '../platform/haptics' import { MobileAgentIcon } from '../components/MobileAgentIcon' import { AgentStateDot } from '../components/AgentStateDot' @@ -58,8 +70,20 @@ export function MobileSessionTabStrip({ setRenameTarget, activeHandleRef, visibleTabs, + canSplitTerminals, + terminalSplitActive, + toggleTerminalSplit, + terminalSplitLayout, + setTerminalSplitLayout, terminals } = controller + const [showTerminalLayout, setShowTerminalLayout] = useState(false) + const chooseSplitLayout = (layout: TerminalSplitLayout) => { + setTerminalSplitLayout(layout) + if (!terminalSplitActive) { + toggleTerminalSplit() + } + } const tabBarKeepsKeyboard = useKeyboardPersistingTaps('handled') const lastTabTapRef = useRef<{ id: string; at: number } | null>(null) const now = useNow(60_000) @@ -268,6 +292,60 @@ export function MobileSessionTabStrip({ ) : null} + {(canSplitTerminals || terminalSplitActive) && ( + setShowTerminalLayout(true)} + /> + )} + setShowTerminalLayout(false)} + actions={[ + { + label: 'One terminal', + icon: terminalSplitActive ? SquareTerminal : Check, + hint: !terminalSplitActive ? 'Selected' : undefined, + onPress: () => { + if (terminalSplitActive) { + toggleTerminalSplit() + } + } + }, + ...( + [ + { + layout: 'auto', + label: 'Auto', + icon: LayoutGrid, + hint: 'Split to fit the available space' + }, + { + layout: 'side-by-side', + label: 'Side by side', + icon: Columns2, + hint: 'Two columns, even with the sidebar open' + }, + { + layout: 'stacked', + label: 'Stacked', + icon: Rows2, + hint: 'Two rows in any orientation' + } + ] as const + ).map(({ layout, label, icon, hint }) => ({ + label, + icon: terminalSplitActive && terminalSplitLayout === layout ? Check : icon, + hint: + terminalSplitActive && terminalSplitLayout === layout ? `Selected · ${hint}` : hint, + disabled: !canSplitTerminals && !terminalSplitActive, + onPress: () => chooseSplitLayout(layout) + })) + ]} + /> {/* Why: pinned outside the scroll strip so the new-agent button stays reachable however far the tabs scroll. */} { + const component = (name: string) => { + const Host = (props: { children?: ReactNode }) => props.children ?? null + Host.displayName = name + return Host + } + return { + View: component('View'), + Text: component('Text'), + Pressable: component('Pressable'), + TerminalWebView: component('TerminalWebView') + } +}) +vi.mock('react-native', () => ({ + View: hosts.View, + Text: hosts.Text, + Pressable: hosts.Pressable, + StyleSheet: { + create: (value: T) => value, + absoluteFillObject: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 } + } +})) +vi.mock('../terminal/TerminalWebView', () => ({ TerminalWebView: hosts.TerminalWebView })) +import { TerminalPaneView } from './TerminalPaneView' + +type Props = Parameters[0] + +it.each([0, 1])( + 'keeps stacked pane %i visible above a tall keyboard and preserves its measured terminal frame', + (index) => { + const onFrame = vi.fn() + const base = mountFixture({ + handle: `term-${index}`, + active: true, + visible: true, + splitIndex: index, + splitDirection: 'column', + splitFrame: { width: 390, height: 500 }, + keyboardInset: 0, + keyboardLift: 0, + textScale: 1, + onFrame, + onRef: vi.fn() + }) + let renderer!: ReturnType + try { + act(() => { + renderer = create(createElement(TerminalPaneView, base)) + }) + const views = () => renderer.root.findAllByType(hosts.View) + expect(views()[2].props.style.height).toBe(222) + act(() => { + renderer.update( + createElement(TerminalPaneView, { ...base, keyboardInset: 300, keyboardLift: 150 }) + ) + }) + const [outer, clip, measured] = views() + const outerStyle = Object.assign({}, ...outer.props.style.filter(Boolean)) + expect(outerStyle.top).toBe(index * 100) + expect(outerStyle.height).toBe(100) + expect(clip.props.style.overflow).toBe('hidden') + expect(measured.props.style.height).toBe(222) + act(() => { + measured.props.onLayout({ nativeEvent: { layout: { width: 390, height: 222 } } }) + }) + expect(onFrame).toHaveBeenLastCalledWith(`term-${index}`, { width: 390, height: 222 }) + const terminal = renderer.root.findByType(hosts.TerminalWebView) + const terminalStyle = Object.assign({}, ...terminal.props.style.filter(Boolean)) + const bottom = + outerStyle.top + 28 + measured.props.style.height + terminalStyle.transform[0].translateY + expect(bottom).toBe(index * 100 + 100) + expect(bottom).toBeGreaterThan(outerStyle.top + 28) + expect(bottom).toBeLessThanOrEqual(200) + } finally { + act(() => renderer?.unmount()) + } + } +) diff --git a/mobile/src/session/TerminalPaneView.tsx b/mobile/src/session/TerminalPaneView.tsx index eae4e4f9f20d..c5d4b122055b 100644 --- a/mobile/src/session/TerminalPaneView.tsx +++ b/mobile/src/session/TerminalPaneView.tsx @@ -1,5 +1,8 @@ -import { useCallback } from 'react' -import { StyleSheet, View } from 'react-native' +import { useCallback, useState } from 'react' +import { StyleSheet, View, Text, Pressable } from 'react-native' +import { terminalPaneKeyboardLayout } from './mobile-terminal-pane-layout' +import { colors, spacing } from '../theme/mobile-theme' +import type { TerminalFrame } from '../terminal/terminal-webview-messages' import { TerminalWebView } from '../terminal/TerminalWebView' import type { MobileTerminalTheme, @@ -12,6 +15,13 @@ import type { type TerminalPaneViewProps = { handle: string active: boolean + visible?: boolean + splitIndex?: number + splitDirection?: 'row' | 'column' + splitFrame?: TerminalFrame + keyboardInset?: number + title?: string + onFrame?: (handle: string, frame: TerminalFrame) => void keyboardLift: number terminalTheme?: MobileTerminalTheme textScale: number @@ -26,6 +36,7 @@ type TerminalPaneViewProps = { onHaptic: (kind: 'selection' | 'success' | 'error' | 'edge-bump') => void onTerminalInput: (handle: string, bytes: string, input?: TerminalPointerInput) => void onTerminalQueryReply: (handle: string, bytes: string) => void + onTerminalInteraction: (handle: string) => void onTerminalTap: (handle: string) => void onFileTap: (handle: string, pathText: string, line: number | null, column: number | null) => void onOpenUrl: (handle: string, url: string) => void @@ -36,6 +47,13 @@ type TerminalPaneViewProps = { export function TerminalPaneView({ handle, active, + visible = active, + splitIndex, + splitDirection = 'row', + splitFrame, + keyboardInset = 0, + title, + onFrame, keyboardLift, terminalTheme, textScale, @@ -50,6 +68,7 @@ export function TerminalPaneView({ onHaptic, onTerminalInput, onTerminalQueryReply, + onTerminalInteraction, onTerminalTap, onFileTap, onOpenUrl, @@ -63,39 +82,78 @@ export function TerminalPaneView({ [handle, onRef] ) + const [headingHeight, setHeadingHeight] = useState(28) + const splitLayout = + splitIndex !== undefined && splitFrame && splitFrame.height > 0 + ? terminalPaneKeyboardLayout(splitFrame, splitDirection, splitIndex, keyboardInset) + : null + return ( ) } @@ -104,6 +162,17 @@ const styles = StyleSheet.create({ terminalPane: { ...StyleSheet.absoluteFillObject }, + paneViewport: { flex: 1, overflow: 'hidden' }, + paneHeading: { + minHeight: 28, + justifyContent: 'center', + paddingHorizontal: spacing.sm, + backgroundColor: colors.bgPanel, + borderBottomWidth: 1, + borderBottomColor: colors.borderSubtle + }, + paneHeadingActive: { borderBottomColor: colors.textPrimary }, + paneTitle: { color: colors.textSecondary, fontSize: 12 }, terminalPaneHidden: { opacity: 0 }, diff --git a/mobile/src/session/mobile-session-terminal-frame-layout.test.tsx b/mobile/src/session/mobile-session-terminal-frame-layout.test.tsx index 1cec63717c73..0ac70b99368b 100644 --- a/mobile/src/session/mobile-session-terminal-frame-layout.test.tsx +++ b/mobile/src/session/mobile-session-terminal-frame-layout.test.tsx @@ -112,3 +112,56 @@ describe('the terminal frame on the page', () => { expect(heights).toEqual([FRAME.height]) }) }) + +it('shows two terminal panes while focus changes without mounting a second session', async () => { + const { TerminalPaneView } = await import('./TerminalPaneView') + const { terminalPaneViewport } = await import('./mobile-terminal-pane-layout') + const geometry = new Map() + const scope = Object.assign(controller('terminal', vi.fn()), { + terminals: ['a', 'b', 'c'].map((handle) => ({ + handle, + title: handle, + isActive: handle === 'a' + })), + activeHandle: 'a', + visibleTerminalHandles: ['a', 'b'], + terminalSplitActive: true, + terminalKeyboardMetrics: new Map(), + getTerminalPaneViewport: (handle: string) => terminalPaneViewport(geometry, handle), + keyboardLift: 0, + activeTerminalKeyboardLift: 0 + }) + let mounted!: ReturnType + try { + act(() => { + mounted = create(createElement(MobileSessionActiveContent, { controller: scope })) + }) + const panes = () => mounted.root.findAllByType(TerminalPaneView) + expect( + panes().map((pane) => [pane.props.handle, pane.props.visible, pane.props.active]) + ).toEqual([ + ['a', true, true], + ['b', true, false], + ['c', false, false] + ]) + expect( + panes() + .slice(0, 2) + .map((pane) => pane.props.splitDirection) + ).toEqual(['column', 'column']) + act(() => { + mounted.update( + createElement(MobileSessionActiveContent, { controller: { ...scope, activeHandle: 'b' } }) + ) + }) + expect( + panes().map((pane) => [pane.props.handle, pane.props.visible, pane.props.active]) + ).toEqual([ + ['a', true, false], + ['b', true, true], + ['c', false, false] + ]) + } finally { + act(() => mounted?.unmount()) + } +}) diff --git a/mobile/src/session/mobile-terminal-layout-choice.test.tsx b/mobile/src/session/mobile-terminal-layout-choice.test.tsx new file mode 100644 index 000000000000..4fd365669277 --- /dev/null +++ b/mobile/src/session/mobile-terminal-layout-choice.test.tsx @@ -0,0 +1,327 @@ +import { createElement, useRef, useState } from 'react' +import { act, create } from 'react-test-renderer' +import { expect, it, vi } from 'vitest' +import { mountFixture } from '../test-support/rpc-recording/recorder-fixture-shape' + +vi.mock('react-native', () => ({ + View: 'View', + Text: 'Text', + Pressable: 'Pressable', + ScrollView: 'ScrollView', + Alert: { alert: vi.fn() }, + ActivityIndicator: 'ActivityIndicator', + Animated: { View: 'View' }, + StyleSheet: { create: (v: T) => v, absoluteFillObject: {} } +})) +vi.mock('lucide-react-native', () => ({ + File: 'Icon', + FileText: 'Icon', + Globe: 'Icon', + Plus: 'Icon', + SquareTerminal: 'Icon', + Columns2: 'Icon', + Rows2: 'Icon', + Check: 'Icon', + LayoutGrid: 'Icon', + Edit3: 'Icon', + Trash2: 'Icon' +})) +vi.mock('../components/BottomDrawer', () => ({ + BottomDrawer: ({ visible, children }: { visible: boolean; children: unknown }) => + visible ? children : null +})) +vi.mock('../platform/haptics', () => ({ triggerMediumImpact: vi.fn(), triggerSelection: vi.fn() })) +vi.mock('../hooks/use-now', () => ({ useNow: () => 0 })) +vi.mock('../components/MobileAgentIcon', () => ({ MobileAgentIcon: () => null })) +vi.mock('../components/AgentStateDot', () => ({ AgentStateDot: () => null })) +vi.mock('./MobileSessionHeaderIconButton', () => ({ + MobileSessionHeaderIconButton: 'HeaderButton' +})) +vi.mock('./QuickCommandsTabButton', () => ({ QuickCommandsTabButton: () => null })) +vi.mock('./mobile-session-styles', () => ({ styles: {} })) +vi.mock('../platform/keyboard-persisting-taps', () => ({ useKeyboardPersistingTaps: () => null })) +vi.mock('../navigation/workspace-execution-host', () => ({ useWorkspaceExecutionHost: () => ({}) })) +vi.mock('../browser/MobileBrowserPane', () => ({ MobileBrowserPane: () => null })) +vi.mock('./MobileNativeChatOverlay', () => ({ MobileNativeChatOverlay: () => null })) +vi.mock('./MobileSessionFileReader', () => ({ FileReader: () => null })) +vi.mock('./MobileSessionMarkdownReader', () => ({ MarkdownReader: () => null })) +vi.mock('../terminal/TerminalWebView', () => ({ TerminalWebView: 'TerminalWebView' })) +const stored = vi.hoisted(() => new Map()) +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { + getItem: vi.fn(async (key: string) => stored.get(key) ?? null), + setItem: vi.fn(async (key: string, value: string) => { + stored.set(key, value) + }) + } +})) +import { useTerminalSplitLayout } from './use-terminal-split-layout' +import { MobileSessionTabStrip } from './MobileSessionTabStrip' +import { MobileSessionActiveContent } from './MobileSessionActiveContent' +import { TerminalPaneView } from './TerminalPaneView' +import { useMobileSessionTabSwitching } from './use-mobile-session-tab-switching' +import { useMobileSessionTerminalWebview } from './use-mobile-session-terminal-webview' +import { resolveTerminalPaneHandles } from './mobile-terminal-pane-layout' +import { MobileTerminalDiagnostics } from './mobile-terminal-diagnostics' + +type Controller = Parameters[0]['controller'] + +it('lets the split menu override sidebar width and rotation without remounting panes or changing focus', async () => { + let setKeyboard!: (height: number) => void + function Harness() { + const preference = useTerminalSplitLayout() + const [split, setSplit] = useState(true) + const [active, setActive] = useState('b') + const [keyboard, setKeyboardState] = useState(0) + setKeyboard = setKeyboardState + const controller = mountFixture({ + ...preference, + terminalSplitActive: split, + toggleTerminalSplit: () => setSplit(!split), + canSplitTerminals: true, + terminals: [ + { handle: 'a', title: 'First' }, + { handle: 'b', title: 'Second' } + ], + activeHandle: active, + visibleTerminalHandles: split ? ['a', 'b'] : [active], + activeHandleRef: { current: active }, + activeSessionTabIdRef: { current: null }, + visibleTabs: [], + tabStripRef: { current: null }, + tabStripOffsetRef: { current: 0 }, + tabStripViewportWidthRef: { current: 0 }, + tabStripContentWidthRef: { current: 0 }, + tabLayoutsRef: { current: new Map() }, + terminalKeyboardMetrics: new Map(), + getTerminalPaneViewport: () => ({ + terminalFrameRef: { current: null }, + viewportRef: { current: null }, + viewportMeasuredRef: { current: false } + }), + keyboardLift: keyboard, + activeTerminalKeyboardLift: 0, + terminalTextScale: 1, + nativeChatSendError: {}, + dictation: {}, + notifyTerminalFrame: vi.fn(), + setTerminalWebViewRef: vi.fn(), + handleTerminalTap: setActive + }) + return createElement( + 'Screen', + null, + createElement(MobileSessionTabStrip, { controller, inTopBar: false }), + createElement(MobileSessionActiveContent, { controller }) + ) + } + let tree!: ReturnType + await act(async () => { + tree = create(createElement(Harness)) + }) + const frame = tree.root + .findByType(MobileSessionActiveContent) + .findAll((node) => typeof node.type === 'string' && String(node.type) === 'View')[0] + const resize = (width: number, height: number) => + act(() => frame.props.onLayout({ nativeEvent: { layout: { width, height } } })) + const panes = () => tree.root.findAllByType(TerminalPaneView) + const geometry = (index: number) => + Object.assign( + {}, + ...panes() + [index].findAll((node) => typeof node.type === 'string' && String(node.type) === 'View')[0] + .props.style.filter(Boolean) + ) + const originalTerminals = tree.root.findAll( + (node) => typeof node.type === 'string' && String(node.type) === 'TerminalWebView' + ) + const choose = (label: string) => { + act(() => + tree.root + .findAll((node) => typeof node.type === 'string' && String(node.type) === 'HeaderButton') + .find((node) => node.props.icon !== undefined && node.props.active !== undefined)! + .props.onPress() + ) + const row = tree.root + .findAll((node) => typeof node.type === 'string' && String(node.type) === 'Pressable') + .find((node) => + node + .findAll((node) => typeof node.type === 'string' && String(node.type) === 'Text') + .some((text) => text.props.children === label) + ) + expect(row, `visible terminal layout choice: ${label}`).toBeDefined() + act(() => row!.props.onPress()) + } + try { + resize(587, 330) + expect(geometry(1).top).toBe(165) + choose('Side by side') + expect(geometry(1)).toMatchObject({ width: '50%', left: '50%', top: 0 }) + resize(927, 330) + expect(geometry(1).left).toBe('50%') + resize(390, 700) + expect(geometry(1).left).toBe('50%') + act(() => setKeyboard(300)) + expect(geometry(1).height).toBe(400) + choose('Stacked') + expect(geometry(1)).toMatchObject({ top: 200, height: 200 }) + act(() => setKeyboard(0)) + resize(927, 330) + expect(geometry(1)).toMatchObject({ top: 165, height: 165 }) + choose('Auto') + expect(geometry(1).left).toBe('50%') + resize(587, 330) + expect(geometry(1).top).toBe(165) + expect(panes().map((p) => [p.props.handle, p.props.active])).toEqual([ + ['a', false], + ['b', true] + ]) + expect( + tree.root.findAll( + (node) => typeof node.type === 'string' && String(node.type) === 'TerminalWebView' + ) + ).toEqual(originalTerminals) + choose('One terminal') + expect(panes().map((p) => p.props.visible)).toEqual([false, true]) + choose('Side by side') + expect(panes().map((p) => p.props.visible)).toEqual([true, true]) + await act(async () => {}) + expect(stored.get('orca:terminalSplitLayout')).toBe('side-by-side') + act(() => tree.unmount()) + await act(async () => { + tree = create(createElement(Harness)) + }) + const restoredFrame = tree.root + .findByType(MobileSessionActiveContent) + .findAll((node) => typeof node.type === 'string' && String(node.type) === 'View')[0] + act(() => + restoredFrame.props.onLayout({ nativeEvent: { layout: { width: 587, height: 330 } } }) + ) + expect(geometry(1)).toMatchObject({ width: '50%', left: '50%' }) + } finally { + act(() => tree.unmount()) + } +}) + +it('keeps C paired with A after replacing B and focusing A by its first terminal touch', () => { + const focus = vi.fn() + const terminals = ['a', 'b', 'c'].map((handle) => ({ + handle, + title: handle, + isActive: handle === 'a' + })) + const tabs = terminals.map((t) => ({ + type: 'terminal' as const, + id: t.handle, + title: t.title, + terminal: t.handle, + isActive: t.isActive + })) + let switchTo!: ReturnType['switchSessionTab'] + let frameCallback: FrameRequestCallback | undefined + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + frameCallback = callback + return 1 + }) + vi.stubGlobal('cancelAnimationFrame', vi.fn()) + function Harness() { + const [active, setActive] = useState('a') + const [pair, setPair] = useState(['a', 'b']) + const visible = resolveTerminalPaneHandles( + active, + pair, + terminals.map((t) => t.handle) + ) + const activeRef = useRef(active) + activeRef.current = active + const visibleRef = useRef(visible) + visibleRef.current = visible + const scope = mountFixture[0]>({ + activeHandle: active, + activeHandleRef: activeRef, + setActiveHandle: setActive, + splitTerminalHandles: pair, + setSplitTerminalHandles: setPair, + visibleTerminalHandles: visible, + visibleTerminalHandlesRef: visibleRef, + terminals, + sessionTabs: tabs, + client: null, + connState: 'connected', + terminalDiagnosticsRef: useRef(new MobileTerminalDiagnostics()), + terminalUnsubsRef: useRef(new Map()), + terminalRefs: useRef(new Map()), + terminalPaneViewportsRef: useRef(new Map()), + terminalGestureInputBucketsRef: useRef(new Map()), + terminalGestureInputQueuesRef: useRef(new Map()), + terminalGestureInputInFlightRef: useRef(new Set()), + pendingSelectionRef: useRef(null), + activeSessionTabTypeRef: useRef(null), + switchSessionTabRef: useRef(null), + setActiveSessionTabId: vi.fn(), + defaultTerminalHandlesToLiveInput: vi.fn(), + subscribeToTerminal: vi.fn(), + unsubscribeTerminal: vi.fn(), + handleTerminalTap: focus + }) + const switching = useMobileSessionTabSwitching(scope) + switchTo = switching.switchSessionTab + const webview = useMobileSessionTerminalWebview({ ...scope, ...switching }) + return createElement( + 'Screen', + null, + terminals.map((terminal) => + createElement( + TerminalPaneView, + mountFixture[0] & { key: string }>({ + key: terminal.handle, + handle: terminal.handle, + active: active === terminal.handle, + visible: visible.includes(terminal.handle), + splitIndex: visible.includes(terminal.handle) + ? visible.indexOf(terminal.handle) + : undefined, + splitFrame: { width: 587, height: 330 }, + splitDirection: 'row', + keyboardLift: 0, + textScale: 1, + onRef: webview.setTerminalWebViewRef, + onTerminalInteraction: webview.handleTerminalInteraction, + onTerminalTap: webview.handleTerminalTap + }) + ) + ) + ) + } + let tree!: ReturnType + act(() => { + tree = create(createElement(Harness)) + }) + const panes = () => tree.root.findAllByType(TerminalPaneView) + const visible = () => + panes() + .filter((p) => p.props.visible) + .sort((a, b) => a.props.splitIndex - b.props.splitIndex) + .map((p) => p.props.handle) + const originalPanes = panes() + try { + act(() => switchTo(tabs[2])) + expect(visible()).toEqual(['c', 'a']) + const a = panes().find((p) => p.props.handle === 'a')! + const terminal = a.find( + (node) => typeof node.type === 'string' && String(node.type) === 'TerminalWebView' + ) + act(() => terminal.props.onTerminalInteraction()) + expect(visible()).toEqual(['c', 'a']) + act(() => { + terminal.props.onTerminalTap() + frameCallback?.(0) + }) + expect(focus).toHaveBeenLastCalledWith('a') + expect(visible()).toEqual(['c', 'a']) + expect(panes()).toEqual(originalPanes) + } finally { + act(() => tree.unmount()) + vi.unstubAllGlobals() + } +}) diff --git a/mobile/src/session/mobile-terminal-pane-layout.test.ts b/mobile/src/session/mobile-terminal-pane-layout.test.ts new file mode 100644 index 000000000000..6271ec3337a5 --- /dev/null +++ b/mobile/src/session/mobile-terminal-pane-layout.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import { + resolveTerminalPaneHandles, + terminalPaneDirection, + terminalPaneViewport +} from './mobile-terminal-pane-layout' + +describe('mobile terminal split selection', () => { + it('keeps pane order when focus moves and collapses a closed companion', () => { + expect(resolveTerminalPaneHandles('b', ['a', 'b'], ['a', 'b', 'c'])).toEqual(['a', 'b']) + expect(resolveTerminalPaneHandles('a', ['a', 'b'], ['a', 'c'])).toEqual(['a']) + expect(resolveTerminalPaneHandles('c', ['a', 'b'], ['a', 'b', 'c'])).toEqual(['c', 'a']) + expect(resolveTerminalPaneHandles(null, ['a', 'b'], ['a', 'b'])).toEqual([]) + }) + it('uses usable bounds for folded portrait and wide landscape', () => { + expect(terminalPaneDirection({ width: 390, height: 700 })).toBe('column') + expect(terminalPaneDirection({ width: 700, height: 900 })).toBe('column') + expect(terminalPaneDirection({ width: 850, height: 330 })).toBe('row') + expect(terminalPaneDirection({ width: 1100, height: 700 })).toBe('row') + }) + it('never shares geometry ownership across terminal handles', () => { + const states = new Map() + const a = terminalPaneViewport(states, 'a') + const b = terminalPaneViewport(states, 'b') + a.viewportRef.current = { cols: 40, rows: 30 } + expect(b.viewportRef.current).toBeNull() + expect(terminalPaneViewport(states, 'a')).toBe(a) + }) +}) + +it('keeps both stacked pane windows above a keyboard taller than one pane without resizing their grids', async () => { + const { terminalPaneKeyboardLayout } = await import('./mobile-terminal-pane-layout') + const frame = { width: 390, height: 500 } + const upper = terminalPaneKeyboardLayout(frame, 'column', 0, 300) + const lower = terminalPaneKeyboardLayout(frame, 'column', 1, 300) + expect(upper).toEqual({ top: 0, height: 100, originalHeight: 250, occlusion: 150 }) + expect(lower).toEqual({ top: 100, height: 100, originalHeight: 250, occlusion: 150 }) + const heading = 28 + const lastRowBottom = lower.top + heading + (lower.originalHeight - heading) - lower.occlusion + expect(lastRowBottom).toBe(200) + expect(lastRowBottom).toBeGreaterThan(lower.top + heading) + expect(lastRowBottom).toBeLessThanOrEqual(frame.height - 300) + expect(terminalPaneKeyboardLayout(frame, 'column', 1, 0).originalHeight).toBe( + lower.originalHeight + ) +}) diff --git a/mobile/src/session/mobile-terminal-pane-layout.ts b/mobile/src/session/mobile-terminal-pane-layout.ts new file mode 100644 index 000000000000..d45e26944942 --- /dev/null +++ b/mobile/src/session/mobile-terminal-pane-layout.ts @@ -0,0 +1,74 @@ +import type { TerminalSplitLayout } from '../storage/preferences' +import type { TerminalFrame } from '../terminal/terminal-webview-messages' + +export type TerminalPaneViewport = { + terminalFrameRef: { current: TerminalFrame | null } + viewportRef: { current: { cols: number; rows: number } | null } + viewportMeasuredRef: { current: boolean } +} + +export function terminalPaneViewport(states: Map, handle: string) { + let state = states.get(handle) + if (!state) { + state = { + terminalFrameRef: { current: null }, + viewportRef: { current: null }, + viewportMeasuredRef: { current: false } + } + states.set(handle, state) + } + return state +} + +export function resolveTerminalPaneHandles( + active: string | null, + pair: readonly string[] | null, + available: readonly string[] +): string[] { + if (!active) { + return [] + } + if (!pair) { + return [active] + } + const surviving = pair.filter((handle) => available.includes(handle)) + if (surviving.includes(active)) { + return surviving.length === 2 ? surviving : [active] + } + const companion = surviving.find((handle) => handle !== active) + return companion ? [active, companion] : [active] +} + +export function terminalPaneDirection( + frame: TerminalFrame, + layout: TerminalSplitLayout = 'auto' +): 'row' | 'column' { + if (layout === 'side-by-side') { + return 'row' + } + if (layout === 'stacked') { + return 'column' + } + return frame.width >= 600 && frame.width > frame.height ? 'row' : 'column' +} + +export function keepsTerminalPaneVisible(handle: string, visible: readonly string[] = []): boolean { + return visible.length === 2 && visible.includes(handle) +} + +export function terminalPaneKeyboardLayout( + frame: TerminalFrame, + direction: 'row' | 'column', + index: number, + keyboardInset: number +) { + const originalHeight = direction === 'column' ? frame.height / 2 : frame.height + const remainingHeight = Math.max(0, frame.height - Math.max(0, keyboardInset)) + const height = direction === 'column' ? remainingHeight / 2 : remainingHeight + return { + top: direction === 'column' ? index * height : 0, + height, + originalHeight, + occlusion: originalHeight - height + } +} diff --git a/mobile/src/session/mobile-terminal-split-gestures.test.tsx b/mobile/src/session/mobile-terminal-split-gestures.test.tsx new file mode 100644 index 000000000000..d52875b2bfa7 --- /dev/null +++ b/mobile/src/session/mobile-terminal-split-gestures.test.tsx @@ -0,0 +1,317 @@ +// @vitest-environment happy-dom +import { createElement, useState } from 'react' +import { act, create } from 'react-test-renderer' +import { afterEach, expect, it, vi } from 'vitest' +import { mountFixture } from '../test-support/rpc-recording/recorder-fixture-shape' +import { createTerminalDocument } from '../terminal/document/create-terminal-document' +import { terminalDocumentDouble } from '../terminal/document/document-terminal-double.test-support' +import { TERMINAL_DOCUMENT_MARKUP } from '../terminal/terminal-webview-html' +import { dispatchTerminalWebViewNotification } from '../terminal/terminal-webview-notification-dispatch' +import { terminalPaneViewport, type TerminalPaneViewport } from './mobile-terminal-pane-layout' +import { useMobileSessionTerminalWebview } from './use-mobile-session-terminal-webview' +import { useMobileSessionTerminalInput } from './use-mobile-session-terminal-input' +import { useMobileSessionTabSwitching } from './use-mobile-session-tab-switching' + +vi.mock('../platform/haptics', () => ({ triggerSelection: vi.fn() })) + +afterEach(() => { + document.body.innerHTML = '' + vi.useRealTimers() +}) + +function fireTouch(surface: HTMLElement, type: string, y?: number) { + const event = new Event(type, { bubbles: true, cancelable: true }) + Object.defineProperty(event, 'touches', { + value: y === undefined ? [] : [{ identifier: 0, clientX: 40, clientY: y, target: surface }] + }) + surface.dispatchEvent(event) +} + +it.each(['touch', 'wheel', 'mouse', 'tap'] as const)( + '%s selects either split pane before its first input; only a touch tap opens the keyboard', + async (gesture) => { + vi.useFakeTimers() + const activeHandleRef = { current: 'a' } + const visibleTerminalHandlesRef = { current: ['a', 'b'] } + const subscriptions = { + current: new Map([ + ['a', vi.fn()], + ['b', vi.fn()] + ]) + } + const geometry = { current: new Map() } + const focus = vi.fn() + const unsubscribe = vi.fn() + const send = vi.fn(async (_handle: string, _bytes: string) => true) + const request = vi.fn(async (_method: string, _params?: unknown) => ({ + id: 'test', + ok: true as const, + result: { send: { accepted: true } } + })) + const client = { sendRequest: request } + const modes = { + bracketedPasteMode: false, + altScreen: true, + mouseTrackingMode: 'none' as const, + sgrMouseMode: false, + sgrMousePixelsMode: false + } + const pointerModes = { ...modes, mouseTrackingMode: 'vt200' as const, sgrMouseMode: true } + const liveHandles = { current: new Set() } + let receive!: (handle: string, message: Record) => void + let tap!: (handle: string) => void + function Probe() { + const [activeHandle, setActiveHandle] = useState('a') + const scope = mountFixture[0]>({ + activeHandle, + setActiveHandle, + activeHandleRef, + visibleTerminalHandlesRef, + visibleTerminalHandles: ['a', 'b'], + terminalUnsubsRef: subscriptions, + terminalPaneViewportsRef: geometry, + getTerminalPaneViewport: (handle) => terminalPaneViewport(geometry.current, handle), + terminals: ['a', 'b'].map((handle) => ({ + handle, + title: handle, + isActive: handle === activeHandle + })), + sessionTabs: ['a', 'b'].map((handle) => ({ + id: handle, + type: 'terminal', + terminal: handle + })), + activeSessionTabTypeRef: { current: 'terminal' }, + setActiveSessionTabId: vi.fn(), + pendingSelectionRef: { current: null }, + terminalDiagnosticsRef: { current: { tabSwitch: vi.fn() } }, + defaultTerminalHandlesToLiveInput: vi.fn(), + switchSessionTabRef: { current: null }, + connState: 'connected', + connStateRef: { current: 'connected' }, + client, + clientRef: { current: client }, + deviceTokenRef: { current: 'test-device' }, + handleTerminalTap: focus, + subscribeToTerminal: vi.fn(), + unsubscribeTerminal: unsubscribe, + activeSessionTab: null, + markdownDocs: new Map(), + fileDocs: new Map(), + ptyModesRef: { + current: new Map( + ['a', 'b'].map((handle) => [ + handle, + gesture === 'mouse' || gesture === 'tap' ? pointerModes : modes + ]) + ) + }, + terminalGestureInputBucketsRef: { current: new Map() }, + terminalGestureInputQueuesRef: { current: new Map() }, + terminalGestureInputInFlightRef: { current: new Set() }, + liveInputTerminalHandlesRef: liveHandles, + sendLiveTerminalInputRef: { current: send } + }) + const switching = useMobileSessionTabSwitching(scope) + const webview = useMobileSessionTerminalWebview(Object.assign(scope, switching)) + const input = useMobileSessionTerminalInput( + mountFixture(Object.assign(scope, switching, webview)) + ) + tap = webview.handleTerminalTap + receive = (handle, message) => + dispatchTerminalWebViewNotification(message, { + reportEngineError: (error) => { + throw new Error(error) + }, + onTerminalInteraction: () => webview.handleTerminalInteraction?.(handle), + onTerminalTap: () => webview.handleTerminalTap(handle), + onTerminalInput: (bytes, pointer) => input.handleTerminalInput(handle, bytes, pointer) + }) + return null + } + let renderer!: ReturnType + const docs: ReturnType[] = [] + const surfaces = new Map() + const opened = vi.fn() + try { + act(() => { + renderer = create(createElement(Probe)) + }) + for (const handle of ['a', 'b']) { + const host = document.createElement('div') + host.innerHTML = TERMINAL_DOCUMENT_MARKUP + document.body.appendChild(host) + const engine = terminalDocumentDouble() + const started = createTerminalDocument({ + root: host, + postToHost: (message) => receive(handle, message), + hasEngine: () => true, + installHostTransport: () => () => {}, + installErrorReporter: () => () => {}, + paintDocumentBackground: () => {}, + viewportRect: () => ({ left: 0, top: 0, width: 400, height: 400 }), + observeViewport: () => () => {}, + createUnicode11Addon: () => null, + createWebglAddon: () => null, + createTerminal: () => ({ + ...engine.terminal, + modes: gesture === 'mouse' || gesture === 'tap' ? pointerModes : modes, + _core: { _renderService: { dimensions: { css: { cell: { width: 8, height: 15 } } } } }, + buffer: { active: { ...engine.terminal.buffer.active, type: 'alternate' } }, + open: (surface) => { + engine.terminal.open(surface) + opened(handle) + } + }) + }) + docs.push(started) + started.send({ type: 'init', cols: 40, rows: 24, initialData: '' }) + await act(async () => { + await vi.advanceTimersByTimeAsync(150) + }) + if (gesture === 'mouse' || gesture === 'tap') { + started.send({ type: 'write', data: '\x1b[?1000h\x1b[?1006h' }) + } + const surface = host.querySelector('#terminal-surface') + if (!surface) { + throw new Error('No terminal surface') + } + surfaces.set(handle, surface) + } + const openedBefore = opened.mock.calls.length + request.mockClear() + for (const handle of ['b', 'a']) { + const surface = surfaces.get(handle)! + await act(async () => { + if (gesture === 'tap') { + fireTouch(surface, 'touchstart', 150) + fireTouch(surface, 'touchend') + } else if (gesture === 'touch') { + fireTouch(surface, 'touchstart', 150) + fireTouch(surface, 'touchmove', 90) + fireTouch(surface, 'touchcancel') + } else if (gesture === 'wheel') { + surface.dispatchEvent( + new WheelEvent('wheel', { + bubbles: true, + cancelable: true, + deltaY: 60, + clientX: 40, + clientY: 150 + }) + ) + } else { + surface.dispatchEvent( + new PointerEvent('pointerdown', { + bubbles: true, + pointerType: 'mouse', + button: 0, + clientX: 40, + clientY: 150 + }) + ) + surface.dispatchEvent( + new PointerEvent('pointerup', { + bubbles: true, + pointerType: 'mouse', + button: 0, + clientX: 40, + clientY: 150 + }) + ) + } + }) + expect(activeHandleRef.current).toBe(handle) + if (gesture === 'mouse' || gesture === 'tap') { + expect(send.mock.calls.at(-1)).toEqual([handle, expect.stringContaining('\x1b[<0;')]) + } else { + expect(request).toHaveBeenCalledWith( + 'terminal.send', + expect.objectContaining({ terminal: handle, text: '\x1b[B'.repeat(4) }), + expect.anything() + ) + } + } + if (gesture === 'wheel') { + const a = surfaces.get('a')! + const b = surfaces.get('b')! + const wheel = (deltaY: number) => + a.dispatchEvent( + new WheelEvent('wheel', { + bubbles: true, + cancelable: true, + deltaY, + clientX: 40, + clientY: 150 + }) + ) + await act(async () => { + fireTouch(b, 'touchstart', 150) + fireTouch(b, 'touchcancel') + }) + const sentBeforeTail = request.mock.calls.filter( + ([method]) => method === 'terminal.send' + ).length + await act(async () => { + wheel(7) + }) + expect(activeHandleRef.current).toBe('b') + await act(async () => { + wheel(30) + }) + expect(activeHandleRef.current).toBe('b') + expect(request.mock.calls.filter(([method]) => method === 'terminal.send')).toHaveLength( + sentBeforeTail + ) + await act(async () => { + await vi.advanceTimersByTimeAsync(250) + wheel(8) + }) + expect(activeHandleRef.current).toBe('a') + expect(request.mock.calls.filter(([method]) => method === 'terminal.send')).toHaveLength( + sentBeforeTail + ) + await act(async () => { + wheel(7) + }) + expect(request).toHaveBeenLastCalledWith( + 'terminal.send', + expect.objectContaining({ terminal: 'a', text: '\x1b[B' }), + expect.anything() + ) + } + await act(async () => { + await vi.advanceTimersByTimeAsync(50) + }) + if (gesture === 'tap') { + expect(focus).toHaveBeenCalledWith('a') + } else { + expect(focus).not.toHaveBeenCalled() + } + focus.mockClear() + expect(unsubscribe).not.toHaveBeenCalled() + expect(visibleTerminalHandlesRef.current).toEqual(['a', 'b']) + expect(opened.mock.calls).toHaveLength(openedBefore) + act(() => { + tap('b') + receive('a', { type: 'terminal-interaction' }) + }) + await act(async () => { + await vi.advanceTimersByTimeAsync(50) + }) + expect(focus).not.toHaveBeenCalled() + const inputCount = request.mock.calls.filter(([method]) => method === 'terminal.send').length + receive('b', { type: 'terminal-input', bytes: '\x1b[B' }) + expect(request.mock.calls.filter(([method]) => method === 'terminal.send')).toHaveLength( + inputCount + ) + receive('hidden', { type: 'terminal-interaction' }) + expect(activeHandleRef.current).toBe('a') + } finally { + for (const doc of docs) { + doc.stop() + } + act(() => renderer?.unmount()) + } + } +) diff --git a/mobile/src/session/mobile-terminal-split-input.test.tsx b/mobile/src/session/mobile-terminal-split-input.test.tsx new file mode 100644 index 000000000000..ee9026c4bc21 --- /dev/null +++ b/mobile/src/session/mobile-terminal-split-input.test.tsx @@ -0,0 +1,110 @@ +// @vitest-environment happy-dom +import { createElement, useState } from 'react' +import { act, create } from 'react-test-renderer' +import { expect, it, vi } from 'vitest' +import { mountFixture } from '../test-support/rpc-recording/recorder-fixture-shape' +import { useTerminalLiveInputCommit } from '../terminal/use-terminal-live-input-commit' +import { useMobileSessionTerminalWebview } from './use-mobile-session-terminal-webview' +import { terminalPaneViewport, type TerminalPaneViewport } from './mobile-terminal-pane-layout' + +vi.mock('../platform/live-input-composing-range', () => ({ + reportedLiveInputComposing: (isComposing: boolean | undefined) => isComposing +})) + +it('a pane tap moves the one input owner without dropping either stream or forwarding old preedit', async () => { + vi.useFakeTimers() + const activeHandleRef = { current: 'a' } + const visibleTerminalHandlesRef = { current: ['a', 'b'] } + const subscriptions = { + current: new Map([ + ['a', vi.fn()], + ['b', vi.fn()] + ]) + } + const geometry = { current: new Map() } + const send = vi.fn(async (_handle: string, _text: string) => true) + const focus = vi.fn() + const unsubscribe = vi.fn() + const handles = new Set(['a', 'b']) + let tap!: (handle: string) => void + let change!: ReturnType['handleLiveInputChange'] + function Probe() { + const [activeHandle, setActiveHandle] = useState('a') + const webview = useMobileSessionTerminalWebview( + mountFixture({ + activeHandle, + activeHandleRef, + terminals: [ + { handle: 'a', title: 'A', isActive: true }, + { handle: 'b', title: 'B', isActive: false } + ], + visibleTerminalHandles: ['a', 'b'], + visibleTerminalHandlesRef, + terminalPaneViewportsRef: geometry, + getTerminalPaneViewport: (handle) => terminalPaneViewport(geometry.current, handle), + setSplitTerminalHandles: vi.fn(), + showNativeChat: false, + connState: 'connected', + switchTab: (handle) => { + activeHandleRef.current = handle + setActiveHandle(handle) + }, + handleTerminalTap: focus, + subscribeToTerminal: vi.fn(), + unsubscribeTerminal: unsubscribe, + terminalUnsubsRef: subscriptions, + activeSessionTab: null, + markdownDocs: new Map(), + fileDocs: new Map() + }) + ) + tap = webview.handleTerminalTap + const input = useTerminalLiveInputCommit({ + activeHandle, + activeHandleRef, + activeSessionTabType: 'terminal', + activeSessionTabTypeRef: { current: 'terminal' }, + connected: true, + liveInputRef: { current: null }, + liveInputTerminalHandles: handles, + liveInputTerminalHandlesRef: { current: handles }, + sendLiveTerminalInputRef: { current: send }, + setLiveInputCapture: vi.fn() + }) + change = input.handleLiveInputChange + return null + } + let renderer!: ReturnType + try { + act(() => { + renderer = create(createElement(Probe)) + }) + act(() => { + change({ nativeEvent: { text: 'ni', isComposing: true } }) + }) + act(() => { + tap('b') + }) + await act(async () => { + await vi.advanceTimersByTimeAsync(30) + }) + expect(activeHandleRef.current).toBe('b') + expect(focus).toHaveBeenCalledWith('b') + expect(unsubscribe).not.toHaveBeenCalled() + expect(subscriptions.current.size).toBe(2) + act(() => { + change({ nativeEvent: { text: 'hello', isComposing: false } }) + }) + await act(async () => { + await vi.advanceTimersByTimeAsync(300) + }) + expect(send.mock.calls).toEqual([['b', 'hello']]) + act(() => { + tap('hidden') + }) + expect(activeHandleRef.current).toBe('b') + } finally { + act(() => renderer?.unmount()) + vi.useRealTimers() + } +}) diff --git a/mobile/src/session/use-mobile-session-controller.ts b/mobile/src/session/use-mobile-session-controller.ts index 33aee62c08eb..3b7a79da8ea6 100644 --- a/mobile/src/session/use-mobile-session-controller.ts +++ b/mobile/src/session/use-mobile-session-controller.ts @@ -45,6 +45,13 @@ export function useMobileSessionController() { feedbackCapabilities, useMobileSessionNativeChatDictation(feedbackCapabilities, sendLiveTerminalInput) ) + if (nativeChatDictation.showNativeChat) { + nativeChatDictation.visibleTerminalHandles = nativeChatDictation.activeHandle + ? [nativeChatDictation.activeHandle] + : [] + nativeChatDictation.visibleTerminalHandlesRef.current = + nativeChatDictation.visibleTerminalHandles + } const subscriptionFoundation = Object.assign( nativeChatDictation, useMobileSessionTerminalSubscriptionFoundation(nativeChatDictation) diff --git a/mobile/src/session/use-mobile-session-keyboard-state.test.tsx b/mobile/src/session/use-mobile-session-keyboard-state.test.tsx index 62cda6ae2fe3..756691c0a513 100644 --- a/mobile/src/session/use-mobile-session-keyboard-state.test.tsx +++ b/mobile/src/session/use-mobile-session-keyboard-state.test.tsx @@ -76,6 +76,8 @@ function Harness(): null { setKeyboardHeight: harness.setKeyboardHeight, // Read only by the viewport refit, which is mocked above; present because the scope names them. activeHandleRef: { current: null }, + visibleTerminalHandlesRef: { current: [] }, + terminalPaneViewportsRef: { current: new Map() }, clientRef: { current: null }, deviceTokenRef: { current: null }, showNativeChatRef: { current: false }, diff --git a/mobile/src/session/use-mobile-session-keyboard-state.ts b/mobile/src/session/use-mobile-session-keyboard-state.ts index b314860b8c6a..9c47065696ee 100644 --- a/mobile/src/session/use-mobile-session-keyboard-state.ts +++ b/mobile/src/session/use-mobile-session-keyboard-state.ts @@ -14,6 +14,8 @@ import type { MobileSessionLifecycleModel } from './use-mobile-session-lifecycle export type MobileSessionKeyboardScope = Pick< MobileSessionLifecycleModel, | 'activeHandleRef' + | 'visibleTerminalHandlesRef' + | 'terminalPaneViewportsRef' | 'activeSessionTabId' | 'clientRef' | 'connState' @@ -63,6 +65,8 @@ export function useMobileSessionKeyboardState(scope: MobileSessionKeyboardScope) viewportMeasuredRef, terminalRefs, activeHandleRef, + visibleTerminalHandlesRef, + terminalPaneViewportsRef, terminalFrameRef, showNativeChatRef, unsubscribeTerminal, @@ -76,6 +80,8 @@ export function useMobileSessionKeyboardState(scope: MobileSessionKeyboardScope) notifyTerminalCellBoxChange } = useTerminalViewportRefit({ activeHandleRef, + visibleTerminalHandlesRef, + terminalPaneViewportsRef, terminalRefs, terminalFrameRef, viewportRef, diff --git a/mobile/src/session/use-mobile-session-lifecycle.ts b/mobile/src/session/use-mobile-session-lifecycle.ts index 183c5c67b7d9..d82b61e223c8 100644 --- a/mobile/src/session/use-mobile-session-lifecycle.ts +++ b/mobile/src/session/use-mobile-session-lifecycle.ts @@ -24,6 +24,7 @@ export function useMobileSessionLifecycle(scope: MobileSessionTabReconciliationM terminalRefs, initializedHandlesRef, activeHandleRef, + visibleTerminalHandlesRef, scheduleDelayedAction, unsubscribeTerminal, subscribeToTerminal @@ -114,6 +115,7 @@ export function useMobileSessionLifecycle(scope: MobileSessionTabReconciliationM // Why: iOS can resume a WKWebView with a blank xterm store and no web-ready; invalidate the latch so init waits for the pong. const outcome = recoverActiveTerminalAfterForeground({ activeHandleRef, + visibleTerminalHandlesRef, terminalRefs, initializedHandlesRef, connStateRef, @@ -139,6 +141,7 @@ export function useMobileSessionLifecycle(scope: MobileSessionTabReconciliationM } recoverActiveTerminalAfterForeground({ activeHandleRef, + visibleTerminalHandlesRef, terminalRefs, initializedHandlesRef, connStateRef, diff --git a/mobile/src/session/use-mobile-session-presentation.ts b/mobile/src/session/use-mobile-session-presentation.ts index cc335efd6ba1..8aeb9617329a 100644 --- a/mobile/src/session/use-mobile-session-presentation.ts +++ b/mobile/src/session/use-mobile-session-presentation.ts @@ -27,6 +27,7 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) hostEndpoint, initialSessionAutoCreateRef, terminalFrameRef, + getTerminalPaneViewport, handleCreateTerminal, visibleTabs, forceReconnectHost @@ -87,7 +88,12 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) const activeTerminalKeyboardLift = computeActiveTerminalKeyboardLift({ keyboardLift, metrics: activeHandle ? terminalKeyboardMetrics.get(activeHandle) : undefined, - terminalFrameHeight: terminalFrameRef.current?.height ?? 0 + terminalFrameHeight: + (activeHandle + ? getTerminalPaneViewport?.(activeHandle).terminalFrameRef.current?.height + : null) ?? + terminalFrameRef.current?.height ?? + 0 }) const toastAnimatedStyle = { opacity: toastOpacityRef.current, diff --git a/mobile/src/session/use-mobile-session-screen-state.ts b/mobile/src/session/use-mobile-session-screen-state.ts index f6240af2affe..38575033bb60 100644 --- a/mobile/src/session/use-mobile-session-screen-state.ts +++ b/mobile/src/session/use-mobile-session-screen-state.ts @@ -1,4 +1,5 @@ import { useState, useRef, useMemo } from 'react' +import { useTerminalSplitLayout } from './use-terminal-split-layout' import { Animated, type ScrollView } from 'react-native' import type { MobileTerminalLinkOpenMode } from '../storage/preferences' import type { TerminalKeyboardAvoidanceMetrics } from '../terminal/terminal-webview-contract' @@ -28,6 +29,7 @@ import type { MobileSessionFoundationModel } from './use-mobile-session-foundati export function useMobileSessionScreenState(scope: MobileSessionFoundationModel) { const { worktreeId, hostId, initialCreateWarning } = scope + const terminalSplitLayout = useTerminalSplitLayout() const [terminals, setTerminals] = useState([]) const terminalsRef = useRef([]) const [sessionTabs, setSessionTabs] = useState([]) @@ -130,6 +132,7 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel) const toastHideTimerRef = useRef | null>(null) const toastSeqRef = useRef(0) return { + ...terminalSplitLayout, terminals, setTerminals, terminalsRef, diff --git a/mobile/src/session/use-mobile-session-startup.ts b/mobile/src/session/use-mobile-session-startup.ts index c9725e6ab10c..43d4a62c8169 100644 --- a/mobile/src/session/use-mobile-session-startup.ts +++ b/mobile/src/session/use-mobile-session-startup.ts @@ -41,6 +41,8 @@ export function useMobileSessionStartup(scope: MobileSessionKeyboardStateModel) clearDelayedActionTimers, showToast, clearTerminalCache, + setSplitTerminalHandles, + terminalPaneViewportsRef, fetchTerminals, ensureSessionTabs } = scope @@ -50,6 +52,8 @@ export function useMobileSessionStartup(scope: MobileSessionKeyboardStateModel) sessionTabActionSheetKeyboardHideSubRef.current?.remove() sessionTabActionSheetKeyboardHideSubRef.current = null clearTerminalCache() + setSplitTerminalHandles(null) + terminalPaneViewportsRef.current.clear() activeHandleRef.current = null activeSessionTabTypeRef.current = null pendingSelectionRef.current = null @@ -89,6 +93,8 @@ export function useMobileSessionStartup(scope: MobileSessionKeyboardStateModel) clearPendingLiveInputCommit, bufferedTerminalDraftState.clearPendingRestorations, clearTerminalCache, + setSplitTerminalHandles, + terminalPaneViewportsRef, hostId, bufferedTerminalDraftState.resetDrafts, worktreeId diff --git a/mobile/src/session/use-mobile-session-tab-application.ts b/mobile/src/session/use-mobile-session-tab-application.ts index 87d3ff3c6975..027eb04e30a5 100644 --- a/mobile/src/session/use-mobile-session-tab-application.ts +++ b/mobile/src/session/use-mobile-session-tab-application.ts @@ -1,3 +1,4 @@ +import { keepsTerminalPaneVisible } from './mobile-terminal-pane-layout' import { pendingSelectionHandle, pendingSelectionTabId, @@ -46,6 +47,7 @@ export function useMobileSessionTabApplication(scope: MobileSessionTerminalListM markdownDocsRef, terminalDiagnosticsRef, activeHandleRef, + visibleTerminalHandlesRef, activeSessionTabTypeRef, pendingSelectionRef, pendingBrowserFocusPageIdRef, @@ -217,7 +219,9 @@ export function useMobileSessionTabApplication(scope: MobileSessionTerminalListM if (typeof active.terminal !== 'string') { const previous = activeHandleRef.current if (previous) { - unsubscribeTerminal(previous) + if (!keepsTerminalPaneVisible(previous, visibleTerminalHandlesRef?.current)) { + unsubscribeTerminal(previous) + } } activeHandleRef.current = null setActiveHandle(null) @@ -225,7 +229,9 @@ export function useMobileSessionTabApplication(scope: MobileSessionTerminalListM } const previous = activeHandleRef.current if (previous && previous !== active.terminal) { - unsubscribeTerminal(previous) + if (!keepsTerminalPaneVisible(previous, visibleTerminalHandlesRef?.current)) { + unsubscribeTerminal(previous) + } } activeHandleRef.current = active.terminal setActiveHandle(active.terminal) @@ -234,7 +240,9 @@ export function useMobileSessionTabApplication(scope: MobileSessionTerminalListM // Why: an empty snapshot can transiently omit a live terminal; explicit close clears it on RPC success. const previous = activeHandleRef.current if (previous) { - unsubscribeTerminal(previous) + if (!keepsTerminalPaneVisible(previous, visibleTerminalHandlesRef?.current)) { + unsubscribeTerminal(previous) + } } activeHandleRef.current = null setActiveHandle(null) diff --git a/mobile/src/session/use-mobile-session-tab-switching.ts b/mobile/src/session/use-mobile-session-tab-switching.ts index c951cbe10c1f..c459938fff27 100644 --- a/mobile/src/session/use-mobile-session-tab-switching.ts +++ b/mobile/src/session/use-mobile-session-tab-switching.ts @@ -1,3 +1,4 @@ +import { keepsTerminalPaneVisible } from './mobile-terminal-pane-layout' import { useCallback } from 'react' import { STARTUP_CWD_FALLBACK_SENTENCE } from '../../../src/shared/startup-cwd-fallback' import { triggerSelection } from '../platform/haptics' @@ -15,6 +16,7 @@ export function useMobileSessionTabSwitching(scope: MobileSessionKeyboardStateMo sessionTabs, defaultTerminalHandlesToLiveInput, setActiveHandle, + setSplitTerminalHandles, setActiveSessionTabId, activeSessionTabId, markdownDocs, @@ -22,6 +24,7 @@ export function useMobileSessionTabSwitching(scope: MobileSessionKeyboardStateMo terminalUnsubsRef, terminalDiagnosticsRef, activeHandleRef, + visibleTerminalHandlesRef, activeSessionTabTypeRef, pendingSelectionRef, switchSessionTabRef, @@ -52,14 +55,25 @@ export function useMobileSessionTabSwitching(scope: MobileSessionKeyboardStateMo activeSessionTabTypeRef.current = 'terminal' defaultTerminalHandlesToLiveInput([handle]) setActiveSessionTabId(matchingTab?.id ?? null) + const visible = visibleTerminalHandlesRef?.current + if (visible?.length === 2 && !visible.includes(handle)) { + const pair = [handle, visible[0]] + visibleTerminalHandlesRef.current = pair + setSplitTerminalHandles(pair) + } const prev = activeHandleRef.current activeHandleRef.current = handle setActiveHandle(handle) if (prev && prev !== handle) { - unsubscribeTerminal(prev) + if (!keepsTerminalPaneVisible(prev, visibleTerminalHandlesRef?.current)) { + unsubscribeTerminal(prev) + } } // Force a fresh subscribe even if eagerly subscribed without viewport - if (terminalUnsubsRef.current.has(handle)) { + if ( + terminalUnsubsRef.current.has(handle) && + (visibleTerminalHandlesRef?.current.length ?? 0) < 2 + ) { unsubscribeTerminal(handle) } subscribeToTerminal(handle) @@ -82,6 +96,7 @@ export function useMobileSessionTabSwitching(scope: MobileSessionKeyboardStateMo defaultTerminalHandlesToLiveInput, reportActivation, sessionTabs, + setSplitTerminalHandles, subscribeToTerminal, unsubscribeTerminal, worktreeId @@ -105,7 +120,9 @@ export function useMobileSessionTabSwitching(scope: MobileSessionKeyboardStateMo setActiveSessionTabId(tab.id) const prev = activeHandleRef.current if (prev) { - unsubscribeTerminal(prev) + if (!keepsTerminalPaneVisible(prev, visibleTerminalHandlesRef?.current)) { + unsubscribeTerminal(prev) + } } activeHandleRef.current = null setActiveHandle(null) @@ -130,7 +147,9 @@ export function useMobileSessionTabSwitching(scope: MobileSessionKeyboardStateMo setActiveSessionTabId(tab.id) const prev = activeHandleRef.current if (prev) { - unsubscribeTerminal(prev) + if (!keepsTerminalPaneVisible(prev, visibleTerminalHandlesRef?.current)) { + unsubscribeTerminal(prev) + } } activeHandleRef.current = null setActiveHandle(null) diff --git a/mobile/src/session/use-mobile-session-terminal-runtime.ts b/mobile/src/session/use-mobile-session-terminal-runtime.ts index fd92974b1058..8ad4e46ce75a 100644 --- a/mobile/src/session/use-mobile-session-terminal-runtime.ts +++ b/mobile/src/session/use-mobile-session-terminal-runtime.ts @@ -1,3 +1,8 @@ +import { + terminalPaneViewport, + resolveTerminalPaneHandles, + type TerminalPaneViewport +} from './mobile-terminal-pane-layout' import type { PendingSessionSelection } from './pending-session-selection' import { useState, useRef, useCallback } from 'react' import type { TerminalFrame } from '../terminal/terminal-webview-messages' @@ -33,6 +38,7 @@ export function useMobileSessionTerminalRuntime(scope: MobileSessionScreenStateM client, clientId, sessionTabs, + terminals, setLiveInputCapture, liveInputTerminalHandles, liveInputTerminalHandlesRef, @@ -57,6 +63,19 @@ export function useMobileSessionTerminalRuntime(scope: MobileSessionScreenStateM // Why: measured once on mount, then passed with every subscribe so the server can auto-fit the PTY to phone dims. const viewportRef = useRef<{ cols: number; rows: number } | null>(null) const viewportMeasuredRef = useRef(false) + const terminalPaneViewportsRef = useRef(new Map()) + const getTerminalPaneViewport = useCallback( + (handle: string) => terminalPaneViewport(terminalPaneViewportsRef.current, handle), + [] + ) + const [splitTerminalHandles, setSplitTerminalHandles] = useState(null) + const visibleTerminalHandles = resolveTerminalPaneHandles( + activeHandle, + splitTerminalHandles, + terminals.map((terminal) => terminal.handle) + ) + const visibleTerminalHandlesRef = useRef([]) + visibleTerminalHandlesRef.current = visibleTerminalHandles const terminalRefs = useRef>(new Map()) const liveInputRef = useRef(null) const commandInputRef = useRef(null) @@ -182,6 +201,12 @@ export function useMobileSessionTerminalRuntime(scope: MobileSessionScreenStateM connStateRef, viewportRef, viewportMeasuredRef, + terminalPaneViewportsRef, + getTerminalPaneViewport, + splitTerminalHandles, + setSplitTerminalHandles, + visibleTerminalHandles, + visibleTerminalHandlesRef, terminalRefs, liveInputRef, commandInputRef, diff --git a/mobile/src/session/use-mobile-session-terminal-stream-display.ts b/mobile/src/session/use-mobile-session-terminal-stream-display.ts index 32c9016dcfe5..946594d31a76 100644 --- a/mobile/src/session/use-mobile-session-terminal-stream-display.ts +++ b/mobile/src/session/use-mobile-session-terminal-stream-display.ts @@ -13,6 +13,7 @@ export function useMobileSessionTerminalStreamDisplay( terminalModes, deviceTokenRef, viewportRef, + getTerminalPaneViewport, terminalUnsubsRef, subscribingHandlesRef, leaseOnlyHandlesRef, @@ -51,6 +52,7 @@ export function useMobileSessionTerminalStreamDisplay( // Why: 'phone' is an observed state, not a setting; the toggle only requests 'auto' or 'desktop'. const next: 'auto' | 'desktop' = current === 'auto' || current === 'phone' ? 'desktop' : 'auto' + const viewport = getTerminalPaneViewport?.(handle).viewportRef.current ?? viewportRef.current toggleInFlightRef.current.add(handle) try { // The reply is unread: the server resizes and reports it on the existing subscription. @@ -62,7 +64,7 @@ export function useMobileSessionTerminalStreamDisplay( ? { client: { id: deviceTokenRef.current, type: 'mobile' as const } } : {}), // Why: late-bind viewport for terminals subscribed before measurement, or auto toggles no-op on a null stored viewport. - ...(viewportRef.current && next === 'auto' ? { viewport: viewportRef.current } : {}) + ...(viewport && next === 'auto' ? { viewport } : {}) }) } catch { // Mode change failed — server state unchanged, UI stays in sync. diff --git a/mobile/src/session/use-mobile-session-terminal-subscription.test.tsx b/mobile/src/session/use-mobile-session-terminal-subscription.test.tsx index 5bf6aedf0388..195512877184 100644 --- a/mobile/src/session/use-mobile-session-terminal-subscription.test.tsx +++ b/mobile/src/session/use-mobile-session-terminal-subscription.test.tsx @@ -15,6 +15,7 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import type { TerminalWebViewHandle } from '../terminal/terminal-webview-contract' import { MobileTerminalDiagnostics } from './mobile-terminal-diagnostics' +import { terminalPaneViewport, type TerminalPaneViewport } from './mobile-terminal-pane-layout' import { TerminalViewportResubscribeBudget } from './mobile-terminal-viewport-resubscribe' import type { MobileSessionTerminalSubscriptionFoundationModel } from './use-mobile-session-terminal-subscription-foundation' import { useMobileSessionTerminalSubscription } from './use-mobile-session-terminal-subscription' @@ -33,6 +34,7 @@ function subscriptionHarness(opts: { frameWidth?: number viewport?: typeof PHONE synchronousEvents?: unknown[] + split?: boolean }) { let fit = opts.fit const order: string[] = [] @@ -88,6 +90,15 @@ function subscriptionHarness(opts: { viewportResubscribeBudgetRef: { current: new TerminalViewportResubscribeBudget() }, webReadyHandlesRef, activeHandleRef: { current: HANDLE }, + activeHandle: HANDLE, + terminals: [{ handle: HANDLE, title: 'Terminal', isActive: true }], + splitTerminalHandles: null, + setSplitTerminalHandles: vi.fn(), + visibleTerminalHandles: [HANDLE], + visibleTerminalHandlesRef: { current: [HANDLE] }, + showNativeChat: false, + switchTab: vi.fn(), + handleTerminalTap: vi.fn(), subscribeSeqRef, layoutSeqRef: { current: new Map() }, terminalFrameRef, @@ -106,6 +117,7 @@ function subscriptionHarness(opts: { unsubscribeTerminalRef: { current: vi.fn() }, signalTerminalInventoryRecovery: vi.fn(), terminalRefs: { current: new Map([[HANDLE, terminal]]) }, + terminalPaneViewportsRef: { current: new Map() }, pendingSelectionRef: { current: null }, nativeChatStream: { notifyWebReady: vi.fn() }, terminalGestureInputBucketsRef: { current: new Map() }, @@ -119,20 +131,57 @@ function subscriptionHarness(opts: { notifyTerminalFrameHeight: vi.fn(), notifyTerminalFrameWidth: vi.fn() } + const second = { + ...terminal, + write: vi.fn(), + init: vi.fn(), + fitDimensions: vi.fn(() => ({ cols: 30, rows: 20 })) + } + const secondGeometry: TerminalPaneViewport = { + terminalFrameRef: { current: { width: 240, height: 320 } }, + viewportRef: { current: null }, + viewportMeasuredRef: { current: false } + } + fields.terminalPaneViewportsRef.current.set(HANDLE, { + terminalFrameRef: fields.terminalFrameRef, + viewportRef: fields.viewportRef, + viewportMeasuredRef: fields.viewportMeasuredRef + }) + fields.terminalPaneViewportsRef.current.set('term-2', secondGeometry) + if (opts.split) { + fields.terminals.push({ handle: 'term-2', title: 'Second', isActive: false }) + fields.visibleTerminalHandles.push('term-2') + fields.visibleTerminalHandlesRef.current.push('term-2') + fields.webReadyHandlesRef.current.add('term-2') + fields.terminalRefs.current.set('term-2', second) + } + fields.getTerminalRef = (handle: string | null) => + handle === HANDLE ? currentTerminal : handle === 'term-2' && opts.split ? second : undefined fields.unsubscribeTerminalRef.current.mockImplementation(fields.unsubscribeTerminal) let subscribe: ((handle: string) => void) | undefined let webReady: ((handle: string) => void) | undefined + let setRef: ((handle: string, ref: TerminalWebViewHandle | null) => void) | undefined let notifyFrame: ((frame: { width: number; height: number }) => void) | undefined function Probe() { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hook destructures only the fields built above. - const scope = fields as unknown as MobileSessionTerminalSubscriptionFoundationModel + const scope = { + ...fields, + getTerminalPaneViewport: (handle: string) => + terminalPaneViewport(fields.terminalPaneViewportsRef.current, handle) + } as unknown as MobileSessionTerminalSubscriptionFoundationModel subscribe = useMobileSessionTerminalSubscription(scope).subscribeToTerminal - const withSubscribe = { ...fields, subscribeToTerminal: subscribe } + const withSubscribe = { + ...fields, + subscribeToTerminal: subscribe, + getTerminalPaneViewport: (handle: string) => + terminalPaneViewport(fields.terminalPaneViewportsRef.current, handle) + } // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the web-ready handler reads only the fields built above. const webviewScope = withSubscribe as unknown as MobileSessionTabSwitchingModel const webview = useMobileSessionTerminalWebview(webviewScope) webReady = webview.handleTerminalWebReady - notifyFrame = webview.notifyTerminalFrame + setRef = webview.setTerminalWebViewRef + notifyFrame = (frame) => webview.notifyTerminalPaneFrame(HANDLE, frame) return null } act(() => { @@ -146,6 +195,8 @@ function subscriptionHarness(opts: { order, stopStream, subscribe: () => act(() => subscribe!(HANDLE)), + subscribeHandle: (handle: string) => act(() => subscribe!(handle)), + second, scrollback, terminal, event: (index: number, data: unknown) => act(() => handlers[index](data)), @@ -153,6 +204,12 @@ function subscriptionHarness(opts: { currentTerminal = next fields.terminalRefs.current.set(HANDLE, next) }, + replaceImperativeHandle: () => + act(() => { + setRef!(HANDLE, null) + currentTerminal = { ...terminal } + setRef!(HANDLE, currentTerminal) + }), // The document's web-ready, carrying the box xterm laid out. documentReady: () => { act(() => webReady!(HANDLE)) @@ -235,9 +292,7 @@ describe('a terminal first subscribe', () => { harness.layOutFrame(360.5, 700) expect(harness.terminalFrameRef.current).toEqual({ width: 360.5, height: 700 }) expect(notifyTerminalFrameWidth).toHaveBeenCalledTimes(1) - expect(notifyTerminalFrameHeight.mock.calls.map(([height]) => height)).toEqual([ - 0, 751, 700, 0, 700 - ]) + expect(notifyTerminalFrameHeight.mock.calls.map(([height]) => height)).toEqual([751, 700, 700]) }) it('goes without dims when no cell box was reported, and the fit pass resubscribes once', async () => { @@ -466,3 +521,52 @@ describe('foreground snapshots preserve the terminal reading position', () => { } ) }) + +describe('two visible terminal subscriptions', () => { + it('retains a split pane frame when a mounted document replaces its imperative handle', () => { + const harness = subscriptionHarness({ fit: PHONE, webReady: true, split: true }) + harness.fields.unsubscribeTerminal(HANDLE) + vi.mocked(harness.terminal.fitDimensions).mockImplementation((frame) => ({ + cols: Math.floor(frame.width / 8), + rows: Math.floor(frame.height / 16) + })) + harness.layOutFrame(376, 224) + harness.fields.unsubscribeTerminal(HANDLE) + const priorSubscriptions = harness.fields.client.subscribe.mock.calls.length + harness.replaceImperativeHandle() + harness.subscribe() + expect(harness.fields.client.subscribe).toHaveBeenCalledTimes(priorSubscriptions + 1) + expect(harness.fields.client.subscribe.mock.calls.at(-1)?.[1]).toMatchObject({ + terminal: HANDLE, + viewport: { cols: 47, rows: 14 } + }) + expect( + harness.fields.terminalPaneViewportsRef.current.get(HANDLE)?.terminalFrameRef.current + ).toEqual({ width: 376, height: 224 }) + }) + + it('subscribes and renders both streams with their own measured grids', () => { + const harness = subscriptionHarness({ fit: PHONE, webReady: true, split: true }) + harness.subscribe() + harness.subscribeHandle('term-2') + const requests = harness.fields.client.subscribe.mock.calls + expect(requests.map((call) => [call[1].terminal, call[1].viewport])).toEqual([ + [HANDLE, PHONE], + ['term-2', { cols: 30, rows: 20 }] + ]) + harness.scrollback(0, PHONE.cols, PHONE.rows) + harness.scrollback(1, 30, 20) + harness.event(0, { type: 'data', chunk: 'first' }) + harness.event(1, { type: 'data', chunk: 'second' }) + expect(harness.terminal.write).toHaveBeenCalledWith('first') + expect(harness.terminal.write).not.toHaveBeenCalledWith('second') + expect(harness.second.write).toHaveBeenCalledWith('second') + expect(harness.second.init).toHaveBeenCalledWith( + expect.objectContaining({ cols: 30, rows: 20, frame: { width: 240, height: 320 } }) + ) + harness.fields.activeHandleRef.current = 'term-2' + harness.event(0, { type: 'data', chunk: 'still live' }) + expect(harness.terminal.write).toHaveBeenCalledWith('still live') + expect(harness.fields.terminalUnsubsRef.current.size).toBe(2) + }) +}) diff --git a/mobile/src/session/use-mobile-session-terminal-subscription.ts b/mobile/src/session/use-mobile-session-terminal-subscription.ts index 9a1233a52352..4661a83fe7fc 100644 --- a/mobile/src/session/use-mobile-session-terminal-subscription.ts +++ b/mobile/src/session/use-mobile-session-terminal-subscription.ts @@ -25,8 +25,7 @@ export function useMobileSessionTerminalSubscription( clientId, setTerminalModes, terminalCwdRef, - viewportRef, - viewportMeasuredRef, + getTerminalPaneViewport, terminalUnsubsRef, subscribingHandlesRef, leaseOnlyHandlesRef, @@ -37,7 +36,6 @@ export function useMobileSessionTerminalSubscription( activeHandleRef, subscribeSeqRef, layoutSeqRef, - terminalFrameRef, scheduleDelayedAction, showToast, markNativeChatInputLeaseReady, @@ -49,6 +47,8 @@ export function useMobileSessionTerminalSubscription( } = scope const subscribeToTerminal = useCallback( (handle: string) => { + const { viewportRef, viewportMeasuredRef, terminalFrameRef } = + getTerminalPaneViewport?.(handle) ?? scope const diagnostics = terminalDiagnosticsRef.current const logSkippedGate = (reason: string) => diagnostics.streamSkipped(handle, reason, handle === activeHandleRef.current) diff --git a/mobile/src/session/use-mobile-session-terminal-webview.ts b/mobile/src/session/use-mobile-session-terminal-webview.ts index 8eb3451ece31..913e5318d96b 100644 --- a/mobile/src/session/use-mobile-session-terminal-webview.ts +++ b/mobile/src/session/use-mobile-session-terminal-webview.ts @@ -1,5 +1,5 @@ -import { pendingSelectionHandle, pendingSelectionWantsHandle } from './pending-session-selection' -import { useEffect, useCallback } from 'react' +import { pendingSelectionWantsHandle } from './pending-session-selection' +import { useEffect, useCallback, useRef } from 'react' import type { TerminalWebViewHandle } from '../terminal/terminal-webview-contract' import type { TerminalFrame } from '../terminal/terminal-webview-messages' import type { MobileSessionTabSwitchingModel } from './use-mobile-session-tab-switching' @@ -17,6 +17,17 @@ export function useMobileSessionTerminalWebview(scope: MobileSessionTabSwitching terminalDiagnosticsRef, webReadyHandlesRef, activeHandleRef, + activeHandle, + terminals, + setSplitTerminalHandles, + visibleTerminalHandles, + visibleTerminalHandlesRef, + getTerminalPaneViewport, + terminalPaneViewportsRef, + connState, + showNativeChat, + switchTab, + handleTerminalTap: focusTerminalTap, pendingSelectionRef, activeSessionTab, unsubscribeTerminal, @@ -45,6 +56,16 @@ export function useMobileSessionTerminalWebview(scope: MobileSessionTabSwitching } }, []) + useEffect(() => { + // Imperative handles change without layout events; inventory removal owns geometry cleanup. + const liveHandles = new Set(terminals.map((terminal) => terminal.handle)) + for (const handle of terminalPaneViewportsRef.current.keys()) { + if (!liveHandles.has(handle)) { + terminalPaneViewportsRef.current.delete(handle) + } + } + }, [terminals, terminalPaneViewportsRef]) + const handleTerminalWebReady = useCallback( (handle: string) => { const wasAlreadyReady = webReadyHandlesRef.current.has(handle) @@ -58,14 +79,14 @@ export function useMobileSessionTerminalWebview(scope: MobileSessionTabSwitching if (wasAlreadyReady && initializedHandlesRef.current.has(handle)) { // Why: WebView reloaded (hot reload / Android churn); old xterm buffer is gone, so resubscribe for a fresh scrollback. unsubscribeTerminal(handle) - if (handle === activeHandleRef.current) { + if (visibleTerminalHandlesRef.current.includes(handle)) { subscribeToTerminal(handle) } return } // Why: a just-created tab can lose activeHandleRef to a lagging snapshot; honor the pending marker so its web-ready subscribe still fires. const isIntendedActive = - handle === activeHandleRef.current || + visibleTerminalHandlesRef.current.includes(handle) || pendingSelectionWantsHandle(pendingSelectionRef.current, handle) // Why: web-ready carried the cell box xterm laid out, so subscribeToTerminal sizes this subscribe. if (isIntendedActive && !terminalUnsubsRef.current.has(handle)) { @@ -75,39 +96,113 @@ export function useMobileSessionTerminalWebview(scope: MobileSessionTabSwitching [nativeChatStream, subscribeToTerminal, unsubscribeTerminal] ) - const subscribeIntendedActiveTerminal = useCallback(() => { - const handle = pendingSelectionHandle(pendingSelectionRef.current) ?? activeHandleRef.current - if (handle && !terminalUnsubsRef.current.has(handle)) { - subscribeToTerminal(handle) - } - }, [activeHandleRef, pendingSelectionRef, subscribeToTerminal, terminalUnsubsRef]) - - /** The terminal frame React Native laid out: kept in the one frame ref, then what it changed. */ const notifyTerminalFrame = useCallback( (frame: TerminalFrame) => { - // Why: notify height imperatively so dock settling re-fits the PTY without rerendering SessionScreen. - notifyTerminalFrameHeight(Math.round(frame.height)) - // Why: the page reports a hidden frame as 0x0; it keeps the box it was laid out at. - if (frame.width <= 0) { + terminalFrameRef.current = frame + }, + [terminalFrameRef] + ) + + const notifyTerminalPaneFrame = useCallback( + (handle: string, frame: TerminalFrame) => { + if (frame.width <= 0 || frame.height <= 0) { return } - const previous = terminalFrameRef.current - terminalFrameRef.current = frame - if (!previous) { - // Why: a ready document held back for its frame subscribes on the first layout. - subscribeIntendedActiveTerminal() - } else if (frame.width !== previous.width) { - notifyTerminalFrameWidth() + const state = getTerminalPaneViewport(handle) + const previous = state.terminalFrameRef.current + state.terminalFrameRef.current = frame + if (!previous || previous.width !== frame.width || previous.height !== frame.height) { + state.viewportMeasuredRef.current = false + if (visibleTerminalHandlesRef.current.includes(handle)) { + if (!terminalUnsubsRef.current.has(handle)) { + subscribeToTerminal(handle) + } + notifyTerminalFrameHeight(Math.round(frame.height)) + if (previous && previous.width !== frame.width) { + notifyTerminalFrameWidth() + } + } } }, [ + getTerminalPaneViewport, notifyTerminalFrameHeight, notifyTerminalFrameWidth, - subscribeIntendedActiveTerminal, - terminalFrameRef + subscribeToTerminal ] ) + const canSplitTerminals = + !!activeHandle && + terminals.some((terminal) => terminal.handle !== activeHandle) && + !showNativeChat + const terminalSplitActive = !showNativeChat && visibleTerminalHandles.length === 2 + const toggleTerminalSplit = useCallback(() => { + if (terminalSplitActive) { + setSplitTerminalHandles(null) + return + } + const companion = terminals.find((terminal) => terminal.handle !== activeHandle) + if (activeHandle && companion) { + setSplitTerminalHandles([activeHandle, companion.handle]) + } + }, [activeHandle, terminalSplitActive, setSplitTerminalHandles, terminals]) + + const focusFrameRef = useRef | null>(null) + const handleTerminalInteraction = useCallback( + (handle: string) => { + if (!visibleTerminalHandlesRef.current.includes(handle)) { + return + } + if (focusFrameRef.current !== null) { + cancelAnimationFrame(focusFrameRef.current) + focusFrameRef.current = null + } + if (activeHandleRef.current !== handle) { + switchTab(handle) + } + }, + [switchTab] + ) + const handleTerminalTap = useCallback( + (handle: string) => { + if (!visibleTerminalHandlesRef.current.includes(handle)) { + return + } + handleTerminalInteraction(handle) + focusFrameRef.current = requestAnimationFrame(() => { + focusFrameRef.current = null + if (activeHandleRef.current === handle) { + focusTerminalTap(handle) + } + }) + }, + [focusTerminalTap, handleTerminalInteraction] + ) + useEffect( + () => () => { + if (focusFrameRef.current !== null) { + cancelAnimationFrame(focusFrameRef.current) + } + }, + [] + ) + + const visibleKey = visibleTerminalHandles.join('\0') + useEffect(() => { + const visible = visibleTerminalHandlesRef.current + for (const handle of terminalUnsubsRef.current.keys()) { + if (!visible.includes(handle)) { + unsubscribeTerminal(handle) + } + } + if (connState === 'connected') { + for (const handle of visible) { + subscribeToTerminal(handle) + } + } + }, [visibleKey, connState, subscribeToTerminal, unsubscribeTerminal]) + useEffect(() => { if (activeSessionTab?.type !== 'markdown') { return @@ -130,7 +225,13 @@ export function useMobileSessionTerminalWebview(scope: MobileSessionTabSwitching return { setTerminalWebViewRef, handleTerminalWebReady, - notifyTerminalFrame + notifyTerminalFrame, + notifyTerminalPaneFrame, + canSplitTerminals, + terminalSplitActive, + toggleTerminalSplit, + handleTerminalInteraction, + handleTerminalTap } } diff --git a/mobile/src/session/use-terminal-split-layout.test.tsx b/mobile/src/session/use-terminal-split-layout.test.tsx new file mode 100644 index 000000000000..da2f295ed41b --- /dev/null +++ b/mobile/src/session/use-terminal-split-layout.test.tsx @@ -0,0 +1,45 @@ +import { createElement } from 'react' +import { act, create } from 'react-test-renderer' +import { expect, it, vi } from 'vitest' +import { Alert } from 'react-native' +import { useTerminalSplitLayout } from './use-terminal-split-layout' +import { loadTerminalSplitLayout, saveTerminalSplitLayout } from '../storage/preferences' + +vi.mock('react-native', () => ({ Alert: { alert: vi.fn() } })) +vi.mock('../storage/preferences', () => ({ + loadTerminalSplitLayout: vi.fn(), + saveTerminalSplitLayout: vi.fn().mockResolvedValue(undefined) +})) + +it('keeps a user choice made before storage hydration and reports failed persistence', async () => { + let resolveRead!: (layout: 'stacked') => void + vi.mocked(loadTerminalSplitLayout).mockReturnValue( + new Promise((resolve) => { + resolveRead = resolve + }) + ) + let preference!: ReturnType + function Harness() { + preference = useTerminalSplitLayout() + return null + } + let tree!: ReturnType + act(() => { + tree = create(createElement(Harness)) + }) + try { + expect(preference.terminalSplitLayout).toBe('auto') + await act(async () => preference.setTerminalSplitLayout('side-by-side')) + await act(async () => resolveRead('stacked')) + expect(preference.terminalSplitLayout).toBe('side-by-side') + vi.mocked(saveTerminalSplitLayout).mockRejectedValueOnce(new Error('storage unavailable')) + await act(async () => preference.setTerminalSplitLayout('stacked')) + expect(preference.terminalSplitLayout).toBe('stacked') + expect(Alert.alert).toHaveBeenCalledWith( + 'Layout could not be saved', + expect.stringContaining('retry') + ) + } finally { + act(() => tree.unmount()) + } +}) diff --git a/mobile/src/session/use-terminal-split-layout.ts b/mobile/src/session/use-terminal-split-layout.ts new file mode 100644 index 000000000000..2287555917d7 --- /dev/null +++ b/mobile/src/session/use-terminal-split-layout.ts @@ -0,0 +1,37 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { Alert } from 'react-native' +import { + loadTerminalSplitLayout, + saveTerminalSplitLayout, + type TerminalSplitLayout +} from '../storage/preferences' + +export function useTerminalSplitLayout() { + const [terminalSplitLayout, setLayout] = useState('auto') + const edited = useRef(false) + useEffect(() => { + let active = true + void loadTerminalSplitLayout().then( + (layout) => { + if (active && !edited.current) { + setLayout(layout) + } + }, + (error: unknown) => console.warn('Terminal split layout could not be loaded', error) + ) + return () => { + active = false + } + }, []) + const setTerminalSplitLayout = useCallback((layout: TerminalSplitLayout) => { + edited.current = true + setLayout(layout) + void saveTerminalSplitLayout(layout).catch(() => { + Alert.alert( + 'Layout could not be saved', + 'This layout applies for now. Choose it again to retry saving.' + ) + }) + }, []) + return { terminalSplitLayout, setTerminalSplitLayout } +} diff --git a/mobile/src/storage/preferences.ts b/mobile/src/storage/preferences.ts index 93a4926c1752..8ee926e34637 100644 --- a/mobile/src/storage/preferences.ts +++ b/mobile/src/storage/preferences.ts @@ -285,3 +285,23 @@ export async function savePinnedIds(hostId: string, ids: Set): Promise = Promise.resolve() + +export async function loadTerminalSplitLayout(): Promise { + await terminalSplitLayoutWrite + const raw = await AsyncStorage.getItem(TERMINAL_SPLIT_LAYOUT_KEY) + return raw === 'side-by-side' || raw === 'stacked' ? raw : 'auto' +} + +export function saveTerminalSplitLayout(layout: TerminalSplitLayout): Promise { + const write = terminalSplitLayoutWrite.then(() => + persistMirrored(TERMINAL_SPLIT_LAYOUT_KEY, layout) + ) + terminalSplitLayoutWrite = write.catch((error: unknown) => { + console.warn('Terminal split layout could not be saved', error) + }) + return write +} diff --git a/mobile/src/terminal/document/mouse-click-drag.ts b/mobile/src/terminal/document/mouse-click-drag.ts index 53415f966efb..ea8592f97ccb 100644 --- a/mobile/src/terminal/document/mouse-click-drag.ts +++ b/mobile/src/terminal/document/mouse-click-drag.ts @@ -144,6 +144,7 @@ export function attachSurfaceMouseClickDragHandler( if (dispatcherShouldBlockSurface(scope) || !scope.term) { return } + notify(scope, { type: 'terminal-interaction' }) // Why: a pointerup lost outside the WebView must not leave the previous // gesture latched (tracking press with no release) when the next one lands. if (scope.mouseGesture) { diff --git a/mobile/src/terminal/document/surface-touch-gestures.ts b/mobile/src/terminal/document/surface-touch-gestures.ts index 2aa13228bed5..af210dc0f893 100644 --- a/mobile/src/terminal/document/surface-touch-gestures.ts +++ b/mobile/src/terminal/document/surface-touch-gestures.ts @@ -106,6 +106,7 @@ export function attachSurfaceEventHandlers( if (targetSurface !== scope.surface || dispatcherShouldBlockSurface(scope)) { return } + notify(scope, { type: 'terminal-interaction' }) if (scope.touchGesture.momentumId) { cancelAnimationFrame(scope.touchGesture.momentumId) scope.touchGesture.momentumId = null diff --git a/mobile/src/terminal/document/wheel-scroll.ts b/mobile/src/terminal/document/wheel-scroll.ts index 1674d7750534..45a7346ef394 100644 --- a/mobile/src/terminal/document/wheel-scroll.ts +++ b/mobile/src/terminal/document/wheel-scroll.ts @@ -1,4 +1,5 @@ import { getCellHeight, getTotalScale } from './cell-metrics' +import { notify } from './host-notify' import { routeScrollLines, shouldRouteScrollToTerminalInput } from './mouse-input-encoding' import { dispatcherShouldBlockSurface } from './tap-dispatch' import { @@ -7,6 +8,8 @@ import { } from './normal-buffer-smooth-scroll' import type { TerminalDocumentScope } from './document-scope' +const WHEEL_SEQUENCE_IDLE_MS = 150 + export function wheelEventPixelDeltaY(scope: TerminalDocumentScope, e: WheelEvent) { const delta = e.deltaY if (typeof delta !== 'number' || !Number.isFinite(delta) || delta === 0) { @@ -27,6 +30,7 @@ export function attachSurfaceWheelHandler( scope: TerminalDocumentScope, targetSurface: HTMLElement ) { + let lastWheelAt: number | null = null targetSurface.addEventListener( 'wheel', function (e) { @@ -53,6 +57,12 @@ export function attachSurfaceWheelHandler( return } + const now = performance.now() + if (lastWheelAt === null || now - lastWheelAt > WHEEL_SEQUENCE_IDLE_MS) { + scope.wheelAccumDeltaY = 0 + notify(scope, { type: 'terminal-interaction' }) + } + lastWheelAt = now if (shouldRouteScrollToTerminalInput(scope)) { resetSmoothScrollOffset(scope) const effectiveCellH = getCellHeight(scope) * getTotalScale(scope) diff --git a/mobile/src/terminal/terminal-cell-box-refit.test.tsx b/mobile/src/terminal/terminal-cell-box-refit.test.tsx index 3688f8781297..4d01d33edc47 100644 --- a/mobile/src/terminal/terminal-cell-box-refit.test.tsx +++ b/mobile/src/terminal/terminal-cell-box-refit.test.tsx @@ -1,3 +1,7 @@ +import { + terminalPaneViewport, + type TerminalPaneViewport +} from '../session/mobile-terminal-pane-layout' import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -13,7 +17,7 @@ vi.mock('react-native', () => ({ const HANDLE = 'term-1' /** The session's refit over one open terminal whose document reported a `cellWidth` box. */ -function refitHarness(cellWidth: number) { +function refitHarness(cellWidth: number, split = false) { const terminal: TerminalWebViewHandle = { prepareForForegroundRecovery: vi.fn(), write: vi.fn(), @@ -37,11 +41,30 @@ function refitHarness(cellWidth: number) { const terminalFrameRef: { current: { width: number; height: number } | null } = { current: { width: 427, height: 710 } } + const terminalPaneViewportsRef = { current: new Map() } + const firstGeometry = terminalPaneViewport(terminalPaneViewportsRef.current, HANDLE) + firstGeometry.terminalFrameRef.current = { width: 300, height: 350 } + const secondGeometry = terminalPaneViewport(terminalPaneViewportsRef.current, 'term-2') + secondGeometry.terminalFrameRef.current = { width: 250, height: 350 } + const second: TerminalWebViewHandle = { + ...terminal, + fitDimensions: vi.fn((frame) => ({ + cols: Math.floor(frame.width / 10), + rows: Math.floor(frame.height / 20) + })) + } + const visibleTerminalHandlesRef = { current: [HANDLE, 'term-2'] } let refit: ReturnType | undefined function Probe() { refit = useTerminalViewportRefit({ activeHandleRef: { current: HANDLE }, - terminalRefs: { current: new Map([[HANDLE, terminal]]) }, + terminalRefs: { + current: new Map([ + [HANDLE, terminal], + ['term-2', second] + ]) + }, + ...(split ? { terminalPaneViewportsRef, visibleTerminalHandlesRef } : {}), terminalFrameRef, viewportRef, viewportMeasuredRef: { current: true }, @@ -61,6 +84,10 @@ function refitHarness(cellWidth: number) { }) return { terminal, + second, + firstGeometry, + secondGeometry, + visibleTerminalHandlesRef, viewportRef, subscribeToTerminal, report: (handle: string) => act(() => refit!.notifyTerminalCellBoxChange(handle)), @@ -125,3 +152,24 @@ describe('a new cell box for the open terminal', () => { expect(harness.viewportRef.current).toEqual({ cols: 54, rows: 47 }) }) }) + +describe('visible split viewport refits', () => { + it('refits both panes independently using legacy resubscribe and ignores hidden panes', async () => { + const harness = refitHarness(10, true) + harness.report('term-2') + await act(async () => { + await vi.advanceTimersByTimeAsync(150) + }) + expect(harness.firstGeometry.viewportRef.current).toEqual({ cols: 30, rows: 47 }) + expect(harness.secondGeometry.viewportRef.current).toEqual({ cols: 25, rows: 17 }) + expect(harness.subscribeToTerminal.mock.calls).toEqual([[HANDLE], ['term-2']]) + harness.subscribeToTerminal.mockClear() + harness.visibleTerminalHandlesRef.current = [HANDLE] + harness.secondGeometry.terminalFrameRef.current = { width: 500, height: 700 } + harness.report('term-2') + await act(async () => { + await vi.advanceTimersByTimeAsync(150) + }) + expect(harness.subscribeToTerminal).not.toHaveBeenCalled() + }) +}) diff --git a/mobile/src/terminal/terminal-foreground-recovery.test.ts b/mobile/src/terminal/terminal-foreground-recovery.test.ts index 50fcda6ec52d..bf4ec32e0235 100644 --- a/mobile/src/terminal/terminal-foreground-recovery.test.ts +++ b/mobile/src/terminal/terminal-foreground-recovery.test.ts @@ -129,3 +129,23 @@ describe('terminal foreground recovery', () => { expect(harness.subscribeToTerminal).not.toHaveBeenCalled() }) }) + +describe('split terminal foreground recovery', () => { + it('replays both visible panes but does not revive a pane closed during the delay', () => { + const harness = createHarness() + harness.terminalRefs.current.set('term-2', harness.terminalRefs.current.get('term-1')!) + harness.initializedHandlesRef.current.add('term-2') + const visibleTerminalHandlesRef = { current: ['term-1', 'term-2'] } + recoverActiveTerminalAfterForeground({ ...harness, visibleTerminalHandlesRef }) + expect(harness.unsubscribeTerminal.mock.calls).toEqual([['term-1'], ['term-2']]) + harness.activeHandleRef.current = 'term-2' + harness.runScheduled() + expect(harness.subscribeToTerminal.mock.calls).toEqual([['term-1'], ['term-2']]) + harness.initializedHandlesRef.current = new Set(['term-1', 'term-2']) + harness.subscribeToTerminal.mockClear() + recoverActiveTerminalAfterForeground({ ...harness, visibleTerminalHandlesRef }) + visibleTerminalHandlesRef.current = ['term-2'] + harness.runScheduled() + expect(harness.subscribeToTerminal.mock.calls).toEqual([['term-2']]) + }) +}) diff --git a/mobile/src/terminal/terminal-foreground-recovery.ts b/mobile/src/terminal/terminal-foreground-recovery.ts index 7abfe48b8c98..748f820bec9b 100644 --- a/mobile/src/terminal/terminal-foreground-recovery.ts +++ b/mobile/src/terminal/terminal-foreground-recovery.ts @@ -11,6 +11,7 @@ export type TerminalForegroundRecoveryOutcome = 'recovered' | 'deferred' | 'skip type TerminalForegroundRecoveryOptions = { activeHandleRef: RefObject + visibleTerminalHandlesRef?: RefObject terminalRefs: RefObject> initializedHandlesRef: RefObject> connStateRef: RefObject @@ -34,6 +35,7 @@ export function shouldRecoverTerminalOnAppStateChange( export function recoverActiveTerminalAfterForeground({ activeHandleRef, + visibleTerminalHandlesRef, terminalRefs, initializedHandlesRef, connStateRef, @@ -51,9 +53,9 @@ export function recoverActiveTerminalAfterForeground({ if (initializedMountedHandles.length === 0) { return 'skipped' } - const handle = activeHandleRef.current - const shouldRecoverActive = - !!handle && terminalRefs.current.has(handle) && initializedHandlesRef.current.has(handle) + const visible = + visibleTerminalHandlesRef?.current ?? (activeHandleRef.current ? [activeHandleRef.current] : []) + const recovering = visible.filter((handle) => initializedMountedHandles.includes(handle)) // Why: inactive terminal WebViews stay mounted with opacity:0; iOS can blank // those backing stores too, so their next activation must accept scrollback. @@ -61,19 +63,19 @@ export function recoverActiveTerminalAfterForeground({ initializedHandlesRef.current.delete(initializedHandle) } - if (!shouldRecoverActive || !handle) { - return 'recovered' + for (const handle of recovering) { + unsubscribeTerminal(handle) + schedule(() => { + if (connStateRef.current !== 'connected') { + return + } + const stillVisible = visibleTerminalHandlesRef + ? visibleTerminalHandlesRef.current.includes(handle) + : activeHandleRef.current === handle + if (stillVisible && terminalRefs.current.has(handle)) { + subscribeToTerminal(handle) + } + }, delayMs) } - - unsubscribeTerminal(handle) - schedule(() => { - if (connStateRef.current !== 'connected') { - return - } - if (activeHandleRef.current !== handle || !terminalRefs.current.has(handle)) { - return - } - subscribeToTerminal(handle) - }, delayMs) return 'recovered' } diff --git a/mobile/src/terminal/terminal-viewport-refit-options.ts b/mobile/src/terminal/terminal-viewport-refit-options.ts new file mode 100644 index 000000000000..f11e3fa7aa8a --- /dev/null +++ b/mobile/src/terminal/terminal-viewport-refit-options.ts @@ -0,0 +1,28 @@ +import type { RefObject } from 'react' +import type { RpcClient } from '../transport/rpc-client' +import type { ConnectionState } from '../transport/types' +import type { TerminalWebViewHandle } from './TerminalWebView' +import type { TerminalFrame } from './terminal-webview-messages' +import type { TerminalViewportDims } from './terminal-viewport-refit' +import type { TerminalPaneViewport } from '../session/mobile-terminal-pane-layout' + +export type TerminalViewportRefitOptions = { + activeHandleRef: RefObject + visibleTerminalHandlesRef?: RefObject + terminalPaneViewportsRef?: RefObject> + terminalRefs: RefObject> + // The terminal frame React Native laid out, unrounded; null until its first layout. + terminalFrameRef: RefObject + viewportRef: RefObject + viewportMeasuredRef: RefObject + // Why: while native chat covers the active terminal, a refit would push phone dims into a PTY nobody on this device is viewing. + nativeChatCoveredRef: RefObject + clientRef: RefObject + deviceTokenRef: RefObject + connState: ConnectionState + tabStripVisible: boolean + // Why: text size (font scale); changing it changes cell size, so the PTY must be re-fitted to a new column count. + textScale: number + unsubscribeTerminal: (handle: string) => void + subscribeToTerminal: (handle: string) => void +} diff --git a/mobile/src/terminal/terminal-viewport-refit.ts b/mobile/src/terminal/terminal-viewport-refit.ts index 3272834d712e..f95c2ffe90ae 100644 --- a/mobile/src/terminal/terminal-viewport-refit.ts +++ b/mobile/src/terminal/terminal-viewport-refit.ts @@ -1,9 +1,7 @@ -import { useCallback, useEffect, useRef, type RefObject } from 'react' +import type { TerminalViewportRefitOptions } from './terminal-viewport-refit-options' +import { terminalPaneViewport } from '../session/mobile-terminal-pane-layout' +import { useCallback, useEffect, useRef } from 'react' import { AppState, Platform, useWindowDimensions, type AppStateStatus } from 'react-native' -import type { RpcClient } from '../transport/rpc-client' -import type { ConnectionState } from '../transport/types' -import type { TerminalWebViewHandle } from './TerminalWebView' -import type { TerminalFrame } from './terminal-webview-messages' import { shouldRecoverTerminalOnAppStateChange } from './terminal-foreground-recovery' import { terminalViewportUpdate } from './mobile-terminal-operations' import { @@ -17,29 +15,12 @@ import { export type TerminalViewportDims = { cols: number; rows: number } -type TerminalViewportRefitOptions = { - activeHandleRef: RefObject - terminalRefs: RefObject> - // The terminal frame React Native laid out, unrounded; null until its first layout. - terminalFrameRef: RefObject - viewportRef: RefObject - viewportMeasuredRef: RefObject - // Why: while native chat covers the active terminal, a refit would push phone dims into a PTY nobody on this device is viewing. - nativeChatCoveredRef: RefObject - clientRef: RefObject - deviceTokenRef: RefObject - connState: ConnectionState - tabStripVisible: boolean - // Why: text size (font scale); changing it changes cell size, so the PTY must be re-fitted to a new column count. - textScale: number - unsubscribeTerminal: (handle: string) => void - subscribeToTerminal: (handle: string) => void -} - // Why: re-measure on layout changes outside the subscribe path (tab strip, fold/rotate/resize), or a PTY renders "cut in half" (#4579). export function useTerminalViewportRefit(options: TerminalViewportRefitOptions) { const { activeHandleRef, + visibleTerminalHandlesRef, + terminalPaneViewportsRef, terminalRefs, terminalFrameRef, viewportRef, @@ -54,6 +35,12 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions) subscribeToTerminal } = options + const invalidateViewports = useCallback(() => { + viewportMeasuredRef.current = false + terminalPaneViewportsRef?.current.forEach((state) => { + state.viewportMeasuredRef.current = false + }) + }, [viewportMeasuredRef, terminalPaneViewportsRef]) const refitTimerRef = useRef | null>(null) const refitRunSeqRef = useRef(0) const forceNextRefitRef = useRef(false) @@ -67,11 +54,11 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions) // Why: marks the armed timer as a height refit so its callback re-checks the keyboard; other refits always run unguarded. const heightOriginatedRefitRef = useRef(false) const scheduleViewportRefit = useCallback( - (options?: { heightOriginated?: boolean }) => { + (trigger?: { heightOriginated?: boolean }) => { if (refitTimerRef.current) { clearTimeout(refitTimerRef.current) } - heightOriginatedRefitRef.current = options?.heightOriginated ?? false + heightOriginatedRefitRef.current = trigger?.heightOriginated ?? false refitTimerRef.current = setTimeout(() => { refitTimerRef.current = null // Why: a height refit can fire after the keyboard reopened within the debounce; re-check so we never reflow the PTY mid-keystroke. @@ -87,80 +74,89 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions) } const runSeq = refitRunSeqRef.current + 1 refitRunSeqRef.current = runSeq - const handle = activeHandleRef.current - if (!handle) { - return - } - // Why: the trigger already marked the viewport stale, and the return-to-terminal resubscribe re-measures — refitting now would resize a covered PTY. - if (nativeChatCoveredRef.current) { - return - } - const ref = terminalRefs.current.get(handle) - if (!ref) { - return - } - const isCurrentTarget = () => - isTerminalViewportRefitTargetCurrent({ - activeHandle: activeHandleRef.current, - expectedHandle: handle, - currentRef: terminalRefs.current.get(handle), - expectedRef: ref, - nativeChatCovered: nativeChatCoveredRef.current, - disposed: disposedRef.current, - runSeq, - currentRunSeq: refitRunSeqRef.current - }) - void (async () => { - await ref.awaitReady() - if (!isCurrentTarget()) { - return - } - const frame = terminalFrameRef.current - const dims = frame ? ref.fitDimensions(frame) : null - if (!dims) { + const handles = + visibleTerminalHandlesRef?.current ?? + (activeHandleRef.current ? [activeHandleRef.current] : []) + const forceRefit = forceNextRefitRef.current + forceNextRefitRef.current = false + handles.forEach((handle) => { + const geometry = terminalPaneViewportsRef + ? terminalPaneViewport(terminalPaneViewportsRef.current, handle) + : options + const { terminalFrameRef, viewportRef, viewportMeasuredRef } = geometry + // Why: the trigger already marked the viewport stale, and the return-to-terminal resubscribe re-measures — refitting now would resize a covered PTY. + if (nativeChatCoveredRef.current && handle === activeHandleRef.current) { return } - const forceRefit = forceNextRefitRef.current - forceNextRefitRef.current = false - const prev = viewportRef.current - if (!forceRefit && prev && prev.cols === dims.cols && prev.rows === dims.rows) { + const ref = terminalRefs.current.get(handle) + if (!ref) { return } - viewportRef.current = dims - viewportMeasuredRef.current = true - // Why: prefer in-place updateViewport over resubscribe to keep the mobile subscriber record alive. See docs/mobile-presence-lock.md. - const rpc = clientRef.current - const deviceToken = deviceTokenRef.current - if (rpc && deviceToken && updateViewportCapabilityRef.current !== 'unsupported') { - try { - const reply = await terminalViewportUpdate.request(rpc, { - terminal: handle, - client: { id: deviceToken, type: 'mobile' as const }, - viewport: dims - }) - if (!isCurrentTarget()) { - return - } - updateViewportCapabilityRef.current = resolveTerminalUpdateViewportCapability(reply) - const outcome = terminalViewportUpdate.interpret(reply) - if (outcome?.updated) { - rpc.updateTerminalSubscriptionViewport(handle, dims) - if (outcome.applied) { - // Why: updateViewport re-streams only the visible screen, so local scrollback stays wrapped at the old width — reflow it locally. - ref.reflow(dims.cols, dims.rows, frame) + const isCurrentTarget = () => + isTerminalViewportRefitTargetCurrent({ + activeHandle: visibleTerminalHandlesRef + ? visibleTerminalHandlesRef.current.includes(handle) + ? handle + : null + : activeHandleRef.current, + expectedHandle: handle, + currentRef: terminalRefs.current.get(handle), + expectedRef: ref, + nativeChatCovered: nativeChatCoveredRef.current && handle === activeHandleRef.current, + disposed: disposedRef.current, + runSeq, + currentRunSeq: refitRunSeqRef.current + }) + void (async () => { + await ref.awaitReady() + if (!isCurrentTarget()) { + return + } + const frame = terminalFrameRef.current + const dims = frame ? ref.fitDimensions(frame) : null + if (!dims) { + return + } + const prev = viewportRef.current + if (!forceRefit && prev && prev.cols === dims.cols && prev.rows === dims.rows) { + return + } + viewportRef.current = dims + viewportMeasuredRef.current = true + // Why: prefer in-place updateViewport over resubscribe to keep the mobile subscriber record alive. See docs/mobile-presence-lock.md. + const rpc = clientRef.current + const deviceToken = deviceTokenRef.current + if (rpc && deviceToken && updateViewportCapabilityRef.current !== 'unsupported') { + try { + const reply = await terminalViewportUpdate.request(rpc, { + terminal: handle, + client: { id: deviceToken, type: 'mobile' as const }, + viewport: dims + }) + if (!isCurrentTarget()) { + return + } + updateViewportCapabilityRef.current = resolveTerminalUpdateViewportCapability(reply) + const outcome = terminalViewportUpdate.interpret(reply) + if (outcome?.updated) { + rpc.updateTerminalSubscriptionViewport(handle, dims) + if (outcome.applied) { + // Why: updateViewport re-streams only the visible screen, so local scrollback stays wrapped at the old width — reflow it locally. + ref.reflow(dims.cols, dims.rows, frame) + } + return } - return + } catch { + // Fall through to legacy resubscribe. } - } catch { - // Fall through to legacy resubscribe. } - } - if (!isCurrentTarget()) { - return - } - unsubscribeTerminal(handle) - subscribeToTerminal(handle) - })() + if (!isCurrentTarget()) { + return + } + unsubscribeTerminal(handle) + subscribeToTerminal(handle) + })() + }) }, 150) }, [ @@ -188,7 +184,7 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions) return } prevTabStripVisibleRef.current = tabStripVisible - viewportMeasuredRef.current = false + invalidateViewports() scheduleViewportRefit() }, [tabStripVisible, viewportMeasuredRef, scheduleViewportRefit]) @@ -205,7 +201,7 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions) if (prev.width === windowWidth && frameHeightRefitStateRef.current.keyboardVisible) { return } - viewportMeasuredRef.current = false + invalidateViewports() scheduleViewportRefit() }, [windowWidth, windowHeight, viewportMeasuredRef, scheduleViewportRefit]) @@ -216,21 +212,14 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions) return } prevTextScaleRef.current = textScale - viewportMeasuredRef.current = false + invalidateViewports() scheduleViewportRefit() }, [textScale, viewportMeasuredRef, scheduleViewportRefit]) // Why: panel dock/undock or a sidebar resize changes the width with no window or tab change; a // width that still fits the PTY's grid (sub-pixel layout jitter) needs no refit. const notifyTerminalFrameWidth = useCallback(() => { - const handle = activeHandleRef.current - const frame = terminalFrameRef.current - const fit = handle && frame ? terminalRefs.current.get(handle)?.fitDimensions(frame) : null - const grid = viewportRef.current - if (fit && grid && fit.cols === grid.cols && fit.rows === grid.rows) { - return - } - viewportMeasuredRef.current = false + invalidateViewports() scheduleViewportRefit() }, [ activeHandleRef, @@ -248,7 +237,7 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions) if (!transition.shouldRefit) { return } - viewportMeasuredRef.current = false + invalidateViewports() scheduleViewportRefit({ heightOriginated: true }) }, [viewportMeasuredRef, scheduleViewportRefit] @@ -266,10 +255,14 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions) // Why: a renderer swap or pixel-ratio change gives the same grid a different cell box. const notifyTerminalCellBoxChange = useCallback( (handle: string) => { - if (handle !== activeHandleRef.current) { + if ( + visibleTerminalHandlesRef + ? !visibleTerminalHandlesRef.current.includes(handle) + : handle !== activeHandleRef.current + ) { return } - viewportMeasuredRef.current = false + invalidateViewports() scheduleViewportRefit() }, [activeHandleRef, viewportMeasuredRef, scheduleViewportRefit] @@ -291,7 +284,7 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions) return } // Why: cached grid can match while the host PTY changed in background; reassert equal dims to converge after iOS resume. - viewportMeasuredRef.current = false + invalidateViewports() scheduleForcedViewportRefit() }) return () => sub.remove() @@ -307,7 +300,7 @@ export function useTerminalViewportRefit(options: TerminalViewportRefitOptions) // Why: an in-place desktop upgrade may add updateViewport; reconnect is where the cached method_not_found goes stale. updateViewportCapabilityRef.current = 'unknown' // Why: reconnect can restore a PTY resized while the socket was down, so equal cached dims still need reassertion. - viewportMeasuredRef.current = false + invalidateViewports() scheduleForcedViewportRefit() }, [connState, viewportMeasuredRef, scheduleForcedViewportRefit]) diff --git a/mobile/src/terminal/terminal-webview-contract.ts b/mobile/src/terminal/terminal-webview-contract.ts index fac3ba74150b..331104210c14 100644 --- a/mobile/src/terminal/terminal-webview-contract.ts +++ b/mobile/src/terminal/terminal-webview-contract.ts @@ -80,6 +80,7 @@ export type TerminalSelectionEvents = { // Only a tap's click passes `input`; wheel and drag reports keep the bytes-only call. onTerminalInput?: (bytes: string, input?: TerminalPointerInput) => void onTerminalQueryReply?: (bytes: string) => void + onTerminalInteraction?: () => void onTerminalTap?: () => void // Tap landed on a detected file path; RN resolves + opens it. onFileTap?: (pathText: string, line: number | null, column: number | null) => void diff --git a/mobile/src/terminal/terminal-webview-notification-dispatch.ts b/mobile/src/terminal/terminal-webview-notification-dispatch.ts index fb2bf780c983..ec3acc988278 100644 --- a/mobile/src/terminal/terminal-webview-notification-dispatch.ts +++ b/mobile/src/terminal/terminal-webview-notification-dispatch.ts @@ -59,6 +59,8 @@ export function dispatchTerminalWebViewNotification( handlers.onTerminalInput?.(bytes) } } + } else if (msg.type === 'terminal-interaction') { + handlers.onTerminalInteraction?.() } else if (msg.type === 'terminal-tap') { handlers.onTerminalTap?.() } else if (msg.type === 'terminal-file-tap') { diff --git a/mobile/src/terminal/use-terminal-webview-controller.ts b/mobile/src/terminal/use-terminal-webview-controller.ts index 01887c9cddf3..731327be23c7 100644 --- a/mobile/src/terminal/use-terminal-webview-controller.ts +++ b/mobile/src/terminal/use-terminal-webview-controller.ts @@ -65,6 +65,7 @@ export function useTerminalWebViewController( onHaptic, onTerminalInput, onTerminalQueryReply, + onTerminalInteraction, onTerminalTap, onFileTap, onOpenUrl, @@ -195,6 +196,7 @@ export function useTerminalWebViewController( onKeyboardAvoidanceMetrics, onHaptic, onTerminalInput, + onTerminalInteraction, onTerminalTap, onFileTap, onOpenUrl, @@ -215,6 +217,7 @@ export function useTerminalWebViewController( onHaptic, onTerminalInput, onTerminalQueryReply, + onTerminalInteraction, onTerminalTap, onFileTap, onOpenUrl, diff --git a/mobile/src/transport/mobile-web-bundle-reply-schemas.test.ts b/mobile/src/transport/mobile-web-bundle-reply-schemas.test.ts index 57f5618763ab..b112d7430f8d 100644 --- a/mobile/src/transport/mobile-web-bundle-reply-schemas.test.ts +++ b/mobile/src/transport/mobile-web-bundle-reply-schemas.test.ts @@ -135,6 +135,26 @@ describe('mobile web bundle manifest reply reader', () => { ).toBe(true) }) + it.each([undefined, true, false, 'true', 1, null])( + 'reads cross-layout host ownership %s without upgrading legacy or malformed declarations', + (value) => { + const route = { + pathname: '/h/[hostId]', + grants: ['navigate'], + canOwnHostArea: true, + ...(value === undefined ? {} : { canOwnHostAreaAcrossLayouts: value }) + } + const parsed = MobileWebBundleManifestReadSchema.safeParse( + manifestReply({ routes: [route] }).manifest + ) + expect(parsed.success).toBe(true) + expect(parsed.data?.routes?.[0]?.canOwnHostArea).toBe(true) + expect(parsed.data?.routes?.[0]?.canOwnHostAreaAcrossLayouts).toBe( + typeof value === 'boolean' ? value : undefined + ) + } + ) + it('reads a route pattern with a trailing rest segment, which no field has to change for', () => { // Forward compatibility for a desktop that later ships a catch-all screen: `page-route-policy` // matches such a pattern, and it only ever sees one the reader let through. Pinned on the diff --git a/mobile/src/transport/mobile-web-bundle-reply-schemas.ts b/mobile/src/transport/mobile-web-bundle-reply-schemas.ts index 6944d441db97..a86c26edfcf6 100644 --- a/mobile/src/transport/mobile-web-bundle-reply-schemas.ts +++ b/mobile/src/transport/mobile-web-bundle-reply-schemas.ts @@ -46,7 +46,8 @@ const pageRouteSchema = z.looseObject({ .max(MOBILE_WEB_BUNDLE_MAX_ROUTE_GRANTS) .optional(), // A value this build cannot read is no declaration, never a refused bundle. - canOwnHostArea: z.boolean().optional().catch(undefined) + canOwnHostArea: z.boolean().optional().catch(undefined), + canOwnHostAreaAcrossLayouts: z.boolean().optional().catch(undefined) }) const assetSchema = z.looseObject({ diff --git a/src/shared/mobile-web-bundle/manifest-contract.test.ts b/src/shared/mobile-web-bundle/manifest-contract.test.ts index 089fb9c91491..f2d389a8924a 100644 --- a/src/shared/mobile-web-bundle/manifest-contract.test.ts +++ b/src/shared/mobile-web-bundle/manifest-contract.test.ts @@ -179,6 +179,15 @@ describe('the page routes a manifest declares', () => { expect(withRoutes([{ pathname: '/h', grants: ['browser.screencast'] }])).toBe(false) }) + it('accepts explicit cross-layout host ownership without changing legacy route declarations', () => { + const legacy = { pathname: '/h/[hostId]', grants: ['navigate'], canOwnHostArea: true } + expect(withRoutes([legacy])).toBe(true) + expect(withRoutes([{ ...legacy, canOwnHostAreaAcrossLayouts: true }])).toBe(true) + for (const invalid of [false, 'true', 1, null]) { + expect(withRoutes([{ ...legacy, canOwnHostAreaAcrossLayouts: invalid }])).toBe(false) + } + }) + it('refuses a route carrying a field the contract does not declare', () => { expect(withRoutes([{ pathname: '/h', grants: [], screen: 'x' }])).toBe(false) }) diff --git a/src/shared/mobile-web-bundle/manifest-contract.ts b/src/shared/mobile-web-bundle/manifest-contract.ts index e50e68974d90..4d588b5632d8 100644 --- a/src/shared/mobile-web-bundle/manifest-contract.ts +++ b/src/shared/mobile-web-bundle/manifest-contract.ts @@ -151,7 +151,9 @@ export const MobileWebBundleRouteSchema = z .max(MOBILE_WEB_BUNDLE_MAX_ROUTE_GRANTS) .optional(), /** The page can draw the wide host area, sidebar included, when `init` says it owns it. */ - canOwnHostArea: z.literal(true).optional() + canOwnHostArea: z.literal(true).optional(), + /** This page also renders the narrow host area; legacy ownership remains wide-only. */ + canOwnHostAreaAcrossLayouts: z.literal(true).optional() }) .strict() // The ceiling is over the union, because the union is what a session's granted list is built From f1e64ef830690f0914437ecde16ab49ac010963b Mon Sep 17 00:00:00 2001 From: Takeshi Matsumoto Date: Sun, 25 Oct 2026 05:56:40 +0900 Subject: [PATCH 2/2] fix(mobile): preserve visible pane content and route ownership boundaries --- .../host-area-session.test.ts | 28 +++++ .../src/mobile-web-shell/page-route-policy.ts | 12 +- .../session/MobileSessionActiveContent.tsx | 3 +- mobile/src/session/TerminalPaneView.test.tsx | 103 ++++++++++++++++++ 4 files changed, 139 insertions(+), 7 deletions(-) diff --git a/mobile/src/mobile-web-shell/host-area-session.test.ts b/mobile/src/mobile-web-shell/host-area-session.test.ts index fea6db70a5b5..7e544313eaf7 100644 --- a/mobile/src/mobile-web-shell/host-area-session.test.ts +++ b/mobile/src/mobile-web-shell/host-area-session.test.ts @@ -117,6 +117,34 @@ describe('the page declaring it can own the host area', () => { expect(routeViewOf(flagOnly, HOST_ROUTE, false).ownsHostArea).toBe(false) expect(routeViewOf(flagOnly, HOST_ROUTE, true).ownsHostArea).toBe(false) }) + + it.each(['/h/[hostId]', '/h/[...page]'])( + 'does not combine ownership declarations from a separate matching %s route', + (acrossLayoutsPattern) => { + const [host, ...details] = desktopRoutes(true) + const routes = [ + host!, + { + pathname: acrossLayoutsPattern, + grants: ['navigate'], + canOwnHostAreaAcrossLayouts: true + }, + ...details + ] + const parsed = MobileWebBundleManifestReadSchema.parse({ + ...MANIFEST_WIRE, + buildId: computeMobileWebBundleId(MANIFEST_WIRE.assets), + routes + }) + expect(routeViewOf(parsed.routes, HOST_ROUTE, false).ownsHostArea).toBe(false) + expect(routeViewOf(parsed.routes, HOST_ROUTE, true).ownsHostArea).toBe(true) + expect( + routeViewOf(parsed.routes, '/h/host-1/session/wt-1', false).pageRouteGrants.map( + (pair) => pair.pathname + ) + ).toContain('/h/[hostId]') + } + ) }) describe('the wide host-area session', () => { diff --git a/mobile/src/mobile-web-shell/page-route-policy.ts b/mobile/src/mobile-web-shell/page-route-policy.ts index 7ca37e987067..633f44d0a203 100644 --- a/mobile/src/mobile-web-shell/page-route-policy.ts +++ b/mobile/src/mobile-web-shell/page-route-policy.ts @@ -205,12 +205,12 @@ export function routeViewOf( } const canOwnHostArea = root !== null && - pageCanOwnHostArea(entries, root) && - (wide || - entries.some( - (route) => - route.canOwnHostAreaAcrossLayouts === true && matchesRoutePattern(root, route.pathname) - )) + entries.some( + (route) => + route.canOwnHostArea === true && + matchesRoutePattern(root, route.pathname) && + (wide || route.canOwnHostAreaAcrossLayouts === true) + ) // New pages keep ownership across rotation; legacy pages require the wide-only contract. const ownsHostArea = canOwnHostArea && pathname === root // No pair for the host route in an owned detail session, so a hop there goes to the shell, which diff --git a/mobile/src/session/MobileSessionActiveContent.tsx b/mobile/src/session/MobileSessionActiveContent.tsx index 3b97e92c50e5..7c135f97b2ca 100644 --- a/mobile/src/session/MobileSessionActiveContent.tsx +++ b/mobile/src/session/MobileSessionActiveContent.tsx @@ -234,7 +234,8 @@ export function MobileSessionActiveContent({ title={terminal.title} onFrame={notifyTerminalPaneFrame} keyboardLift={ - terminal.handle !== activeHandle + terminal.handle !== activeHandle && + !(terminalSplitActive && visibleTerminalHandles.includes(terminal.handle)) ? 0 : terminalSplitActive ? computeActiveTerminalKeyboardLift({ diff --git a/mobile/src/session/TerminalPaneView.test.tsx b/mobile/src/session/TerminalPaneView.test.tsx index 57c1627b173b..6ed37180d3a5 100644 --- a/mobile/src/session/TerminalPaneView.test.tsx +++ b/mobile/src/session/TerminalPaneView.test.tsx @@ -20,13 +20,23 @@ vi.mock('react-native', () => ({ View: hosts.View, Text: hosts.Text, Pressable: hosts.Pressable, + ActivityIndicator: hosts.View, + Animated: { View: hosts.View }, StyleSheet: { create: (value: T) => value, absoluteFillObject: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 } } })) vi.mock('../terminal/TerminalWebView', () => ({ TerminalWebView: hosts.TerminalWebView })) +vi.mock('../storage/preferences', () => ({ saveTerminalTextScale: () => Promise.resolve() })) +vi.mock('../browser/MobileBrowserPane', () => ({ MobileBrowserPane: () => null })) +vi.mock('./MobileNativeChatOverlay', () => ({ MobileNativeChatOverlay: () => null })) +vi.mock('./MobileSessionFileReader', () => ({ FileReader: () => null })) +vi.mock('./MobileSessionMarkdownReader', () => ({ MarkdownReader: () => null })) +vi.mock('./mobile-session-styles', () => ({ styles: {} })) import { TerminalPaneView } from './TerminalPaneView' +import { MobileSessionActiveContent } from './MobileSessionActiveContent' +import { terminalPaneViewport } from './mobile-terminal-pane-layout' type Props = Parameters[0] @@ -81,3 +91,96 @@ it.each([0, 1])( } } ) + +it.each(['stacked', 'side-by-side'] as const)( + 'keeps visible %s terminal content above the keyboard independently of input focus', + (layout) => { + const frame = { width: 900, height: 500 } + const terminalHeight = layout === 'stacked' ? 222 : 472 + const visibleHeight = layout === 'stacked' ? 72 : 172 + const expectedLift = layout === 'stacked' ? 150 : 300 + const geometry = new Map() + for (const handle of ['a', 'b', 'c']) { + terminalPaneViewport(geometry, handle).terminalFrameRef.current = { + width: layout === 'stacked' ? 900 : 450, + height: terminalHeight + } + } + const controller = mountFixture[0]['controller']>( + { + terminals: ['a', 'b', 'c'].map((handle) => ({ handle, title: handle })), + activeHandle: 'a', + terminalSplitActive: true, + terminalSplitLayout: layout, + visibleTerminalHandles: ['a', 'b'], + terminalKeyboardMetrics: new Map([ + ['a', { rows: 10, rowPitch: 5, cursorY: 2, contentBottomRow: 2, altScreen: false }], + [ + 'b', + { + rows: 40, + rowPitch: terminalHeight / 40, + cursorY: 39, + contentBottomRow: 39, + altScreen: true + } + ] + ]), + getTerminalPaneViewport: (handle) => terminalPaneViewport(geometry, handle), + keyboardLift: 0, + activeTerminalKeyboardLift: 0, + notifyTerminalFrame: vi.fn(), + dictation: { isRecording: false }, + nativeChatSendError: { message: null, clear: vi.fn() } + } + ) + let renderer!: ReturnType + const render = (activeHandle: string, keyboardLift: number) => { + const element = createElement(MobileSessionActiveContent, { + controller: { ...controller, activeHandle, keyboardLift } + }) + act(() => { + if (renderer) { + renderer.update(element) + } else { + renderer = create(element) + } + }) + } + const terminalStyle = (handle: string) => { + const pane = renderer.root + .findAllByType(TerminalPaneView) + .find((item) => item.props.handle === handle)! + const terminal = pane.findByType(hosts.TerminalWebView) + return Object.assign({}, ...terminal.props.style.filter(Boolean)) + } + try { + render('a', 0) + act(() => { + renderer.root + .findAllByType(hosts.View)[0] + .props.onLayout({ nativeEvent: { layout: frame } }) + }) + for (const focused of ['a', 'b', 'a']) { + render(focused, 300) + expect(terminalStyle('a').transform).toBeUndefined() + expect(terminalStyle('b').transform).toEqual([{ translateY: -expectedLift }]) + expect(terminalStyle('c').transform).toBeUndefined() + for (const pane of renderer.root.findAllByType(TerminalPaneView).slice(0, 2)) { + const [outer, clip, measured] = pane.findAllByType(hosts.View) + const outerStyle = Object.assign({}, ...outer.props.style.filter(Boolean)) + expect(outerStyle.height - 28).toBe(visibleHeight) + expect(clip.props.style.overflow).toBe('hidden') + expect(measured.props.style.height).toBe(terminalHeight) + } + expect(terminalHeight + terminalStyle('b').transform[0].translateY).toBe(visibleHeight) + } + render('a', 0) + expect(terminalStyle('a').transform).toBeUndefined() + expect(terminalStyle('b').transform).toBeUndefined() + expect(terminalStyle('c').transform).toBeUndefined() + } finally { + act(() => renderer?.unmount()) + } + } +)