From dc7cd2382f6b5792ebc8acd245e8d25e908c0a6f Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:24:03 -0400 Subject: [PATCH] section 4: Phase 4: Frontend terminal client and xterm view --- frontend/package.json | 3 + frontend/src/api/terminals.ts | 81 +++++++ .../src/components/terminal/TerminalView.tsx | 190 ++++++++++++++++ frontend/src/hooks/useTerminalSocket.test.tsx | 204 ++++++++++++++++++ frontend/src/hooks/useTerminalSocket.ts | 135 ++++++++++++ frontend/src/lib/terminal-protocol.test.ts | 47 ++++ frontend/src/lib/terminal-protocol.ts | 54 +++++ frontend/src/lib/terminal-theme.ts | 70 ++++++ frontend/src/lib/websocket-url.test.ts | 40 ++++ frontend/src/lib/websocket-url.ts | 8 + pnpm-lock.yaml | 24 +++ 11 files changed, 856 insertions(+) create mode 100644 frontend/src/api/terminals.ts create mode 100644 frontend/src/components/terminal/TerminalView.tsx create mode 100644 frontend/src/hooks/useTerminalSocket.test.tsx create mode 100644 frontend/src/hooks/useTerminalSocket.ts create mode 100644 frontend/src/lib/terminal-protocol.test.ts create mode 100644 frontend/src/lib/terminal-protocol.ts create mode 100644 frontend/src/lib/terminal-theme.ts create mode 100644 frontend/src/lib/websocket-url.test.ts create mode 100644 frontend/src/lib/websocket-url.ts diff --git a/frontend/package.json b/frontend/package.json index 58a65cc4..ed03830f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -29,6 +29,9 @@ "@radix-ui/react-tabs": "^1.1.13", "@tailwindcss/vite": "^4.1.14", "@tanstack/react-query": "^5.90.5", + "@xterm/addon-fit": "^0.11.0", + "@xterm/addon-web-links": "^0.12.0", + "@xterm/xterm": "^6.0.0", "better-auth": "^1.4.17", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", diff --git a/frontend/src/api/terminals.ts b/frontend/src/api/terminals.ts new file mode 100644 index 00000000..ffa31bef --- /dev/null +++ b/frontend/src/api/terminals.ts @@ -0,0 +1,81 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import type { CreateTerminalRequest, ResizeTerminalRequest, TerminalInfo } from '@opencode-manager/shared/types' +import { API_BASE_URL } from '@/config' +import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper' + +function directoryQuery(directory: string | undefined): string { + return directory ? `?${new URLSearchParams({ directory }).toString()}` : '' +} + +export function terminalsQueryKey(repoId: number, directory: string | undefined) { + return ['terminals', repoId, directory ?? null] as const +} + +export async function listTerminals(repoId: number, directory?: string): Promise { + const data = await fetchWrapper<{ terminals: TerminalInfo[] }>( + `${API_BASE_URL}/api/repos/${repoId}/terminals${directoryQuery(directory)}`, + ) + return data.terminals +} + +export async function createTerminal(repoId: number, body: CreateTerminalRequest): Promise { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/terminals`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }) +} + +export async function resizeTerminal(repoId: number, ptyID: string, body: ResizeTerminalRequest): Promise { + return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }) +} + +export async function removeTerminal(repoId: number, ptyID: string, directory?: string): Promise { + return fetchWrapperVoid( + `${API_BASE_URL}/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}${directoryQuery(directory)}`, + { method: 'DELETE' }, + ) +} + +export interface UseTerminalsOptions { + enabled: boolean + refetchInterval?: number | false +} + +export function useTerminals(repoId: number, directory: string | undefined, options: UseTerminalsOptions) { + return useQuery({ + queryKey: terminalsQueryKey(repoId, directory), + queryFn: () => listTerminals(repoId, directory), + enabled: options.enabled, + refetchInterval: options.refetchInterval, + }) +} + +export function useCreateTerminal(repoId: number) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (body: CreateTerminalRequest) => createTerminal(repoId, body), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['terminals', repoId] }) + }, + }) +} + +export interface RemoveTerminalVariables { + ptyID: string + directory?: string +} + +export function useRemoveTerminal(repoId: number) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: ({ ptyID, directory }: RemoveTerminalVariables) => removeTerminal(repoId, ptyID, directory), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['terminals', repoId] }) + }, + }) +} diff --git a/frontend/src/components/terminal/TerminalView.tsx b/frontend/src/components/terminal/TerminalView.tsx new file mode 100644 index 00000000..62892053 --- /dev/null +++ b/frontend/src/components/terminal/TerminalView.tsx @@ -0,0 +1,190 @@ +import { useCallback, useEffect, useRef } from 'react' +import { Terminal } from '@xterm/xterm' +import { FitAddon } from '@xterm/addon-fit' +import { WebLinksAddon } from '@xterm/addon-web-links' +import '@xterm/xterm/css/xterm.css' +import { resizeTerminal } from '@/api/terminals' +import { applyCtrlModifier } from '@/lib/terminal-protocol' +import { resolveTerminalTheme } from '@/lib/terminal-theme' +import { useTerminalSocket } from '@/hooks/useTerminalSocket' +import { useMobile } from '@/hooks/useMobile' +import { cn } from '@/lib/utils' + +const RESIZE_DEBOUNCE_MS = 150 + +const MONOSPACE_FONT = 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace' + +function defaultOpenLink(uri: string) { + window.open(uri, '_blank', 'noopener,noreferrer') +} + +export interface TerminalViewProps { + repoId: number + directory: string | undefined + ptyID: string + active: boolean + ctrlArmed: boolean + onCtrlConsumed: () => void + onOpenLink?: (uri: string) => void + onExited: () => void +} + +export function TerminalView({ + repoId, + directory, + ptyID, + active, + ctrlArmed, + onCtrlConsumed, + onOpenLink, + onExited, +}: TerminalViewProps) { + const containerRef = useRef(null) + const terminalRef = useRef(null) + const fitAddonRef = useRef(null) + const sendRef = useRef<(data: string) => void>(() => {}) + const ctrlArmedRef = useRef(ctrlArmed) + const onCtrlConsumedRef = useRef(onCtrlConsumed) + const onOpenLinkRef = useRef(onOpenLink) + const onExitedRef = useRef(onExited) + const isMobile = useMobile() + const isMobileRef = useRef(isMobile) + + ctrlArmedRef.current = ctrlArmed + onCtrlConsumedRef.current = onCtrlConsumed + onOpenLinkRef.current = onOpenLink + onExitedRef.current = onExited + isMobileRef.current = isMobile + + const handleOutput = useCallback((text: string) => { + terminalRef.current?.write(text) + }, []) + + const handleExit = useCallback(() => { + terminalRef.current?.write('\r\n[process exited]\r\n') + onExitedRef.current() + }, []) + + const { send } = useTerminalSocket({ + repoId, + directory, + ptyID, + onOutput: handleOutput, + onExit: handleExit, + enabled: true, + }) + sendRef.current = send + + useEffect(() => { + const container = containerRef.current + if (!container) return + + const terminal = new Terminal({ + cursorBlink: true, + scrollback: 5000, + fontFamily: MONOSPACE_FONT, + fontSize: isMobileRef.current ? 12 : 13, + theme: resolveTerminalTheme(document.documentElement), + }) + const fitAddon = new FitAddon() + terminal.loadAddon(fitAddon) + terminal.loadAddon( + new WebLinksAddon((_event, uri) => { + const openLink = onOpenLinkRef.current ?? defaultOpenLink + openLink(uri) + }), + ) + terminal.open(container) + + terminalRef.current = terminal + fitAddonRef.current = fitAddon + + const dataDisposable = terminal.onData((data) => { + if (ctrlArmedRef.current) { + sendRef.current(applyCtrlModifier(data)) + onCtrlConsumedRef.current() + return + } + sendRef.current(data) + }) + + return () => { + dataDisposable.dispose() + terminal.dispose() + terminalRef.current = null + fitAddonRef.current = null + } + }, []) + + useEffect(() => { + const terminal = terminalRef.current + if (!terminal) return + terminal.options.fontSize = isMobile ? 12 : 13 + try { + fitAddonRef.current?.fit() + } catch { + return + } + }, [isMobile]) + + useEffect(() => { + const root = document.documentElement + const applyTheme = () => { + const terminal = terminalRef.current + if (!terminal) return + terminal.options.theme = resolveTerminalTheme(root) + } + const observer = new MutationObserver(applyTheme) + observer.observe(root, { attributes: true, attributeFilter: ['class', 'style'] }) + return () => observer.disconnect() + }, []) + + useEffect(() => { + const container = containerRef.current + if (!container) return + + let timer: ReturnType | null = null + + const scheduleResize = () => { + if (timer) clearTimeout(timer) + timer = setTimeout(() => { + const terminal = terminalRef.current + const fitAddon = fitAddonRef.current + if (!terminal || !fitAddon) return + try { + fitAddon.fit() + } catch { + return + } + resizeTerminal(repoId, ptyID, { directory, cols: terminal.cols, rows: terminal.rows }).catch(() => {}) + }, RESIZE_DEBOUNCE_MS) + } + + const observer = new ResizeObserver(scheduleResize) + observer.observe(container) + scheduleResize() + + return () => { + observer.disconnect() + if (timer) clearTimeout(timer) + } + }, [repoId, directory, ptyID]) + + useEffect(() => { + if (!active) return + try { + fitAddonRef.current?.fit() + } catch { + return + } + terminalRef.current?.focus() + }, [active]) + + return ( +
+ ) +} diff --git a/frontend/src/hooks/useTerminalSocket.test.tsx b/frontend/src/hooks/useTerminalSocket.test.tsx new file mode 100644 index 00000000..3e09c747 --- /dev/null +++ b/frontend/src/hooks/useTerminalSocket.test.tsx @@ -0,0 +1,204 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, renderHook } from '@testing-library/react' +import { useTerminalSocket } from './useTerminalSocket' + +class FakeWebSocket { + static CONNECTING = 0 + static OPEN = 1 + static CLOSING = 2 + static CLOSED = 3 + static instances: FakeWebSocket[] = [] + + url: string + binaryType = 'blob' + readyState = FakeWebSocket.CONNECTING + sent: string[] = [] + onopen: ((event: Event) => void) | null = null + onmessage: ((event: MessageEvent) => void) | null = null + onclose: ((event: CloseEvent) => void) | null = null + onerror: ((event: Event) => void) | null = null + + constructor(url: string) { + this.url = url + FakeWebSocket.instances.push(this) + } + + send(data: string) { + this.sent.push(data) + } + + close() { + this.readyState = FakeWebSocket.CLOSED + } + + open() { + this.readyState = FakeWebSocket.OPEN + this.onopen?.(new Event('open')) + } + + message(data: string | ArrayBuffer) { + this.onmessage?.({ data } as MessageEvent) + } + + serverClose(code: number) { + this.readyState = FakeWebSocket.CLOSED + this.onclose?.({ code } as CloseEvent) + } +} + +function metaFrame(cursor: number): ArrayBuffer { + const payload = new TextEncoder().encode(JSON.stringify({ cursor })) + const bytes = new Uint8Array(payload.length + 1) + bytes[0] = 0x00 + bytes.set(payload, 1) + return bytes.buffer +} + +function renderSocket(overrides: Partial[0]> = {}) { + return renderHook(() => + useTerminalSocket({ + repoId: 1, + directory: '/work/repo', + ptyID: 'pty-1', + onOutput: vi.fn(), + onExit: vi.fn(), + enabled: true, + ...overrides, + }), + ) +} + +describe('useTerminalSocket', () => { + beforeEach(() => { + FakeWebSocket.instances = [] + vi.stubGlobal('WebSocket', FakeWebSocket) + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + }) + + it('includes the directory in the connection url', () => { + renderSocket() + const url = new URL(FakeWebSocket.instances[0].url) + expect(url.pathname).toBe('/api/repos/1/terminals/pty-1/connect') + expect(url.searchParams.get('directory')).toBe('/work/repo') + }) + + it('accumulates the cursor and sends it when reconnecting after 1006', () => { + renderSocket() + const first = FakeWebSocket.instances[0] + + act(() => { + first.open() + first.message(metaFrame(5)) + first.message('abc') + }) + + act(() => { + first.serverClose(1006) + }) + + expect(FakeWebSocket.instances).toHaveLength(1) + act(() => { + vi.advanceTimersByTime(1000) + }) + + expect(FakeWebSocket.instances).toHaveLength(2) + const second = new URL(FakeWebSocket.instances[1].url) + expect(second.searchParams.get('cursor')).toBe('8') + expect(second.searchParams.get('directory')).toBe('/work/repo') + }) + + it('calls onExit without reconnecting on close code 4404', () => { + const onExit = vi.fn() + renderSocket({ onExit }) + + act(() => { + FakeWebSocket.instances[0].serverClose(4404) + }) + act(() => { + vi.advanceTimersByTime(60000) + }) + + expect(onExit).toHaveBeenCalledTimes(1) + expect(FakeWebSocket.instances).toHaveLength(1) + }) + + it('exhausts the retry budget when upstream connections keep failing after open', () => { + const { result } = renderSocket() + const delays = [1000, 2000, 5000, 5000, 5000] + + for (const delay of delays) { + const socket = FakeWebSocket.instances[FakeWebSocket.instances.length - 1] + act(() => { + socket.open() + socket.serverClose(1011) + }) + expect(result.current.status).toBe('reconnecting') + act(() => { + vi.advanceTimersByTime(delay) + }) + } + + const finalSocket = FakeWebSocket.instances[FakeWebSocket.instances.length - 1] + act(() => { + finalSocket.open() + finalSocket.serverClose(1011) + }) + + expect(result.current.status).toBe('closed') + expect(FakeWebSocket.instances).toHaveLength(6) + + act(() => { + vi.advanceTimersByTime(60000) + }) + expect(FakeWebSocket.instances).toHaveLength(6) + }) + + it('resets the retry budget only after a healthy upstream session', () => { + const { result } = renderSocket() + + act(() => { + FakeWebSocket.instances[0].open() + FakeWebSocket.instances[0].message(metaFrame(0)) + FakeWebSocket.instances[0].serverClose(1011) + }) + act(() => { + vi.advanceTimersByTime(1000) + }) + + expect(FakeWebSocket.instances).toHaveLength(2) + act(() => { + FakeWebSocket.instances[1].open() + FakeWebSocket.instances[1].serverClose(1011) + }) + expect(result.current.status).toBe('reconnecting') + act(() => { + vi.advanceTimersByTime(2000) + }) + + expect(FakeWebSocket.instances).toHaveLength(3) + }) + + it('forwards send to the open socket', () => { + const { result } = renderSocket() + const socket = FakeWebSocket.instances[0] + + act(() => { + socket.open() + }) + act(() => { + result.current.send('ls\n') + }) + + expect(socket.sent).toContain('ls\n') + }) + + it('does not connect when disabled', () => { + renderSocket({ enabled: false }) + expect(FakeWebSocket.instances).toHaveLength(0) + }) +}) diff --git a/frontend/src/hooks/useTerminalSocket.ts b/frontend/src/hooks/useTerminalSocket.ts new file mode 100644 index 00000000..5cf39a8d --- /dev/null +++ b/frontend/src/hooks/useTerminalSocket.ts @@ -0,0 +1,135 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { TerminalFrameDecoder } from '@/lib/terminal-protocol' +import { toWebSocketUrl } from '@/lib/websocket-url' + +export type TerminalSocketStatus = 'connecting' | 'open' | 'reconnecting' | 'closed' + +export interface UseTerminalSocketOptions { + repoId: number + directory: string | undefined + ptyID: string + onOutput: (text: string) => void + onExit: () => void + enabled: boolean +} + +const RECONNECT_DELAYS_MS = [1000, 2000, 5000, 5000, 5000] +const TERMINAL_CLOSE_CODES = new Set([1000, 4404]) + +function buildSocketUrl( + repoId: number, + ptyID: string, + directory: string | undefined, + cursor: number | undefined, +): string { + const params = new URLSearchParams() + if (directory !== undefined) params.set('directory', directory) + if (cursor !== undefined) params.set('cursor', String(cursor)) + const query = params.toString() + return toWebSocketUrl( + `/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}/connect${query ? `?${query}` : ''}`, + ) +} + +export function useTerminalSocket({ + repoId, + directory, + ptyID, + onOutput, + onExit, + enabled, +}: UseTerminalSocketOptions) { + const socketRef = useRef(null) + const cursorRef = useRef(undefined) + const onOutputRef = useRef(onOutput) + const onExitRef = useRef(onExit) + onOutputRef.current = onOutput + onExitRef.current = onExit + + const [status, setStatus] = useState(enabled ? 'connecting' : 'closed') + + const send = useCallback((data: string) => { + const socket = socketRef.current + if (socket && socket.readyState === WebSocket.OPEN) { + socket.send(data) + } + }, []) + + useEffect(() => { + if (!enabled) { + setStatus('closed') + return + } + + let disposed = false + let attempt = 0 + let reconnectTimer: ReturnType | null = null + const decoder = new TerminalFrameDecoder() + cursorRef.current = undefined + + const connect = () => { + if (disposed) return + setStatus(attempt === 0 ? 'connecting' : 'reconnecting') + + const socket = new WebSocket(buildSocketUrl(repoId, ptyID, directory, cursorRef.current)) + socket.binaryType = 'arraybuffer' + socketRef.current = socket + + socket.onopen = () => { + if (disposed || socketRef.current !== socket) return + setStatus('open') + } + + socket.onmessage = (event) => { + if (disposed || socketRef.current !== socket) return + const frame = decoder.decode(event.data as string | ArrayBuffer) + if (frame.type === 'cursor') { + attempt = 0 + cursorRef.current = frame.cursor + return + } + cursorRef.current = (cursorRef.current ?? 0) + frame.text.length + onOutputRef.current(frame.text) + } + + socket.onclose = (event) => { + if (disposed || socketRef.current !== socket) return + socketRef.current = null + + if (TERMINAL_CLOSE_CODES.has(event.code)) { + setStatus('closed') + onExitRef.current() + return + } + + if (attempt >= RECONNECT_DELAYS_MS.length) { + setStatus('closed') + return + } + + const delay = RECONNECT_DELAYS_MS[attempt] + attempt += 1 + setStatus('reconnecting') + reconnectTimer = setTimeout(connect, delay) + } + } + + connect() + + return () => { + disposed = true + if (reconnectTimer) clearTimeout(reconnectTimer) + const socket = socketRef.current + socketRef.current = null + if (socket) { + socket.onopen = null + socket.onmessage = null + socket.onclose = null + socket.onerror = null + socket.close() + } + } + }, [repoId, directory, ptyID, enabled]) + + return { send, status } +} diff --git a/frontend/src/lib/terminal-protocol.test.ts b/frontend/src/lib/terminal-protocol.test.ts new file mode 100644 index 00000000..a23d25ee --- /dev/null +++ b/frontend/src/lib/terminal-protocol.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' +import { TerminalFrameDecoder, applyCtrlModifier } from './terminal-protocol' + +function metaFrame(cursor: number): ArrayBuffer { + const payload = new TextEncoder().encode(JSON.stringify({ cursor })) + const bytes = new Uint8Array(payload.length + 1) + bytes[0] = 0x00 + bytes.set(payload, 1) + return bytes.buffer +} + +describe('TerminalFrameDecoder', () => { + it('decodes the meta frame into a cursor', () => { + const decoder = new TerminalFrameDecoder() + expect(decoder.decode(metaFrame(42))).toEqual({ type: 'cursor', cursor: 42 }) + }) + + it('decodes split multibyte UTF-8 across binary frames', () => { + const decoder = new TerminalFrameDecoder() + const encoded = new TextEncoder().encode('→') + const first = encoded.slice(0, 1) + const second = encoded.slice(1) + + expect(decoder.decode(first.buffer)).toEqual({ type: 'output', text: '' }) + expect(decoder.decode(second.buffer)).toEqual({ type: 'output', text: '→' }) + }) + + it('passes string frames through', () => { + const decoder = new TerminalFrameDecoder() + expect(decoder.decode('plain text')).toEqual({ type: 'output', text: 'plain text' }) + }) +}) + +describe('applyCtrlModifier', () => { + it('maps a letter to its control code', () => { + expect(applyCtrlModifier('c')).toBe('\x03') + }) + + it('maps a control symbol to its control code', () => { + expect(applyCtrlModifier('[')).toBe('\x1b') + }) + + it('returns non-letter input unchanged', () => { + expect(applyCtrlModifier('1')).toBe('1') + expect(applyCtrlModifier('ab')).toBe('ab') + }) +}) diff --git a/frontend/src/lib/terminal-protocol.ts b/frontend/src/lib/terminal-protocol.ts new file mode 100644 index 00000000..f2cb7f39 --- /dev/null +++ b/frontend/src/lib/terminal-protocol.ts @@ -0,0 +1,54 @@ +const META_FRAME_PREFIX = 0x00 + +const CTRL_SYMBOLS: Record = { + '@': '\x00', + '[': '\x1b', + '\\': '\x1c', + ']': '\x1d', + '^': '\x1e', + '_': '\x1f', +} + +export type TerminalFrame = + | { type: 'output'; text: string } + | { type: 'cursor'; cursor: number } + +export class TerminalFrameDecoder { + private readonly decoder = new TextDecoder('utf-8') + + decode(data: string | ArrayBuffer): TerminalFrame { + if (typeof data === 'string') { + return { type: 'output', text: data } + } + + const bytes = new Uint8Array(data) + if (bytes.length > 0 && bytes[0] === META_FRAME_PREFIX) { + return this.decodeMetaFrame(bytes.subarray(1)) + } + + return { type: 'output', text: this.decoder.decode(bytes, { stream: true }) } + } + + private decodeMetaFrame(payload: Uint8Array): TerminalFrame { + try { + const parsed = JSON.parse(new TextDecoder('utf-8').decode(payload)) as { cursor?: unknown } + if (typeof parsed.cursor === 'number' && Number.isSafeInteger(parsed.cursor)) { + return { type: 'cursor', cursor: parsed.cursor } + } + } catch { + return { type: 'output', text: '' } + } + return { type: 'output', text: '' } + } +} + +export function applyCtrlModifier(data: string): string { + if (data.length !== 1) return data + + const upper = data.toUpperCase() + if (upper >= 'A' && upper <= 'Z') { + return String.fromCharCode(upper.charCodeAt(0) - 64) + } + + return CTRL_SYMBOLS[data] ?? data +} diff --git a/frontend/src/lib/terminal-theme.ts b/frontend/src/lib/terminal-theme.ts new file mode 100644 index 00000000..914226e6 --- /dev/null +++ b/frontend/src/lib/terminal-theme.ts @@ -0,0 +1,70 @@ +import type { ITheme } from '@xterm/xterm' + +const BASE_TOKENS = { + background: 'background', + foreground: 'foreground', + cursor: 'primary', + selectionBackground: 'accent', +} as const + +const ANSI_TOKENS = { + black: 'muted', + red: 'destructive', + green: 'success', + yellow: 'warning', + blue: 'info', + magenta: 'highlight', + cyan: 'syntax-property', + white: 'foreground', +} as const + +type AnsiName = keyof typeof ANSI_TOKENS + +function collectTokenColors(root: HTMLElement): Map { + const tokens = new Set([ + ...Object.values(BASE_TOKENS), + ...Object.values(ANSI_TOKENS), + ]) + + const probes = new Map() + for (const token of tokens) { + const probe = document.createElement('span') + probe.style.color = `var(--color-${token})` + probe.style.position = 'absolute' + probe.style.width = '0' + probe.style.height = '0' + probe.style.overflow = 'hidden' + probe.style.opacity = '0' + probe.style.pointerEvents = 'none' + root.appendChild(probe) + probes.set(token, probe) + } + + const colors = new Map() + for (const [token, probe] of probes) { + colors.set(token, getComputedStyle(probe).color) + root.removeChild(probe) + } + return colors +} + +function ansiTheme(colors: Map): Record}`, string | undefined> { + const theme = {} as Record}`, string | undefined> + for (const name of Object.keys(ANSI_TOKENS) as AnsiName[]) { + const color = colors.get(ANSI_TOKENS[name]) + theme[name] = color + theme[`bright${name[0].toUpperCase()}${name.slice(1)}` as `bright${Capitalize}`] = color + } + return theme +} + +export function resolveTerminalTheme(root: HTMLElement): ITheme { + const colors = collectTokenColors(root) + return { + background: colors.get(BASE_TOKENS.background), + foreground: colors.get(BASE_TOKENS.foreground), + cursor: colors.get(BASE_TOKENS.cursor), + selectionBackground: colors.get(BASE_TOKENS.selectionBackground), + ...ansiTheme(colors), + } +} diff --git a/frontend/src/lib/websocket-url.test.ts b/frontend/src/lib/websocket-url.test.ts new file mode 100644 index 00000000..002333c2 --- /dev/null +++ b/frontend/src/lib/websocket-url.test.ts @@ -0,0 +1,40 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { toWebSocketUrl } from './websocket-url' + +const state = vi.hoisted(() => ({ apiBaseUrl: '' })) + +vi.mock('@/config', () => ({ + get API_BASE_URL() { + return state.apiBaseUrl + }, +})) + +describe('toWebSocketUrl', () => { + afterEach(() => { + state.apiBaseUrl = '' + }) + + it('uses the page origin over http when no API base url is configured', () => { + expect(toWebSocketUrl('/api/repos/1/terminals/t/connect')).toBe( + 'ws://localhost/api/repos/1/terminals/t/connect', + ) + }) + + it('uses the page origin over https when no API base url is configured', () => { + const original = window.location + Object.defineProperty(window, 'location', { + configurable: true, + value: new URL('https://example.com'), + }) + try { + expect(toWebSocketUrl('/api/x')).toBe('wss://example.com/api/x') + } finally { + Object.defineProperty(window, 'location', { configurable: true, value: original }) + } + }) + + it('uses an absolute API base url and preserves the query', () => { + state.apiBaseUrl = 'https://api.example.com' + expect(toWebSocketUrl('/api/x?directory=%2Ftmp')).toBe('wss://api.example.com/api/x?directory=%2Ftmp') + }) +}) diff --git a/frontend/src/lib/websocket-url.ts b/frontend/src/lib/websocket-url.ts new file mode 100644 index 00000000..d554c1a9 --- /dev/null +++ b/frontend/src/lib/websocket-url.ts @@ -0,0 +1,8 @@ +import { API_BASE_URL } from '@/config' + +export function toWebSocketUrl(pathWithQuery: string): string { + const base = API_BASE_URL || window.location.origin + const url = new URL(pathWithQuery, base) + url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:' + return url.toString() +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ff3f88c7..294f9a94 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -153,6 +153,15 @@ importers: '@tanstack/react-query': specifier: ^5.90.5 version: 5.90.16(react@19.2.3) + '@xterm/addon-fit': + specifier: ^0.11.0 + version: 0.11.0 + '@xterm/addon-web-links': + specifier: ^0.12.0 + version: 0.12.0 + '@xterm/xterm': + specifier: ^6.0.0 + version: 6.0.0 better-auth: specifier: ^1.4.17 version: 1.4.17(better-sqlite3@12.9.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(solid-js@1.9.15)(vitest@3.2.4) @@ -2541,6 +2550,15 @@ packages: '@vitest/utils@3.2.4': resolution: {integrity: sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==} + '@xterm/addon-fit@0.11.0': + resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==} + + '@xterm/addon-web-links@0.12.0': + resolution: {integrity: sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw==} + + '@xterm/xterm@6.0.0': + resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==} + abbrev@4.0.0: resolution: {integrity: sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==} engines: {node: ^20.17.0 || >=22.9.0} @@ -7945,6 +7963,12 @@ snapshots: loupe: 3.2.1 tinyrainbow: 2.0.0 + '@xterm/addon-fit@0.11.0': {} + + '@xterm/addon-web-links@0.12.0': {} + + '@xterm/xterm@6.0.0': {} + abbrev@4.0.0: {} abort-controller@3.0.0: