Compare commits

...

8 Commits

Author SHA1 Message Date
8cea4a899c v1.10.5: inference XML tool-call fallback parser
Some local models (qwen3-coder via llama-swap) emit tool calls as inline XML
inside delta.content rather than structured delta.tool_calls. streamCompletion
now buffers delta.content, extracts complete <tool_call>...</tool_call> blocks
via parseXmlToolCall, and pushes synthetic entries (id prefix xml_call_) into
the existing toolCallsBuffer. Native JSON path unchanged — both coexist.
Partial openers are held back so a tool tag never leaks to the chat mid-tag.
Unclosed XML at end-of-stream is flushed as plain content (no silent drops).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 17:32:42 +00:00
3fceea064a booterm: fitFull() bypasses FitAddon scrollbar subtraction; push initial PTY size
FitAddon's proposeDimensions() always subtracts a phantom scrollbar width even
when CSS hides the scrollbar — losing one column of usable width. fitFull()
divides host clientWidth/clientHeight by the renderer's reported cell size
directly. Also POSTs the resized cols/rows back to /api/term/.../resize on
initial mount and after fonts.ready so bash/opencode get the correct PTY
size before the user types.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 17:32:42 +00:00
fccab20920 merge v1.10.4-booterm-mobile 2026-05-19 17:16:50 +00:00
ea9d261f0f v1.10.4: booterm mobile UX — copy/paste, swipe-close, send-to-chat, search
- Long-press selection + floating menu (mobile + desktop right-click): Copy,
  Paste, Select All, Search, Send to chat. Tap-outside / Esc dismiss.
- Pane-header Paste button (📋) for iOS user-gesture clipboard read.
- Swipe-left-to-close on mobile pane pill with red "Close" overlay and
  translateX visual hint; spring-back below 80px threshold.
- Send-to-chat reverse path: chatInputsRegistry + sendToChat event mirror
  the existing terminalsRegistry pattern. ChatInput appends with newline
  separator on receive and focuses (no auto-send).
- Scrollback search via xterm-addon-search@^0.13.0: SearchBar overlay with
  N-of-M match counter (onDidChangeResults), Enter/Shift-Enter cycling.
- Cmd/Ctrl+F intercept in Session.tsx when active pane is terminal; xterm
  also intercepts when focused. Browser native find passes through elsewhere.
- terminalsRegistry signature extended with openSearch + paste callbacks.

Includes deferred CLAUDE.md updates documenting v1.10/v1.10.1/v1.10.2/v1.10.3
learnings (uid 1000 collision, libc match, two event buses, vite proxy order,
mobile pane URL sync, xterm canvas selection).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 17:16:47 +00:00
4d466c5710 merge v1.10.3-booterm-ux 2026-05-19 13:52:50 +00:00
875db86e31 v1.10.3: booterm mobile/UX fixes + global keyboard shortcuts
Five issues + keyboard shortcuts across booterm and the workspace shell.

Auto-switch on create (mobile): addSplitPane now returns the new pane id;
Session.tsx wraps it with addPaneAndSwitch which pushes ?pane=<newId> on
mobile so the URL-sync effect doesn't fight the just-set activePaneIdx.
NewPaneMenu uses the wrapper; desktop Split dropdown is unaffected.

Tab-away reconnect: TerminalPane has a connect()/manualReconnect() state
machine. ws.onclose backs off 500ms/1s/2s × 3 attempts, then surfaces a
[Disconnected] banner with a Reconnect button. visibilitychange listener
calls manualReconnect when the tab returns and the WS isn't OPEN. tmux
session persists server-side so scrollback is intact on resume.

Copy/paste: attachCustomKeyEventHandler binds Cmd/Ctrl-C (copy if
selection, else send ^C), Cmd/Ctrl-Shift-C (always swallow — copy if any,
no-op otherwise — never sends ^C), Cmd/Ctrl-V and Cmd/Ctrl-Shift-V
(navigator.clipboard.readText → ws.send). No custom right-click menu —
browser's native menu is preserved.

Scroll: removed `set -g mouse on` from tmux.conf so xterm.js sees wheel
and touch events natively. scrollback: 10_000, fastScrollModifier: 'shift',
altClickMovesCursor: false. Container has touch-action: pan-y for mobile.

Right-edge gap: inline <style> overrides xterm's defaults to width:100%
height:100% and hides the scrollbar chrome. Host container is
flex-1 min-w-0 self-stretch w-full. Three refit triggers: ResizeObserver
(rAF-wrapped), document.fonts.ready, and useEffect on the new active prop.
Background color matched between outer div, inner div, and xterm theme.

Keyboard shortcuts in Session.tsx (window-level keydown):
  Cmd/Ctrl+`              focus active terminal, else jump to last
  Cmd/Ctrl+Shift+T        new terminal pane
  Cmd/Ctrl+Shift+C        new chat pane (defers to xterm copy if focused)
  Cmd/Ctrl+W              close active pane
  Cmd/Ctrl+Tab/Shift+Tab  cycle next / prev pane
  Cmd/Ctrl+1..9           jump to pane N
terminalsRegistry gains a focus() callback per registration so Cmd+`
can call term.focus() on the active terminal.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 13:52:44 +00:00
8eaf9591dc merge v1.10.2-booterm-glibc 2026-05-19 13:14:25 +00:00
5d52b79a07 v1.10.2: booterm runtime on bookworm-slim (glibc), su-exec → gosu
Switched the booterm runtime + proddeps stages from node:20-alpine (musl)
to node:20-bookworm-slim (glibc) so host-installed glibc binaries (Claude
Code, opencode, nvm node) run inside the container when invoked from the
terminal pane. node-pty's native .node has to be compiled in the same
libc env as the runtime, so both stages flip together; the TypeScript-only
builder stage stays on alpine.

