feat(mobile): one link setting for chat and terminal links, with Ask each time (#42802)

* feat(mobile): open chat links where the link setting says, with Ask each time

The Browser setting now covers web links in terminal output and chat with
one rule: Ask each time shows the link sheet, Orca browser opens a desktop
tab directly (the phone browser where no tab can open), and Phone browser
opens the phone browser. Nothing saved means Ask each time; saved choices
keep the same storage key.

* perf(mobile): keep the chat link handler stable across reconnects
This commit is contained in:
Kelvin Amoaba
2026-11-15 20:46:41 +00:00
committed by GitHub
parent 28fd7052ad
commit 42419ed7c0
26 changed files with 253 additions and 121 deletions
@@ -1,15 +1,12 @@
import { useState } from 'react'
import { Copy, ExternalLink, Globe } from 'lucide-react-native'
import {
ActionSheetModal,
type ActionSheetAction
} from '../../../../components/sheets/ActionSheetModal'
import { openExternalLink } from '../../../../platform/external-links/external-link'
import { useClipboardWriter } from '../../../../platform/clipboard/clipboard'
import { triggerError, triggerSuccess } from '../../../../platform/haptics/haptics'
import { useMobileTranslation } from '../../../../i18n/use-mobile-translation'
import { ActionSheetModal, type ActionSheetAction } from '../../components/sheets/ActionSheetModal'
import { openExternalLink } from '../../platform/external-links/external-link'
import { useClipboardWriter } from '../../platform/clipboard/clipboard'
import { triggerError, triggerSuccess } from '../../platform/haptics/haptics'
import { useMobileTranslation } from '../../i18n/use-mobile-translation'
// Choices for a tapped chat link: Orca's browser on the host, the phone's browser, or the clipboard.
// Choices for a tapped web link: Orca's browser on the host, the phone's browser, or the clipboard.
export function MobileLinkActionSheet(props: {
url: string
// Called once the sheet has slid away; the URL stays on screen until then.
@@ -0,0 +1,43 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { openExternalLink } from '../../platform/external-links/external-link'
import { openMobileWebLink } from './mobile-web-link-open'
vi.mock('../../platform/external-links/external-link', () => ({ openExternalLink: vi.fn() }))
const url = 'https://example.com/pr/1'
describe('openMobileWebLink', () => {
const openInOrca = vi.fn()
const ask = vi.fn()
beforeEach(() => {
vi.resetAllMocks()
})
it('asks instead of opening anything in ask mode', () => {
openMobileWebLink(url, 'ask', openInOrca, ask)
expect(ask).toHaveBeenCalledWith(url)
expect(openInOrca).not.toHaveBeenCalled()
expect(openExternalLink).not.toHaveBeenCalled()
})
it('opens an Orca browser tab directly when one can open', () => {
openMobileWebLink(url, 'orca-browser', openInOrca, ask)
expect(openInOrca).toHaveBeenCalledWith(url)
expect(openExternalLink).not.toHaveBeenCalled()
expect(ask).not.toHaveBeenCalled()
})
it('falls back to the phone browser where no Orca browser tab can open', () => {
openMobileWebLink(url, 'orca-browser', undefined, ask)
expect(openExternalLink).toHaveBeenCalledWith(url)
expect(ask).not.toHaveBeenCalled()
})
it('opens the phone browser directly in phone-browser mode', () => {
openMobileWebLink(url, 'phone-browser', openInOrca, ask)
expect(openExternalLink).toHaveBeenCalledWith(url)
expect(openInOrca).not.toHaveBeenCalled()
expect(ask).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,21 @@
import { openExternalLink } from '../../platform/external-links/external-link'
import type { MobileLinkOpenMode } from '../../storage/preferences'
/**
* Where a web link tapped in terminal output or chat opens. The phone's browser stands in
* wherever no Orca browser tab can open (see useOpenUrlInOrca).
*/
export function openMobileWebLink(
url: string,
mode: MobileLinkOpenMode,
openInOrca: ((url: string) => void) | undefined,
ask: (url: string) => void
): void {
if (mode === 'ask') {
ask(url)
} else if (mode === 'orca-browser' && openInOrca) {
openInOrca(url)
} else {
openExternalLink(url)
}
}
@@ -1,5 +1,3 @@
import { useCallback } from 'react'
import { openExternalLink } from '../../platform/external-links/external-link'
import { useMobileFileTapHandlers } from './use-mobile-file-tap-handlers'
import { resolveMobileNativeChatSessionId } from '../../session/native-chat/conversation/mobile-native-chat-eligibility'
import { useProvideSessionScreenHandlers } from '../../session/session-screen-handlers'
@@ -11,10 +9,8 @@ export function useMobileSessionFileActions(scope: MobileSessionTerminalSendActi
hostId,
worktreeId,
routeWorktreeName,
isFloatingWorkspaceRoute,
client,
sessionTabsRef,
terminalLinkOpenMode,
activeSessionTabIdRef,
terminalCwdRef,
activeHandleRef,
@@ -52,25 +48,9 @@ export function useMobileSessionFileActions(scope: MobileSessionTerminalSendActi
onResumedTerminal: switchTab
})
const handleTerminalOpenUrl = useCallback(
(handle: string, url: string) => {
if (handle !== activeHandleRef.current) {
return
}
// Why: browser.tabCreate resolves a real worktree, which the floating
// sentinel doesn't have — open taps in the phone browser instead.
if (terminalLinkOpenMode === 'phone-browser' || isFloatingWorkspaceRoute) {
openExternalLink(url)
return
}
void handleCreateBrowserRef.current?.(url)
},
[terminalLinkOpenMode, isFloatingWorkspaceRoute]
)
return {
handleFileTap,
handleNativeChatFileTap,
handleTerminalOpenUrl
handleNativeChatFileTap
}
}
+4 -2
View File
@@ -2828,12 +2828,14 @@
"title": "Darstellung"
},
"browserSettingsScreen": {
"askEachTime": "Jedes Mal fragen",
"askEachTimeDescription": "Jedes Mal zwischen Orca-Browser, Smartphone-Browser und Link kopieren wählen.",
"desktopBrowser": "Orca-Browser auf dem Desktop",
"desktopBrowserDescription": "Im gestreamten Browser des gekoppelten Desktops öffnen.",
"linksDescription": "Auswählen, wo HTTP(S)-Links aus der Terminalausgabe beim Antippen geöffnet werden.",
"terminalAndChatLinksDescription": "Auswählen, wo Weblinks aus der Terminalausgabe und dem Chat beim Antippen geöffnet werden.",
"linksHeading": "LINKS",
"loadFailed": "Browser-Einstellungen konnten nicht geladen werden. Erneut versuchen.",
"openTerminalLinks": "Terminal-Links öffnen",
"openLinks": "Links öffnen",
"phoneBrowser": "Browser auf dem Smartphone",
"phoneBrowserDescription": "In Safari, Chrome oder einem anderen Browser auf diesem Smartphone öffnen.",
"saveFailed": "Browser-Einstellungen konnten nicht gespeichert werden. Erneut versuchen.",
+4 -2
View File
@@ -42,16 +42,18 @@
"checkUpdates": "Check for updates"
},
"browserSettingsScreen": {
"askEachTime": "Ask each time",
"askEachTimeDescription": "Choose Orca browser, phone browser, or copy the link each time.",
"desktopBrowser": "Orca browser on desktop",
"desktopBrowserDescription": "Open in the streamed browser from your paired desktop.",
"phoneBrowser": "Phone browser",
"phoneBrowserDescription": "Open in Safari, Chrome, or another browser on this phone.",
"title": "Browser",
"linksHeading": "LINKS",
"linksDescription": "Choose where HTTP(S) links tapped in terminal output open.",
"terminalAndChatLinksDescription": "Choose where web links tapped in terminal output and chat open.",
"loadFailed": "Could not load browser preferences. Try again.",
"saveFailed": "Could not save browser preferences. Try again.",
"openTerminalLinks": "Open terminal links"
"openLinks": "Open links"
},
"menuItems": {
"appearance": "Appearance",
+4 -2
View File
@@ -2901,12 +2901,14 @@
"title": "Apariencia"
},
"browserSettingsScreen": {
"askEachTime": "Preguntar cada vez",
"askEachTimeDescription": "Elige cada vez entre el navegador de Orca, el del teléfono o copiar el enlace.",
"desktopBrowser": "Navegador de Orca en el escritorio",
"desktopBrowserDescription": "Abrir en el navegador de tu escritorio emparejado y verlo en el teléfono.",
"linksDescription": "Elige dónde se abren los enlaces HTTP(S) que tocas en la salida de la terminal.",
"terminalAndChatLinksDescription": "Elige dónde se abren los enlaces web que tocas en la salida de la terminal y en el chat.",
"linksHeading": "ENLACES",
"loadFailed": "No se pudieron cargar las preferencias del navegador. Vuelve a intentarlo.",
"openTerminalLinks": "Abrir enlaces de la terminal",
"openLinks": "Abrir enlaces",
"phoneBrowser": "Navegador del teléfono",
"phoneBrowserDescription": "Abrir en Safari, Chrome u otro navegador de este teléfono.",
"saveFailed": "No se pudieron guardar las preferencias del navegador. Vuelve a intentarlo.",
+4 -2
View File
@@ -2901,12 +2901,14 @@
"title": "Apparence"
},
"browserSettingsScreen": {
"askEachTime": "Demander à chaque fois",
"askEachTimeDescription": "Choisissez à chaque fois le navigateur Orca, celui du téléphone ou la copie du lien.",
"desktopBrowser": "Navigateur Orca sur l'ordinateur",
"desktopBrowserDescription": "Ouvrir dans le navigateur diffusé depuis votre ordinateur appairé.",
"linksDescription": "Choisissez où ouvrir les liens HTTP(S) que vous touchez dans la sortie du terminal.",
"terminalAndChatLinksDescription": "Choisissez où ouvrir les liens web que vous touchez dans la sortie du terminal et dans le chat.",
"linksHeading": "LIENS",
"loadFailed": "Impossible de charger les préférences du navigateur. Réessayez.",
"openTerminalLinks": "Ouvrir les liens du terminal",
"openLinks": "Ouvrir les liens",
"phoneBrowser": "Navigateur du téléphone",
"phoneBrowserDescription": "Ouvrir dans Safari, Chrome ou un autre navigateur sur ce téléphone.",
"saveFailed": "Impossible d'enregistrer les préférences du navigateur. Réessayez.",
+4 -2
View File
@@ -2824,12 +2824,14 @@
"title": "外観"
},
"browserSettingsScreen": {
"askEachTime": "毎回確認する",
"askEachTimeDescription": "Orca ブラウザ、スマートフォンのブラウザ、リンクのコピーから毎回選びます。",
"desktopBrowser": "デスクトップの Orca ブラウザ",
"desktopBrowserDescription": "ペアリング済みのデスクトップからストリーミングされるブラウザで開きます。",
"linksDescription": "ターミナル出力でタップした HTTP(S) リンクを開く場所を選択してください。",
"terminalAndChatLinksDescription": "ターミナル出力とチャットでタップした Web リンクを開く場所を選択してください。",
"linksHeading": "リンク",
"loadFailed": "ブラウザ設定を読み込めませんでした。再試行してください。",
"openTerminalLinks": "ターミナルのリンクを開く",
"openLinks": "リンクを開く",
"phoneBrowser": "スマートフォンのブラウザ",
"phoneBrowserDescription": "このスマートフォンの Safari、Chrome などのブラウザで開きます。",
"saveFailed": "ブラウザ設定を保存できませんでした。再試行してください。",
+4 -2
View File
@@ -2824,12 +2824,14 @@
"title": "모양"
},
"browserSettingsScreen": {
"askEachTime": "매번 묻기",
"askEachTimeDescription": "Orca 브라우저, 휴대폰 브라우저, 링크 복사 중에서 매번 선택합니다.",
"desktopBrowser": "데스크톱 Orca 브라우저",
"desktopBrowserDescription": "페어링된 데스크톱에서 스트리밍되는 브라우저로 엽니다.",
"linksDescription": "터미널 출력의 HTTP(S) 링크를 탭했을 때 열 브라우저를 선택하세요.",
"terminalAndChatLinksDescription": "터미널 출력과 채팅의 웹 링크를 탭했을 때 열 위치를 선택하세요.",
"linksHeading": "링크",
"loadFailed": "브라우저 설정을 불러오지 못했습니다. 다시 시도하세요.",
"openTerminalLinks": "터미널 링크 열기",
"openLinks": "링크 열기",
"phoneBrowser": "휴대폰 브라우저",
"phoneBrowserDescription": "이 휴대폰의 Safari, Chrome 또는 다른 브라우저에서 엽니다.",
"saveFailed": "브라우저 설정을 저장하지 못했습니다. 다시 시도하세요.",
+4 -2
View File
@@ -3312,12 +3312,14 @@
"title": "Aparência"
},
"browserSettingsScreen": {
"askEachTime": "Perguntar sempre",
"askEachTimeDescription": "Escolha sempre entre o navegador do Orca, o do celular ou copiar o link.",
"desktopBrowser": "Navegador do Orca no desktop",
"desktopBrowserDescription": "Abrir no navegador transmitido pelo seu desktop pareado.",
"linksDescription": "Escolha onde abrir os links HTTP(S) ao tocar neles na saída do terminal.",
"terminalAndChatLinksDescription": "Escolha onde abrir os links da web ao tocar neles na saída do terminal e no chat.",
"linksHeading": "LINKS",
"loadFailed": "Não foi possível carregar as preferências do navegador. Tente novamente.",
"openTerminalLinks": "Abrir links do terminal",
"openLinks": "Abrir links",
"phoneBrowser": "Navegador do celular",
"phoneBrowserDescription": "Abrir no Safari, Chrome ou outro navegador neste celular.",
"saveFailed": "Não foi possível salvar as preferências do navegador. Tente novamente.",
+4 -2
View File
@@ -2974,12 +2974,14 @@
"title": "Внешний вид"
},
"browserSettingsScreen": {
"askEachTime": "Спрашивать каждый раз",
"askEachTimeDescription": "Каждый раз выбирать браузер Orca, браузер телефона или копирование ссылки.",
"desktopBrowser": "Браузер Orca на компьютере",
"desktopBrowserDescription": "Открывать в браузере сопряжённого компьютера с трансляцией на телефон.",
"linksDescription": "Выберите, где открывать HTTP(S)-ссылки при нажатии на них в выводе терминала.",
"terminalAndChatLinksDescription": "Выберите, где открывать веб-ссылки при нажатии на них в выводе терминала и в чате.",
"linksHeading": "ССЫЛКИ",
"loadFailed": "Не удалось загрузить настройки браузера. Повторите попытку.",
"openTerminalLinks": "Открывать ссылки из терминала",
"openLinks": "Открывать ссылки",
"phoneBrowser": "Браузер телефона",
"phoneBrowserDescription": "Открывать в Safari, Chrome или другом браузере на этом телефоне.",
"saveFailed": "Не удалось сохранить настройки браузера. Повторите попытку.",
+4 -2
View File
@@ -2828,12 +2828,14 @@
"title": "Görünüm"
},
"browserSettingsScreen": {
"askEachTime": "Her seferinde sor",
"askEachTimeDescription": "Her seferinde Orca tarayıcısı, telefon tarayıcısı veya bağlantıyı kopyalama arasında seçim yapın.",
"desktopBrowser": "Masaüstündeki Orca tarayıcısı",
"desktopBrowserDescription": "Eşleştirdiğiniz masaüstü bilgisayardan aktarılan tarayıcıda açın.",
"linksDescription": "Terminal çıktısında dokunduğunuz HTTP(S) bağlantılarının nerede açılacağını seçin.",
"terminalAndChatLinksDescription": "Terminal çıktısında ve sohbette dokunduğunuz web bağlantılarının nerede açılacağını seçin.",
"linksHeading": "BAĞLANTILAR",
"loadFailed": "Tarayıcı tercihleri yüklenemedi. Yeniden deneyin.",
"openTerminalLinks": "Terminal bağlantılarını aç",
"openLinks": "Bağlantıları aç",
"phoneBrowser": "Telefon tarayıcısı",
"phoneBrowserDescription": "Bu telefondaki Safari, Chrome veya başka bir tarayıcıda açın.",
"saveFailed": "Tarayıcı tercihleri kaydedilemedi. Yeniden deneyin.",
+4 -2
View File
@@ -2824,12 +2824,14 @@
"title": "外觀"
},
"browserSettingsScreen": {
"askEachTime": "每次詢問",
"askEachTimeDescription": "每次選擇 Orca 瀏覽器、手機瀏覽器或複製連結。",
"desktopBrowser": "電腦上的 Orca 瀏覽器",
"desktopBrowserDescription": "在已配對電腦的瀏覽器中開啟,並串流至手機。",
"linksDescription": "選擇點按終端機輸出中的 HTTP(S) 連結時,要在哪裡開啟。",
"terminalAndChatLinksDescription": "選擇點按終端機輸出和聊天中的網頁連結時,要在哪裡開啟。",
"linksHeading": "連結",
"loadFailed": "無法載入瀏覽器偏好設定,請再試一次。",
"openTerminalLinks": "開啟終端機連結",
"openLinks": "開啟連結",
"phoneBrowser": "手機瀏覽器",
"phoneBrowserDescription": "在此手機上的 Safari、Chrome 或其他瀏覽器中開啟。",
"saveFailed": "無法儲存瀏覽器偏好設定,請再試一次。",
+4 -2
View File
@@ -2830,12 +2830,14 @@
"title": "外观"
},
"browserSettingsScreen": {
"askEachTime": "每次询问",
"askEachTimeDescription": "每次选择 Orca 浏览器、手机浏览器或复制链接",
"desktopBrowser": "桌面 Orca 浏览器",
"desktopBrowserDescription": "在已配对桌面通过串流提供的浏览器中打开",
"linksDescription": "选择点按终端输出中的 HTTP(S) 链接时使用的浏览器",
"terminalAndChatLinksDescription": "选择点按终端输出和聊天中的网页链接时使用的浏览器",
"linksHeading": "链接",
"loadFailed": "无法加载浏览器偏好设置。请重试",
"openTerminalLinks": "打开终端链接",
"openLinks": "打开链接",
"phoneBrowser": "手机浏览器",
"phoneBrowserDescription": "在此手机的 Safari、Chrome 或其他浏览器中打开",
"saveFailed": "无法保存浏览器偏好设置。请重试",
@@ -24,6 +24,7 @@ import { renderAnimatedToast } from '../components/feedback/TransientToast'
import type { MobileSessionController } from './use-mobile-session-controller'
import { useMobileSessionContentKeyboardLift } from '../terminal/session/input-controls/use-mobile-session-keyboard-lift'
import { useOpenUrlInOrca } from '../browser/tab-navigation/use-open-url-in-orca'
import { useMobileTerminalLinkOpen } from '../terminal/session/links/use-mobile-terminal-link-open'
import { useWorkspaceExecutionHost } from '../navigation/workspace-execution-host'
import { useOpenHostAccounts } from '../accounts/use-open-mobile-accounts'
import { useHostProfile } from '../host-catalog/use-host-profile'
@@ -95,7 +96,6 @@ export function MobileSessionActiveContent({
notifyTerminalCellBoxChange,
handleFileTap,
handleNativeChatFileTap,
handleTerminalOpenUrl,
handleTerminalInput,
handleTerminalQueryReply,
handleSelectionMode,
@@ -120,6 +120,7 @@ export function MobileSessionActiveContent({
const { keyboardLift, activeTerminalKeyboardLift, toastAnimatedStyle } =
useMobileSessionContentKeyboardLift(controller)
const openUrlInOrca = useOpenUrlInOrca(controller)
const terminalLinks = useMobileTerminalLinkOpen(controller, openUrlInOrca)
const hostProfile = useHostProfile(hostId)
const hostTitle = useHostDisplay(hostProfile).title
const nativeChatHostOutage = mobileSessionNativeChatHostOutage(controller, hostTitle, t)
@@ -329,7 +330,7 @@ export function MobileSessionActiveContent({
onTerminalInteraction={handleTerminalInteraction}
onTerminalTap={handleTerminalTap}
onFileTap={handleFileTap}
onOpenUrl={handleTerminalOpenUrl}
onOpenUrl={terminalLinks.handleTerminalOpenUrl}
/>
)}
</MountedTerminalPanes>
@@ -368,6 +369,7 @@ export function MobileSessionActiveContent({
// A workspace routed to another server stops with that server, whose name the phone lacks.
hostName={executionHost === undefined && hostProfile ? hostTitle : null}
onOpenUrlInOrca={openUrlInOrca}
linkOpenMode={controller.linkOpenMode}
hostOutage={nativeChatHostOutage}
onRunInTerminal={(command) =>
void controller.handleCreateTerminal(undefined, {
@@ -382,6 +384,7 @@ export function MobileSessionActiveContent({
</MobileNativeChatForkProvider>
</MobileAgentMessageProvider>
</MobileNativeChatDictationPreviewContext.Provider>
{terminalLinks.terminalLinkSheet}
{toast}
</View>
)
@@ -189,7 +189,8 @@ function Harness(props: HarnessProps) {
sessionId: null,
getSendCompletionGeneration: () => 0,
keyboardInset: 0,
hostName: null
hostName: null,
linkOpenMode: 'ask'
})
}
export async function render(props: HarnessProps = lastProps ?? {}) {
@@ -17,6 +17,7 @@ import {
useMobileNativeChatReplyReveals
} from './transcript/tool-results/mobile-native-chat-reply-reveals'
import { MobileNativeChatRowOverlaysHost } from './transcript/message-actions/MobileNativeChatRowOverlaysHost'
import type { MobileLinkOpenMode } from '../../storage/preferences'
import { nativeChatAskRequiresTerminal } from '../../../../src/shared/native-chat/native-chat-agent-support'
import { tuiAgentDisplayName } from '../../../../src/shared/agent-launch/catalog/tui-agent-display-names'
import { MobileNativeChatNoticeContext } from './transcript/notices/mobile-native-chat-notice-context'
@@ -56,8 +57,9 @@ type Props = {
hostName: string | null
/** Opens the accounts of the host that runs this chat; absent when the phone can't reach them. */
onOpenAccounts?: () => void
/** Offered for tapped links; absent where the host can't open a browser tab. */
/** Opens tapped links in Orca's browser; absent where the host can't open a browser tab. */
onOpenUrlInOrca?: (url: string) => void
linkOpenMode: MobileLinkOpenMode
/** Opens a host terminal tab in this chat's workspace running `command`. */
onRunInTerminal: (command: string) => void
hostOutage?: MobileNativeChatHostOutage | null
@@ -108,6 +110,7 @@ function MobileNativeChatOverlayContent({
keyboardInset,
hostName,
onOpenUrlInOrca,
linkOpenMode,
onRunInTerminal,
hostOutage = null,
onOpenAccounts
@@ -270,6 +273,7 @@ function MobileNativeChatOverlayContent({
conversation={{ surfaceId: sendSurfaceId, sessionId }}
imageSource={imageSource}
onOpenUrlInOrca={onOpenUrlInOrca}
linkOpenMode={linkOpenMode}
rewind={controller.nativeChatRewind}
>
<MobileMarkdownLinksContext.Provider value={markdownLinks}>
@@ -1,11 +1,13 @@
import { useCallback, useMemo } from 'react'
import { useCallback, useLayoutEffect, useMemo, useRef } from 'react'
import type { AgentSessionRewindSurface } from '../../../../../../src/shared/agent-session/lifecycle/rewind/agent-session-rewind-request'
import type { NativeChatMessage } from '../../../../../../src/shared/native-chat/native-chat-types'
import { triggerMediumImpact } from '../../../../platform/haptics/haptics'
import { MobileImageViewer } from '../../../../files/media/presentation/MobileImageViewer'
import { MobileImageViewerActions } from '../../visual/MobileImageViewerActions'
import { MobileNativeChatMessageActionsSheet } from './MobileNativeChatMessageActionsSheet'
import { MobileLinkActionSheet } from './MobileLinkActionSheet'
import { MobileLinkActionSheet } from '../../../../browser/link-open/MobileLinkActionSheet'
import { openMobileWebLink } from '../../../../browser/link-open/mobile-web-link-open'
import type { MobileLinkOpenMode } from '../../../../storage/preferences'
import { MarkdownLinkHandlerContext } from '../../../../components/markdown/links/markdown-link-handler'
import {
MobileNativeChatRowOverlaysContext,
@@ -24,6 +26,7 @@ export function MobileNativeChatRowOverlaysHost({
conversation,
imageSource,
onOpenUrlInOrca,
linkOpenMode,
rewind,
children
}: {
@@ -31,6 +34,7 @@ export function MobileNativeChatRowOverlaysHost({
imageSource?: MobileNativeChatImageSource
/** Absent where the host can't open a browser tab for this chat. */
onOpenUrlInOrca?: (url: string) => void
linkOpenMode: MobileLinkOpenMode
/** The chat's "Rewind to here"; absent where it can't rewind. */
rewind?: AgentSessionRewindSurface
children?: React.ReactNode
@@ -54,7 +58,20 @@ export function MobileNativeChatRowOverlaysHost({
}),
[setShown, openRewind, imageSource]
)
const openLink = useCallback((link: string) => setShown({ link }), [setShown])
// Why a ref: every markdown block reads openLink, so a reconnect must not change its identity.
const linkRouteRef = useRef({ linkOpenMode, onOpenUrlInOrca })
useLayoutEffect(() => {
linkRouteRef.current = { linkOpenMode, onOpenUrlInOrca }
}, [linkOpenMode, onOpenUrlInOrca])
const openLink = useCallback(
(url: string) => {
const route = linkRouteRef.current
openMobileWebLink(url, route.linkOpenMode, route.onOpenUrlInOrca, (link) =>
setShown({ link })
)
},
[setShown]
)
// Memoize overlay callbacks so streamed words cannot rebuild them.
const opened = useMemo(() => {
const close = () => setShown(null)
@@ -2,16 +2,16 @@ import { useShellStorage } from '../platform/shell-storage/shell-storage'
import { settleSessionPreferenceRead } from './session-preference-read'
import { useCallback, useState } from 'react'
import { useFocusEffect } from 'expo-router'
import { loadTerminalLinkOpenMode, loadTerminalTextScale } from '../storage/preferences'
import { loadLinkOpenMode, loadTerminalTextScale } from '../storage/preferences'
import type { MobileSessionKeyboardStateModel } from '../terminal/session/input-controls/use-mobile-session-keyboard-state'
export function useMobileSessionPreferenceFocus(
scope: Pick<
MobileSessionKeyboardStateModel,
'setTerminalTextScale' | 'terminalTextScaleRevisionRef' | 'setTerminalLinkOpenMode'
'setTerminalTextScale' | 'terminalTextScaleRevisionRef' | 'setLinkOpenMode'
>
) {
const { setTerminalTextScale, terminalTextScaleRevisionRef, setTerminalLinkOpenMode } = scope
const { setTerminalTextScale, terminalTextScaleRevisionRef, setLinkOpenMode } = scope
const shellStorage = useShellStorage()
const [terminalPreferencesReady, setTerminalPreferencesReady] = useState(false)
// Reload on Settings return without dropping readiness or remounting terminal panes.
@@ -20,7 +20,7 @@ export function useMobileSessionPreferenceFocus(
let active = true
const scaleRevision = terminalTextScaleRevisionRef.current
void settleSessionPreferenceRead(
Promise.all([loadTerminalTextScale(), loadTerminalLinkOpenMode()])
Promise.all([loadTerminalTextScale(), loadLinkOpenMode()])
).then((preferences) => {
if (active) {
if (preferences) {
@@ -28,7 +28,7 @@ export function useMobileSessionPreferenceFocus(
if (terminalTextScaleRevisionRef.current === scaleRevision) {
setTerminalTextScale(scale)
}
setTerminalLinkOpenMode(linkMode)
setLinkOpenMode(linkMode)
}
setTerminalPreferencesReady(true)
}
@@ -3,7 +3,7 @@ import { useTerminalSplitLayout } from '../terminal/session/pane-layout/use-term
import { createLiveInputCapture } from '../terminal/session/input-controls/live-input-capture'
import { Animated } from 'react-native'
import type { MobileAnimatedValue } from '../platform/animated-handles'
import type { MobileTerminalLinkOpenMode } from '../storage/preferences'
import { DEFAULT_LINK_OPEN_MODE, type MobileLinkOpenMode } from '../storage/preferences'
import type { TerminalKeyboardAvoidanceMetrics } from '../terminal/webview/terminal-webview-contract'
import {
getDefaultTerminalAccessoryBuiltInIds,
@@ -39,8 +39,7 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel)
const [terminalsLoaded, setTerminalsLoaded] = useWorktreeSessionTabsLoaded(worktreeId)
const [terminalTextScale, setTerminalTextScale] = useState(1)
const terminalTextScaleRevisionRef = useRef(0)
const [terminalLinkOpenMode, setTerminalLinkOpenMode] =
useState<MobileTerminalLinkOpenMode>('orca-browser')
const [linkOpenMode, setLinkOpenMode] = useState<MobileLinkOpenMode>(DEFAULT_LINK_OPEN_MODE)
const [liveInputCapture] = useState(createLiveInputCapture)
const [activeHandle, setActiveHandle] = useState<string | null>(null)
const [coveredStreamRevision, setCoveredStreamRevision] = useState(0)
@@ -119,8 +118,8 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel)
terminalTextScale,
setTerminalTextScale,
terminalTextScaleRevisionRef,
terminalLinkOpenMode,
setTerminalLinkOpenMode,
linkOpenMode,
setLinkOpenMode,
liveInputCapture,
setLiveInputCapture: liveInputCapture.set,
activeHandle,
@@ -3,11 +3,7 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import BrowserSettingsScreen from './browser-settings-screen'
import { PickerModal } from '../components/sheets/PickerModal'
import {
loadTerminalLinkOpenMode,
saveTerminalLinkOpenMode,
type MobileTerminalLinkOpenMode
} from '../storage/preferences'
import { loadLinkOpenMode, saveLinkOpenMode, type MobileLinkOpenMode } from '../storage/preferences'
vi.mock(
'./settings-screen-frame',
@@ -31,8 +27,9 @@ vi.mock('expo-router', () => ({ useRouter: () => ({ back() {} }) }))
vi.mock('lucide-react-native', () => ({ ChevronLeft: 'Icon', ChevronRight: 'Icon', Globe: 'Icon' }))
vi.mock('../components/sheets/PickerModal', () => ({ PickerModal: () => null }))
vi.mock('../storage/preferences', () => ({
loadTerminalLinkOpenMode: vi.fn(),
saveTerminalLinkOpenMode: vi.fn()
DEFAULT_LINK_OPEN_MODE: 'ask',
loadLinkOpenMode: vi.fn(),
saveLinkOpenMode: vi.fn()
}))
let renderer: ReactTestRenderer
@@ -43,14 +40,14 @@ afterEach(() => {
describe('browser settings persistence', () => {
it('does not replace a new selection with an older pending hydration read', async () => {
let resolveLoad = (_value: MobileTerminalLinkOpenMode) => {}
vi.mocked(loadTerminalLinkOpenMode).mockImplementation(
let resolveLoad = (_value: MobileLinkOpenMode) => {}
vi.mocked(loadLinkOpenMode).mockImplementation(
() =>
new Promise((resolve) => {
resolveLoad = resolve
})
)
vi.mocked(saveTerminalLinkOpenMode).mockResolvedValue()
vi.mocked(saveLinkOpenMode).mockResolvedValue()
await act(async () => {
renderer = create(createElement(BrowserSettingsScreen))
})
@@ -64,14 +61,14 @@ describe('browser settings persistence', () => {
})
it('restores the hydrated destination when the save fails before the first read finishes', async () => {
let resolveLoad = (_value: MobileTerminalLinkOpenMode) => {}
vi.mocked(loadTerminalLinkOpenMode).mockImplementation(
let resolveLoad = (_value: MobileLinkOpenMode) => {}
vi.mocked(loadLinkOpenMode).mockImplementation(
() =>
new Promise((resolve) => {
resolveLoad = resolve
})
)
vi.mocked(saveTerminalLinkOpenMode).mockRejectedValue(new Error('storage unavailable'))
vi.mocked(saveLinkOpenMode).mockRejectedValue(new Error('storage unavailable'))
await act(async () => {
renderer = create(createElement(BrowserSettingsScreen))
})
+26 -20
View File
@@ -6,16 +6,25 @@ import { PickerModal, type PickerOption } from '../components/sheets/PickerModal
import type { Translate } from '../i18n/mobile-i18n'
import { useMobileTranslation } from '../i18n/use-mobile-translation'
import {
loadTerminalLinkOpenMode,
saveTerminalLinkOpenMode,
type MobileTerminalLinkOpenMode
DEFAULT_LINK_OPEN_MODE,
loadLinkOpenMode,
saveLinkOpenMode,
type MobileLinkOpenMode
} from '../storage/preferences'
import { colors } from '../theme/mobile-theme'
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
import { SettingsNote, SettingsScreen, SettingsSection } from './settings-screen-frame'
function linkModeOptions(t: Translate): PickerOption<MobileTerminalLinkOpenMode>[] {
function linkModeOptions(t: Translate): PickerOption<MobileLinkOpenMode>[] {
return [
{
value: 'ask',
label: t('settings.browserSettingsScreen.askEachTime', 'Ask each time'),
subtitle: t(
'settings.browserSettingsScreen.askEachTimeDescription',
'Choose Orca browser, phone browser, or copy the link each time.'
)
},
{
value: 'orca-browser',
label: t('settings.browserSettingsScreen.desktopBrowser', 'Orca browser on desktop'),
@@ -36,8 +45,8 @@ function linkModeOptions(t: Translate): PickerOption<MobileTerminalLinkOpenMode>
}
function linkModeLabel(
mode: MobileTerminalLinkOpenMode,
options: PickerOption<MobileTerminalLinkOpenMode>[]
mode: MobileLinkOpenMode,
options: PickerOption<MobileLinkOpenMode>[]
): string {
return options.find((option) => option.value === mode)?.label ?? options[0]!.label
}
@@ -50,18 +59,18 @@ export default function BrowserSettingsScreen({
const t = useMobileTranslation()
useMobileColorScheme()
const router = useRouter()
const [linkMode, setLinkMode] = useState<MobileTerminalLinkOpenMode>('orca-browser')
const [linkMode, setLinkMode] = useState<MobileLinkOpenMode>(DEFAULT_LINK_OPEN_MODE)
const [pickerOpen, setPickerOpen] = useState(false)
const [error, setError] = useState<'load' | 'save' | null>(null)
const options = linkModeOptions(t)
const selectionRevision = useRef(0)
const failedSelectionRevision = useRef<number | null>(null)
const savedMode = useRef<MobileTerminalLinkOpenMode>('orca-browser')
const savedMode = useRef<MobileLinkOpenMode>(DEFAULT_LINK_OPEN_MODE)
const hasSaved = useRef(false)
useEffect(() => {
let active = true
void loadTerminalLinkOpenMode().then(
void loadLinkOpenMode().then(
(mode) => {
if (!hasSaved.current) {
savedMode.current = mode
@@ -85,11 +94,11 @@ export default function BrowserSettingsScreen({
}
}, [])
const selectLinkMode = useCallback((mode: MobileTerminalLinkOpenMode) => {
const selectLinkMode = useCallback((mode: MobileLinkOpenMode) => {
setError(null)
const revision = ++selectionRevision.current
setLinkMode(mode)
void saveTerminalLinkOpenMode(mode).then(
void saveLinkOpenMode(mode).then(
() => {
savedMode.current = mode
hasSaved.current = true
@@ -123,9 +132,9 @@ export default function BrowserSettingsScreen({
title={t('settings.browserSettingsScreen.title', 'Browser')}
onBack={onBack ?? (() => router.back())}
overlays={
<PickerModal<MobileTerminalLinkOpenMode>
<PickerModal<MobileLinkOpenMode>
visible={pickerOpen}
title={t('settings.browserSettingsScreen.openTerminalLinks', 'Open terminal links')}
title={t('settings.browserSettingsScreen.openLinks', 'Open links')}
options={options}
selected={linkMode}
onSelect={selectLinkMode}
@@ -140,8 +149,8 @@ export default function BrowserSettingsScreen({
<>
<SettingsNote>
{t(
'settings.browserSettingsScreen.linksDescription',
'Choose where HTTP(S) links tapped in terminal output open.'
'settings.browserSettingsScreen.terminalAndChatLinksDescription',
'Choose where web links tapped in terminal output and chat open.'
)}
</SettingsNote>
{errorNote}
@@ -150,14 +159,11 @@ export default function BrowserSettingsScreen({
>
<ListRow
key="linkMode"
title={t('settings.browserSettingsScreen.openTerminalLinks', 'Open terminal links')}
title={t('settings.browserSettingsScreen.openLinks', 'Open links')}
subtitle={linkModeLabel(linkMode, options)}
leading={<Globe size={18} color={colors.textSecondary} />}
navigates
accessibilityLabel={t(
'settings.browserSettingsScreen.openTerminalLinks',
'Open terminal links'
)}
accessibilityLabel={t('settings.browserSettingsScreen.openLinks', 'Open links')}
onPress={() => setPickerOpen(true)}
/>
</SettingsSection>
+4 -4
View File
@@ -1,6 +1,6 @@
import AsyncStorage from '@react-native-async-storage/async-storage'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { loadTerminalLinkOpenMode, saveTerminalLinkOpenMode } from './preferences'
import { loadLinkOpenMode, saveLinkOpenMode } from './preferences'
import {
loadDefaultSessionView,
loadSessionViewOverrides,
@@ -199,9 +199,9 @@ describe('terminal link open mode preference', () => {
}
stored = value
})
const firstMount = saveTerminalLinkOpenMode('phone-browser')
const secondMount = saveTerminalLinkOpenMode('orca-browser')
const reader = loadTerminalLinkOpenMode()
const firstMount = saveLinkOpenMode('phone-browser')
const secondMount = saveLinkOpenMode('orca-browser')
const reader = loadLinkOpenMode()
await Promise.resolve()
expect(stored).toBe('orca-browser')
firstWrite.resolve()
+19 -15
View File
@@ -154,31 +154,35 @@ export async function saveHostDockWidth(width: number): Promise<void> {
await persistMirrored(DOCK_WIDTH_KEY, value)
}
export type MobileTerminalLinkOpenMode = 'orca-browser' | 'phone-browser'
/** Where a web link tapped in terminal output or chat opens; 'ask' shows the link sheet each time. */
export type MobileLinkOpenMode = 'ask' | 'orca-browser' | 'phone-browser'
const TERMINAL_LINK_OPEN_MODE_KEY = 'orca:terminalLinkOpenMode'
export const DEFAULT_TERMINAL_LINK_OPEN_MODE: MobileTerminalLinkOpenMode = 'orca-browser'
let terminalLinkWriteBarrier: Promise<void> | null = null
// The key predates chat links following this choice; renaming it would drop saved choices.
const LINK_OPEN_MODE_KEY = 'orca:terminalLinkOpenMode'
export const DEFAULT_LINK_OPEN_MODE: MobileLinkOpenMode = 'ask'
let linkOpenModeWriteBarrier: Promise<void> | null = null
export async function loadTerminalLinkOpenMode(): Promise<MobileTerminalLinkOpenMode> {
await terminalLinkWriteBarrier
export async function loadLinkOpenMode(): Promise<MobileLinkOpenMode> {
await linkOpenModeWriteBarrier
try {
const raw = await AsyncStorage.getItem(TERMINAL_LINK_OPEN_MODE_KEY)
return raw === 'phone-browser' || raw === 'orca-browser' ? raw : DEFAULT_TERMINAL_LINK_OPEN_MODE
const raw = await AsyncStorage.getItem(LINK_OPEN_MODE_KEY)
return raw === 'ask' || raw === 'phone-browser' || raw === 'orca-browser'
? raw
: DEFAULT_LINK_OPEN_MODE
} catch {
return DEFAULT_TERMINAL_LINK_OPEN_MODE
return DEFAULT_LINK_OPEN_MODE
}
}
export function saveTerminalLinkOpenMode(mode: MobileTerminalLinkOpenMode): Promise<void> {
const write = (terminalLinkWriteBarrier ?? Promise.resolve()).then(() =>
persistMirrored(TERMINAL_LINK_OPEN_MODE_KEY, mode)
export function saveLinkOpenMode(mode: MobileLinkOpenMode): Promise<void> {
const write = (linkOpenModeWriteBarrier ?? Promise.resolve()).then(() =>
persistMirrored(LINK_OPEN_MODE_KEY, mode)
)
const barrier = write.catch(() => undefined)
terminalLinkWriteBarrier = barrier
linkOpenModeWriteBarrier = barrier
void barrier.then(() => {
if (terminalLinkWriteBarrier === barrier) {
terminalLinkWriteBarrier = null
if (linkOpenModeWriteBarrier === barrier) {
linkOpenModeWriteBarrier = null
}
})
return write
@@ -0,0 +1,38 @@
import { useCallback, useState } from 'react'
import { MobileLinkActionSheet } from '../../../browser/link-open/MobileLinkActionSheet'
import { openMobileWebLink } from '../../../browser/link-open/mobile-web-link-open'
import type { MobileSessionController } from '../../../session/use-mobile-session-controller'
export function useMobileTerminalLinkOpen(
controller: Pick<
MobileSessionController,
'activeHandleRef' | 'linkOpenMode' | 'activeSessionTab'
>,
openInOrca: ((url: string) => void) | undefined
) {
const { activeHandleRef, linkOpenMode } = controller
const tabId = controller.activeSessionTab?.id
const [asked, setAsked] = useState<{ url: string; tabId: string | undefined } | null>(null)
// A sheet asked from one tab must not reappear after the person returns to it.
if (asked && asked.tabId !== tabId) {
setAsked(null)
}
const handleTerminalOpenUrl = useCallback(
(handle: string, url: string) => {
if (handle !== activeHandleRef.current) {
return
}
openMobileWebLink(url, linkOpenMode, openInOrca, (link) => setAsked({ url: link, tabId }))
},
[activeHandleRef, linkOpenMode, openInOrca, tabId]
)
const terminalLinkSheet =
asked && asked.tabId === tabId ? (
<MobileLinkActionSheet
url={asked.url}
openInOrca={openInOrca}
onClose={() => setAsked(null)}
/>
) : null
return { handleTerminalOpenUrl, terminalLinkSheet }
}