From 42419ed7c02230bdbff19944b6585640061b0faa Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:46:41 +0000 Subject: [PATCH] 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 --- .../link-open}/MobileLinkActionSheet.tsx | 15 +++--- .../link-open/mobile-web-link-open.test.ts | 43 +++++++++++++++++ .../browser/link-open/mobile-web-link-open.ts | 21 +++++++++ .../use-mobile-session-file-actions.ts | 22 +-------- mobile/src/i18n/locales/de.json | 6 ++- mobile/src/i18n/locales/en.json | 6 ++- mobile/src/i18n/locales/es.json | 6 ++- mobile/src/i18n/locales/fr.json | 6 ++- mobile/src/i18n/locales/ja.json | 6 ++- mobile/src/i18n/locales/ko.json | 6 ++- mobile/src/i18n/locales/pt.json | 6 ++- mobile/src/i18n/locales/ru.json | 6 ++- mobile/src/i18n/locales/tr.json | 6 ++- mobile/src/i18n/locales/zh-Hant.json | 6 ++- mobile/src/i18n/locales/zh.json | 6 ++- .../session/MobileSessionActiveContent.tsx | 7 ++- .../__mocks__/mobile-prompt-controller.ts | 3 +- .../native-chat/MobileNativeChatOverlay.tsx | 6 ++- .../MobileNativeChatRowOverlaysHost.tsx | 23 ++++++++-- .../use-mobile-session-preference-focus.ts | 10 ++-- .../use-mobile-session-screen-state.ts | 9 ++-- .../browser-settings-persistence.test.tsx | 23 ++++------ .../src/settings/browser-settings-screen.tsx | 46 +++++++++++-------- mobile/src/storage/preferences.test.ts | 8 ++-- mobile/src/storage/preferences.ts | 34 ++++++++------ .../links/use-mobile-terminal-link-open.tsx | 38 +++++++++++++++ 26 files changed, 253 insertions(+), 121 deletions(-) rename mobile/src/{session/native-chat/transcript/message-actions => browser/link-open}/MobileLinkActionSheet.tsx (76%) create mode 100644 mobile/src/browser/link-open/mobile-web-link-open.test.ts create mode 100644 mobile/src/browser/link-open/mobile-web-link-open.ts create mode 100644 mobile/src/terminal/session/links/use-mobile-terminal-link-open.tsx diff --git a/mobile/src/session/native-chat/transcript/message-actions/MobileLinkActionSheet.tsx b/mobile/src/browser/link-open/MobileLinkActionSheet.tsx similarity index 76% rename from mobile/src/session/native-chat/transcript/message-actions/MobileLinkActionSheet.tsx rename to mobile/src/browser/link-open/MobileLinkActionSheet.tsx index dd927a19134..b27bec64ddf 100644 --- a/mobile/src/session/native-chat/transcript/message-actions/MobileLinkActionSheet.tsx +++ b/mobile/src/browser/link-open/MobileLinkActionSheet.tsx @@ -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. diff --git a/mobile/src/browser/link-open/mobile-web-link-open.test.ts b/mobile/src/browser/link-open/mobile-web-link-open.test.ts new file mode 100644 index 00000000000..02bcbc7afe9 --- /dev/null +++ b/mobile/src/browser/link-open/mobile-web-link-open.test.ts @@ -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() + }) +}) diff --git a/mobile/src/browser/link-open/mobile-web-link-open.ts b/mobile/src/browser/link-open/mobile-web-link-open.ts new file mode 100644 index 00000000000..e7a5fed5ea0 --- /dev/null +++ b/mobile/src/browser/link-open/mobile-web-link-open.ts @@ -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) + } +} diff --git a/mobile/src/files/session-documents/use-mobile-session-file-actions.ts b/mobile/src/files/session-documents/use-mobile-session-file-actions.ts index 811623843c0..6e553224bbd 100644 --- a/mobile/src/files/session-documents/use-mobile-session-file-actions.ts +++ b/mobile/src/files/session-documents/use-mobile-session-file-actions.ts @@ -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 } } diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index 69d5025d9c3..ec3216f538e 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -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.", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index e1d6bb8a918..e5850552e6c 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -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", diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index 62daf9a0ee9..12e3c191ddc 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -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.", diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index 18d9df379ce..0d1efcb82e5 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -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.", diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index b99a26e7b9a..006c4420212 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -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": "ブラウザ設定を保存できませんでした。再試行してください。", diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index 21ba08b5eb6..f57fac2d812 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -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": "브라우저 설정을 저장하지 못했습니다. 다시 시도하세요.", diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index 84a469a9b4b..a0366e4c9a9 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -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.", diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index d32028251cf..9cdcea7b87c 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -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": "Не удалось сохранить настройки браузера. Повторите попытку.", diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index a837f86d261..315d74bf167 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -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.", diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index 3ab22869694..3b679a15104 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -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": "無法儲存瀏覽器偏好設定,請再試一次。", diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index 00565b09973..24396bb9c89 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -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": "无法保存浏览器偏好设置。请重试", diff --git a/mobile/src/session/MobileSessionActiveContent.tsx b/mobile/src/session/MobileSessionActiveContent.tsx index 58522f7835e..8e86c1791c2 100644 --- a/mobile/src/session/MobileSessionActiveContent.tsx +++ b/mobile/src/session/MobileSessionActiveContent.tsx @@ -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} /> )} @@ -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({ + {terminalLinks.terminalLinkSheet} {toast} ) diff --git a/mobile/src/session/__mocks__/mobile-prompt-controller.ts b/mobile/src/session/__mocks__/mobile-prompt-controller.ts index 26c8b59d89f..4d74f685209 100644 --- a/mobile/src/session/__mocks__/mobile-prompt-controller.ts +++ b/mobile/src/session/__mocks__/mobile-prompt-controller.ts @@ -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 ?? {}) { diff --git a/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx b/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx index 9f6bae41e7c..78c5d5b68be 100644 --- a/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx +++ b/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx @@ -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} > diff --git a/mobile/src/session/native-chat/transcript/message-actions/MobileNativeChatRowOverlaysHost.tsx b/mobile/src/session/native-chat/transcript/message-actions/MobileNativeChatRowOverlaysHost.tsx index 5b2a1f3fd57..0af7d55fc15 100644 --- a/mobile/src/session/native-chat/transcript/message-actions/MobileNativeChatRowOverlaysHost.tsx +++ b/mobile/src/session/native-chat/transcript/message-actions/MobileNativeChatRowOverlaysHost.tsx @@ -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) diff --git a/mobile/src/session/use-mobile-session-preference-focus.ts b/mobile/src/session/use-mobile-session-preference-focus.ts index b408816ba5f..18ee9334f46 100644 --- a/mobile/src/session/use-mobile-session-preference-focus.ts +++ b/mobile/src/session/use-mobile-session-preference-focus.ts @@ -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) } diff --git a/mobile/src/session/use-mobile-session-screen-state.ts b/mobile/src/session/use-mobile-session-screen-state.ts index 0fbe5488482..bb4762e735a 100644 --- a/mobile/src/session/use-mobile-session-screen-state.ts +++ b/mobile/src/session/use-mobile-session-screen-state.ts @@ -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('orca-browser') + const [linkOpenMode, setLinkOpenMode] = useState(DEFAULT_LINK_OPEN_MODE) const [liveInputCapture] = useState(createLiveInputCapture) const [activeHandle, setActiveHandle] = useState(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, diff --git a/mobile/src/settings/browser-settings-persistence.test.tsx b/mobile/src/settings/browser-settings-persistence.test.tsx index 7b9651145b8..044b48f0ff5 100644 --- a/mobile/src/settings/browser-settings-persistence.test.tsx +++ b/mobile/src/settings/browser-settings-persistence.test.tsx @@ -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)) }) diff --git a/mobile/src/settings/browser-settings-screen.tsx b/mobile/src/settings/browser-settings-screen.tsx index e1f0dc30c73..ef42e8f2e73 100644 --- a/mobile/src/settings/browser-settings-screen.tsx +++ b/mobile/src/settings/browser-settings-screen.tsx @@ -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[] { +function linkModeOptions(t: Translate): PickerOption[] { 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 } function linkModeLabel( - mode: MobileTerminalLinkOpenMode, - options: PickerOption[] + mode: MobileLinkOpenMode, + options: PickerOption[] ): 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('orca-browser') + const [linkMode, setLinkMode] = useState(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(null) - const savedMode = useRef('orca-browser') + const savedMode = useRef(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={ - + 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({ <> {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.' )} {errorNote} @@ -150,14 +159,11 @@ export default function BrowserSettingsScreen({ > } navigates - accessibilityLabel={t( - 'settings.browserSettingsScreen.openTerminalLinks', - 'Open terminal links' - )} + accessibilityLabel={t('settings.browserSettingsScreen.openLinks', 'Open links')} onPress={() => setPickerOpen(true)} /> diff --git a/mobile/src/storage/preferences.test.ts b/mobile/src/storage/preferences.test.ts index de82242577c..252919d04fa 100644 --- a/mobile/src/storage/preferences.test.ts +++ b/mobile/src/storage/preferences.test.ts @@ -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() diff --git a/mobile/src/storage/preferences.ts b/mobile/src/storage/preferences.ts index fbb1ee53f58..57e045cf189 100644 --- a/mobile/src/storage/preferences.ts +++ b/mobile/src/storage/preferences.ts @@ -154,31 +154,35 @@ export async function saveHostDockWidth(width: number): Promise { 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 | 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 | null = null -export async function loadTerminalLinkOpenMode(): Promise { - await terminalLinkWriteBarrier +export async function loadLinkOpenMode(): Promise { + 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 { - const write = (terminalLinkWriteBarrier ?? Promise.resolve()).then(() => - persistMirrored(TERMINAL_LINK_OPEN_MODE_KEY, mode) +export function saveLinkOpenMode(mode: MobileLinkOpenMode): Promise { + 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 diff --git a/mobile/src/terminal/session/links/use-mobile-terminal-link-open.tsx b/mobile/src/terminal/session/links/use-mobile-terminal-link-open.tsx new file mode 100644 index 00000000000..8154b6d45cd --- /dev/null +++ b/mobile/src/terminal/session/links/use-mobile-terminal-link-open.tsx @@ -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 ? ( + setAsked(null)} + /> + ) : null + return { handleTerminalOpenUrl, terminalLinkSheet } +}