su-exec is alpine-only; Debian replacement is gosu — swapped in both the
runtime apt install and the tmux default-command. uid/gid 1000 collision
with the bookworm `node` user handled via userdel/groupdel before
groupadd/useradd.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 13:14:21 +00:00
14 changed files with 1460 additions and 97 deletions

View File

@@ -6,6 +6,8 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
Self-hosted single-user developer chat app. AI assistant with read-only file tools (view_file, list_dir, grep, find_files) running against a local llama-swap inference server. Sessions organized by project, with a multi-pane workspace (chat + file browser side by side).
Plus `apps/booterm` (second container, port 9501, bookworm-slim+glibc): Fastify + node-pty + tmux. Browser terminal panes WS to `/ws/term/sessions/:sid/panes/:pid`; per-session tmux session `bc-<sid>`, per-pane window `term-<pid>`. Shells drop privs to samkintop via `gosu` in `tmux.conf` default-command.
## Commands
```bash
@@ -35,7 +37,7 @@ Tests: `pnpm -C apps/server test` runs 23 vitest tests. No test harness on `apps
## Architecture
**Monorepo**: pnpm workspaces with `apps/server` (Fastify + postgres) and `apps/web` (React + Vite).
**Monorepo**: pnpm workspaces with `apps/server` (Fastify + postgres), `apps/web` (React + Vite), and `apps/booterm` (Fastify + node-pty + tmux).
### Server (`apps/server/src/`)
@@ -99,6 +101,10 @@ Required: `DATABASE_URL`, `LLAMA_SWAP_URL`. Optional: `PORT` (3000), `HOST` (0.0
- Don't accumulate `.bak-*` files. Clean them up in the same batch or immediately after merge.
- Fastify global JSON parser tolerates empty bodies (overridden in `index.ts`); bodyless POSTs (archive, unarchive, stop) work without setting `Content-Type` tricks on the client.
- Event dedup discipline: for any mutation the server publishes via `broker.publishUser`, do NOT add a local `sessionEvents.emit(...)` after the API call — `useUserEvents` forwards the WS frame onto the bus. Frontend mutation handlers must be idempotent (dedup by id, no-op on already-present).
- `node:20-*` base images ship a `node` user at uid/gid 1000 — delete it (`userdel`/`groupdel` on debian, `deluser`/`delgroup` on alpine) before adding samkintop at 1000.
- node-pty's compiled `.node` is libc-specific: proddeps and runtime Dockerfile stages must share libc (alpine↔musl or bookworm-slim↔glibc); the TS-only builder stage can stay alpine for speed.
- pnpm 10 `--frozen-lockfile` skips node-pty's postinstall — the Docker proddeps stage runs `cd node_modules/node-pty && npm run install` to force the native compile.
- A local PreToolUse hook (`security_reminder_hook.py`) regex-flags Node's older `child_process` spawn helpers as unsafe (false positive even on the File-suffixed variant). Use `spawn` — it's accepted.
## Conventions
@@ -109,3 +115,7 @@ Required: `DATABASE_URL`, `LLAMA_SWAP_URL`. Optional: `PORT` (3000), `HOST` (0.0
- Discriminated unions for type narrowing: `Pane` (by `kind`), `SessionEvent` (by `type`), `InferenceFrame` (by `type`).
- shadcn primitives live in `components/ui/`. Don't modify them unless adding a new primitive.
- `inferLanguage()` from `lib/attachments.ts` is the canonical file-extension-to-language map. `CodeBlock.tsx` keeps its own `LANG_MAP` because it also resolves markdown fence names.
- Two UI event buses: `hooks/sessionEvents.ts` for DB-state events (chat_created, session_updated); `lib/events.ts` for ephemeral UI (`sendToTerminal`, `terminalsRegistry`). Don't merge — different subscriber lifecycles.
- `vite.config.ts` proxy entries are order-sensitive: more-specific prefixes (`/api/term`, `/ws/term`) must come BEFORE `/api`.
- Mobile pane URL sync (`Session.tsx`): the `?pane=<id>` effect resets `activePaneIdx` whenever `panes` changes. New-pane creation on mobile must push `?pane=` atomically — `addPaneAndSwitch` is the wrapper that does this. `addSplitPane` returns the new pane id for callers.
- xterm.js v5 uses canvas rendering — browser doesn't see xterm's selection; the native right-click menu has no working Copy for terminal text. App keybindings (`Cmd/Ctrl-C`, `Cmd/Ctrl-Shift-C`) are the path.

View File

@@ -15,28 +15,45 @@ COPY apps/booterm ./apps/booterm
RUN pnpm --filter=@boocode/booterm build
# ---- Prod-deps stage: hoisted, native built via npm rebuild ----
FROM node:20-alpine AS proddeps
# v1.10.2: switched to bookworm-slim (glibc) so node-pty's native .node is
# compiled against the same libc as the runtime stage. A musl-built .node
# won't dlopen in a glibc node binary, so both stages must match.
FROM node:20-bookworm-slim AS proddeps
ENV COREPACK_DEFAULT_TO_LATEST=0
RUN corepack enable && corepack prepare pnpm@10.15.1 --activate
RUN apk add --no-cache python3 make g++
RUN apt-get update && apt-get install -y --no-install-recommends \
python3 make g++ ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /prod
COPY apps/booterm/package.json ./package.json
RUN pnpm install --prod --config.node-linker=hoisted --config.strict-peer-dependencies=false
# pnpm 10 ignores build scripts; force compile with npm directly.
# node-gyp is bundled with npm in the node:20-alpine image.
# node-gyp is bundled with npm in the node:20-bookworm-slim image.
RUN cd node_modules/node-pty && npm run install
# Sanity check — fail the build if the artifact still isn't there
RUN test -f node_modules/node-pty/build/Release/pty.node && echo "pty.node OK" || (echo "pty.node MISSING" && exit 1)
# ---- Runtime ----
FROM node:20-alpine AS runtime
RUN apk add --no-cache tmux libstdc++ bash su-exec shadow
# v1.10.1: terminal shells inside tmux drop privs to samkintop via su-exec.
# v1.10.2: switched from node:20-alpine (musl) to node:20-bookworm-slim (glibc)
# so glibc-linked binaries from /home/samkintop (Claude Code, opencode, the
# host's nvm node) run inside the container when invoked from the terminal
# pane. Side-effect: su-exec is alpine-only — Debian replacement is gosu.
FROM node:20-bookworm-slim AS runtime
RUN apt-get update && apt-get install -y --no-install-recommends \
tmux bash gosu ca-certificates procps \
&& rm -rf /var/lib/apt/lists/*
# Mirror uid/gid 1000:1000 from the host so the bind-mounted /home/samkintop
# (added in docker-compose) is owned by the user from the container's view.
RUN deluser --remove-home node 2>/dev/null; delgroup node 2>/dev/null; \
addgroup -g 1000 samkintop && \
adduser -D -u 1000 -G samkintop -s /bin/bash samkintop
# bookworm-slim ships a `node` user at 1000 — wipe whatever sits on uid/gid
# 1000 first, then create samkintop fresh.
RUN if id -u 1000 >/dev/null 2>&1; then \
userdel -r "$(id -un 1000)" 2>/dev/null || true; \
fi; \
if getent group 1000 >/dev/null 2>&1; then \
groupdel "$(getent group 1000 | cut -d: -f1)" 2>/dev/null || true; \
fi; \
groupadd -g 1000 samkintop && \
useradd -m -u 1000 -g 1000 -s /bin/bash samkintop
WORKDIR /app
COPY --from=builder /build/apps/booterm/dist ./dist
COPY --from=proddeps /prod/package.json ./package.json

View File

@@ -1,13 +1,20 @@
set -g default-terminal "screen-256color"
set -g history-limit 50000
set -g mouse on
# v1.10.3: `set -g mouse on` removed. tmux's mouse mode captured wheel/touch
# events at the protocol level, so xterm.js never saw them and the viewport
# couldn't scroll on mobile. With mouse off, xterm.js handles scrollback
# natively (wheel on desktop, finger-drag on mobile via touch-action: pan-y).
# Tradeoff: lose tmux mouse pane-resize and scroll-inside-vim; acceptable for
# the homelab single-user setup.
setw -g mode-keys vi
set -g status off
set -g destroy-unattached off
# v1.10.1: shells drop privs to samkintop (uid 1000) so the terminal runs in
# the user's environment, not root. `env HOME=… USER=…` is required because
# su-exec only changes uid/gid — it leaves env intact, and tmux server runs
# as root so HOME would otherwise be /root. bash -l then sources samkintop's
# ~/.profile / ~/.bashrc to pick up PATH (nvm, ~/.local/bin, ~/.opencode/bin).
set -g default-command "su-exec samkintop:samkintop env HOME=/home/samkintop USER=samkintop SHELL=/bin/bash bash -l"
# gosu (and su-exec before it) only changes uid/gid — it leaves env intact,
# and the tmux server runs as root so HOME would otherwise be /root. bash -l
# then sources samkintop's ~/.profile / ~/.bashrc to pick up PATH (nvm,
# ~/.local/bin, ~/.opencode/bin).
# v1.10.2: su-exec → gosu (alpine → debian; functionally identical).
set -g default-command "gosu samkintop:samkintop env HOME=/home/samkintop USER=samkintop SHELL=/bin/bash bash -l"

View File

@@ -310,6 +310,70 @@ interface StreamOptions {
temperature?: number;
}
// v1.10.5 Qwen-coder XML fallback. Some local models (notably qwen3-coder via
// llama-swap) emit tool calls as inline XML inside delta.content rather than
// the structured delta.tool_calls field. The XML shape is:
// <tool_call>
// <function=NAME>
// <parameter=KEY>
// VALUE
// </parameter>
// ...more parameters...
// </function>
// </tool_call>
// Multiple <tool_call> blocks may appear back-to-back; they never nest.
// streamCompletion buffers delta.content, extracts complete blocks, parses
// them via parseXmlToolCall, and pushes synthetic entries into the existing
// toolCallsBuffer alongside any native JSON-format tool calls.
const XML_TOOL_OPEN = '<tool_call>';
const XML_TOOL_CLOSE = '</tool_call>';
function parseXmlToolCall(
block: string,
): { name: string; args: Record<string, unknown> } | null {
const nameMatch = block.match(/<function=([^>]+)>/);
if (!nameMatch || !nameMatch[1]) return null;
const name = nameMatch[1].trim();
if (!name) return null;
const args: Record<string, unknown> = {};
// Non-greedy body so each <parameter=…>…</parameter> pair is matched
// independently even when multiple appear in the same block.
const paramRe = /<parameter=([^>]+)>([\s\S]*?)<\/parameter>/g;
for (const m of block.matchAll(paramRe)) {
const key = (m[1] ?? '').trim();
if (!key) continue;
const raw = (m[2] ?? '').trim();
try {
args[key] = JSON.parse(raw);
} catch {
args[key] = raw;
}
}
return { name, args };
}
// Locate the first character that begins (or completely contains) an
// unfinished <tool_call> opener in `s`. Returns -1 when `s` can be flushed
// to the client in full without risking a partial tag leak.
// Case 1: a full `<tool_call>` opener with no matching closer — caller
// must keep everything from that index forward until the next
// chunk arrives with the closer.
// Case 2: `s` ends with a strict prefix of `<tool_call>` (e.g. `<tool_c`).
// Caller must keep just that suffix in the buffer.
// Note: case 1 assumes the calling loop already extracted every complete
// <tool_call>…</tool_call> pair before reaching this check.
function partialXmlOpenerStart(s: string): number {
const fullOpener = s.indexOf(XML_TOOL_OPEN);
if (fullOpener !== -1) return fullOpener;
const lastLt = s.lastIndexOf('<');
if (lastLt === -1) return -1;
const suffix = s.slice(lastLt);
if (XML_TOOL_OPEN.startsWith(suffix) && suffix.length < XML_TOOL_OPEN.length) {
return lastLt;
}
return -1;
}
async function streamCompletion(
ctx: InferenceContext,
model: string,
@@ -344,6 +408,10 @@ async function streamCompletion(
}
let content = '';
// v1.10.5: holds delta.content bytes that may contain a partial XML tool
// call. Anything not part of a (possibly forming) <tool_call>…</tool_call>
// pair is flushed to content + onDelta as soon as we know it's safe.
let pendingBuffer = '';
let finishReason: string | null = null;
let promptTokens: number | null = null;
let completionTokens: number | null = null;
@@ -377,8 +445,50 @@ async function streamCompletion(
if (!choice) continue;
const delta = choice.delta ?? {};
if (typeof delta.content === 'string' && delta.content.length > 0) {
content += delta.content;
onDelta(delta.content);
// v1.10.5 XML fallback. Append, then extract any complete tool_call
// blocks before deciding what's safe to flush as visible content.
pendingBuffer += delta.content;
while (true) {
const startIdx = pendingBuffer.indexOf(XML_TOOL_OPEN);
if (startIdx === -1) break;
const closeIdx = pendingBuffer.indexOf(XML_TOOL_CLOSE, startIdx);
if (closeIdx === -1) break;
const blockEnd = closeIdx + XML_TOOL_CLOSE.length;
const block = pendingBuffer.slice(startIdx, blockEnd);
// Any text before the opener is plain content — flush it now.
if (startIdx > 0) {
const before = pendingBuffer.slice(0, startIdx);
content += before;
onDelta(before);
}
const parsedCall = parseXmlToolCall(block);
if (parsedCall) {
const synthIdx = toolCallsBuffer.size;
toolCallsBuffer.set(synthIdx, {
id: `xml_call_${synthIdx}`,
name: parsedCall.name,
argsText: JSON.stringify(parsedCall.args),
});
}
// If parsing failed we still drop the block — emitting unparseable
// XML to the chat would look worse than silently swallowing it.
pendingBuffer = pendingBuffer.slice(blockEnd);
}
// After all complete blocks are out, hold back any (partial or full)
// unclosed opener; flush the rest.
const partialIdx = partialXmlOpenerStart(pendingBuffer);
if (partialIdx >= 0) {
if (partialIdx > 0) {
const flush = pendingBuffer.slice(0, partialIdx);
content += flush;
onDelta(flush);
}
pendingBuffer = pendingBuffer.slice(partialIdx);
} else if (pendingBuffer.length > 0) {
content += pendingBuffer;
onDelta(pendingBuffer);
pendingBuffer = '';
}
}
if (Array.isArray(delta.tool_calls)) {
for (const tc of delta.tool_calls) {
@@ -393,6 +503,15 @@ async function streamCompletion(
if (choice.finish_reason) finishReason = choice.finish_reason;
}
// v1.10.5: if the stream ended mid-XML (e.g. model truncated, no closer
// ever arrived), flush whatever was buffered as plain content so it isn't
// silently dropped. Better to show a stray `<tool_call>` than vanish text.
if (pendingBuffer.length > 0) {
content += pendingBuffer;
onDelta(pendingBuffer);
pendingBuffer = '';
}
const toolCalls: ToolCall[] = [];
for (const [, t] of [...toolCallsBuffer.entries()].sort(([a], [b]) => a - b)) {
let args: Record<string, unknown> = {};

View File

@@ -29,6 +29,7 @@
"tw-animate-css": "^1.4.0",
"xterm": "^5.3.0",
"xterm-addon-fit": "^0.8.0",
"xterm-addon-search": "^0.13.0",
"xterm-addon-web-links": "^0.9.0"
},
"devDependencies": {

View File

@@ -25,6 +25,7 @@ import { AgentPicker } from '@/components/AgentPicker';
import { SkillSlashCommand } from '@/components/SkillSlashCommand';
import { api } from '@/api/client';
import { sessionEvents } from '@/hooks/sessionEvents';
import { chatInputsRegistry, sendToChat } from '@/lib/events';
import { useSkills } from '@/hooks/useSkills';
import { useViewport } from '@/hooks/useViewport';
@@ -51,9 +52,16 @@ interface Props {
// empty). Callers wire this to api.chats.skillInvoke. Omitting the prop
// disables slash-command dispatch (input is sent as literal text).
onSlashCommand?: (skillName: string, userMessage: string) => void | Promise<void>;
// v1.10.4: send-to-chat reverse path. When chatId is provided, this input
// registers in chatInputsRegistry so the terminal floating menu can list
// it, and subscribes to sendToChat events scoped to this chatId. Receiving
// an event appends the text to the current draft (with a newline separator
// when non-empty) and focuses — no auto-send.
chatId?: string;
chatLabel?: string;
}
export function ChatInput({ disabled, projectId, agentId, onAgentChange, sessionId, webSearchEnabled, onSend, onForceSend, onSlashCommand }: Props) {
export function ChatInput({ disabled, projectId, agentId, onAgentChange, sessionId, webSearchEnabled, onSend, onForceSend, onSlashCommand, chatId, chatLabel }: Props) {
const { isMobile } = useViewport();
const [value, setValue] = useState('');
const [busy, setBusy] = useState(false);
@@ -107,6 +115,35 @@ export function ChatInput({ disabled, projectId, agentId, onAgentChange, session
});
}, []);
// v1.10.4: register this input in the chat-input registry so the terminal
// pane's "Send to chat" menu can list it. Re-registers when chatLabel
// changes (e.g. rename) so the menu reflects the current name.
useEffect(() => {
if (!chatId) return;
return chatInputsRegistry.register(chatId, chatLabel ?? 'Chat', () => {
textareaRef.current?.focus();
});
}, [chatId, chatLabel]);
// v1.10.4: subscribe to send_to_chat events scoped by chatId. Appends the
// payload text to the current draft (with a newline separator if the
// draft is non-empty) and focuses the textarea. Does NOT auto-submit.
useEffect(() => {
if (!chatId) return;
return sendToChat.subscribe(({ chat_id, text }) => {
if (chat_id !== chatId) return;
setValue((prev) => (prev.length === 0 ? text : `${prev}\n${text}`));
requestAnimationFrame(() => {
const ta = textareaRef.current;
if (!ta) return;
ta.focus();
// Put caret at end so the user can keep typing immediately.
const end = ta.value.length;
ta.selectionStart = ta.selectionEnd = end;
});
});
}, [chatId]);
function removeAttachment(id: string) {
setAttachments(prev => prev.filter(a => a.id !== id));
}

View File

@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useRef, useState } from 'react';
import {
Bot,
ChevronDown,
@@ -31,6 +31,15 @@ interface Props {
onRenameChat: (chatId: string, name: string) => Promise<void>;
}
// v1.10.4: swipe-left-to-close on the pane pill. Threshold matches the spec
// (80px). Vertical bail-out at 30px because the pill sits inside a vertical
// scrollable header — diagonal-ish swipes shouldn't accidentally close panes.
const SWIPE_CLOSE_PX = 80;
const SWIPE_VERTICAL_BAIL_PX = 30;
// Visual cap: pill translates left up to this much. Past this, dragX stays
// pinned so the user has a clear "release to close" indicator.
const SWIPE_VISUAL_CAP = 120;
function paneIcon(kind: WorkspacePane['kind']) {
if (kind === 'terminal') return <Terminal size={14} />;
if (kind === 'agent') return <Bot size={14} />;
@@ -70,11 +79,66 @@ export function MobileTabSwitcher({
const [open, setOpen] = useState(false);
const [renamingChatId, setRenamingChatId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState('');
// v1.10.4: swipe-left state. dragX is the (clamped, negative) drag offset
// in px. suppressClick latches when a swipe completes so the trailing click
// doesn't pop open the BottomSheet on the just-closed pane.
const [dragX, setDragX] = useState(0);
const swipeStart = useRef<{ x: number; y: number } | null>(null);
const swipeBailed = useRef(false);
const suppressClick = useRef(false);
const active = panes[activePaneIdx];
const activeLabel = active ? paneLabel(active, chats) : 'Empty';
const activeChatId = paneActiveChatId(active);
function onPillTouchStart(e: React.TouchEvent<HTMLDivElement>): void {
if (e.touches.length !== 1) return;
const t = e.touches[0]!;
swipeStart.current = { x: t.clientX, y: t.clientY };
swipeBailed.current = false;
setDragX(0);
}
function onPillTouchMove(e: React.TouchEvent<HTMLDivElement>): void {
if (!swipeStart.current || swipeBailed.current) return;
if (e.touches.length !== 1) return;
const t = e.touches[0]!;
const dx = t.clientX - swipeStart.current.x;
const dy = t.clientY - swipeStart.current.y;
// Bail to scroll if vertical motion dominates before horizontal.
if (Math.abs(dy) > SWIPE_VERTICAL_BAIL_PX && Math.abs(dy) > Math.abs(dx)) {
swipeBailed.current = true;
setDragX(0);
return;
}
// Only allow leftward drag (negative). Cap visual displacement.
const clamped = Math.max(-SWIPE_VISUAL_CAP, Math.min(0, dx));
setDragX(clamped);
}
function onPillTouchEnd(): void {
const finalDx = dragX;
swipeStart.current = null;
if (swipeBailed.current) {
setDragX(0);
return;
}
if (finalDx <= -SWIPE_CLOSE_PX && panes.length > 1) {
suppressClick.current = true;
// Reset dragX after the close so subsequent re-renders look right.
setDragX(0);
onRemovePane(activePaneIdx);
return;
}
setDragX(0);
}
function onPillClick(): void {
if (suppressClick.current) {
suppressClick.current = false;
return;
}
setOpen(true);
}
const swipeProgress = Math.min(1, Math.abs(dragX) / SWIPE_CLOSE_PX);
// Long-press mirrors ChatTabBar: synthesize a contextmenu event on the row
// so the trailing kebab's Radix DropdownMenu opens at the touch point.
const longPress = useLongPress(({ clientX, clientY, target }) => {
@@ -113,17 +177,39 @@ export function MobileTabSwitcher({
return (
<>
<div
className="flex-1 relative min-w-0"
onTouchStart={onPillTouchStart}
onTouchMove={onPillTouchMove}
onTouchEnd={onPillTouchEnd}
onTouchCancel={onPillTouchEnd}
>
{/* v1.10.4: red "Close" hint behind the pill. Opacity tracks the
swipe progress (0 at rest, 1 at the close threshold). aria-hidden
because the actionable affordance is the swipe, not this label. */}
<div
aria-hidden="true"
className="absolute inset-0 flex items-center justify-end pr-4 rounded-full bg-destructive/80 text-destructive-foreground text-xs font-medium"
style={{ opacity: swipeProgress, pointerEvents: 'none' }}
>
Close
</div>
<button
type="button"
onClick={() => setOpen(true)}
className="flex-1 inline-flex items-center gap-1.5 min-h-[44px] px-3 text-sm rounded-full bg-muted/40 hover:bg-muted/70 text-foreground min-w-0"
onClick={onPillClick}
className="flex-1 w-full inline-flex items-center gap-1.5 min-h-[44px] px-3 text-sm rounded-full bg-muted/40 hover:bg-muted/70 text-foreground min-w-0 relative"
aria-label="Switch pane"
style={{
transform: `translateX(${dragX}px)`,
transition: dragX === 0 ? 'transform 180ms ease-out' : 'none',
}}
>
<span className="shrink-0 text-muted-foreground">{paneIcon(active?.kind ?? 'chat')}</span>
<StatusDot chatId={activeChatId} />
<span className="truncate flex-1 text-left">{activeLabel}</span>
<ChevronDown size={14} className="opacity-60 shrink-0" />
</button>
</div>
<BottomSheet open={open} onClose={() => setOpen(false)} title="Panes">
<ul className="px-2 py-2 space-y-1">

View File

@@ -1,9 +1,10 @@
import { useEffect, useMemo, useState } from 'react';
import { PanelRight, MessageSquare, Terminal, Bot, X } from 'lucide-react';
import { PanelRight, MessageSquare, Terminal, Bot, Clipboard, X } from 'lucide-react';
import type { Chat, Project, Session, WorkspacePane } from '@/api/types';
import { MAX_PANES, type UseWorkspacePanesResult } from '@/hooks/useWorkspacePanes';
import type { UseSessionChatsResult } from '@/hooks/useSessionChats';
import { useViewport } from '@/hooks/useViewport';
import { terminalsRegistry } from '@/lib/events';
import { ChatPane } from '@/components/panes/ChatPane';
import { SettingsPane } from '@/components/panes/SettingsPane';
import { TerminalPane } from '@/components/panes/TerminalPane';
@@ -238,6 +239,23 @@ export function Workspace({
<span className="text-xs text-muted-foreground">
{terminalLabels.get(pane.id) ?? 'Terminal'}
</span>
{/* v1.10.4: iOS Safari restricts navigator.clipboard.readText
outside direct user gestures. A real button click IS a
gesture, so this works where keystroke-driven paste may
not on iOS. The action lives in TerminalPane behind the
registry's paste() callback. */}
<button
type="button"
onClick={(e) => {
e.stopPropagation();
terminalsRegistry.get(pane.id)?.paste();
}}
className="ml-auto inline-flex items-center justify-center size-5 rounded text-muted-foreground hover:bg-muted hover:text-foreground max-md:size-7"
aria-label="Paste from clipboard"
title="Paste from clipboard"
>
<Clipboard size={12} />
</button>
{panes.length > 1 && (
<button
type="button"
@@ -245,7 +263,7 @@ export function Workspace({
e.stopPropagation();
removePane(idx);
}}
className="ml-auto inline-flex items-center justify-center size-5 rounded text-muted-foreground hover:bg-muted hover:text-foreground"
className="inline-flex items-center justify-center size-5 rounded text-muted-foreground hover:bg-muted hover:text-foreground max-md:size-7"
aria-label="Close terminal pane"
title="Close terminal pane"
>
@@ -271,6 +289,7 @@ export function Workspace({
sessionId={sessionId}
paneId={pane.id}
label={terminalLabels.get(pane.id) ?? 'Terminal'}
active={idx === activePaneIdx}
/>
) : pane.kind === 'chat' && pane.chatId ? (
<ChatPane

View File

@@ -196,6 +196,8 @@ export function ChatPane({ sessionId, chatId, projectId, agentId, onAgentChange,
onSend={handleSend}
onForceSend={streaming ? handleForceSend : undefined}
onSlashCommand={handleSlashCommand}
chatId={chatId}
chatLabel={sessionChats?.find((c) => c.id === chatId)?.name ?? 'Chat'}
/>
</div>
</div>

File diff suppressed because it is too large Load Diff

View File

@@ -11,8 +11,11 @@ function generateId(): string {
return crypto.randomUUID();
}
function emptyPane(): WorkspacePane {
return { id: generateId(), kind: 'empty', chatIds: [], activeChatIdx: -1 };
// v1.10.3: optional id arg lets addSplitPane lift id generation out of the
// setPanes updater so the new pane's id can be returned synchronously to the
// caller (needed for mobile URL state).
function emptyPane(id: string = generateId()): WorkspacePane {
return { id, kind: 'empty', chatIds: [], activeChatIdx: -1 };
}
function chatPane(chatId: string): WorkspacePane {
@@ -23,8 +26,8 @@ function chatPane(chatId: string): WorkspacePane {
// tmux window key on booterm — see apps/booterm/src/pty/manager.ts. They
// persist in localStorage along with chat panes so a refresh resumes the
// same tmux window via the idempotent start endpoint.
function terminalPane(): WorkspacePane {
return { id: generateId(), kind: 'terminal', chatIds: [], activeChatIdx: -1 };
function terminalPane(id: string = generateId()): WorkspacePane {
return { id, kind: 'terminal', chatIds: [], activeChatIdx: -1 };
}
// v1.9: settings pane factory. No chats, no state beyond identity — the
@@ -80,7 +83,11 @@ export interface UseWorkspacePanesResult {
closeTabsToRight: (paneIdx: number, pivotChatId: string) => void;
closeAllTabs: (paneIdx: number) => void;
showLandingPage: (paneIdx: number) => void;
addSplitPane: (kind: 'chat' | 'terminal' | 'agent') => void;
// v1.10.3: returns the new pane's id (or null if the operation was a no-op:
// 'agent' kind is a toast stub, or max panes reached). Callers can use the
// id to update mobile URL state so the URL-sync effect doesn't fight the
// freshly-set activePaneIdx.
addSplitPane: (kind: 'chat' | 'terminal' | 'agent') => string | null;
// Open-on-first-click, close-on-second-click. Singleton — settings panes
// don't count toward MAX_PANES. Closing the only remaining pane (edge case)
// falls back to an empty pane to preserve the "always one pane" invariant.
@@ -241,22 +248,29 @@ export function useWorkspacePanes(sessionId: string): UseWorkspacePanesResult {
});
}, []);
const addSplitPane = useCallback((kind: 'chat' | 'terminal' | 'agent') => {
const addSplitPane = useCallback((kind: 'chat' | 'terminal' | 'agent'): string | null => {
if (kind === 'agent') {
toast('Agent panes coming in BooCoder');
return;
return null;
}
// Generate the id outside the updater so we can return it deterministically.
// setPanes's updater can be invoked twice in strict mode; using a fixed id
// ensures both invocations agree and the returned id matches what landed.
const newPaneId = generateId();
let success = false;
setPanes((prev) => {
// v1.9: settings panes are excluded from the MAX cap (decision c).
if (nonSettingsCount(prev) >= MAX_PANES) {
toast.error(`Maximum ${MAX_PANES} panes`);
return prev;
}
const newPane = kind === 'terminal' ? terminalPane() : emptyPane();
const newPane = kind === 'terminal' ? terminalPane(newPaneId) : emptyPane(newPaneId);
const next = [...prev, newPane];
setActivePaneIdx(next.length - 1);
success = true;
return next;
});
return success ? newPaneId : null;
}, []);
const toggleSettingsPane = useCallback(() => {

View File

@@ -4,7 +4,8 @@
//
// Also exposes a tiny registry of currently-mounted terminal panes so the
// MessageBubble context menu can list them. TerminalPane registers on mount,
// unregisters on unmount.
// unregisters on unmount. v1.10.4 adds a parallel ChatInput registry used by
// the terminal floating menu's "Send to chat" submenu.
type Listener<T> = (payload: T) => void;
@@ -41,9 +42,25 @@ export interface SendToTerminalPayload {
export const sendToTerminal = createEvent<SendToTerminalPayload>();
// v1.10.4: reverse direction. Terminal floating menu "Send to chat" emits this
// with the target chat's chat_id; ChatInput subscribes and appends to its draft.
export interface SendToChatPayload {
chat_id: string;
text: string;
}
export const sendToChat = createEvent<SendToChatPayload>();
export interface TerminalRegistration {
paneId: string;
label: string;
// v1.10.3 kbd-shortcuts: Cmd+` needs to focus the active terminal's xterm
// input layer. TerminalPane binds this to term.focus().
focus: () => void;
// v1.10.4: Cmd+F opens the search bar over the active terminal. Workspace
// also binds a "Paste" button in the terminal pane header to paste().
openSearch: () => void;
paste: () => void;
}
const terminalRegistry = new Map<string, TerminalRegistration>();
@@ -60,8 +77,14 @@ function notifyRegistry(): void {
}
export const terminalsRegistry = {
register(paneId: string, label: string): () => void {
terminalRegistry.set(paneId, { paneId, label });
register(
paneId: string,
label: string,
focus: () => void,
openSearch: () => void,
paste: () => void,
): () => void {
terminalRegistry.set(paneId, { paneId, label, focus, openSearch, paste });
notifyRegistry();
return () => {
terminalRegistry.delete(paneId);
@@ -71,6 +94,9 @@ export const terminalsRegistry = {
list(): TerminalRegistration[] {
return Array.from(terminalRegistry.values());
},
get(paneId: string): TerminalRegistration | undefined {
return terminalRegistry.get(paneId);
},
subscribe(listener: Listener<void>): () => void {
registryListeners.add(listener);
return () => {
@@ -78,3 +104,48 @@ export const terminalsRegistry = {
};
},
};
// v1.10.4: parallel registry of mounted ChatInput components so the terminal
// floating menu's "Send to chat" submenu can list open chats. Mirrors
// terminalsRegistry exactly; same subscriber pattern.
export interface ChatInputRegistration {
chatId: string;
label: string;
focus: () => void;
}
const chatInputRegistry = new Map<string, ChatInputRegistration>();
const chatInputListeners = new Set<Listener<void>>();
function notifyChatInputs(): void {
for (const l of chatInputListeners) {
try {
l();
} catch {
/* ignore */
}
}
}
export const chatInputsRegistry = {
register(chatId: string, label: string, focus: () => void): () => void {
chatInputRegistry.set(chatId, { chatId, label, focus });
notifyChatInputs();
return () => {
chatInputRegistry.delete(chatId);
notifyChatInputs();
};
},
list(): ChatInputRegistration[] {
return Array.from(chatInputRegistry.values());
},
get(chatId: string): ChatInputRegistration | undefined {
return chatInputRegistry.get(chatId);
},
subscribe(listener: Listener<void>): () => void {
chatInputListeners.add(listener);
return () => {
chatInputListeners.delete(listener);
};
},
};

View File

@@ -10,6 +10,7 @@ import { ChevronRight, FolderTree, Menu } from 'lucide-react';
import { api } from '@/api/client';
import type { Project, Session as SessionType } from '@/api/types';
import { sessionEvents } from '@/hooks/sessionEvents';
import { terminalsRegistry } from '@/lib/events';
import { useActivePane } from '@/hooks/useActivePane';
import { useSidebarDrawer } from '@/hooks/useSidebarDrawer';
import { useRightRailDrawer } from '@/hooks/useRightRailDrawer';
@@ -170,6 +171,122 @@ function SessionInner({ sessionId }: { sessionId: string }) {
[setActivePaneIdx, isMobile, panes, navigate, location.pathname, location.search],
);
// v1.10.3 fix: addSplitPane sets activePaneIdx, but on mobile the URL-sync
// effect below sees a stale ?pane= and immediately resets the index. Push
// the new pane's id to the URL atomically so the effect's next pass sees a
// matching id and is a no-op. Desktop has no URL pane state — fall through.
const addPaneAndSwitch = useCallback(
(kind: 'chat' | 'terminal' | 'agent') => {
const newPaneId = addSplitPane(kind);
if (newPaneId === null) return;
if (isMobile) {
const params = new URLSearchParams(location.search);
params.set('pane', newPaneId);
navigate(`${location.pathname}?${params.toString()}`);
}
},
[addSplitPane, isMobile, navigate, location.pathname, location.search],
);
// v1.10.3 keyboard shortcuts. Window-level keydown so they fire from
// anywhere in the session view. Only Cmd/Ctrl-Shift-C defers to the xterm
// (which has its own copy binding for that combo); everything else fires
// regardless of focus. Cmd-W and Cmd-T are typically reserved by the
// browser — preventDefault() works in most browsers but not all.
useEffect(() => {
function onKey(e: KeyboardEvent): void {
const mod = e.ctrlKey || e.metaKey;
if (!mod) return;
const key = e.key.toLowerCase();
const target = e.target;
const inXterm = target instanceof Element && target.closest('.xterm') !== null;
// Cmd/Ctrl + ` — focus the active terminal or jump to the most recent
// terminal pane and focus it. No-op if there are no terminal panes.
if (key === '`') {
e.preventDefault();
const activePane = panes[activePaneIdx];
if (activePane?.kind === 'terminal') {
terminalsRegistry.get(activePane.id)?.focus();
return;
}
let lastTermIdx = -1;
for (let i = panes.length - 1; i >= 0; i--) {
if (panes[i]?.kind === 'terminal') {
lastTermIdx = i;
break;
}
}
if (lastTermIdx < 0) return;
const target = panes[lastTermIdx];
switchActivePane(lastTermIdx);
if (target) {
// The terminal may have just mounted on mobile (it was return-null
// before the switch). Defer focus until the new render commits.
setTimeout(() => terminalsRegistry.get(target.id)?.focus(), 80);
}
return;
}
// Cmd/Ctrl + Shift + T — new terminal pane and switch to it.
if (key === 't' && e.shiftKey) {
e.preventDefault();
addPaneAndSwitch('terminal');
return;
}
// Cmd/Ctrl + Shift + C — new chat pane and switch to it. The xterm's
// own Shift-C binding is "copy selection" — defer to it when in xterm.
if (key === 'c' && e.shiftKey) {
if (inXterm) return;
e.preventDefault();
addPaneAndSwitch('chat');
return;
}
// Cmd/Ctrl + W — close the active pane.
if (key === 'w' && !e.shiftKey) {
e.preventDefault();
removePane(activePaneIdx);
return;
}
// v1.10.4: Cmd/Ctrl + F — when the active pane is a terminal, open the
// scrollback search bar. When it isn't, fall through to the browser's
// native find (no preventDefault, no early return).
if (key === 'f' && !e.shiftKey) {
const activePane = panes[activePaneIdx];
if (activePane?.kind === 'terminal') {
e.preventDefault();
terminalsRegistry.get(activePane.id)?.openSearch();
}
return;
}
// Cmd/Ctrl + Tab / Shift+Tab — cycle through panes.
if (key === 'tab') {
if (panes.length <= 1) return;
e.preventDefault();
const dir = e.shiftKey ? -1 : 1;
const next = (activePaneIdx + dir + panes.length) % panes.length;
switchActivePane(next);
return;
}
// Cmd/Ctrl + 1..9 — direct jump to pane N.
if (/^[1-9]$/.test(key)) {
const idx = parseInt(key, 10) - 1;
if (idx < panes.length) {
e.preventDefault();
switchActivePane(idx);
}
return;
}
}
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [panes, activePaneIdx, switchActivePane, addPaneAndSwitch, removePane]);
async function saveName() {
if (!session) return;
const trimmed = name.trim();
@@ -264,7 +381,7 @@ function SessionInner({ sessionId }: { sessionId: string }) {
onRenameChat={renameChat}
/>
<NewPaneMenu
onAddPane={addSplitPane}
onAddPane={addPaneAndSwitch}
disabled={panes.length >= MAX_PANES}
/>
</div>

13
pnpm-lock.yaml generated
View File

@@ -142,6 +142,9 @@ importers:
xterm-addon-fit:
specifier: ^0.8.0
version: 0.8.0(xterm@5.3.0)
xterm-addon-search:
specifier: ^0.13.0
version: 0.13.0(xterm@5.3.0)
xterm-addon-web-links:
specifier: ^0.9.0
version: 0.9.0(xterm@5.3.0)
@@ -3909,6 +3912,12 @@ packages:
peerDependencies:
xterm: ^5.0.0
xterm-addon-search@0.13.0:
resolution: {integrity: sha512-sDUwG4CnqxUjSEFh676DlS3gsh3XYCzAvBPSvJ5OPgF3MRL3iHLPfsb06doRicLC2xXNpeG2cWk8x1qpESWJMA==}
deprecated: This package is now deprecated. Move to @xterm/addon-search instead.
peerDependencies:
xterm: ^5.0.0
xterm-addon-web-links@0.9.0:
resolution: {integrity: sha512-LIzi4jBbPlrKMZF3ihoyqayWyTXAwGfu4yprz1aK2p71e9UKXN6RRzVONR0L+Zd+Ik5tPVI9bwp9e8fDTQh49Q==}
deprecated: This package is now deprecated. Move to @xterm/addon-web-links instead.
@@ -7967,6 +7976,10 @@ snapshots:
dependencies:
xterm: 5.3.0
xterm-addon-search@0.13.0(xterm@5.3.0):
dependencies:
xterm: 5.3.0
xterm-addon-web-links@0.9.0(xterm@5.3.0):
dependencies:
xterm: 5.3.0