@devries-cameron20 / t3code Mirror · read-only / commits / b07fdeb143
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 02:00 UTC

fix(mobile): iOS terminal can copy, paste, and stop freezing (#25828)

Co-authored-by: danddanddand <47586871+danddanddand@users.noreply.github.com> Co-authored-by: whoisaldo <whois.younes@gmail.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: juliusmarminge <julius0216@outlook.com> Co-authored-by: Claudesaul <139932571+Claudesaul@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Nov 8, 2026 at 22:24 UTC b07fdeb1438071a56c909ec705393bed89d1d321
10 files changed +277 -39
apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift
+2 -2
@@ -7,7 +7,7 @@ public class T3TerminalModule: Module {
7 // Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
8 // logs so a stale native binary is distinguishable from a broken key pipeline.
9 Constants([
10 - "hardwareKeyRevision": 3,
10 + "hardwareKeyRevision": 4,
11 "outputRevision": 1,
12 ])
13
@@ -71,7 +71,7 @@ public class T3TerminalModule: Module {
71 Prop("sharedGrid") { (view: T3TerminalView, sharedGrid: [Int]) in
72 view.sharedGrid = sharedGrid
73 }
74 - Events("onInput", "onResize", "onCapture")
74 + Events("onInput", "onResize", "onCapture", "onPaste")
75
76 OnViewDidUpdateProps { (view: T3TerminalView) in
77 view.applyPendingBuffer()
apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift
+153 -24
@@ -110,6 +110,11 @@ private enum TerminalHardwareKeyEncoder {
110 }
111 }
112
113 +/// Ghostty callbacks can fire during deinit and hop to main after it, so they must not retain the view.
114 +private final class TerminalViewRef {
115 + weak var view: T3TerminalView?
116 +}
117 +
118 private enum TerminalInputSequence {
119 /// Terminal Enter is carriage return. Sending line feed instead is Ctrl+J,
120 /// which raw-mode TUIs may interpret as the literal J key.
@@ -128,6 +133,7 @@ private enum TerminalInputSequence {
133 private final class TerminalInputField: UITextField {
134 var onDeleteBackward: (() -> Void)?
135 var onInsert: ((String) -> Void)?
136 + var onPaste: (() -> Void)?
137
138 private static let hardwareKeyCommands = TerminalHardwareKeyEncoder.makeKeyCommands(
139 action: #selector(handleHardwareKeyCommand(_:))
@@ -146,6 +152,16 @@ private final class TerminalInputField: UITextField {
152 super.deleteBackward()
153 }
154
155 + // System pastes must bypass typed input to preserve paste encoding and chunking.
156 + override func paste(_ sender: Any?) {
157 + // Commit an in-progress composition first so it reaches the PTY ahead of the paste.
158 + if markedTextRange != nil {
159 + unmarkText()
160 + sendActions(for: .editingChanged)
161 + }
162 + onPaste?()
163 + }
164 +
165 @objc
166 private func handleHardwareKeyCommand(_ command: UIKeyCommand) {
167 guard let input = command.input else { return }
@@ -188,7 +204,7 @@ private extension UIColor {
204 }
205 }
206
191 -public final class T3TerminalView: ExpoView, UITextFieldDelegate {
207 +public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInteractionDelegate {
208 private static let minimumVerticalScrollStepPoints: CGFloat = 18
209 private static let verticalScrollStepMultiplier: CGFloat = 1.15
210
@@ -196,14 +212,18 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
212 private let inputField = TerminalInputField()
213 private let focusTapGesture = UITapGestureRecognizer()
214 private let scrollPanGesture = UIPanGestureRecognizer()
215 + private let editMenuGesture = UILongPressGestureRecognizer()
216 + private lazy var editMenuInteraction = UIEditMenuInteraction(delegate: self)
217 private var lastViewportSize: CGSize = .zero
218 private var lastContentScale: CGFloat = 0
219 private var lastReportedGrid: (cols: Int, rows: Int)?
220 private var lastAppliedBuffer = ""
221 private var streamedOutput: TerminalOutputBuffer?
222 private var pendingVerticalScrollPoints: CGFloat = 0
223 + private var menuText: String?
224 private var sentInput = ""
225 private var app: ghostty_app_t?
226 + private let callbackRef = TerminalViewRef()
227 private var surface: ghostty_surface_t?
228 private var isCreatingSurface = false
229 private var surfaceCreationFailed = false
@@ -213,18 +233,11 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
233 let onInput = EventDispatcher()
234 let onResize = EventDispatcher()
235 let onCapture = EventDispatcher()
236 + let onPaste = EventDispatcher()
237 var captureRequest: Double = 0 {
238 didSet {
239 guard captureRequest > 0, captureRequest != oldValue else { return }
219 - guard let surface else { onCapture(["text": ""]); return }
220 - let selection = ghostty_selection_s(
221 - top_left: ghostty_point_s(tag: GHOSTTY_POINT_VIEWPORT, coord: GHOSTTY_POINT_COORD_TOP_LEFT, x: 0, y: 0),
222 - bottom_right: ghostty_point_s(tag: GHOSTTY_POINT_VIEWPORT, coord: GHOSTTY_POINT_COORD_BOTTOM_RIGHT, x: 0, y: 0),
223 - rectangle: false)
224 - var captured = ghostty_text_s()
225 - guard ghostty_surface_read_text(surface, selection, &captured) else { onCapture(["text": ""]); return }
226 - defer { ghostty_surface_free_text(surface, &captured) }
227 - let text = captured.text.flatMap { String(bytes: UnsafeBufferPointer(start: UnsafeRawPointer($0).assumingMemoryBound(to: UInt8.self), count: Int(captured.text_len)), encoding: .utf8) } ?? ""
240 + let text = readViewportText() ?? ""
241 // Android joins snapshot rows with "\n" and trims each row's trailing whitespace, so do
242 // the same here: identical terminal content must capture identically on both platforms.
243 let normalized = text.split(separator: "\n", omittingEmptySubsequences: false)
@@ -272,7 +285,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
285 didSet {
286 guard oldValue != fontSize else { return }
287 inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular)
275 - refreshSurface()
288 + resetSurface()
289 }
290 }
291
@@ -308,14 +321,14 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
321 didSet {
322 guard oldValue != appearanceScheme else { return }
323 appearance = TerminalAppearanceScheme(value: appearanceScheme)
311 - refreshSurface()
324 + resetSurface()
325 }
326 }
327
328 var themeConfig: String = "" {
329 didSet {
330 guard oldValue != themeConfig else { return }
318 - refreshSurface()
331 + resetSurface()
332 }
333 }
334
@@ -331,6 +344,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
344
345 public required init(appContext: AppContext? = nil) {
346 super.init(appContext: appContext)
347 + callbackRef.view = self
348
349 applyTheme()
350 clipsToBounds = true
@@ -370,6 +384,9 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
384 self?.emitInput(data)
385 self?.resetInputField()
386 }
387 + inputField.onPaste = { [weak self] in
388 + self?.emitPaste()
389 + }
390
391 focusTapGesture.addTarget(self, action: #selector(handleViewportTap))
392 terminalViewport.addGestureRecognizer(focusTapGesture)
@@ -377,6 +394,10 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
394 scrollPanGesture.maximumNumberOfTouches = 1
395 scrollPanGesture.cancelsTouchesInView = false
396 terminalViewport.addGestureRecognizer(scrollPanGesture)
397 + editMenuGesture.addTarget(self, action: #selector(handleViewportLongPress(_:)))
398 + terminalViewport.addGestureRecognizer(editMenuGesture)
399 + terminalViewport.addInteraction(editMenuInteraction)
400 + focusTapGesture.require(toFail: editMenuGesture)
401
402 addSubview(terminalViewport)
403 addSubview(inputField)
@@ -438,6 +459,23 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
459 requestKeyboardFocus()
460 }
461
462 + private func readViewportText() -> String? {
463 + guard let surface else { return nil }
464 + let selection = ghostty_selection_s(
465 + top_left: ghostty_point_s(tag: GHOSTTY_POINT_VIEWPORT, coord: GHOSTTY_POINT_COORD_TOP_LEFT, x: 0, y: 0),
466 + bottom_right: ghostty_point_s(tag: GHOSTTY_POINT_VIEWPORT, coord: GHOSTTY_POINT_COORD_BOTTOM_RIGHT, x: 0, y: 0),
467 + rectangle: false)
468 + var captured = ghostty_text_s()
469 + guard ghostty_surface_read_text(surface, selection, &captured) else { return nil }
470 + defer { ghostty_surface_free_text(surface, &captured) }
471 + guard let text = captured.text else { return nil }
472 + return String(
473 + bytes: UnsafeBufferPointer(
474 + start: UnsafeRawPointer(text).assumingMemoryBound(to: UInt8.self),
475 + count: Int(captured.text_len)),
476 + encoding: .utf8)
477 + }
478 +
479 @objc
480 private func handleViewportPan(_ gesture: UIPanGestureRecognizer) {
481 guard let surface else { return }
@@ -504,6 +542,83 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
542 }
543 }
544
545 + @objc
546 + private func handleViewportLongPress(_ gesture: UILongPressGestureRecognizer) {
547 + guard gesture.state == .began else { return }
548 + // Freeze the text the user pressed on; output keeps streaming while the menu is open.
549 + menuText = readViewportText().flatMap { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : $0 }
550 + guard menuText != nil || canPaste else { return }
551 + editMenuInteraction.presentEditMenu(
552 + with: UIEditMenuConfiguration(identifier: nil, sourcePoint: gesture.location(in: terminalViewport))
553 + )
554 + }
555 +
556 + public func editMenuInteraction(
557 + _ interaction: UIEditMenuInteraction,
558 + menuFor configuration: UIEditMenuConfiguration,
559 + suggestedActions: [UIMenuElement]
560 + ) -> UIMenu? {
561 + // The hidden input field would otherwise add actions such as Scan Text or Writing Tools.
562 + // Keep the system Paste command: unlike a custom action, it reads without a paste prompt.
563 + var children: [UIMenuElement] = Self.pasteCommand(in: suggestedActions).map { [$0] } ?? []
564 + if let text = menuText {
565 + children.append(
566 + UIAction(title: "Select Text", image: UIImage(systemName: "text.cursor")) { [weak self] _ in
567 + self?.presentTextSelection(text)
568 + })
569 + }
570 + return children.isEmpty ? nil : UIMenu(children: children)
571 + }
572 +
573 + private func presentTextSelection(_ text: String) {
574 + guard let window else { return }
575 + var responder: UIResponder? = self
576 + while let current = responder, !(current is UIViewController) {
577 + responder = current.next
578 + }
579 + guard let presenter = responder as? UIViewController,
580 + presenter.viewIfLoaded?.window === window,
581 + presenter.presentedViewController == nil,
582 + !presenter.isBeingPresented,
583 + !presenter.isBeingDismissed,
584 + presenter.transitionCoordinator == nil
585 + else { return }
586 +
587 + inputField.resignFirstResponder()
588 + let controller = TerminalTextSelectionViewController(text: text, fontSize: fontSize)
589 + let navigation = UINavigationController(rootViewController: controller)
590 + navigation.modalPresentationStyle = .pageSheet
591 + presenter.present(navigation, animated: !UIAccessibility.isReduceMotionEnabled)
592 + }
593 +
594 + private static func pasteCommand(in elements: [UIMenuElement]) -> UIMenuElement? {
595 + for element in elements {
596 + if let command = element as? UICommand,
597 + command.action == #selector(UIResponderStandardEditActions.paste(_:)) {
598 + return command
599 + }
600 + if let menu = element as? UIMenu, let command = pasteCommand(in: menu.children) {
601 + return command
602 + }
603 + }
604 + return nil
605 + }
606 +
607 + public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
608 + if action == #selector(UIResponderStandardEditActions.paste(_:)) {
609 + return canPaste
610 + }
611 + return super.canPerformAction(action, withSender: sender)
612 + }
613 +
614 + public override func paste(_ sender: Any?) {
615 + emitPaste()
616 + }
617 +
618 + private var canPaste: Bool {
619 + !readOnly && UIPasteboard.general.hasStrings
620 + }
621 +
622 @objc
623 private func handleInputEditingDidBegin() {
624 // A composition abandoned by losing focus must not reach the PTY with the next keystroke.
@@ -528,9 +643,15 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
643 defer { isCreatingSurface = false }
644
645 var runtimeConfig = ghostty_runtime_config_s(
531 - userdata: Unmanaged.passUnretained(self).toOpaque(),
646 + userdata: Unmanaged.passUnretained(callbackRef).toOpaque(),
647 supports_selection_clipboard: false,
533 - wakeup_cb: { _ in },
648 + // The io thread queues app messages (titles, bells) in a bounded mailbox. Unless the main
649 + // thread drains it, the io thread blocks and the next feed or surface free hangs the app.
650 + wakeup_cb: { userdata in
651 + guard let userdata else { return }
652 + let ref = Unmanaged<TerminalViewRef>.fromOpaque(userdata).takeUnretainedValue()
653 + DispatchQueue.main.async { ref.view?.tickApp() }
654 + },
655 action_cb: { _, _, _ in false },
656 read_clipboard_cb: { _, _, _, _, _, _ in GHOSTTY_CLIPBOARD_READ_UNSUPPORTED },
657 confirm_read_clipboard_cb: { _, _, _, _ in },
@@ -589,12 +710,9 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
710 setNeedsLayout()
711 }
712
592 - private func refreshSurface() {
593 - resetSurface()
594 - createSurfaceIfPossible()
595 - }
596 -
713 private func destroySurface() {
714 + // Unblock the io thread before ghostty_surface_free joins it.
715 + tickApp()
716 if let surface {
717 ghostty_surface_set_write_callback(surface, nil, nil)
718 ghostty_surface_free(surface)
@@ -619,6 +737,11 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
737 applyRemoteBuffer(initialBuffer)
738 }
739
740 + private func tickApp() {
741 + guard let app else { return }
742 + ghostty_app_tick(app)
743 + }
744 +
745 private func applyRemoteBuffer(_ buffer: String) {
746 guard streamedOutput == nil else { return }
747 guard surface != nil else {
@@ -649,7 +772,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
772 output.write(bytes, reset: reset)
773 streamedOutput = output
774 if reset {
652 - refreshSurface()
775 + resetSurface()
776 } else if surface == nil {
777 createSurfaceIfPossible()
778 } else {
@@ -666,6 +789,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
789 private func feedData(_ data: Data) {
790 guard let surface, !data.isEmpty else { return }
791
792 + tickApp()
793 data.withUnsafeBytes { buffer in
794 guard let pointer = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
795 return
@@ -679,15 +803,15 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
803 private func setupWriteCallback() {
804 guard let surface else { return }
805
682 - let userdata = Unmanaged.passUnretained(self).toOpaque()
806 + let userdata = Unmanaged.passUnretained(callbackRef).toOpaque()
807 ghostty_surface_set_write_callback(surface, { userdata, data, len in
808 guard let userdata, let data, len > 0 else { return }
685 - let view = Unmanaged<T3TerminalView>.fromOpaque(userdata).takeUnretainedValue()
809 + let ref = Unmanaged<TerminalViewRef>.fromOpaque(userdata).takeUnretainedValue()
810 let bytes = Data(bytes: data, count: len)
811 guard let input = String(data: bytes, encoding: .utf8), !input.isEmpty else { return }
812
813 DispatchQueue.main.async {
690 - view.emitInput(input)
814 + ref.view?.emitInput(input)
815 }
816 }, userdata)
817 }
@@ -776,6 +900,11 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
900 onInput(["data": data])
901 }
902
903 + private func emitPaste() {
904 + guard let text = UIPasteboard.general.string, !text.isEmpty else { return }
905 + onPaste(["text": text])
906 + }
907 +
908 private func textInputModeDidChange() {
909 guard let app else { return }
910 ghostty_app_keyboard_changed(app)
apps/mobile/modules/t3-terminal/ios/TerminalTextSelectionViewController.swift new
+59
@@ -0,0 +1,59 @@
1 +import UIKit
2 +
3 +final class TerminalTextSelectionViewController: UIViewController {
4 + private let text: String
5 + private let fontSize: CGFloat
6 +
7 + init(text: String, fontSize: CGFloat) {
8 + self.text = text
9 + self.fontSize = fontSize
10 + super.init(nibName: nil, bundle: nil)
11 + }
12 +
13 + required init?(coder: NSCoder) {
14 + return nil
15 + }
16 +
17 + override func viewDidLoad() {
18 + super.viewDidLoad()
19 + title = "Terminal text"
20 + view.backgroundColor = .systemBackground
21 +
22 + navigationItem.leftBarButtonItem = UIBarButtonItem(
23 + title: "Copy All", style: .plain, target: self, action: #selector(copyAll))
24 + navigationItem.rightBarButtonItem = UIBarButtonItem(
25 + barButtonSystemItem: .done, target: self, action: #selector(close))
26 +
27 + let textView = UITextView()
28 + textView.text = text
29 + textView.font = .monospacedSystemFont(ofSize: max(fontSize, 14), weight: .regular)
30 + textView.textColor = .label
31 + textView.backgroundColor = .systemBackground
32 + textView.isEditable = false
33 + textView.isSelectable = true
34 + // Login flows print auth URLs; tapping one opens it.
35 + textView.dataDetectorTypes = .link
36 + textView.accessibilityLabel = "Terminal output"
37 + textView.textContainerInset = UIEdgeInsets(top: 16, left: 12, bottom: 16, right: 12)
38 + textView.translatesAutoresizingMaskIntoConstraints = false
39 + view.addSubview(textView)
40 +
41 + NSLayoutConstraint.activate([
42 + textView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
43 + textView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
44 + textView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
45 + textView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
46 + ])
47 + }
48 +
49 + @objc
50 + private func copyAll() {
51 + UIPasteboard.general.string = text
52 + close()
53 + }
54 +
55 + @objc
56 + private func close() {
57 + dismiss(animated: !UIAccessibility.isReduceMotionEnabled)
58 + }
59 +}
apps/mobile/src/components/ui/AppSymbol.android.tsx
+2
@@ -45,6 +45,7 @@ import IconMoodPlus from "@tabler/icons-react-native/IconMoodPlus";
45 import IconTag from "@tabler/icons-react-native/IconTag";
46 import IconTicket from "@tabler/icons-react-native/IconTicket";
47 import IconClock from "@tabler/icons-react-native/IconClock";
48 +import IconClipboard from "@tabler/icons-react-native/IconClipboard";
49 import IconCode from "@tabler/icons-react-native/IconCode";
50 import IconCopy from "@tabler/icons-react-native/IconCopy";
51 import IconDatabase from "@tabler/icons-react-native/IconDatabase";
@@ -310,6 +311,7 @@ const ANDROID_ICON_BY_MATERIAL_NAME = {
311 close: IconX,
312 construction: IconHammer,
313 content_copy: IconCopy,
314 + content_paste: IconClipboard,
315 desktop_windows: IconDeviceDesktop,
316 edit: IconEdit,
317 error: IconAlertCircle,
apps/mobile/src/components/ui/Sheet.tsx
+2 -1
@@ -33,7 +33,8 @@ export function Sheet(props: SheetProps) {
33 onDismiss={props.onClose}
34 onNativeDismiss={props.onClose}
35 >
36 - <View collapsable={false} className="flex-1 bg-sheet">
36 + {/* Flex children are not bounded by the FormSheet host, so pin to its edges. */}
37 + <View collapsable={false} className="absolute inset-0 bg-sheet">
38 <ScreenStack style={{ flex: 1 }}>
39 <NativeScreen
40 activityState={2}
apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx
+29 -1
@@ -16,9 +16,17 @@ const mocks = vi.hoisted(() => ({
16 mounts: vi.fn(),
17 unmounts: vi.fn(),
18 write: vi.fn(async (_data: string, _reset: boolean) => {}),
19 + paste: (_text: string) => {},
20 }));
21
21 -function RawView({ ref: nativeRef, initialBuffer, onResize }: NativeTerminalSurfaceProps) {
22 +function RawView({ ref: nativeRef, initialBuffer, onResize, onPaste }: NativeTerminalSurfaceProps) {
23 + useLayoutEffect(() => {
24 + mocks.paste = (text) =>
25 + onPaste?.({ nativeEvent: { text } } as NativeSyntheticEvent<{ text: string }>);
26 + return () => {
27 + mocks.paste = () => {};
28 + };
29 + }, [onPaste]);
30 useImperativeHandle(nativeRef, () => ({ writeOutput: mocks.write }));
31 useLayoutEffect(() => {
32 mocks.mounts();
@@ -63,6 +71,7 @@ function setup(revision: number | null) {
71 mocks.write.mockResolvedValue(undefined);
72 mocks.mounts.mockClear();
73 mocks.unmounts.mockClear();
74 + mocks.paste = () => {};
75 const document = { nodeType: 9, addEventListener() {}, removeEventListener() {} };
76 const container = {
77 nodeType: 1,
@@ -81,6 +90,11 @@ function setup(revision: number | null) {
90 async render(
91 state: typeof EMPTY_TERMINAL_BUFFER_STATE,
92 terminalKey = "environment:thread:term-1",
93 + input: {
94 + isRunning?: boolean;
95 + readOnly?: boolean;
96 + onPaste?: (text: string) => void;
97 + } = {},
98 ) {
99 await act(async () => {
100 root.render(
@@ -97,6 +111,7 @@ function setup(revision: number | null) {
111 isRunning
112 onInput={() => {}}
113 onResize={() => {}}
114 + {...input}
115 />,
116 );
117 });
@@ -151,3 +166,16 @@ it.each([null, 1])(
166 }
167 },
168 );
169 +
170 +it("forwards a native paste only while the terminal is writable and running", async () => {
171 + await using harness = setup(1);
172 + const pasted: string[] = [];
173 + const onPaste = (text: string) => pasted.push(text);
174 + await harness.render(EMPTY_TERMINAL_BUFFER_STATE, undefined, { onPaste });
175 + mocks.paste("one\ntwo");
176 + await harness.render(EMPTY_TERMINAL_BUFFER_STATE, undefined, { onPaste, readOnly: true });
177 + mocks.paste("read-only");
178 + await harness.render(EMPTY_TERMINAL_BUFFER_STATE, undefined, { onPaste, isRunning: false });
179 + mocks.paste("exited");
180 + expect(pasted).toEqual(["one\ntwo"]);
181 +});
apps/mobile/src/features/terminal/NativeTerminalSurface.tsx
+4
@@ -58,6 +58,7 @@ interface TerminalSurfaceProps extends ViewProps {
58 readonly onCapture?: (text: string) => void;
59 readonly theme?: TerminalTheme;
60 readonly onInput: (data: string) => void;
61 + readonly onPaste?: (text: string) => void;
62 readonly onResize: (size: { readonly cols: number; readonly rows: number }) => void;
63 }
64
@@ -288,6 +289,9 @@ const ReadyTerminalSurface = memo(function ReadyTerminalSurface({
289 style={{ flex: 1 }}
290 themeConfig={buildGhosttyThemeConfig(theme)}
291 onInput={handleNativeInput}
292 + onPaste={(event) => {
293 + if (props.isRunning && !props.readOnly) props.onPaste?.(event.nativeEvent.text);
294 + }}
295 onResize={handleNativeResize}
296 captureRequest={props.captureRequest}
297 onCapture={(event) => props.onCapture?.(event.nativeEvent.text)}
apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+17 -11
@@ -193,7 +193,6 @@ class TerminalClipboardReadError extends Schema.TaggedError<TerminalClipboardRea
193 type TerminalToolbarAction =
194 | { readonly kind: "send"; readonly key: string; readonly label: string; readonly data: string }
195 | { readonly kind: "clear"; readonly key: string; readonly label: string }
196 - | { readonly kind: "paste"; readonly key: string; readonly label: string }
196 | {
197 readonly kind: "modifier";
198 readonly key: string;
@@ -560,7 +559,6 @@ function ThreadTerminal(props: {
559 { kind: "send", key: "esc", label: "esc", data: "\u001b" },
560 ...modifierActions,
561 { kind: "send", key: "tab", label: "tab", data: "\t" },
563 - { kind: "paste", key: "paste", label: "paste" },
562 { kind: "clear", key: "clear", label: "clear" },
563 { kind: "send", key: "tilde", label: "~", data: "~" },
564 { kind: "send", key: "pipe", label: "|", data: "|" },
@@ -620,9 +618,9 @@ function ThreadTerminal(props: {
618 return result._tag === "Success";
619 };
620
623 - const pasteFromClipboard = async () => {
621 + const pasteText = async (readText: () => Promise<string>) => {
622 await pasteSession.paste({
625 - readText: Clipboard.getStringAsync,
623 + readText,
624 write: writeInput,
625 onReadError: (cause) => {
626 console.error(new TerminalClipboardReadError({ terminalId, cause }));
@@ -643,7 +641,7 @@ function ThreadTerminal(props: {
641 hostPlatform,
642 });
643 if (resolved.kind === "paste") {
646 - void pasteFromClipboard();
644 + void pasteText(Clipboard.getStringAsync);
645 return;
646 }
647 void writeInput(resolved.data);
@@ -756,15 +754,16 @@ function ThreadTerminal(props: {
754 return;
755 }
756
759 - if (action.kind === "paste") {
760 - setPendingModifier(null);
761 - void pasteFromClipboard();
762 - return;
763 - }
764 -
757 writeModifiedInput(action.data);
758 };
759
760 + const handlePaste = (readText: () => Promise<string>) => {
761 + // Pasted text bypasses the native field, so a syllable it holds must not be recomposed.
762 + surfaceRef.current?.resetInput();
763 + setPendingModifier(null);
764 + void pasteText(readText);
765 + };
766 +
767 const handleDismissKeyboard = () => {
768 setAccessory((current) => ({ ...current, dismissed: true }));
769 void KeyboardController.dismiss();
@@ -930,6 +929,7 @@ function ThreadTerminal(props: {
929 Dialog.alert("No terminal output", "There is no visible output to attach.");
930 }}
931 onInput={handleInput}
932 + onPaste={(text) => handlePaste(async () => text)}
933 onResize={handleResize}
934 style={{ flex: 1 }}
935 terminalKey={terminalKey}
@@ -1010,6 +1010,12 @@ function ThreadTerminal(props: {
1010 );
1011 })}
1012 </ComposerToolbarScroller>
1013 + <ComposerToolbarButton
1014 + accessibilityLabel="Paste"
1015 + icon={{ ios: "doc.on.clipboard", android: "content_paste" }}
1016 + onPress={() => handlePaste(Clipboard.getStringAsync)}
1017 + showChevron={false}
1018 + />
1019 <ComposerToolbarButton
1020 accessibilityLabel="Dismiss keyboard"
1021 icon={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
apps/mobile/src/features/terminal/nativeTerminalModule.ts
+6
@@ -16,6 +16,10 @@ interface TerminalInputEvent {
16 readonly data: string;
17 }
18
19 +interface TerminalPasteEvent {
20 + readonly text: string;
21 +}
22 +
23 interface TerminalResizeEvent {
24 readonly cols: number;
25 readonly rows: number;
@@ -39,6 +43,8 @@ export interface NativeTerminalSurfaceProps extends ViewProps {
43 /** `[cols, rows]` of the shared PTY, or empty before the server reports one. */
44 readonly sharedGrid?: ReadonlyArray<number>;
45 readonly onInput?: (event: NativeSyntheticEvent<TerminalInputEvent>) => void;
46 + /** iOS only: clipboard text from a system paste (edit menu, ⌘V, shortcut bar). */
47 + readonly onPaste?: (event: NativeSyntheticEvent<TerminalPasteEvent>) => void;
48 readonly onResize?: (event: NativeSyntheticEvent<TerminalResizeEvent>) => void;
49 }
50
docs/user/terminal.md
+3
@@ -17,6 +17,9 @@ then copy. Cmd+A on macOS and Ctrl+Shift+A elsewhere select the same output.
17 Ctrl+A still moves to the beginning of shell input on Windows and Linux.
18 Jump to latest in the context menu returns to the current output.
19
20 +On iPhone and iPad, long-press the terminal to paste or to choose Select Text.
21 +Select Text shows the visible output, where you can copy text or tap a link.
22 +
23 ## fish
24
25 T3 Code starts fish with `no-query-term`, avoiding startup waits for terminal