diff --git a/ui/src/components/TerminalTab.test.tsx b/ui/src/components/TerminalTab.test.tsx
new file mode 100644
index 0000000..48296d9
--- /dev/null
+++ b/ui/src/components/TerminalTab.test.tsx
@@ -0,0 +1,71 @@
+import { createRef } from 'react'
+import { fireEvent, render, screen, within } from '@testing-library/react'
+import { beforeEach, expect, it, vi } from 'vitest'
+import type { ConnectionStatus } from '../hooks/useTerminalConnection'
+import TerminalTab from './TerminalTab'
+
+const connection = vi.hoisted(() => ({
+ status: 'connected' as ConnectionStatus,
+ connect: vi.fn(),
+ sendShortcut: vi.fn(),
+}))
+vi.mock('../hooks/useTerminalConnection', () => ({
+ useTerminalConnection: () => ({
+ ...connection, containerRef: createRef(), termRef: { current: {} }, errorMsg: '连接已断开',
+ }),
+}))
+vi.mock('../contexts/ThemeContext', () => ({ useTheme: () => ({ mode: 'dark', colors: { colorPrimary: '#1677ff' } }) }))
+const props = { serverId: 1, serverName: 'demo', isActive: true, fontSize: 14 }
+
+beforeEach(() => { connection.status = 'connected'; vi.clearAllMocks() })
+
+it('keeps the shortcut group and toggle together outside the terminal body', () => {
+ const { container } = render()
+ const group = screen.getByRole('group', { name: '终端快捷键' })
+ const toggle = screen.getByRole('button', { name: '隐藏快捷键' })
+ expect(group.parentElement).toBe(toggle.parentElement)
+ expect(group.parentElement).toHaveClass('terminal-tools')
+ expect(container.querySelector('.terminal-body')).not.toHaveAttribute('style')
+ expect(toggle).not.toHaveAttribute('style')
+ expect(within(group).getAllByRole('button')).toHaveLength(16)
+ expect(toggle).toHaveAttribute('aria-expanded', 'true')
+})
+
+it('collapses and restores shortcuts without replacing the terminal host', () => {
+ const { container } = render()
+ const host = container.querySelector('.terminal-container')
+ fireEvent.click(screen.getByRole('button', { name: '隐藏快捷键' }))
+ expect(screen.queryByRole('group', { name: '终端快捷键' })).not.toBeInTheDocument()
+ const toggle = screen.getByRole('button', { name: '显示快捷键' })
+ expect(toggle).toHaveAttribute('aria-expanded', 'false')
+ expect(toggle).toHaveTextContent('快捷键')
+ fireEvent.click(toggle)
+ expect(screen.getByRole('group', { name: '终端快捷键' })).toBeInTheDocument()
+ expect(container.querySelector('.terminal-container')).toBe(host)
+ expect(connection.connect).not.toHaveBeenCalled()
+})
+
+it('preserves control sequences and does not take keyboard focus on mouse down', () => {
+ render()
+ const ctrlC = screen.getByRole('button', { name: 'Ctrl+C' })
+ expect(fireEvent.mouseDown(ctrlC)).toBe(false)
+ fireEvent.click(ctrlC)
+ fireEvent.click(screen.getByRole('button', { name: '↑' }))
+ fireEvent.click(screen.getByRole('button', { name: ':wq' }))
+ expect(connection.sendShortcut.mock.calls).toEqual([['\x03'], ['\x1b[A'], [':wq\r']])
+})
+
+it('removes the entire footer while connecting or disconnected', () => {
+ connection.status = 'connecting'
+ const view = render()
+ expect(view.container.querySelector('.terminal-tools')).toBeNull()
+ connection.status = 'connected'
+ view.rerender()
+ expect(screen.getByRole('button', { name: '隐藏快捷键' })).toBeInTheDocument()
+ connection.status = 'error'
+ view.rerender()
+ expect(view.container.querySelector('.terminal-tools')).toBeNull()
+ expect(screen.getByRole('alert')).toHaveTextContent('连接已断开')
+ fireEvent.click(screen.getByRole('button', { name: /重新连接/ }))
+ expect(connection.connect).toHaveBeenCalledOnce()
+})
diff --git a/ui/src/components/TerminalTab.tsx b/ui/src/components/TerminalTab.tsx
index 83e9a7e..1181c2e 100644
--- a/ui/src/components/TerminalTab.tsx
+++ b/ui/src/components/TerminalTab.tsx
@@ -50,7 +50,7 @@ export default function TerminalTab({ serverId, serverName, isActive, fontSize,
return (
-
+
{status === 'connecting' &&
正在连接 {serverName}…
}
{status === 'error' && termRef.current &&
@@ -65,13 +65,15 @@ export default function TerminalTab({ serverId, serverName, isActive, fontSize,
}
- {showBar && status === 'connected' &&
- {SHORTCUTS.map(shortcut =>
)}
+ {status === 'connected' &&
+ {showBar &&
+ {SHORTCUTS.map(shortcut => )}
+
}
+
}
- {status === 'connected' &&
}
)
}
diff --git a/ui/src/hooks/useTerminalConnection.test.tsx b/ui/src/hooks/useTerminalConnection.test.tsx
index 30a1c18..e2118f4 100644
--- a/ui/src/hooks/useTerminalConnection.test.tsx
+++ b/ui/src/hooks/useTerminalConnection.test.tsx
@@ -81,6 +81,18 @@ describe('terminal connection ownership', () => {
view.unmount()
})
+ it('writes stdout and stderr without overriding the terminal scroll position', () => {
+ const view = render(
)
+ const socket = Socket.instances[0]
+ const terminal = mocks.terminals[0]
+ terminal.scrollToBottom = vi.fn()
+ act(() => { socket.receive(4); socket.receive(0, 'output'); socket.receive(1, 'stderr') })
+ expect(terminal.write.mock.calls.map(([bytes]: [Uint8Array]) => new TextDecoder().decode(bytes))).toEqual(['output', 'stderr'])
+ expect(terminal.scrollToBottom).not.toHaveBeenCalled()
+ expect(terminal.options.scrollback).toBe(5000)
+ view.unmount()
+ })
+
it('detaches old sockets, guards late callbacks and uses current theme/font on manual reconnect', () => {
const view = render(
)
const old = Socket.instances[0]
diff --git a/ui/src/hooks/useTerminalConnection.ts b/ui/src/hooks/useTerminalConnection.ts
index 7801f21..ad421f0 100644
--- a/ui/src/hooks/useTerminalConnection.ts
+++ b/ui/src/hooks/useTerminalConnection.ts
@@ -2,16 +2,11 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { Terminal, type ITheme } from '@xterm/xterm'
import { FitAddon } from '@xterm/addon-fit'
import { WebLinksAddon } from '@xterm/addon-web-links'
+import { attachTerminalTouch } from '../utils/terminalTouch'
export type ConnectionStatus = 'connecting' | 'connected' | 'error'
export const INPUT_CHUNK_BYTES = 16 * 1024
-// 新数据到达时,若光标位于视口底部(用户没有上翻浏览历史)则自动滚到底部
-const autoScrollBottom = (term: Terminal) => {
- const buffer = term.buffer.active
- if (buffer.cursorY === term.rows - 1 || buffer.cursorY === 0) term.scrollToBottom()
-}
-
export function* inputFrames(data: string) {
const bytes = new TextEncoder().encode(data)
for (let offset = 0; offset < bytes.length; offset += INPUT_CHUNK_BYTES) {
@@ -74,6 +69,7 @@ export function useTerminalConnection(serverId: number, fontSize: number, theme:
term.loadAddon(fit)
term.loadAddon(new WebLinksAddon())
term.open(containerRef.current)
+ const disposeTouch = attachTerminalTouch(term)
termRef.current = term
fitRef.current = fit
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'
@@ -134,7 +130,7 @@ export function useTerminalConnection(serverId: number, fontSize: number, theme:
const payload = buffer.subarray(1)
switch (buffer[0]) {
case 0x00:
- case 0x01: term.write(payload); autoScrollBottom(term); break
+ case 0x01: term.write(payload); break
case 0x02: fail(new TextDecoder().decode(payload)); break
case 0x03:
try {
@@ -166,6 +162,7 @@ export function useTerminalConnection(serverId: number, fontSize: number, theme:
observer.disconnect()
dataSubscription.dispose()
resizeSubscription.dispose()
+ disposeTouch()
term.dispose()
queue = []
wsRef.current = null
diff --git a/ui/src/styles/terminal.css b/ui/src/styles/terminal.css
index feac9c8..33eb08f 100644
--- a/ui/src/styles/terminal.css
+++ b/ui/src/styles/terminal.css
@@ -1,7 +1,7 @@
.terminal-session { height: 100%; width: 100%; display: flex; flex-direction: column; position: relative; }
-.terminal-body { flex: 1; min-height: 0; position: relative; }
-.terminal-container { width: 100%; height: 100%; padding: 10px 12px; background: var(--bg-terminal, #1a1a2e); touch-action: manipulation; }
-.terminal-container .xterm { height: 100%; overflow: auto; -webkit-overflow-scrolling: touch; }
+.terminal-body { flex: 1; min-height: 0; min-width: 0; position: relative; }
+/* FitAddon measures this host's full size, so keep the inset outside its content box. */
+.terminal-container { position: absolute; inset: 10px 12px; background: var(--bg-terminal, #1a1a2e); touch-action: manipulation; }
.terminal-overlay { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 10px; padding: 24px; background: var(--bg-terminal); color: var(--text-tertiary); font-size: 12px; z-index: 10; }
.terminal-disconnected { position: absolute; bottom: 0; left: 0; right: 0; display: flex; align-items: center; gap: 16px; padding: 12px 16px; max-height: 45%; overflow-y: auto; background: var(--bg-elevated); border-top: 1px solid #ff787540; box-shadow: 0 -4px 20px #0000000a; z-index: 10; }
.terminal-disconnected > span { flex: 1; min-width: 0; color: #f07070; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
@@ -10,18 +10,24 @@
.terminal-error-icon { font-size: 30px; color: #f07070; margin-bottom: 20px; }
.terminal-error-card p { color: var(--text-secondary); font-size: 13px; line-height: 1.8; }
.terminal-error-card small { display: block; color: var(--text-tertiary); margin: 8px 0 20px; }
-.mobile-shortcut-bar { position: absolute; bottom: 0; left: 0; right: 0; display: flex; flex-wrap: wrap; align-items: center; align-content: flex-start; gap: 5px; padding: 6px 10px; min-height: 44px; max-height: 88px; overflow-y: auto; background: var(--bg-tab-bar); border-top: 1px solid var(--border-subtle); scrollbar-width: none; z-index: 15; }
+.terminal-tools { --shortcut-height: 29px; --shortcut-gap: 5px; display: flex; align-items: flex-start; flex-shrink: 0; gap: 10px; padding: 6px 10px; background: var(--bg-tab-bar); border-top: 1px solid var(--border-subtle); }
+.mobile-shortcut-bar { display: flex; flex: 1; min-width: 0; flex-wrap: wrap; align-items: center; gap: var(--shortcut-gap); max-height: calc(var(--shortcut-height) * 2 + var(--shortcut-gap)); overflow-y: auto; overscroll-behavior: contain; scrollbar-width: none; -webkit-overflow-scrolling: touch; }
.mobile-shortcut-bar::-webkit-scrollbar { display: none; }
-.terminal-shortcut { flex-shrink: 0; display: inline-flex; align-items: center; justify-content: center; padding: 4px 10px; min-width: 34px; height: 29px; border: 1px solid var(--border-subtle); border-radius: 5px; background: var(--fill-subtle); color: var(--text-secondary); font: 11px var(--font-mono); cursor: pointer; user-select: none; -webkit-tap-highlight-color: transparent; transition: background 120ms, border-color 120ms; box-shadow: 0 1px 0 #00000018; }
+.terminal-shortcut { flex-shrink: 0; display: inline-flex; align-items: center; justify-content: center; padding: 4px 10px; min-width: 34px; height: var(--shortcut-height); border: 1px solid var(--border-subtle); border-radius: 5px; background: var(--fill-subtle); color: var(--text-secondary); font: 11px var(--font-mono); cursor: pointer; user-select: none; -webkit-tap-highlight-color: transparent; touch-action: manipulation; transition: background 120ms, border-color 120ms; box-shadow: 0 1px 0 #00000018; }
.terminal-shortcut:hover { background: var(--fill-hover); border-color: var(--accent-border); }
.terminal-shortcut:active { background: var(--accent-soft); color: var(--color-primary); }
-.shortcut-toggle { position: absolute; right: 12px; display: flex; align-items: center; justify-content: center; width: 30px; height: 28px; border-radius: 6px; border: 1px solid var(--border-subtle); background: var(--bg-tab-bar); color: var(--text-tertiary); font-size: 15px; z-index: 20; cursor: pointer; box-shadow: 0 2px 8px #00000015; }
-.shortcut-toggle[aria-pressed='true'] { color: var(--color-primary); }
+.shortcut-toggle { display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; gap: 6px; min-width: 30px; height: var(--shortcut-height); margin-left: auto; padding: 0 7px; border-radius: 6px; border: 1px solid var(--border-subtle); background: var(--fill-subtle); color: var(--text-tertiary); font-size: 15px; cursor: pointer; touch-action: manipulation; }
+.shortcut-toggle span:not(.anticon) { font: 11px var(--font-ui); }
+.shortcut-toggle[aria-expanded='true'] { color: var(--color-primary); }
.shortcut-toggle:hover { border-color: var(--accent-border); }
[data-theme='light'] .terminal-disconnected > span { color: #b73442; }
+@media (pointer: coarse) {
+ .terminal-tools { --shortcut-height: 40px; --shortcut-gap: 6px; }
+ .terminal-shortcut, .shortcut-toggle { min-width: 40px; }
+}
@media (max-width: 767px) {
- .terminal-container { padding: 8px; }
+ .terminal-container { inset: 8px; }
.terminal-disconnected { flex-wrap: wrap; gap: 8px; padding: 10px 12px; max-height: 50%; }
.terminal-disconnected > span { flex-basis: 100%; }
- .mobile-shortcut-bar { padding-left: 8px; padding-right: 8px; }
+ .terminal-tools { padding-left: 8px; padding-right: 8px; }
}
diff --git a/ui/src/utils/terminalTouch.test.ts b/ui/src/utils/terminalTouch.test.ts
new file mode 100644
index 0000000..f7b1b06
--- /dev/null
+++ b/ui/src/utils/terminalTouch.test.ts
@@ -0,0 +1,74 @@
+import type { Terminal } from '@xterm/xterm'
+import { beforeEach, expect, it, vi } from 'vitest'
+import { attachTerminalTouch } from './terminalTouch'
+
+let element: HTMLDivElement
+let terminal: { element: HTMLDivElement; rows: number; buffer: { active: { type: string } }; scrollLines: ReturnType
}
+const touch = (y: number, x = 20, identifier = 1) => ({ clientX: x, clientY: y, identifier })
+function dispatch(type: string, touches: ReturnType[], target: HTMLElement = element) {
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ Object.defineProperty(event, 'touches', { value: touches })
+ target.dispatchEvent(event)
+ return event
+}
+beforeEach(() => {
+ element = document.createElement('div')
+ element.getBoundingClientRect = () => ({ height: 200 }) as DOMRect
+ terminal = { element, rows: 10, buffer: { active: { type: 'normal' } }, scrollLines: vi.fn() }
+})
+
+it('maps vertical dragging to terminal rows and accumulates fractional movement', () => {
+ const dispose = attachTerminalTouch(terminal as unknown as Terminal)
+ dispatch('touchstart', [touch(100)])
+ expect(dispatch('touchmove', [touch(109)]).defaultPrevented).toBe(true)
+ expect(terminal.scrollLines).not.toHaveBeenCalled()
+ dispatch('touchmove', [touch(129)])
+ dispatch('touchmove', [touch(145)])
+ dispatch('touchmove', [touch(115)])
+ expect(terminal.scrollLines.mock.calls).toEqual([[-1], [-1], [2]])
+ dispose()
+})
+
+it('leaves taps, horizontal swipes and multi-touch gestures alone', () => {
+ const dispose = attachTerminalTouch(terminal as unknown as Terminal)
+ dispatch('touchstart', [touch(100)])
+ expect(dispatch('touchmove', [touch(103)]).defaultPrevented).toBe(false)
+ expect(dispatch('touchmove', [touch(110, 100)]).defaultPrevented).toBe(false)
+ expect(dispatch('touchmove', [touch(140), touch(140, 40, 2)]).defaultPrevented).toBe(false)
+ dispatch('touchmove', [touch(160)])
+ dispatch('touchstart', [touch(100)])
+ dispatch('touchmove', [touch(160, 20, 2)])
+ expect(terminal.scrollLines).not.toHaveBeenCalled()
+ dispose()
+})
+
+it('does not intercept alternate-screen applications or scrollbar controls', () => {
+ const dispose = attachTerminalTouch(terminal as unknown as Terminal)
+ terminal.buffer.active.type = 'alternate'
+ dispatch('touchstart', [touch(100)])
+ expect(dispatch('touchmove', [touch(160)]).defaultPrevented).toBe(false)
+ terminal.buffer.active.type = 'normal'
+ const scrollbar = document.createElement('div')
+ scrollbar.className = 'scrollbar'
+ element.append(scrollbar)
+ dispatch('touchstart', [touch(100)], scrollbar)
+ dispatch('touchmove', [touch(160)], scrollbar)
+ expect(terminal.scrollLines).not.toHaveBeenCalled()
+ dispose()
+})
+
+it('ends gestures on cancellation and removes every listener on disposal', () => {
+ const dispose = attachTerminalTouch(terminal as unknown as Terminal)
+ for (const end of ['touchend', 'touchcancel']) {
+ dispatch('touchstart', [touch(100)])
+ dispatch(end, [])
+ dispatch('touchmove', [touch(160)])
+ }
+ expect(terminal.scrollLines).not.toHaveBeenCalled()
+ const remove = vi.spyOn(element, 'removeEventListener')
+ dispose()
+ expect(remove.mock.calls.map(([type]) => type)).toEqual(['touchstart', 'touchmove', 'touchend', 'touchcancel'])
+ dispatch('touchstart', [touch(100)])
+ dispatch('touchmove', [touch(160)])
+ expect(terminal.scrollLines).not.toHaveBeenCalled()
+})
diff --git a/ui/src/utils/terminalTouch.ts b/ui/src/utils/terminalTouch.ts
new file mode 100644
index 0000000..f23bfb9
--- /dev/null
+++ b/ui/src/utils/terminalTouch.ts
@@ -0,0 +1,38 @@
+import type { Terminal } from '@xterm/xterm'
+
+export function attachTerminalTouch(term: Terminal): () => void {
+ const element = term.element
+ if (!element) return () => {}
+ let gesture: { id: number; x: number; y: number; cellHeight: number; lines: number } | undefined
+ const reset = () => { gesture = undefined }
+ const start = (event: TouchEvent) => {
+ reset()
+ if (event.touches.length !== 1 || term.buffer.active.type !== 'normal') return
+ if (event.target instanceof Element && event.target.closest('.scrollbar')) return
+ const cellHeight = element.getBoundingClientRect().height / term.rows
+ if (!cellHeight) return
+ const touch = event.touches[0]
+ gesture = { id: touch.identifier, x: touch.clientX, y: touch.clientY, cellHeight, lines: 0 }
+ }
+ const move = (event: TouchEvent) => {
+ if (!gesture || event.touches.length !== 1 || term.buffer.active.type !== 'normal') { reset(); return }
+ const touch = event.touches[0]
+ if (touch.identifier !== gesture.id) { reset(); return }
+ const deltaY = gesture.y - touch.clientY
+ if (Math.abs(deltaY) < 6 || Math.abs(deltaY) < Math.abs(gesture.x - touch.clientX)) return
+ if (event.cancelable) event.preventDefault()
+ const lines = Math.trunc(deltaY / gesture.cellHeight)
+ if (lines !== gesture.lines) term.scrollLines(lines - gesture.lines)
+ gesture.lines = lines
+ }
+ element.addEventListener('touchstart', start, { passive: true })
+ element.addEventListener('touchmove', move, { passive: false })
+ element.addEventListener('touchend', reset)
+ element.addEventListener('touchcancel', reset)
+ return () => {
+ element.removeEventListener('touchstart', start)
+ element.removeEventListener('touchmove', move)
+ element.removeEventListener('touchend', reset)
+ element.removeEventListener('touchcancel', reset)
+ }
+}