mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-30 16:39:33 +01:00
This commit is contained in:
commit
eb40f4aaa5
55 files changed
+6950
-1039
No files matched your search
+5
-3
@@ -10,7 +10,7 @@
|
||||
|
||||
**Session lineage lines** (tab → tab it spawned, `sessionLineageLines`, per-device, desktop default ON): a create request may name its spawner via a `parentSessionId` body field or the `X-Codeman-Parent-Session` header; `resolveParentSessionId()` (route-helpers.ts) resolves it (exact id or unique ≥8-char prefix, live, visible, same owner) and ⚠️ anything unresolvable is DROPPED, never a 400. Rides `toState()`, no new SSE event. ⚠️ Rendering is a LAYER on the existing SVG pass (`_appendLineageConnectionLines` at the tail of `_updateConnectionLinesImmediate()`) and draws EVERY family, emphasizing the selected tab's (what it spawned, and the family it was spawned into: `lineage-family--focus`, thicker, opaque, drawn last; lanes stay in strip order), so a selection change must redraw (`_updateActiveTabImmediate`, gated on `_lineageTotalEdges`), and again on the strip's size `transitionend` (the active tab widens for ~150ms after the redraw). Geometry is pure in `computeLineageTree()`: one rounded orthogonal tree per spawning tab, every route starting at the PARENT (siblings share the trunk exactly), routed ONLY through the gaps between tab rows plus a spine left of every row, so it never crosses a tab or the terminal. ⚠️ That room is reserved in CSS by `.session-tabs.lineage-tree` (`_syncLineageGutter()`, called before the wrap is measured), keyed on whether ANY family exists, never on the selection, or every tab switch would resize the header and the PTY. Colors are keyed on the SPAWNING tab, claimed in strip order for every family, and memoized (never by draw index or selection order). ⚠️ Desktop only (z-index vs the fixed mobile header). ⚠️ Paths must keep `data-agent-id="lineage:<childId>"` (the entrance animation queries it); skip endpoints scrolled out of the strip. → [architecture-invariants#session-lineage-lines-tab--tab-it-spawned](../../docs/architecture-invariants.md#session-lineage-lines-tab--tab-it-spawned)
|
||||
|
||||
**Split-pane sessions** (`showSplitButton`, header button, default OFF, desktop-only at 1180px (width alone, so a wide Android tablet clears it), per-device): a second live session ("Pane B") beside the active one, in a `TerminalTile` (terminal-tile.js; the picker, divider and auto-collapse stay in terminal-split.js) with its own xterm + WebSocket, resizable via a draggable divider. Pane B reconnects after a drop, sends input through the exactly-once queue over its own socket (`_registerInputSocket`), has clickable paths and image paste, and owns its geometry (no 40x10 floor, `zc` columns adopted, font changes call `tile.fit()`). ⚠️ Only typed input enters that persisted queue: xterm's query replies are dropped and focus/mouse reports go out ephemeral. ⚠️ App-level terminal actions find their pane through `_focusedPane()` (the terminal focused last), never `this.terminal`. Still plainer than the primary pane (no local-echo overlay, CJK IME textarea or touch handlers), though it wires the same keyCode-229 soft-keyboard controller (Android autocorrect, #441/#541), and NOT persisted across reloads. The tile grid (below) reuses `TerminalTile`, and the two are never open together. → [architecture-invariants#split-pane-sessions](../../docs/architecture-invariants.md#split-pane-sessions)
|
||||
**Split-pane sessions** (`showSplitButton`, header button, default OFF, desktop-only at 1180px (width alone, so a wide Android tablet clears it), per-device): a second live session ("Pane B") beside the active one, in a `TerminalTile` (terminal-tile.js; the picker, divider and auto-collapse stay in terminal-split.js) with its own xterm + WebSocket, resizable via a draggable divider. Pane B reconnects after a drop, sends input through the exactly-once queue over its own socket (`_registerInputSocket`), has clickable paths and image paste, and owns its geometry (no 40x10 floor, `zc` columns adopted, font changes call `tile.fit()`). ⚠️ Only typed input enters that persisted queue: xterm's query replies are dropped and focus/mouse reports go out ephemeral. ⚠️ App-level terminal actions find their pane through `_focusedPane()` (the terminal focused last), never `this.terminal`. Still plainer than the primary pane (no local-echo overlay, CJK IME textarea or touch handlers), though it wires the same soft-keyboard input as the main pane: the iOS native-input owner (`_iosNativeInput`, #830) on iOS WebKit touch, otherwise the keyCode-229 controller (Android autocorrect, #441/#541), and NOT persisted across reloads. The tile grid (below) reuses `TerminalTile`, and the two are never open together. → [architecture-invariants#split-pane-sessions](../../docs/architecture-invariants.md#split-pane-sessions)
|
||||
|
||||
**Tile grid** (`showTileGridButton`, header Tiles button + `Ctrl+Shift+G`, default ON on desktop and OFF on handhelds and touch-primary tablets (primary pointer coarse, `getDefaultSettings()`; a touchscreen laptop keeps ON), desktop-only at 1180px, per-device; tile-grid.js, design `docs/tile-grid-plan.md`): 1 to 6 live sessions side by side (the cap is ONE constant, `TILE_GRID_MAX` in constants.js, owner decision; the layout table still covers 7 to 9, unreachable), each a `TerminalTile` with a header (state dot, harness logo, name, model, menu, zoom, ×; no +, owner decision), laid out by count (`CodemanTileGrid`, constants.js) with draggable column/row dividers, zoom (tmux-style), an Attach overlay, and per-browser persistence (`codeman:tile-grid`, localStorage only: cells with `null` holes, `count`, focus, user zoom, divider fractions, never content; written on every change, kept by EVERY close, restored INSIDE `handleInit` in place of the single-view select, so the main terminal never loads on that page load). While the grid is open the main terminal is PARKED: `activeSessionId` is the focused tile's session, and every main-terminal path that would write, fetch, resize or reconnect stands aside through `_tilesOwnTerminal()` (the WebGL long-task observer included). ⚠️ Every capture a tile fetches (initial, reconnect refresh, `{t:'r'}`, history pull) goes through ONE `TileLoadQueue` (concurrency 1, a deadline covering the body), because each is a synchronous tmux call on the server. ⚠️ Only a USER-initiated pick of a non-tiled session (or `leaveTiles`, a followed link) leaves the grid; an `auto` selection never collapses it, and every app-driven fallback (close, delete, restore) picks a tile. A caller of `closeTileGrid({ reselect: false })` must null `activeSessionId` before any `_cleanupPreviousSession`, or the parked terminal's stale content is saved as a snapshot. ⚠️ The grid and the split are never open together. ⚠️ Tile chords go through `tileShortcutFor` and are swallowed in every xterm key handler BEFORE the Shift+Enter gate; the toggle follows `showTileGridButton` (owner decision: OFF makes the chord inert, it passes through like any unbound key). ⚠️ The Tiles button's click and Ctrl+Shift+G are ONE function, `toggleTileGrid` (owner decision): they open the grid AT ONCE on `tileGridOpenSet` (constants.js): the stored grid EXACTLY as the user left it (owner decision 11: `restoreTileGridCells`, never filled to the count nor trimmed to the window; a cell whose session is gone since is filled from the ranking, a hole the user made stays), else an open split's two, else the open sessions as `rankTileSessions` orders them (working first, keyed off `lastSubmitAt` ONLY, then needing input, then most recent; `_mobileOverviewState`'s states), the active one focused, filled to the remembered count (`codeman:tile-count`, default 6, at most `_tileGridLimit()`) by `tileGridSetForCount`, never a menu. ⚠️ `removeTile(..., { gone: true })` (a session deleted, popped out or refused) keeps the stored `count` so the next open refills that cell; a removal by hand lowers it. Right-click is the 2 / 4 / 6 count menu (`openTileCountMenu`, owner decision 10), which owns its Escape. The button has no native title: its hover card (`_installTileGridHint`, `#tileGridHint`) says it, is its `aria-describedby` (always present, hidden, kept current) and hides in the capture phase on any press, click or right-click, so the menu never opens beside it. ⚠️ The open, the count menu and the toggle's close animate opacity and transform only (the close leaves an inert cloned still copy until the single view's selection settles, at most 700 ms); nothing moves under `prefers-reduced-motion`. ⚠️ Opening builds one tile terminal per frame (`_connectTilesPaced`), so `openTileGrid` returns before the terminals exist: focus is handed over in `_connectTile` (`focusOnConnect`). ⚠️ A divider drag reflows locally per frame and sends ONE resize per affected tile at pointer-up. ⚠️ The grid is CELLS (owner: an empty cell can be any cell): `grid.cells` (id or `null`) is the one source of truth, `grid.ids` a derived getter, never written; the shape still comes from the tile count, a shape change goes through `fitTileCells`, and the stored `ids` carry the cells with `null` holes. ⚠️ A tile moves (its header dragged or its tab dropped onto another tile or an empty cell, `Ctrl+Shift+Arrows`) ONLY through `_reorderTiles`: never a remount, reconnect or reload, and since sizes belong to the cells only a tile whose cell size changed fits; off while a tile is zoomed. The header drag carries its own type, never text, and is not `draggedTabId`; the header focuses on click, never on press, so a cancelled drag changes nothing. The arrow chords skip text fields. ⚠️ Sessions Run from this tab join the open grid (`_joinTileGridFromRun`, called from `_ensureCreatedSessionVisible`); sessions created elsewhere never do. SuchLine truncated
|
||||
|
||||
@@ -32,6 +32,8 @@
|
||||
|
||||
Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. Load order is the `<script>` order in `index.html` (each module's `@loadorder` tag mirrors it). `i18n.js` translates static + newly inserted application DOM while skipping terminal/response/file/user-name surfaces; `input-cjk.js` handles CJK IME composition via an always-visible textarea below the terminal (`window.cjkActive` blocks xterm's onData). `terminal-keycode229-recovery.js` forwards a committed `input` event that xterm's `_inputEvent` guard drops (Chrome-on-Android soft keyboards send `composed: true` after a keydown), and only when xterm emitted no canonical data for that keystroke. ⚠️ **That decision is settled at the NEXT keydown as well as on its own zero-delay timer** (#441): the drain runs from xterm's custom key handler, which fires BEFORE xterm processes that key, so a soft keyboard that commits the last character and sends Enter in one InputConnection transaction puts the character on the wire ahead of the `\r`. On the timer alone that character is not merely late, it is LOST: xterm emits the `\r` first and bumps the canonical counter past the candidate's snapshot, so the candidate stands down (measured, `hell\r` where the user typed `hello`). The edit-based diff described below is settled first at that keydown, so the drain decides with the evidence the timer had and Enter's textarea clear cannot turn the pending line into DELs. Ordering is pinned by `test/terminal-keycode229-recovery.browser.test.ts`, which the CI gate does NOT run. The same module replaces xterm's `_handleAnyTextareaChanges` (an append-only `newValue.replace(oldValue, '')` diff) with an edit-based one, so an Android autocorrect on space (delete + insert) reaches the PTY once instead of duplicating the line; ⚠️ that diff is settled at the NEXT keydown, before xterm handles that key, because xterm clears the textarea for Enter and a pending diff would then send one DEL per character ahead of the submitted line (except a composition xterm finalizes synchronously at that key, which stays xterm's). ⚠️ Every xterm that takes keyboard input wires its OWN controller from this module (`create()` returns null unless `matchMedia('(pointer: coarse)')` matches or the user agent is Android, so a desktop dead key is not forwarded twice, #716, while an Android device whose mouse, trackpad cover or stylus Chromium reports as the fine primary pointer keeps the soft-keyboard recovery): the primary pane (terminal-ui.js `initTerminal()`) and each `TerminalTile` (terminal-tile.js `_createKeyCode229Recovery()`, so every grid tile and the split's Pane B, which a wide Android tablet reaches), each on its own textarea, composition helper and session; in both, `handleKeyEvent` must run ABOVE the custom key handler's keyCode-229 early return, and `notifyCanonicalData` sits in the onData lambda, never in the send path the recovered bytes also take. `mobile-ime-preview.js` (iOS WebKit only) paints the text an IME is composing: an iOS IME commit is routed into the local-echo overlay through the ordinary printable/paste branch and then `_transferMobileImeCommitToLocalEcho`, and without local echo the preview clears only on output parsed AFTER the commit (or its 2 s fallback). ⚠️ It watches keydown in the capture phase on `terminal.element`, never on the textarea, because xterm finalizes the composition and emits the commit in its own capture listener on the textarea.
|
||||
|
||||
**iOS native input ownership (#830)**: `terminal-ios-native-input.js` loads after `mobile-ime-preview.js` and before the terminal hosts. `MobileImePreview.isIosWebKitTouch` is the shared gate: supported main panes and tiles install `_iosNativeInput`, never `_keyCode229Recovery`. The owner retains the native textarea line, reconciles replacements/deletions as one transaction, and projects trackpad selection through `.ios-native-caret` without sending arrows. The main marker uses the local-echo layout anchor while the overlay owns the line; missing overlay geometry hides it. External producers call `_prepareExternalInput(pane, reason)` before sending. Toolbar Enter uses `submitFromToolbar()`, capturing the focused pane once; text, the 80ms gap and CR reserve that session's FIFO even across a switch. Browser regressions: `test/ios-native-input.browser.test.ts`; run `node scripts/prepare-test-vendor.mjs` first. → [ios-native-input](../../docs/ios-native-input.md)
|
||||
|
||||
**Entrance animations** (`entrance-animations.js`, all OFF by default): opt-in animations for tabs, terminal, windows, connection lines and tile-grid tiles, chosen via `data-tab-anim` / `data-term-anim` / `data-win-anim` / `data-line-anim` / `data-tile-anim` on `<html>`; the default `legacy` theme short-circuits every hook (tiles keep the grid's own `settle`). ⚠️ Tabs and lines are destroyed mid-animation on re-render, so re-apply to the fresh element by id with a negative `animation-delay` (resume, never restart). ⚠️ Terminal-pane styles may animate only transform / opacity / clip-path (anything else resizes the PTY via FitAddon); `blur` is the ONE sanctioned `filter` exception, do not generalise it. ⚠️ Line glow lives in `--line-glow` so blur keyframes interpolate. Every animation setting lives in App Settings → **Animations** (`#settings-animations`); put new ones there. ⚠️ Tiles are OFF by default (Animations → Tile Animations, default `settle` = the grid's own fade, no screen beat); a theme only presets it. A tile's FRAME animates transform/opacity only (six at once, no filter) with `tile-enter*`/`tile-leave*` keyframe names (what the mount and the still copy listen for); its SCREEN replays the pane style on `.tile-body.term-enter`; a reload's restore always settles. Persisted per-device in `codeman:*Anim` localStorage keys, never in `SettingsUpdateSchema`; lab at `?animlab=1`. Test: `test/entrance-animations.test.ts`. → [architecture-invariants#entrance-animations](../../docs/architecture-invariants.md#entrance-animations)
|
||||
|
||||
**Mobile tab strip scrolling** (issue #257): under 768px the tab strip scrolls horizontally, so the active tab must be kept reachable. `_updateActiveTabImmediate()` reveals it via `computeTabScrollLeft()` (constants.js, rect math on the strip's own `scrollLeft`, never `scrollIntoView()`, which scrolls the document under the fixed header); `_fullRenderSessionTabs()` must restore `scrollLeft` across rebuilds and re-reveal only when the active tab changed (`_lastRenderedActiveTabId`) or, grouped by state, the ACTIVE tab moved to another state band (`_noteActiveTabBand()`, both render paths, scrolling row only; another tab's move never scrolls). ⚠️ The phone-block `min-width` on `.session-tab.active .tab-name` keeps the tab's centre off the gear/close icons, sized for numberless tabs 10+ (floor 40px); do not shrink it. With the opt-in tab "+" on (`showTabNewButton`, `html.tabs-show-new`) a third icon joins them and the reserve grows to 68px, still under the 80px `max-width`. ⚠️ Never reintroduce hoisting the active session to the front of the strip. Tests: `test/mobile-tab-tap-zones.test.ts`, `test/tab-triage.test.ts`. → [architecture-invariants#mobile-tab-strip-scrolling](../../docs/architecture-invariants.md#mobile-tab-strip-scrolling)
|
||||
@@ -76,7 +78,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Shell keyboard accessory bar + one-shot Ctrl** (`keyboard-accessory.js`): a shell-mode session swaps the mobile accessory bar for terminal controls; `setMode()` records `extendedKeyboardBar` as the base layout and `refreshForActiveSession()` resolves base-vs-shell. ⚠️ Ctrl is a one-shot modifier applied in `terminal.onData` (after `shouldSuppressTerminalQueryResponse`, before every send path), and must skip `isTerminalFocusOrMouseReport()` chunks. ⚠️ It must disarm on use, second tap, any other accessory key, session switch, keyboard dismissal and layout swap. ⚠️ `_handleCjkInput()` must apply it too (the CJK textarea bypasses onData). Mapping: `ctrlByteFor()`. ⚠️ mobile.css's light-skin repaint must keep excluding `.accessory-btn:not(.armed)` or the armed state is invisible. → [architecture-invariants#shell-keyboard-accessory-bar-and-one-shot-ctrl](../../docs/architecture-invariants.md#shell-keyboard-accessory-bar-and-one-shot-ctrl)
|
||||
|
||||
**Mobile prompt composer** (`keyboard-accessory.js`): the agent bars' Paste key is **Compose**, a native multiline dialog where only **Send** submits (the shell bar keeps plain Paste). Opening it adopts the whole terminal prompt (`_takePendingLocalEcho`), erasing the flushed prefix with backspaces counted in code points. ⚠️ Drafts are per-session and in memory only (`_composerDrafts`), never persisted (prompts carry secrets). ⚠️ Delivery is a hand-built bracketed-paste frame via `_sendInputAsync` WITHOUT `useMux`, then a separate delayed Enter WITH it; never `terminal.paste()`, and the frame must never take the mux fallback (`TmuxManager.sendInput()` strips every `\r`, the frame's line separator, so the lines weld into one inside a second pair of markers and get submitted). ⚠️ `_composerMaxLength` must stay derived from `MAX_INPUT_LENGTH` minus the markers, or an oversized frame wedges the durable queue. ⚠️ The composer overlay needs its own gutter restatement after the fold rules. The textarea carries `dir="auto"`, so a prompt written in Persian, Arabic or Hebrew lays out right to left from its first letter (#715). Test: `test/mobile-prompt-composer.test.ts`. → [architecture-invariants#mobile-prompt-composer](../../docs/architecture-invariants.md#mobile-prompt-composer)
|
||||
**Mobile prompt composer** (`keyboard-accessory.js`): the agent bars' Paste key is **Compose**, a native multiline dialog where only **Send** submits (the shell bar keeps plain Paste). Opening it adopts the whole terminal prompt (`_takePendingLocalEcho`), erasing the flushed prefix with backspaces counted in code points. ⚠️ Drafts are per-session and in memory only (`_composerDrafts`), never persisted (prompts carry secrets). ⚠️ Delivery is a hand-built bracketed-paste frame enqueued on the session FIFO (`_enqueueInput`, `_sendBracketedPaste()`) WITHOUT `useMux`, then a `gap` and a separate Enter WITH it; never `terminal.paste()`, and the frame must never take the mux fallback (`TmuxManager.sendInput()` strips every `\r`, the frame's line separator, so the lines weld into one inside a second pair of markers and get submitted). ⚠️ `_composerMaxLength` must stay derived from `MAX_INPUT_LENGTH` minus the markers, or an oversized frame wedges the durable queue. ⚠️ The composer overlay needs its own gutter restatement after the fold rules. The textarea carries `dir="auto"`, so a prompt written in Persian, Arabic or Hebrew lays out right to left from its first letter (#715). Test: `test/mobile-prompt-composer.test.ts`. → [architecture-invariants#mobile-prompt-composer](../../docs/architecture-invariants.md#mobile-prompt-composer)
|
||||
|
||||
**Terminal resilience**: a replay clear is the queued in-stream `\x1bc` in `_resetTerminalForReplay()`, never `reset()`/`clear()` (queued bytes fuse into the snapshot); the renderer watchdog `_kickRenderer()` reads xterm privates, pinned by `test/xterm-private-api.test.ts` against the resolved lockfile version; every terminal capture fetch has a deadline that covers the BODY (`_fetchTerminalCapture`). → [architecture-invariants#terminal-resilience-replay-clears-renderer-liveness-fetch-deadlines](../../docs/architecture-invariants.md#terminal-resilience-replay-clears-renderer-liveness-fetch-deadlines)
|
||||
|
||||
@@ -86,7 +88,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Phone toolbar: Enter replaces Shell** (post-1.8.0): inside `@media (max-width: 599px)` `btn-shell` is `display:none` and `btn-enter` takes its slot (`order: 4`); starting a shell moved into the Run dropdown (`Terminal / Shell` → `setRunMode('shell')` → `run()` → `runShell()`, button label "Run SH"). `runMode` is `z.string().max(20)` server-side, so new modes need no schema change. Desktop and tablet keep the green Run Shell button unchanged.
|
||||
|
||||
⚠️ **`sendEnterKey()` MUST go through `terminal._core.coreService.triggerDataEvent('\r', true)`** — not `sendInput()`, and never a raw POST to `/api/sessions/:id/input`. `localEchoEnabled` defaults to `MobileDetection.isTouchDevice()`, so on every phone the characters you type are buffered in the `LocalEchoOverlay` and have **never reached the PTY**; the `onData` Enter branch in terminal-ui.js is what flushes `pendingText` first and only then sends `\r` (after an 80ms delay so text lands first). Sending a bare `\r` submits an empty line and strands the typed text on screen, so the button looks dead. Replaying the keypress reuses the overlay flush, the flushed-offset cleanup and the ordering instead of reimplementing them. `KeyboardAccessory.sendKey()` is for escape sequences (arrows/Esc) and is the WRONG template to copy for input. The one deliberate exception: while the CJK field is visible (`#cjkInput.cjk-input-visible`), `onData` drops everything under `window.cjkActive`, so `sendEnterKey()` calls `CjkInput.submit()` instead, which sends what the field holds (a Send on Enter answer, or live text not yet flushed) and then Enter.
|
||||
**`sendEnterKey()` must call `submitFromToolbar()`**, never a raw input POST. The semantic submit captures the focused pane once and calls `_prepareExternalInput` to settle/reset native ownership. For the main pane, it reuses local-echo Enter handling: pending text, the 80ms gap and the CR are reserved atomically in the captured session's FIFO. For a tile, the CR goes to the tile's session. A session switch cannot redirect the delayed CR, and a missing pane must not fall back to another session. The one deliberate exception: while the CJK field is visible (`#cjkInput.cjk-input-visible`), `onData` drops everything under `window.cjkActive`, so `sendEnterKey()` calls `CjkInput.submit()` instead, which sends what the field holds (a Send on Enter answer, or live text not yet flushed) then Enter, on the session `CjkInput` captured for that text (`_sendCjkPrompt` reserves the text, 120 ms gap and Enter on that session's FIFO).
|
||||
|
||||
⚠️ **Skin overrides outrank plain class rules.** `styles.css` nests its skin block inside `html:not([data-skin="og"]) { … }`, so a bare `.btn-toolbar` rule in there resolves to specificity **(0,2,1)** and beats a `.btn-toolbar.btn-x` rule **(0,2,0)** in `mobile.css` regardless of load order. Toolbar-button colors set from mobile.css therefore need `!important`: that is why mobile.css leans on it so heavily. Symptom: only your `!important` properties land and everything else silently renders in generic toolbar grey. Press feedback on the phone bars sidesteps this: the `:active` rules for `.btn-toolbar`, the mobile icon buttons and `.accessory-btn` (mobile.css) use `transform` and `filter` only, which nothing on these buttons sets at a higher specificity, so one rule reads the same on every skin; a background `:active` lost to the skin block on all but og, and an inset `box-shadow` lost to the skin hover rules, which is why neither is used. The light skins darken instead of brightening, and `prefers-reduced-motion` drops the scale.
|
||||
|
||||
|
||||
+99
-22
@@ -4134,15 +4134,85 @@ class CodemanApp {
|
||||
}
|
||||
}
|
||||
|
||||
// Session-owned reservations survive pane switches and terminal replacement.
|
||||
_inputFifo(sessionId) {
|
||||
if (!this._inputFifos) this._inputFifos = new Map();
|
||||
if (!this._inputFifos.has(sessionId)) this._inputFifos.set(sessionId, { ops: [], timer: null, draining: false });
|
||||
return this._inputFifos.get(sessionId);
|
||||
}
|
||||
|
||||
_enqueueInput(sessionId, ops) {
|
||||
if (!sessionId || (this.sessions && !this.sessions.has(sessionId))) return;
|
||||
const fifo = this._inputFifo(sessionId);
|
||||
fifo.ops.push(...ops);
|
||||
this._drainInputFifo(sessionId, fifo);
|
||||
}
|
||||
|
||||
_drainInputFifo(sessionId, fifo) {
|
||||
if (fifo.timer !== null || fifo.draining) return;
|
||||
fifo.draining = true;
|
||||
try {
|
||||
while (fifo.ops.length && this._inputFifos.get(sessionId) === fifo) {
|
||||
const op = fifo.ops.shift();
|
||||
if (op.gap !== undefined) {
|
||||
fifo.timer = setTimeout(() => {
|
||||
fifo.timer = null;
|
||||
if (this._inputFifos.get(sessionId) === fifo) this._drainInputFifo(sessionId, fifo);
|
||||
}, op.gap);
|
||||
break;
|
||||
}
|
||||
if (op.key) {
|
||||
fetch(`/api/sessions/${sessionId}/send-key`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: op.key }),
|
||||
}).catch(() => {});
|
||||
} else if (op.write) {
|
||||
this._enqueueReliableInput(sessionId, op.write, { useMux: op.useMux });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fifo.draining = false;
|
||||
}
|
||||
}
|
||||
|
||||
_sealPendingInput(sessionId) {
|
||||
const timer = this._inputFlushTimeout?.get(sessionId);
|
||||
clearTimeout(timer);
|
||||
this._inputFlushTimeout?.delete(sessionId);
|
||||
const text = this._pendingInput?.get(sessionId);
|
||||
this._pendingInput?.delete(sessionId);
|
||||
if (text) this._enqueueInput(sessionId, [{ write: text }]);
|
||||
}
|
||||
|
||||
_settleMainInput(reason) {
|
||||
const sessionId = this.activeSessionId;
|
||||
this._iosNativeInput?.settle?.();
|
||||
this._sealPendingInput(sessionId);
|
||||
if (sessionId) this._flushLocalEchoTo(sessionId);
|
||||
this._iosNativeInput?.reset?.(reason);
|
||||
this._mobileImePreview?.reset?.();
|
||||
this._mobileImeCommitOutputSeq = null;
|
||||
this._localEchoOverlay?.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Public input entry point — name/signature kept for all call sites.
|
||||
* Records the input durably, then delivers it reliably (exactly-once). Never
|
||||
* blocks the keystroke flush; never silently drops on a half-open socket.
|
||||
* Seals the session's batched keystrokes, then enqueues the input on that
|
||||
* session's FIFO, which hands it to the durable exactly-once layer
|
||||
* (_enqueueReliableInput). It can wait behind an earlier `gap` (a delayed
|
||||
* Enter); it never silently drops on a half-open socket.
|
||||
* @param {string} sessionId
|
||||
* @param {string} input
|
||||
* @param {{useMux?: boolean}} [opts] - useMux only affects the POST fallback.
|
||||
*/
|
||||
_sendInputAsync(sessionId, input, opts) {
|
||||
this._sealPendingInput(sessionId);
|
||||
this._enqueueInput(sessionId, [{ write: input, ...opts }]);
|
||||
}
|
||||
|
||||
// Durable delivery starts here; FIFO gaps order enqueueing, not ACK completion.
|
||||
_enqueueReliableInput(sessionId, input, opts) {
|
||||
if (!sessionId || !input) return;
|
||||
const useMux = opts?.useMux === true;
|
||||
// Both transports refuse a frame over the server's limit (issue #484), and a
|
||||
@@ -9385,6 +9455,24 @@ class CodemanApp {
|
||||
// `skipSnapshot`: the tile grid opening on the session it parks
|
||||
// (tile-grid.js openTileGrid), whose snapshot closing the grid discards.
|
||||
_cleanupPreviousSession(newSessionId, { skipSnapshot = false, keepCjkDraft = false } = {}) {
|
||||
// Clear CJK input to prevent sending stale text to the wrong session.
|
||||
// Must go through CjkInput.clear() — a raw value wipe leaves the module's
|
||||
// pending flush timers armed and drops the phantom char it relies on.
|
||||
// A held Send on Enter draft survives a reload of the same session: nothing
|
||||
// switched, and the answer would be gone. On a real switch it is stashed for
|
||||
// the session being left (selectSession restores it on the way back), so a
|
||||
// stray swipe does not lose it. Live mode still clears, since a pending
|
||||
// debounced flush could fire mid-reconnect.
|
||||
if (typeof CjkInput !== 'undefined') {
|
||||
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) {
|
||||
if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
|
||||
CjkInput.clear();
|
||||
}
|
||||
} else {
|
||||
const cjkEl = document.getElementById('cjkInput');
|
||||
if (cjkEl) cjkEl.value = '';
|
||||
}
|
||||
this._settleMainInput('session');
|
||||
// Snapshot the OUTGOING session's xterm rendered state (viewport + scrollback +
|
||||
// colors/attrs) before the terminal gets cleared/reset. Lets us restore the
|
||||
// exact view on switch-back rather than replaying codex's byte stream, which
|
||||
@@ -9434,24 +9522,6 @@ class CodemanApp {
|
||||
// Close WebSocket for previous session (new one opens after buffer load)
|
||||
this._disconnectWs();
|
||||
|
||||
// Clear CJK input to prevent sending stale text to the wrong session.
|
||||
// Must go through CjkInput.clear() — a raw value wipe leaves the module's
|
||||
// pending flush timers armed and drops the phantom char it relies on.
|
||||
// A held Send on Enter draft survives a reload of the same session: nothing
|
||||
// switched, and the answer would be gone. On a real switch it is stashed for
|
||||
// the session being left (selectSession restores it on the way back), so a
|
||||
// stray swipe does not lose it. Live mode still clears, since a pending
|
||||
// debounced flush could fire mid-reconnect.
|
||||
if (typeof CjkInput !== 'undefined') {
|
||||
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) {
|
||||
if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
|
||||
CjkInput.clear();
|
||||
}
|
||||
} else {
|
||||
const cjkEl = document.getElementById('cjkInput');
|
||||
if (cjkEl) cjkEl.value = '';
|
||||
}
|
||||
|
||||
// Clean up flicker filter state when switching sessions
|
||||
this._clearTimer('flickerFilterTimeout');
|
||||
this.flickerFilterBuffer = '';
|
||||
@@ -9497,7 +9567,6 @@ class CodemanApp {
|
||||
if (ta) ta.dispatchEvent(new CompositionEvent('compositionend', { data: '' }));
|
||||
}
|
||||
} catch {}
|
||||
this._flushLocalEchoTo(this.activeSessionId);
|
||||
this._localEchoOverlay?.clear();
|
||||
// Predictions are ephemeral + already sent: nothing to save/restore
|
||||
// across a tab switch (unlike the buffer overlay's setFlushed machinery)
|
||||
@@ -10017,7 +10086,7 @@ class CodemanApp {
|
||||
// hides this one from it. Flush first or the characters are cleared
|
||||
// unread. The geometry replay re-enters here with no gesture behind it,
|
||||
// so on a touch device this fires while the user is still typing.
|
||||
this._flushLocalEchoTo(sessionId);
|
||||
this._settleMainInput('session');
|
||||
this.activeSessionId = null;
|
||||
}
|
||||
// Focus terminal SYNCHRONOUSLY before any await — iOS Safari only honors
|
||||
@@ -10830,6 +10899,14 @@ class CodemanApp {
|
||||
this._activeRename.cancel();
|
||||
}
|
||||
this.sessions.delete(sessionId);
|
||||
const fifo = this._inputFifos?.get(sessionId);
|
||||
clearTimeout(fifo?.timer);
|
||||
this._inputFifos?.delete(sessionId);
|
||||
const inputTimer = this._inputFlushTimeout?.get(sessionId);
|
||||
clearTimeout(inputTimer);
|
||||
this._inputFlushTimeout?.delete(sessionId);
|
||||
this._pendingInput?.delete(sessionId);
|
||||
this._lastKeystrokeTime?.delete(sessionId);
|
||||
// Remove from tab order
|
||||
const orderIndex = this.sessionOrder.indexOf(sessionId);
|
||||
if (orderIndex !== -1) {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*
|
||||
* For drag-and-drop: listens on the terminal container for file drops.
|
||||
*
|
||||
* @dependency app.js (uses global `app` for sendInput, activeSessionId, showToast)
|
||||
* @dependency app.js (uses global `app` for _sendInputAsync, _prepareExternalInput, activeSessionId, showToast)
|
||||
* @dependency panels-ui.js (provides showToast)
|
||||
*/
|
||||
|
||||
@@ -142,6 +142,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
return;
|
||||
}
|
||||
|
||||
const pane = this._paneForSession?.(sessionId);
|
||||
if (pane) this._prepareExternalInput?.(pane, 'toolbar-attachment');
|
||||
const stillActive = this.activeSessionId === sessionId;
|
||||
// The overlay holds the prompt only while local echo actually owns it. A
|
||||
// session handed back to plain PTY echo by a composer nav key (echo
|
||||
@@ -152,6 +154,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// goes to the PTY like any other background write.
|
||||
const overlayOwnsPrompt =
|
||||
stillActive &&
|
||||
(!pane || (pane.isPrimary && pane.sessionId === sessionId)) &&
|
||||
!this._tilesOwnTerminal?.() &&
|
||||
this._localEchoEnabled &&
|
||||
this._localEchoOverlay &&
|
||||
@@ -394,10 +397,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
const paths = results.filter(Boolean);
|
||||
if (paths.length > 0 && options.insert !== false) {
|
||||
// Insert all paths in one shot, space-separated, in selection order, into
|
||||
// the session the batch was uploaded TO. Not sendInput(): it re-reads
|
||||
// activeSessionId, and after the awaits above that is whatever tab the
|
||||
// user switched to mid-upload, so the paths landed in the wrong session.
|
||||
// Same delivery sendInput() uses (durable queue, useMux for the POST path).
|
||||
// the session the batch was uploaded to, captured before the awaits above,
|
||||
// not the active tab the user may have switched to mid-upload.
|
||||
// Delivery uses the durable session-bound path, with useMux for the POST fallback.
|
||||
const pane = this._paneForSession?.(sessionId);
|
||||
if (pane) this._prepareExternalInput?.(pane, 'upload-insert', { flushEcho: true });
|
||||
this._sendInputAsync(sessionId, paths.join(' '), { useMux: true });
|
||||
}
|
||||
|
||||
|
||||
@@ -4547,6 +4547,7 @@
|
||||
<script defer src="mobile-ime-preview.js"></script>
|
||||
<!-- Forwards committed input events that xterm drops on Android/GBoard soft keyboards. Must precede terminal-ui.js. -->
|
||||
<script defer src="terminal-keycode229-recovery.js"></script>
|
||||
<script defer src="terminal-ios-native-input.js"></script>
|
||||
<!-- Hardened markdown HTML sanitizer (wires DOMPurify). Must precede app.js. -->
|
||||
<script defer src="sanitize-html.js"></script>
|
||||
<!-- Owner tab layout projection (grouped vertical rail); pure, read by app.js. -->
|
||||
|
||||
+76
-29
@@ -17,10 +17,10 @@
|
||||
* and a lone digit at a pending dialog goes without it). Shift+Enter is a
|
||||
* newline, Esc clears, Backspace and the arrows reach the PTY only from an
|
||||
* empty field, and so do the Ctrl shortcuts. Autocorrect is on. A held draft
|
||||
* belongs to one session (_owner): clear() stashes it under that session and
|
||||
* restoreDraft() brings it back when the session is shown again, except a
|
||||
* clear({ discard: true }) (the keyboard bar's clear-line key), which throws
|
||||
* it away.
|
||||
* belongs to one session: a captured target takes precedence over _owner when
|
||||
* clear() stashes it, and restoreDraft() brings it back when that session is
|
||||
* shown again, except a clear({ discard: true }) (the keyboard bar's clear-line
|
||||
* key), which throws it away.
|
||||
*
|
||||
* ## Android IME challenge
|
||||
*
|
||||
@@ -65,6 +65,9 @@
|
||||
const CjkInput = (() => {
|
||||
let _textarea = null;
|
||||
let _send = null;
|
||||
let _captureTarget = null;
|
||||
let _target;
|
||||
let _hasTarget = false;
|
||||
let _initialized = false;
|
||||
let _composing = false;
|
||||
let _flushTimer = null;
|
||||
@@ -88,10 +91,10 @@ const CjkInput = (() => {
|
||||
let _holdApplied = false;
|
||||
// Send-on-Enter: held drafts of the sessions switched away from, by session id.
|
||||
const _drafts = new Map();
|
||||
// Send-on-Enter: the session the field's text belongs to (the one last shown,
|
||||
// set by restoreDraft). clear() stashes a held draft under it, so every path
|
||||
// that drops the active session before the next cleanup (goHome, the tile
|
||||
// grid's _replaceTileGrid and _onTileAdoptedElsewhere) keeps the answer.
|
||||
// Send-on-Enter: the session last shown, set by restoreDraft. A captured
|
||||
// target takes precedence; otherwise clear() stashes a held draft under this
|
||||
// owner, so paths that drop the active session before the next cleanup
|
||||
// (goHome, _replaceTileGrid and _onTileAdoptedElsewhere) keep the answer.
|
||||
let _owner = null;
|
||||
const _listeners = {};
|
||||
|
||||
@@ -195,8 +198,21 @@ const CjkInput = (() => {
|
||||
return str.replace(//g, '');
|
||||
}
|
||||
|
||||
function _holdTarget() {
|
||||
if (!_hasTarget) {
|
||||
_target = _captureTarget?.();
|
||||
_hasTarget = true;
|
||||
}
|
||||
}
|
||||
|
||||
function _targetForSend() {
|
||||
return _hasTarget ? _target : _captureTarget?.();
|
||||
}
|
||||
|
||||
function _resetToPhantom() {
|
||||
_heldBase = '';
|
||||
_target = undefined;
|
||||
_hasTarget = false;
|
||||
// Skip redundant writes: every programmatic value/selection mutation can
|
||||
// desync an Android IME's input session (InputConnection) — after which
|
||||
// the keyboard composes in its own UI but NO events ever reach the page.
|
||||
@@ -236,7 +252,7 @@ const CjkInput = (() => {
|
||||
const val = _strip(_textarea.value);
|
||||
_t(`flush ${val ? 'send len=' + val.length : 'empty'}`);
|
||||
if (val) {
|
||||
_send(val);
|
||||
_send(val, _targetForSend());
|
||||
}
|
||||
_resetToPhantom();
|
||||
}
|
||||
@@ -273,14 +289,15 @@ const CjkInput = (() => {
|
||||
* (terminal-ui.js _sendCjkPrompt). Enter is never part of the text's write:
|
||||
* Codex takes characters arriving in one burst as a paste and folds an Enter
|
||||
* inside it into the paste, and Claude Code does the same for a long burst, so
|
||||
* even `1\r` in one write sits unsent. Returns false when the text was refused
|
||||
* (too long, no session), so the field keeps it. */
|
||||
function _sendHeld(val) {
|
||||
* even `1\r` in one write sits unsent. Returns false when the text is refused
|
||||
* (too long, no session), so the field keeps it. `sessionId` is the target
|
||||
* captured when the text started (see _targetForSend). */
|
||||
function _sendHeld(val, sessionId) {
|
||||
if (!_sendPrompt) {
|
||||
_t('hold send DROP no-prompt-path');
|
||||
return false;
|
||||
}
|
||||
return _sendPrompt(val) !== false;
|
||||
return _sendPrompt(val, sessionId) !== false;
|
||||
}
|
||||
|
||||
/** Enter: send what the field holds (or a bare Enter when it is empty) and
|
||||
@@ -296,11 +313,11 @@ const CjkInput = (() => {
|
||||
if (_hold && !val.trim()) val = '';
|
||||
if (_hold && val) {
|
||||
// Refused (too long, no session): keep the text so nothing is lost.
|
||||
if (!_sendHeld(val)) return false;
|
||||
if (!_sendHeld(val, _targetForSend())) return false;
|
||||
} else if (val) {
|
||||
_send(val + '\r');
|
||||
_send(val + '\r', _targetForSend());
|
||||
} else {
|
||||
_send('\r');
|
||||
_send('\r', _targetForSend());
|
||||
}
|
||||
_resetToPhantom();
|
||||
if (_hold) _autoGrow();
|
||||
@@ -336,10 +353,17 @@ const CjkInput = (() => {
|
||||
return;
|
||||
}
|
||||
_t('hold ctrl key');
|
||||
_textarea.value = PHANTOM + before;
|
||||
_textarea.setSelectionRange(1 + at, 1 + at);
|
||||
_heldBase = before;
|
||||
_send(now[at]);
|
||||
// The control key goes to the session this field's text was captured for;
|
||||
// with no draft left, the next answer captures its own destination.
|
||||
const target = _targetForSend();
|
||||
if (!before) {
|
||||
_resetToPhantom();
|
||||
} else {
|
||||
_textarea.value = PHANTOM + before;
|
||||
_textarea.setSelectionRange(1 + at, 1 + at);
|
||||
_heldBase = before;
|
||||
}
|
||||
_send(now[at], target);
|
||||
}
|
||||
|
||||
/** Send-on-Enter input handling: nothing is flushed, the field only settles.
|
||||
@@ -353,7 +377,7 @@ const CjkInput = (() => {
|
||||
const wasEmpty = !_heldBase;
|
||||
_heldBase = _strip(_textarea.value);
|
||||
if (!_heldBase) {
|
||||
if (wasEmpty) _send('\x7f');
|
||||
if (wasEmpty) _send('\x7f', _targetForSend());
|
||||
_resetToPhantom();
|
||||
} else if (!_textarea.value.startsWith(PHANTOM)) {
|
||||
// Backspace at the very start of the text deleted the phantom: put it
|
||||
@@ -397,11 +421,12 @@ const CjkInput = (() => {
|
||||
}
|
||||
|
||||
return {
|
||||
init({ send, sendPrompt = null }) {
|
||||
init({ send, sendPrompt = null, captureTarget }) {
|
||||
if (_initialized) this.destroy();
|
||||
|
||||
_send = send;
|
||||
_sendPrompt = sendPrompt;
|
||||
_captureTarget = captureTarget;
|
||||
_composing = false;
|
||||
_printableKeydownAt = null;
|
||||
_flushTimer = null;
|
||||
@@ -461,6 +486,7 @@ const CjkInput = (() => {
|
||||
// ── Composition tracking (keyboard IME — works for CJK typing) ──
|
||||
_listeners.compositionstart = () => {
|
||||
_t(`compstart ${_vdesc(_textarea.value)}`);
|
||||
_holdTarget();
|
||||
_composing = true;
|
||||
_printableKeydownAt = null;
|
||||
_cancelDebouncedFlush();
|
||||
@@ -515,7 +541,7 @@ const CjkInput = (() => {
|
||||
// and the arrows already follow.
|
||||
if (e.ctrlKey && CTRL_KEYS[e.key] && (!_hold || _isEffectivelyEmpty())) {
|
||||
e.preventDefault();
|
||||
_send(CTRL_KEYS[e.key]);
|
||||
_send(CTRL_KEYS[e.key], _targetForSend());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -527,7 +553,7 @@ const CjkInput = (() => {
|
||||
// Backspace: forward to PTY when no real text in textarea
|
||||
if (e.key === 'Backspace' && _isEffectivelyEmpty()) {
|
||||
e.preventDefault();
|
||||
_send('\x7f');
|
||||
_send('\x7f', _targetForSend());
|
||||
_resetToPhantom();
|
||||
return;
|
||||
}
|
||||
@@ -539,14 +565,14 @@ const CjkInput = (() => {
|
||||
const modNav = _modifiedNavSequence(e);
|
||||
if (modNav) {
|
||||
e.preventDefault();
|
||||
_send(modNav);
|
||||
_send(modNav, _targetForSend());
|
||||
return;
|
||||
}
|
||||
|
||||
// Arrow/function keys: forward to PTY when no real text
|
||||
if (PASSTHROUGH_KEYS[e.key] && _isEffectivelyEmpty()) {
|
||||
e.preventDefault();
|
||||
_send(PASSTHROUGH_KEYS[e.key]);
|
||||
_send(PASSTHROUGH_KEYS[e.key], _targetForSend());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -554,6 +580,7 @@ const CjkInput = (() => {
|
||||
// the committed text. Let the browser/IME produce the input event so
|
||||
// full-width punctuation and other layout transforms are preserved.
|
||||
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey && _isEffectivelyEmpty()) {
|
||||
_holdTarget();
|
||||
_printableKeydownAt = performance.now();
|
||||
return;
|
||||
}
|
||||
@@ -565,6 +592,7 @@ const CjkInput = (() => {
|
||||
_t(`input ${e.inputType || '?'} ic=${e.isComposing} c=${_composing} ${_vdesc(_textarea.value)}`);
|
||||
const printableKeydownAt = _printableKeydownAt;
|
||||
_printableKeydownAt = null;
|
||||
if (!_isEffectivelyEmpty()) _holdTarget();
|
||||
// ── Stuck-composition recovery ──
|
||||
// Some IMEs (WeChat/Sogou keyboards) fire compositionstart without a
|
||||
// matching compositionend. A stale _composing=true blocks every flush
|
||||
@@ -591,7 +619,7 @@ const CjkInput = (() => {
|
||||
if (_composing) return;
|
||||
if (_isEffectivelyEmpty()) {
|
||||
_cancelDebouncedFlush();
|
||||
_send('\x7f');
|
||||
_send('\x7f', _targetForSend());
|
||||
_resetToPhantom();
|
||||
return;
|
||||
}
|
||||
@@ -640,6 +668,15 @@ const CjkInput = (() => {
|
||||
return this;
|
||||
},
|
||||
|
||||
/** Commit settled text before pane ownership changes; never send composition. */
|
||||
flushNow() {
|
||||
if (!_initialized || !_textarea) return;
|
||||
_cancelDebouncedFlush();
|
||||
clearTimeout(_compositionFlushTimer);
|
||||
_compositionFlushTimer = null;
|
||||
_flush();
|
||||
},
|
||||
|
||||
/**
|
||||
* Discard pending text and timers (e.g. on session switch, so stale text
|
||||
* can't flush into the wrong session). Restores the phantom so backspace
|
||||
@@ -653,13 +690,15 @@ const CjkInput = (() => {
|
||||
// nothing is stashed, any older stash of this session goes too, and the
|
||||
// field keeps its owner, since the session shown has not changed.
|
||||
if (_owner) _drafts.delete(_owner);
|
||||
if (_hasTarget && _target) _drafts.delete(_target);
|
||||
} else {
|
||||
// Send-on-Enter: a held draft is stashed for the session it was typed
|
||||
// for, whichever path got here. discardDraft() drops the owner of a
|
||||
// removed session, so its text is not stashed again.
|
||||
if (_hold && _owner) {
|
||||
const sessionId = _hasTarget && _target ? _target : _owner;
|
||||
if (_hold && sessionId) {
|
||||
const draft = _strip(_textarea.value);
|
||||
if (draft.trim()) _drafts.set(_owner, draft);
|
||||
if (draft.trim()) _drafts.set(sessionId, draft);
|
||||
}
|
||||
_owner = null;
|
||||
}
|
||||
@@ -748,6 +787,7 @@ const CjkInput = (() => {
|
||||
* clear(); restoreDraft() puts it back when that session is shown again.
|
||||
*/
|
||||
stashDraft(sessionId) {
|
||||
if (_hasTarget && _target) sessionId = _target;
|
||||
if (!_initialized || !_textarea || !_hold || !sessionId) return;
|
||||
// An empty field leaves any stash alone: a draft only sits in the map
|
||||
// while its session is not shown (restoreDraft takes it out), and the
|
||||
@@ -771,6 +811,10 @@ const CjkInput = (() => {
|
||||
_textarea.value = PHANTOM + draft;
|
||||
_textarea.setSelectionRange(_textarea.value.length, _textarea.value.length);
|
||||
_heldBase = draft;
|
||||
// The restored text belongs to this session: Enter after a focus move to
|
||||
// another pane must still send it here (see _targetForSend).
|
||||
_target = sessionId;
|
||||
_hasTarget = true;
|
||||
_autoGrow();
|
||||
},
|
||||
|
||||
@@ -802,6 +846,9 @@ const CjkInput = (() => {
|
||||
window.cjkActive = false;
|
||||
_composing = false;
|
||||
_printableKeydownAt = null;
|
||||
_target = undefined;
|
||||
_hasTarget = false;
|
||||
_captureTarget = null;
|
||||
for (const key of Object.keys(_listeners)) delete _listeners[key];
|
||||
_initialized = false;
|
||||
},
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
* @globals {class} FocusTrap
|
||||
*
|
||||
* @dependency mobile-handlers.js (MobileDetection.isTouchDevice)
|
||||
* @dependency app.js (uses global `app` for sendInput, activeSessionId, terminal)
|
||||
* @dependency app.js (uses global `app` for _enqueueInput, _sendInputAsync, _prepareExternalInput, activeSessionId, terminal)
|
||||
* @loadorder 5 of 15 — loaded after notification-manager.js, before app.js
|
||||
*/
|
||||
|
||||
@@ -1189,7 +1189,7 @@ const KeyboardAccessoryBar = {
|
||||
|
||||
/** Handle accessory button actions */
|
||||
handleAction(action, btn) {
|
||||
if (typeof app === 'undefined' || !app.activeSessionId) return;
|
||||
if (typeof app === 'undefined') return;
|
||||
|
||||
// Any key other than Ctrl itself spends the modifier. It is a one-shot for
|
||||
// the next TYPED character, so an accessory key tapped in between (Esc, an
|
||||
@@ -1228,10 +1228,12 @@ const KeyboardAccessoryBar = {
|
||||
// Tab means "complete what I just typed", but with local echo the typed
|
||||
// text is still buffered in the overlay and has never reached the PTY —
|
||||
// a bare \t would ask the CLI to complete an empty composer.
|
||||
this.flushPendingThen(() => this.sendKey('\t'));
|
||||
this.flushPendingThen('\t');
|
||||
break;
|
||||
case 'shift-tab':
|
||||
this.sendKey('\x1b[Z');
|
||||
// Cycles a mode, never edits the composer: leave the unsent draft in the
|
||||
// overlay, as a typed Shift+Tab does.
|
||||
this.sendKey('\x1b[Z', { keepDraft: true });
|
||||
break;
|
||||
case 'ctrl-o':
|
||||
this.sendKey('\x0f');
|
||||
@@ -1268,6 +1270,7 @@ const KeyboardAccessoryBar = {
|
||||
this.pickPath();
|
||||
break;
|
||||
case 'clear-input':
|
||||
this._prepareInput(undefined, 'accessory-clear');
|
||||
app.clearTerminalInput?.();
|
||||
break;
|
||||
case 'dismiss':
|
||||
@@ -1331,38 +1334,53 @@ const KeyboardAccessoryBar = {
|
||||
this.element.classList.toggle('codex-enabled', this._isCodexSession());
|
||||
},
|
||||
|
||||
/** Capture the destination before settling native input; background drafts
|
||||
* must never reset a different pane's owner. */
|
||||
_prepareInput(sessionId, reason, opts) {
|
||||
const target = sessionId || (typeof app._focusedPane === 'function' ? app._focusedPane()?.sessionId : app.activeSessionId);
|
||||
const pane = app._paneForSession?.(target);
|
||||
if (pane) {
|
||||
if (opts) app._prepareExternalInput?.(pane, reason, opts);
|
||||
else app._prepareExternalInput?.(pane, reason);
|
||||
}
|
||||
return target;
|
||||
},
|
||||
|
||||
/** Send a slash command to the active session.
|
||||
* Sends text and Enter separately so Ink processes them as distinct events. */
|
||||
* Sends text and Enter separately so Ink processes them as distinct events.
|
||||
* The unsent local-echo draft stays in the overlay: flushing it would submit `draft/command`. */
|
||||
sendCommand(command) {
|
||||
if (!app.activeSessionId) return;
|
||||
// Send command text first (without Enter)
|
||||
app.sendInput(command);
|
||||
// Send Enter separately after a brief delay so Ink has time to process the text.
|
||||
setTimeout(() => app.sendInput('\r'), 120);
|
||||
const sessionId = this._prepareInput(undefined, 'accessory-command');
|
||||
if (!sessionId) return;
|
||||
app._enqueueInput(sessionId, [{ write: command, useMux: true }, { gap: 120 }, { write: '\r', useMux: true }]);
|
||||
},
|
||||
|
||||
/**
|
||||
* Flush whatever the local-echo overlay is still holding, THEN run `after()`.
|
||||
*
|
||||
* On a phone the characters you type sit in the overlay and have never
|
||||
* reached the PTY, so any key that acts on "what I just typed" has to push
|
||||
* that text out first or the CLI acts on an empty composer. Mirrors the
|
||||
* flush the typed path performs in terminal-ui.js's onData; the 120ms is the
|
||||
* same settle delay sendCommand uses, so the text lands before the key.
|
||||
* Flush local echo and reserve the following key atomically in the session
|
||||
* FIFO, so switching panes during the settle gap cannot redirect the key.
|
||||
*/
|
||||
flushPendingThen(after) {
|
||||
const overlay = app._localEchoOverlay;
|
||||
flushPendingThen(sequence, reason = 'accessory-key', passthrough = false) {
|
||||
const pane = app._focusedPane?.();
|
||||
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
|
||||
if (!sessionId) return;
|
||||
if (pane) app._prepareExternalInput?.(pane, reason);
|
||||
const overlay = !pane || pane.isPrimary ? app._localEchoOverlay : null;
|
||||
const pending = (app._localEchoEnabled && overlay?.pendingText) || '';
|
||||
if (!pending) {
|
||||
after();
|
||||
return;
|
||||
if (passthrough) {
|
||||
if (!app._echoPassthroughSessions) app._echoPassthroughSessions = new Set();
|
||||
app._echoPassthroughSessions.add(sessionId);
|
||||
}
|
||||
overlay.clear();
|
||||
overlay.suppressBufferDetection?.();
|
||||
app._flushedOffsets?.delete(app.activeSessionId);
|
||||
app._flushedTexts?.delete(app.activeSessionId);
|
||||
app.sendInput(pending);
|
||||
setTimeout(after, 120);
|
||||
const ops = [];
|
||||
if (pending) {
|
||||
overlay.clear();
|
||||
overlay.suppressBufferDetection?.();
|
||||
app._flushedOffsets?.delete(sessionId);
|
||||
app._flushedTexts?.delete(sessionId);
|
||||
ops.push({ write: pending, useMux: true }, { gap: 120 });
|
||||
}
|
||||
app._predictiveEcho?.clearPredictions();
|
||||
ops.push({ write: sequence });
|
||||
app._enqueueInput(sessionId, ops);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -1380,38 +1398,41 @@ const KeyboardAccessoryBar = {
|
||||
* broken because what came back was never what the row showed.
|
||||
*/
|
||||
sendNavKey(sequence) {
|
||||
if (!app.activeSessionId) return;
|
||||
if (!app._echoPassthroughSessions) app._echoPassthroughSessions = new Set();
|
||||
app._echoPassthroughSessions.add(app.activeSessionId);
|
||||
this.flushPendingThen(() => this.sendKey(sequence));
|
||||
this.flushPendingThen(sequence, 'accessory-navigation', true);
|
||||
},
|
||||
|
||||
/** Send a special key (arrow, escape, etc.) directly to the PTY.
|
||||
* Bypasses tmux send-keys -l (literal mode) since escape sequences
|
||||
* must be written raw to be interpreted as key presses by Ink. */
|
||||
sendKey(escapeSequence) {
|
||||
if (!app.activeSessionId) return;
|
||||
// Arrows/Esc move the server-side cursor and bypass onData: clear
|
||||
// predictions now instead of waiting out the ~150ms off-row grace.
|
||||
* must be written raw to be interpreted as key presses by Ink.
|
||||
* `keepDraft` leaves the unsent local-echo draft in the overlay. */
|
||||
sendKey(escapeSequence, { keepDraft = false } = {}) {
|
||||
const sessionId = this._prepareInput(undefined, 'accessory-key', keepDraft ? undefined : { flushEcho: true });
|
||||
if (!sessionId) return;
|
||||
app._predictiveEcho?.clearPredictions();
|
||||
fetch(`/api/sessions/${app.activeSessionId}/input`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ input: escapeSequence })
|
||||
}).catch(() => {});
|
||||
app._enqueueInput(sessionId, [{ write: escapeSequence }]);
|
||||
},
|
||||
|
||||
/** Browse the active session's workspace and insert a selected path without Enter. */
|
||||
pickPath() {
|
||||
if (!app.activeSessionId) return;
|
||||
const session = app.sessions?.get(app.activeSessionId);
|
||||
const pane = app._focusedPane?.();
|
||||
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
|
||||
if (!sessionId) return;
|
||||
const session = app.sessions?.get(sessionId);
|
||||
PathPicker.open({
|
||||
title: 'Insert File or Folder Path',
|
||||
sessionId: app.activeSessionId,
|
||||
sessionId,
|
||||
initialPath: session?.workingDir || '',
|
||||
directoriesOnly: false,
|
||||
onSelect: (path) => {
|
||||
app.insertTerminalText?.(path);
|
||||
const targetPane = app._paneForSession?.(sessionId);
|
||||
if (targetPane?.isPrimary && app._localEchoPolicy === 'predict') app._predictiveEcho?.clearPredictions();
|
||||
if (targetPane?.isPrimary && app._localEchoEnabled && app._localEchoOverlay && !app._echoPassthroughSessions?.has(sessionId)) {
|
||||
app._prepareExternalInput?.(targetPane, 'accessory-path');
|
||||
app._localEchoOverlay.appendText(path);
|
||||
} else {
|
||||
if (targetPane) app._prepareExternalInput?.(targetPane, 'accessory-path', { flushEcho: true });
|
||||
app._sendInputAsync(sessionId, path, { useMux: true });
|
||||
}
|
||||
setTimeout(() => app.terminal?.focus(), 100);
|
||||
},
|
||||
});
|
||||
@@ -1421,6 +1442,9 @@ const KeyboardAccessoryBar = {
|
||||
* exists only in the overlay; flushed text already reached the PTY, so erase
|
||||
* that prefix before making the textarea authoritative. */
|
||||
_takePendingLocalEcho(sessionId) {
|
||||
this._prepareInput(sessionId, 'accessory-compose-adopt');
|
||||
const pane = app._focusedPane?.();
|
||||
if (pane && (!pane.isPrimary || pane.sessionId !== sessionId)) return '';
|
||||
if (!app._localEchoEnabled || !app._localEchoOverlay) return '';
|
||||
const pending = app._localEchoOverlay.pendingText || '';
|
||||
const overlayFlushed = app._localEchoOverlay.getFlushed?.() || {};
|
||||
@@ -1458,17 +1482,15 @@ const KeyboardAccessoryBar = {
|
||||
* Enter stays a separate delayed write because Codex drops keys sharing a
|
||||
* PTY read with a bracketed paste. */
|
||||
_sendComposedPrompt(sessionId, text) {
|
||||
if (!this._sendBracketedPaste(sessionId, text, 'Prompt')) return false;
|
||||
setTimeout(() => app._sendInputAsync(sessionId, '\r', { useMux: true }), 120);
|
||||
return true;
|
||||
return this._sendBracketedPaste(sessionId, text, 'Prompt', true);
|
||||
},
|
||||
|
||||
/** One bracketed-paste write on the durable session-bound path, the same
|
||||
* bytes a terminal paste produces, so the receiving shell or CLI takes a
|
||||
* multi-line block as one edit. Never presses Enter: callers decide.
|
||||
* `label` names the payload in the too-long toast. */
|
||||
_sendBracketedPaste(sessionId, text, label) {
|
||||
if (!sessionId || !text || typeof app._sendInputAsync !== 'function') return false;
|
||||
_sendBracketedPaste(sessionId, text, label, submit = false) {
|
||||
if (!sessionId || !text || typeof app._enqueueInput !== 'function') return false;
|
||||
app._predictiveEcho?.clearPredictions();
|
||||
// Match xterm's prepareTextForTerminal(): CR keeps embedded newlines inside
|
||||
// the single-line input transport and is what terminal.paste() emitted.
|
||||
@@ -1483,7 +1505,10 @@ const KeyboardAccessoryBar = {
|
||||
app.showToast?.(`${label} is too long to send (maximum ${this._composerMaxLength.toLocaleString()} characters)`, 'error');
|
||||
return false;
|
||||
}
|
||||
app._sendInputAsync(sessionId, `${COMPOSER_PASTE_START}${pasteText}${COMPOSER_PASTE_END}`);
|
||||
this._prepareInput(sessionId, submit ? 'accessory-compose-send' : 'accessory-paste', { flushEcho: true });
|
||||
const ops = [{ write: `${COMPOSER_PASTE_START}${pasteText}${COMPOSER_PASTE_END}` }];
|
||||
if (submit) ops.push({ gap: 120 }, { write: '\r', useMux: true });
|
||||
app._enqueueInput(sessionId, ops);
|
||||
return true;
|
||||
},
|
||||
|
||||
@@ -1500,13 +1525,15 @@ const KeyboardAccessoryBar = {
|
||||
/** Open the manual agent prompt composer. Enter remains a newline; only the
|
||||
* Send button submits. Cancel/backdrop/Escape preserve the per-session draft. */
|
||||
composePrompt() {
|
||||
if (typeof app === 'undefined' || !app.activeSessionId) return;
|
||||
if (this._isShellSession()) {
|
||||
if (typeof app === 'undefined') return;
|
||||
const pane = app._focusedPane?.();
|
||||
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
|
||||
if (!sessionId) return;
|
||||
if (app.sessions?.get(sessionId)?.mode === 'shell') {
|
||||
this.pasteFromClipboard();
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionId = app.activeSessionId;
|
||||
const pending = this._takePendingLocalEcho(sessionId);
|
||||
const saved = this._composerDrafts.get(sessionId) || '';
|
||||
// A parked draft and text typed (or attached) on the prompt since are two
|
||||
@@ -1614,7 +1641,7 @@ const KeyboardAccessoryBar = {
|
||||
};
|
||||
syncUploadUi();
|
||||
try {
|
||||
const paths = await app._uploadAndInsertImages(images, { insert: false });
|
||||
const paths = await app._uploadAndInsertImages(images, { insert: false, sessionId });
|
||||
if (paths?.length) {
|
||||
const currentOverlay =
|
||||
this._composerOverlay?.isConnected && this._composerOverlay.dataset.sessionId === sessionId
|
||||
@@ -1687,10 +1714,13 @@ const KeyboardAccessoryBar = {
|
||||
// draft would be prepended to it the next time the composer opens.
|
||||
this._composerDrafts.delete(sessionId);
|
||||
close({ focusTerminal: true, preserveDraft: false });
|
||||
const targetPane = app._focusedPane?.();
|
||||
if (targetPane?.sessionId === sessionId) app._prepareExternalInput?.(targetPane, 'accessory-compose-insert');
|
||||
if (
|
||||
app._localEchoEnabled &&
|
||||
app._localEchoOverlay &&
|
||||
app.activeSessionId === sessionId &&
|
||||
(!targetPane || (targetPane.isPrimary && targetPane.sessionId === sessionId)) &&
|
||||
!app._tilesOwnTerminal?.() &&
|
||||
!app._echoPassthroughSessions?.has(sessionId)
|
||||
) {
|
||||
@@ -1737,10 +1767,11 @@ const KeyboardAccessoryBar = {
|
||||
* All upload paths reuse app._uploadAndInsertImages() (image-input.js), which
|
||||
* uploads to /api/sessions/:id/paste-image and inserts the saved path. */
|
||||
pasteFromClipboard() {
|
||||
if (typeof app === 'undefined' || !app.activeSessionId) return;
|
||||
// The shell this overlay was opened for: a tab switch while it is open must
|
||||
// not deliver the paste to whatever session is active at Send time.
|
||||
const sessionId = app.activeSessionId;
|
||||
if (typeof app === 'undefined') return;
|
||||
// Capture once: switching focus while the dialog is open cannot redirect it.
|
||||
const pane = app._focusedPane?.();
|
||||
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
|
||||
if (!sessionId) return;
|
||||
|
||||
// Create overlay
|
||||
const overlay = document.createElement('div');
|
||||
|
||||
@@ -42,7 +42,9 @@
|
||||
const KEEP_COMPOSING_KEYCODES = new Set([20, 229, 16, 17, 18]);
|
||||
const CONTROL_OR_LINE_BREAK = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;
|
||||
|
||||
function isIosWebKitTouch(nav = navigator) {
|
||||
// Shared with CodemanIosNativeInput.isSupported(); keep platform gating here
|
||||
// because the preview predates and loads before the native input owner.
|
||||
function isIosWebKitTouch(nav = global.navigator) {
|
||||
const userAgent = String(nav && nav.userAgent ? nav.userAgent : '');
|
||||
const platform = String(nav && nav.platform ? nav.platform : '');
|
||||
const touchPoints = Number(nav && nav.maxTouchPoints ? nav.maxTouchPoints : 0);
|
||||
@@ -59,6 +61,12 @@
|
||||
const render = typeof options.render === 'function' ? options.render : function () {};
|
||||
const clear = typeof options.clear === 'function' ? options.clear : function () {};
|
||||
const onCommit = typeof options.onCommit === 'function' ? options.onCommit : function () {};
|
||||
const ownsNativeInput =
|
||||
typeof options.ownsNativeInput === 'function'
|
||||
? options.ownsNativeInput
|
||||
: function () {
|
||||
return false;
|
||||
};
|
||||
const scheduleFrame = options.scheduleFrame || global.requestAnimationFrame.bind(global);
|
||||
const cancelFrame = options.cancelFrame || global.cancelAnimationFrame.bind(global);
|
||||
const setTimer = options.setTimer || global.setTimeout.bind(global);
|
||||
@@ -73,6 +81,7 @@
|
||||
let frameToken = null;
|
||||
let timerToken = null;
|
||||
let finalizedByKeydown = false;
|
||||
let compositionStart = 0;
|
||||
let destroyed = false;
|
||||
let invokingClear = false;
|
||||
|
||||
@@ -140,17 +149,19 @@
|
||||
cleanup();
|
||||
if (destroyed) return;
|
||||
composing = true;
|
||||
compositionStart = textarea.selectionStart == null ? textarea.value.length : textarea.selectionStart;
|
||||
}
|
||||
|
||||
function updateComposition(event) {
|
||||
if (!composing) return;
|
||||
latestValue = event.data == null ? '' : String(event.data);
|
||||
const segment = safely(ownsNativeInput) ? textarea.value.slice(compositionStart, textarea.selectionEnd) : '';
|
||||
latestValue = event.data == null ? segment : String(event.data);
|
||||
scheduleLatestPreview('provisional');
|
||||
}
|
||||
|
||||
function onComposingInput(event) {
|
||||
if (!event.isComposing) return;
|
||||
updateComposition({ data: event.data == null ? textarea.value : event.data });
|
||||
updateComposition({ data: event.data == null && !safely(ownsNativeInput) ? textarea.value : event.data });
|
||||
}
|
||||
|
||||
function armFallbackTimer(isCurrent) {
|
||||
@@ -203,6 +214,9 @@
|
||||
// finalizes it. `isComposing` and `key` are deliberately not consulted,
|
||||
// because xterm does not consult them.
|
||||
function onKeydown(event) {
|
||||
// Native ownership, not xterm's terminal-key heuristic, decides when the
|
||||
// retained field has finished composing.
|
||||
if (safely(ownsNativeInput)) return;
|
||||
if (keydownTarget !== textarea && event.target !== textarea) return;
|
||||
if (!composing || KEEP_COMPOSING_KEYCODES.has(event.keyCode)) return;
|
||||
finalizeComposition(latestValue, true);
|
||||
@@ -246,6 +260,16 @@
|
||||
return true;
|
||||
}
|
||||
|
||||
function nativeTransaction({ inserted, deleted, composition }) {
|
||||
if (destroyed || !awaitingCommit) return false;
|
||||
if (inserted && consumeTerminalData(inserted)) return true;
|
||||
// No inserted text (or unsafe terminal controls): nothing can display a
|
||||
// commit later. In particular deletion-only/unchanged compositions settle
|
||||
// now instead of leaving unrelated input to consume the 2 s fallback.
|
||||
cleanup();
|
||||
return false;
|
||||
}
|
||||
|
||||
function completeCommit(result) {
|
||||
if (destroyed || !result || result.predicted !== true || !committed) return;
|
||||
cleanup();
|
||||
@@ -275,6 +299,7 @@
|
||||
|
||||
return {
|
||||
consumeTerminalData,
|
||||
nativeTransaction,
|
||||
completeCommit,
|
||||
noteAuthoritativeOutput,
|
||||
reset,
|
||||
|
||||
@@ -2070,18 +2070,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
/** Send Enter to the active session (phone toolbar button).
|
||||
*
|
||||
* MUST go through xterm's onData path, NOT straight to sendInput()/the API.
|
||||
* With local echo on (the mobile default) the characters you typed are still
|
||||
* buffered in the LocalEchoOverlay and have NEVER reached the PTY. The onData
|
||||
* Enter branch (terminal-ui.js) is what flushes that pending text and only
|
||||
* then sends \r. Send a bare \r instead and you submit an empty line while the
|
||||
* typed text stays stranded on screen — which reads as "the button does
|
||||
* nothing". triggerDataEvent replays it exactly as if the key were pressed,
|
||||
* so overlay flush, flushed-offset cleanup and ordering are all reused. */
|
||||
/** Submit the focused pane through the shared native-input/echo boundary. */
|
||||
sendEnterKey() {
|
||||
if (!this.activeSessionId) return;
|
||||
// While the CJK field is visible, onData drops everything (cjkActive), this
|
||||
// Enter included. Press Enter in the field instead: it sends what the field
|
||||
// holds (a Send on Enter answer, or live text not yet flushed), then Enter.
|
||||
@@ -2092,14 +2082,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
CjkInput.submit?.();
|
||||
return;
|
||||
}
|
||||
const coreService = this.terminal?._core?.coreService;
|
||||
if (coreService && typeof coreService.triggerDataEvent === 'function') {
|
||||
coreService.triggerDataEvent('\r', true);
|
||||
return;
|
||||
}
|
||||
// Fallback only if xterm's private core API moves: correct when local echo
|
||||
// is off, and still better than doing nothing.
|
||||
this.sendInput('\r');
|
||||
this.submitFromToolbar();
|
||||
},
|
||||
|
||||
_initRunMode() {
|
||||
|
||||
@@ -0,0 +1,731 @@
|
||||
/**
|
||||
* @fileoverview iOS WebKit native editing owner for xterm's helper textarea.
|
||||
*
|
||||
* Keep the native line intact and reconcile its projected text into one ordered
|
||||
* transaction. xterm retains commands, paste and composition rendering, but no
|
||||
* competing text producer. Native selection is visual only: never send arrows.
|
||||
*
|
||||
* The shared platform predicate lives in MobileImePreview, which already owns
|
||||
* it and loads first. Delegating keeps native ownership and preview gating in
|
||||
* lockstep without adding another platform detector or script dependency.
|
||||
*
|
||||
* @dependency mobile-ime-preview.js (shared isIosWebKitTouch predicate)
|
||||
* @loadorder 5.56 (after mobile-ime-preview.js, before terminal-ui.js/terminal-tile.js)
|
||||
*/
|
||||
(function (global) {
|
||||
'use strict';
|
||||
|
||||
// WebKit removes one grapheme cluster per Backspace, and Claude Code and Codex
|
||||
// delete one grapheme per DEL, so an edit is counted in graphemes: a red heart,
|
||||
// a skin-tone emoji, a flag or a ZWJ family is one DEL, as it was through xterm.
|
||||
// Code points stand in where Intl.Segmenter is missing.
|
||||
const graphemeSegmenter = (function () {
|
||||
try {
|
||||
return typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'
|
||||
? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
|
||||
: null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
function graphemes(text) {
|
||||
return graphemeSegmenter ? Array.from(graphemeSegmenter.segment(text), (part) => part.segment) : Array.from(text);
|
||||
}
|
||||
|
||||
function editBetween(previous, next) {
|
||||
// A pure append (including a combining mark or tone typed onto the last letter)
|
||||
// is sent as-is, as xterm sends it: re-typing the extended cluster would make
|
||||
// a code-point line editor (zsh) double the base letter.
|
||||
if (next.startsWith(previous)) return { deleted: 0, inserted: next.slice(previous.length) };
|
||||
const a = graphemes(previous);
|
||||
const b = graphemes(next);
|
||||
let prefix = 0;
|
||||
while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix += 1;
|
||||
return { deleted: a.length - prefix, inserted: b.slice(prefix).join('') };
|
||||
}
|
||||
|
||||
// Native line breaks are provisional dictation text, never submit commands.
|
||||
function project(value) {
|
||||
return value.replace(/\r\n|[\r\n]/g, ' ');
|
||||
}
|
||||
|
||||
const TERMINAL_KEYS = Object.freeze({
|
||||
Enter: 13,
|
||||
Tab: 9,
|
||||
Escape: 27,
|
||||
ArrowLeft: 37,
|
||||
ArrowUp: 38,
|
||||
ArrowRight: 39,
|
||||
ArrowDown: 40,
|
||||
Home: 36,
|
||||
End: 35,
|
||||
PageUp: 33,
|
||||
PageDown: 34,
|
||||
Insert: 45,
|
||||
Delete: 46,
|
||||
F1: 112,
|
||||
F2: 113,
|
||||
F3: 114,
|
||||
F4: 115,
|
||||
F5: 116,
|
||||
F6: 117,
|
||||
F7: 118,
|
||||
F8: 119,
|
||||
F9: 120,
|
||||
F10: 121,
|
||||
F11: 122,
|
||||
F12: 123,
|
||||
});
|
||||
const IOS_COMMANDS = new Set([
|
||||
'UIKeyInputUpArrow',
|
||||
'UIKeyInputDownArrow',
|
||||
'UIKeyInputLeftArrow',
|
||||
'UIKeyInputRightArrow',
|
||||
'UIKeyInputEscape',
|
||||
]);
|
||||
|
||||
function classifyKey(ev, textarea) {
|
||||
if (ev.isComposing || ev.key === 'Process' || ev.keyCode === 229) return 'compose';
|
||||
if (
|
||||
ev.ctrlKey ||
|
||||
ev.metaKey ||
|
||||
ev.altKey ||
|
||||
IOS_COMMANDS.has(ev.key) ||
|
||||
(Object.prototype.hasOwnProperty.call(TERMINAL_KEYS, ev.key) && TERMINAL_KEYS[ev.key] === ev.keyCode)
|
||||
)
|
||||
return 'command';
|
||||
if (ev.key === 'Backspace' && ev.keyCode === 8 && textarea && textarea.value === '') {
|
||||
return 'backspace-terminal';
|
||||
}
|
||||
return 'native';
|
||||
}
|
||||
|
||||
function isSupported() {
|
||||
return !!(global.MobileImePreview && global.MobileImePreview.isIosWebKitTouch(global.navigator));
|
||||
}
|
||||
|
||||
function create(options) {
|
||||
const opts = options || {};
|
||||
function record(entry) {
|
||||
try {
|
||||
if (typeof opts.log === 'function') opts.log(entry);
|
||||
} catch (_) {
|
||||
/* Diagnostics are optional. */
|
||||
}
|
||||
}
|
||||
function guard(hook, fn, fallback) {
|
||||
return function (...args) {
|
||||
try {
|
||||
return fn.apply(this, args);
|
||||
} catch (error) {
|
||||
record({ type: 'error', hook, error });
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const patches = [];
|
||||
const listeners = [];
|
||||
let textarea;
|
||||
let whitespace;
|
||||
let destroyed = false;
|
||||
let timer = null;
|
||||
let synced = '';
|
||||
let cursor = 0;
|
||||
let invalidated = false;
|
||||
let foreignSnapshot = null;
|
||||
let foreignTimer = null;
|
||||
const caretListeners = new Set(typeof opts.onCaret === 'function' ? [opts.onCaret] : []);
|
||||
let notifyCaret = function () {};
|
||||
let composing = false;
|
||||
let compositionPending = false;
|
||||
let reconciling = false;
|
||||
let again = false;
|
||||
let generation = 0;
|
||||
|
||||
function cancelPending() {
|
||||
if (timer !== null) {
|
||||
global.clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
if (foreignTimer !== null) {
|
||||
global.clearTimeout(foreignTimer);
|
||||
foreignTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
const destroy = guard('destroy', function () {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
cancelPending();
|
||||
notifyCaret();
|
||||
caretListeners.clear();
|
||||
for (const [target, type, listener] of listeners) target.removeEventListener(type, listener, true);
|
||||
if (whitespace) {
|
||||
if (whitespace.value) textarea.style.setProperty('white-space', whitespace.value, whitespace.priority);
|
||||
else textarea.style.removeProperty('white-space');
|
||||
}
|
||||
// Restore property ownership as well as function identity: most methods
|
||||
// originally live on xterm's prototype, not on the instance.
|
||||
for (let i = patches.length - 1; i >= 0; i -= 1) {
|
||||
const { target, name, descriptor } = patches[i];
|
||||
if (descriptor) Object.defineProperty(target, name, descriptor);
|
||||
else delete target[name];
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
const terminal = opts.terminal;
|
||||
const core = terminal && terminal._core;
|
||||
const helper = core && core._compositionHelper;
|
||||
textarea = terminal && terminal.textarea;
|
||||
if (
|
||||
!textarea ||
|
||||
!core ||
|
||||
!helper ||
|
||||
!core.coreService ||
|
||||
typeof core.coreService.triggerDataEvent !== 'function' ||
|
||||
typeof core._inputEvent !== 'function' ||
|
||||
typeof core._handleTextAreaBlur !== 'function' ||
|
||||
typeof helper._handleAnyTextareaChanges !== 'function' ||
|
||||
typeof helper._finalizeComposition !== 'function' ||
|
||||
!helper._compositionView ||
|
||||
!helper._compositionView.classList ||
|
||||
typeof textarea.setSelectionRange !== 'function' ||
|
||||
(terminal.options && terminal.options.screenReaderMode) ||
|
||||
(opts.isScreenReaderMode && opts.isScreenReaderMode())
|
||||
)
|
||||
return null;
|
||||
|
||||
const sendTransaction = opts.sendTransaction;
|
||||
if (typeof sendTransaction !== 'function') return null;
|
||||
whitespace = {
|
||||
value: textarea.style.getPropertyValue('white-space'),
|
||||
priority: textarea.style.getPropertyPriority('white-space'),
|
||||
};
|
||||
// nowrap collapses whitespace, making WebKit replace trailing spaces with
|
||||
// NBSP. pre preserves native spaces without wrapping or changing real NBSP.
|
||||
textarea.style.setProperty('white-space', 'pre');
|
||||
// A pre-existing field has no provenance: it is not evidence of PTY input.
|
||||
invalidated = textarea.value !== '';
|
||||
|
||||
const caret = guard(
|
||||
'caret',
|
||||
function () {
|
||||
const text = project(textarea.value);
|
||||
const offset = project(textarea.value.slice(0, textarea.selectionEnd)).length;
|
||||
return {
|
||||
visible:
|
||||
!destroyed &&
|
||||
textarea.ownerDocument.activeElement === textarea &&
|
||||
!composing &&
|
||||
textarea.selectionStart === textarea.selectionEnd &&
|
||||
offset < text.length &&
|
||||
text === synced &&
|
||||
!invalidated &&
|
||||
!foreignSnapshot,
|
||||
text,
|
||||
offset,
|
||||
// Advances only when an edit is reconciled (sent) or the line is reset;
|
||||
// a borrowed clipboard value and its restoration leave it unchanged.
|
||||
generation,
|
||||
};
|
||||
},
|
||||
{ visible: false, text: '', offset: 0, generation: 0 }
|
||||
);
|
||||
let previousCaret;
|
||||
notifyCaret = function () {
|
||||
const current = caret();
|
||||
if (
|
||||
previousCaret &&
|
||||
previousCaret.visible === current.visible &&
|
||||
previousCaret.text === current.text &&
|
||||
previousCaret.offset === current.offset &&
|
||||
previousCaret.generation === current.generation
|
||||
)
|
||||
return;
|
||||
previousCaret = current;
|
||||
for (const callback of caretListeners) {
|
||||
try {
|
||||
callback({ ...current });
|
||||
} catch (error) {
|
||||
record({ type: 'error', hook: 'onCaret', error });
|
||||
}
|
||||
}
|
||||
};
|
||||
const onCaret = guard('onCaret', function (callback) {
|
||||
if (destroyed || typeof callback !== 'function') return function () {};
|
||||
caretListeners.add(callback);
|
||||
return function () {
|
||||
caretListeners.delete(callback);
|
||||
};
|
||||
});
|
||||
|
||||
function restoreForeign() {
|
||||
if (!foreignSnapshot || destroyed) return;
|
||||
const snapshot = foreignSnapshot;
|
||||
foreignSnapshot = null;
|
||||
if (foreignTimer !== null) {
|
||||
global.clearTimeout(foreignTimer);
|
||||
foreignTimer = null;
|
||||
}
|
||||
textarea.value = snapshot.value;
|
||||
textarea.setSelectionRange(snapshot.start, snapshot.end, snapshot.direction);
|
||||
synced = snapshot.synced;
|
||||
notifyCaret();
|
||||
}
|
||||
|
||||
function invalidate() {
|
||||
if (invalidated) return;
|
||||
record({ type: 'drift', value: textarea.value, synced });
|
||||
// Never replace a supposedly sent baseline with an unproven field.
|
||||
cancelPending();
|
||||
foreignSnapshot = null;
|
||||
synced = '';
|
||||
cursor = 0;
|
||||
invalidated = true;
|
||||
generation += 1;
|
||||
record({ type: 'reset', reason: 'drift', generation });
|
||||
notifyCaret();
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
if (destroyed || timer !== null) return;
|
||||
timer = global.setTimeout(
|
||||
guard('timer', function () {
|
||||
timer = null;
|
||||
if (!destroyed) reconcile();
|
||||
}),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
function notifyTransaction(transaction) {
|
||||
try {
|
||||
if (typeof opts.onTransaction === 'function') opts.onTransaction(transaction);
|
||||
} catch (error) {
|
||||
record({ type: 'error', hook: 'onTransaction', error });
|
||||
}
|
||||
}
|
||||
|
||||
function reconcile() {
|
||||
if (destroyed || composing || invalidated || foreignSnapshot) return;
|
||||
if (reconciling) {
|
||||
again = true;
|
||||
return;
|
||||
}
|
||||
do {
|
||||
again = false;
|
||||
const current = project(textarea.value);
|
||||
const transaction = { ...editBetween(synced, current), composition: compositionPending };
|
||||
compositionPending = false;
|
||||
const ops = [];
|
||||
if (current !== synced) {
|
||||
const { deleted, inserted } = transaction;
|
||||
record({ type: 'reconcile', deleted, inserted });
|
||||
for (let i = 0; i < deleted; i += 1) ops.push('\x7f');
|
||||
if (inserted) ops.push(inserted);
|
||||
synced = current;
|
||||
cursor = Array.from(current).length;
|
||||
generation += 1;
|
||||
}
|
||||
// Publish the end-anchored baseline BEFORE calling out. A reset inside
|
||||
// the transaction survives; the destination receives all ops atomically.
|
||||
reconciling = true;
|
||||
try {
|
||||
if (ops.length) {
|
||||
// These ops bypass xterm's triggerDataEvent(data, true), so its
|
||||
// scrollOnUserInput never runs; scroll to the prompt as xterm would.
|
||||
try {
|
||||
if (
|
||||
terminal.options &&
|
||||
terminal.options.scrollOnUserInput !== false &&
|
||||
typeof terminal.scrollToBottom === 'function'
|
||||
)
|
||||
terminal.scrollToBottom();
|
||||
} catch (error) {
|
||||
record({ type: 'error', hook: 'scrollOnUserInput', error });
|
||||
}
|
||||
try {
|
||||
sendTransaction(ops);
|
||||
} catch (error) {
|
||||
record({ type: 'error', hook: 'sendTransaction', error });
|
||||
invalidated = true;
|
||||
}
|
||||
}
|
||||
// Empty/deletion-only compositions still settle the visual preview.
|
||||
notifyTransaction(transaction);
|
||||
} finally {
|
||||
reconciling = false;
|
||||
}
|
||||
} while (again && !destroyed && !composing && !invalidated && !foreignSnapshot);
|
||||
notifyCaret();
|
||||
}
|
||||
|
||||
const settle = guard('settle', function () {
|
||||
cancelPending();
|
||||
reconcile();
|
||||
});
|
||||
const reset = guard('reset', function (reason) {
|
||||
if (destroyed) return;
|
||||
cancelPending();
|
||||
foreignSnapshot = null;
|
||||
textarea.value = '';
|
||||
invalidated = false;
|
||||
synced = '';
|
||||
cursor = 0;
|
||||
generation += 1;
|
||||
composing = false;
|
||||
compositionPending = false;
|
||||
record({ type: 'reset', reason, generation });
|
||||
notifyTransaction({ inserted: '', deleted: 0, composition: false });
|
||||
notifyCaret();
|
||||
});
|
||||
const keyFilter = guard(
|
||||
'keyFilter',
|
||||
function (ev) {
|
||||
if (destroyed) return true;
|
||||
if (ev.type === 'keypress') return false;
|
||||
if (ev.type === 'keyup') return textarea.ownerDocument.activeElement === textarea;
|
||||
if (ev.type !== 'keydown') return true;
|
||||
restoreForeign();
|
||||
const kind = composing ? 'compose' : classifyKey(ev, textarea);
|
||||
if (kind === 'compose') {
|
||||
schedule();
|
||||
return false;
|
||||
}
|
||||
if (kind === 'command') {
|
||||
settle();
|
||||
reset('command');
|
||||
return true;
|
||||
}
|
||||
if (kind === 'backspace-terminal') {
|
||||
settle();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
false
|
||||
);
|
||||
|
||||
function patch(target, name, replacement) {
|
||||
patches.push({ target, name, descriptor: Object.getOwnPropertyDescriptor(target, name) });
|
||||
target[name] = guard(name, replacement, false);
|
||||
}
|
||||
function listen(type, fn, target = textarea) {
|
||||
const listener = guard(type, fn);
|
||||
listeners.push([target, type, listener]);
|
||||
target.addEventListener(type, listener, true);
|
||||
}
|
||||
|
||||
patch(core, '_inputEvent', function (ev) {
|
||||
if (ev && ev.data && ev.inputType === 'insertText') core._unprocessedDeadKey = false;
|
||||
return false;
|
||||
});
|
||||
patch(helper, '_handleAnyTextareaChanges', schedule);
|
||||
patch(helper, '_finalizeComposition', function () {
|
||||
helper._compositionView.classList.remove('active');
|
||||
helper._isComposing = false;
|
||||
helper._isSendingComposition = false;
|
||||
schedule();
|
||||
});
|
||||
const originalBlur = core._handleTextAreaBlur;
|
||||
patch(core, '_handleTextAreaBlur', function (...args) {
|
||||
restoreForeign();
|
||||
const value = textarea.value;
|
||||
const start = textarea.selectionStart;
|
||||
const end = textarea.selectionEnd;
|
||||
const direction = textarea.selectionDirection;
|
||||
const before = generation;
|
||||
try {
|
||||
return originalBlur.apply(this, args);
|
||||
} finally {
|
||||
if (opts.blurPolicy === 'stock') {
|
||||
synced = '';
|
||||
cursor = 0;
|
||||
invalidated = false;
|
||||
} else if (!destroyed && generation === before) {
|
||||
textarea.value = value;
|
||||
textarea.setSelectionRange(start, end, direction);
|
||||
}
|
||||
notifyCaret();
|
||||
}
|
||||
});
|
||||
|
||||
listen('beforeinput', function (ev) {
|
||||
if (destroyed || composing || ev.isComposing) return;
|
||||
if (foreignSnapshot || project(textarea.value) !== synced) invalidate();
|
||||
});
|
||||
listen('input', function (ev) {
|
||||
if (!destroyed && !ev.isComposing && !composing) {
|
||||
if (foreignSnapshot) invalidate();
|
||||
if (invalidated) reset('drift');
|
||||
else reconcile();
|
||||
}
|
||||
if (!destroyed) notifyCaret();
|
||||
});
|
||||
listen('compositionstart', function () {
|
||||
if (!destroyed) {
|
||||
composing = true;
|
||||
notifyCaret();
|
||||
}
|
||||
});
|
||||
listen('compositionend', function () {
|
||||
if (destroyed) return;
|
||||
composing = false;
|
||||
compositionPending = true;
|
||||
notifyCaret();
|
||||
schedule();
|
||||
});
|
||||
listen(
|
||||
'selectionchange',
|
||||
function () {
|
||||
if (!destroyed && textarea.ownerDocument.activeElement === textarea) notifyCaret();
|
||||
},
|
||||
textarea.ownerDocument
|
||||
);
|
||||
listen('focus', notifyCaret);
|
||||
listen('blur', notifyCaret);
|
||||
// xterm temporarily lends the helper to native Copy. Restore only before
|
||||
// a new key edit, after Copy has read it, or before blur preservation.
|
||||
if (terminal.element)
|
||||
listen(
|
||||
'contextmenu',
|
||||
function () {
|
||||
if (destroyed || foreignSnapshot) return;
|
||||
foreignSnapshot = {
|
||||
value: textarea.value,
|
||||
start: textarea.selectionStart,
|
||||
end: textarea.selectionEnd,
|
||||
direction: textarea.selectionDirection,
|
||||
synced,
|
||||
};
|
||||
notifyCaret();
|
||||
},
|
||||
terminal.element
|
||||
);
|
||||
listen('keydown', restoreForeign);
|
||||
listen(
|
||||
'copy',
|
||||
function () {
|
||||
if (destroyed || !foreignSnapshot || foreignTimer !== null) return;
|
||||
foreignTimer = global.setTimeout(
|
||||
guard('copy timer', function () {
|
||||
foreignTimer = null;
|
||||
restoreForeign();
|
||||
}),
|
||||
0
|
||||
);
|
||||
},
|
||||
textarea.ownerDocument
|
||||
);
|
||||
listen('blur', restoreForeign);
|
||||
// xterm's paste handler emits the clipboard (bracketed when the app asks)
|
||||
// but never cancels the event, so the browser would also insert it into
|
||||
// the field and reconcile would send it a second time. Cancel only the
|
||||
// native insertion; xterm's bubble listener still runs.
|
||||
listen('paste', function (ev) {
|
||||
if (destroyed) return;
|
||||
settle();
|
||||
reset('paste');
|
||||
ev.preventDefault();
|
||||
});
|
||||
notifyCaret();
|
||||
|
||||
return {
|
||||
keyFilter,
|
||||
reset,
|
||||
settle,
|
||||
destroy,
|
||||
caret,
|
||||
onCaret,
|
||||
state: guard('state', function () {
|
||||
return {
|
||||
value: textarea.value,
|
||||
synced,
|
||||
cursor,
|
||||
composing,
|
||||
invalidated,
|
||||
selectionStart: textarea.selectionStart,
|
||||
selectionEnd: textarea.selectionEnd,
|
||||
generation,
|
||||
};
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
record({ type: 'error', hook: 'create', error });
|
||||
destroy();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Visual only: an anchor(caret) supplies the exact viewport cell, 'hide', or
|
||||
// null to resolve against parsed xterm cells. Neither mode moves native input.
|
||||
// subscribe(callback) follows overlay repaints without an xterm render.
|
||||
function bufferCaretAnchor(terminal, caret) {
|
||||
const buffer = terminal.buffer.active;
|
||||
const text = caret.text;
|
||||
if (!text || caret.offset < 0 || caret.offset > text.length) return null;
|
||||
let row = buffer.baseY + buffer.cursorY;
|
||||
let col = buffer.cursorX;
|
||||
let line = buffer.getLine(row);
|
||||
// Read only as far as the native field and one preceding repetition.
|
||||
function previousCell() {
|
||||
while (line) {
|
||||
if (col === 0) {
|
||||
if (!line.isWrapped || row === 0) return null;
|
||||
const following = line;
|
||||
line = buffer.getLine(--row);
|
||||
if (!line) return null;
|
||||
col = terminal.cols;
|
||||
// A wide glyph that did not fit leaves unused cells before a soft
|
||||
// wrap. Validate that padding against the following glyph's width;
|
||||
// ordinary blank cells (including printed spaces) remain text.
|
||||
let padding = 0;
|
||||
while (col - padding > 0) {
|
||||
const cell = line.getCell(col - padding - 1);
|
||||
if (!cell || cell.getWidth() !== 1 || cell.getChars()) break;
|
||||
padding += 1;
|
||||
}
|
||||
const first = following.getCell(0);
|
||||
if (padding && first && first.getWidth() > padding) col -= padding;
|
||||
}
|
||||
const cell = line.getCell(--col);
|
||||
if (!cell) return null;
|
||||
if (cell.getWidth() === 0) continue;
|
||||
const chars = cell.getChars();
|
||||
if (!chars) return null;
|
||||
return { chars, col, row: row - buffer.viewportY };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const cells = [];
|
||||
let remaining = text.length;
|
||||
while (remaining > 0) {
|
||||
const cell = previousCell();
|
||||
if (!cell || cell.chars.length > remaining || text.slice(remaining - cell.chars.length, remaining) !== cell.chars)
|
||||
return null;
|
||||
cells.push(cell);
|
||||
remaining -= cell.chars.length;
|
||||
}
|
||||
// A previous identical native-length suffix makes provenance ambiguous.
|
||||
remaining = text.length;
|
||||
while (remaining > 0) {
|
||||
const cell = previousCell();
|
||||
if (!cell || cell.chars.length > remaining || text.slice(remaining - cell.chars.length, remaining) !== cell.chars)
|
||||
break;
|
||||
remaining -= cell.chars.length;
|
||||
}
|
||||
if (remaining === 0) return null;
|
||||
let offset = 0;
|
||||
for (let i = cells.length - 1; i >= 0; i -= 1) {
|
||||
const cell = cells[i];
|
||||
if (caret.offset === offset) return { col: cell.col, row: cell.row };
|
||||
offset += cell.chars.length;
|
||||
if (caret.offset < offset) return null; // No cell inside a cluster.
|
||||
}
|
||||
return { col: buffer.cursorX, row: buffer.baseY + buffer.cursorY - buffer.viewportY };
|
||||
}
|
||||
function attachCaretMarker(terminal, owner, options) {
|
||||
const anchor = options && typeof options.anchor === 'function' ? options.anchor : null;
|
||||
const disposables = [];
|
||||
let marker;
|
||||
let disposed = false;
|
||||
let caretGeneration = 0;
|
||||
let awaitingEcho = false;
|
||||
function dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
for (const cleanup of disposables) {
|
||||
try {
|
||||
cleanup();
|
||||
} catch (_) {
|
||||
/* Terminal teardown may already have run. */
|
||||
}
|
||||
}
|
||||
if (marker) marker.remove();
|
||||
}
|
||||
try {
|
||||
const screen = terminal.element && terminal.element.querySelector('.xterm-screen');
|
||||
if (!screen || !owner || typeof owner.caret !== 'function' || typeof owner.onCaret !== 'function') return dispose;
|
||||
caretGeneration = owner.caret().generation;
|
||||
marker = screen.ownerDocument.createElement('div');
|
||||
marker.className = 'ios-native-caret';
|
||||
marker.setAttribute('aria-hidden', 'true');
|
||||
marker.style.cssText = 'position:absolute;width:2px;pointer-events:none;display:none;z-index:10';
|
||||
screen.appendChild(marker);
|
||||
function position() {
|
||||
try {
|
||||
const caret = owner.caret();
|
||||
const core = terminal._core;
|
||||
const dimensions = core && core._renderService && core._renderService.dimensions;
|
||||
const cell = dimensions && dimensions.css && dimensions.css.cell;
|
||||
if (disposed || !caret.visible || !cell || !cell.width || !cell.height || !terminal.cols) {
|
||||
marker.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
let target = null;
|
||||
if (anchor) {
|
||||
try {
|
||||
target = anchor(caret);
|
||||
} catch (_) {
|
||||
target = 'hide';
|
||||
}
|
||||
}
|
||||
if (target == null && !awaitingEcho) target = bufferCaretAnchor(terminal, caret);
|
||||
if (!target || target === 'hide' || target.row < 0 || target.row >= terminal.rows) {
|
||||
marker.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
marker.style.display = 'block';
|
||||
marker.style.left = target.col * cell.width + 'px';
|
||||
marker.style.top = target.row * cell.height + 'px';
|
||||
marker.style.height = cell.height + 'px';
|
||||
marker.style.backgroundColor = (terminal.options.theme && terminal.options.theme.cursor) || 'currentColor';
|
||||
} catch (_) {
|
||||
marker.style.display = 'none';
|
||||
}
|
||||
}
|
||||
disposables.push(
|
||||
owner.onCaret((caret) => {
|
||||
// Await parsed output only for a reconciled edit or reset (generation),
|
||||
// never for a borrowed clipboard value or its restoration.
|
||||
if (caret.generation !== caretGeneration) {
|
||||
caretGeneration = caret.generation;
|
||||
awaitingEcho = true;
|
||||
}
|
||||
position();
|
||||
})
|
||||
);
|
||||
if (typeof terminal.onWriteParsed === 'function') {
|
||||
const subscription = terminal.onWriteParsed(() => {
|
||||
awaitingEcho = false;
|
||||
position();
|
||||
});
|
||||
disposables.push(() => subscription.dispose());
|
||||
}
|
||||
for (const name of ['onRender', 'onCursorMove']) {
|
||||
if (typeof terminal[name] === 'function') {
|
||||
const subscription = terminal[name](position);
|
||||
disposables.push(() => subscription.dispose());
|
||||
}
|
||||
}
|
||||
if (options && typeof options.subscribe === 'function') {
|
||||
try {
|
||||
const unsubscribe = options.subscribe(position);
|
||||
if (typeof unsubscribe === 'function') disposables.push(unsubscribe);
|
||||
} catch (_) {
|
||||
/* Optional anchor feed. */
|
||||
}
|
||||
}
|
||||
position();
|
||||
return dispose;
|
||||
} catch (_) {
|
||||
dispose();
|
||||
return dispose;
|
||||
}
|
||||
}
|
||||
|
||||
global.CodemanIosNativeInput = Object.freeze({ create, editBetween, classifyKey, attachCaretMarker, isSupported });
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
@@ -60,15 +60,36 @@
|
||||
(function (global) {
|
||||
'use strict';
|
||||
|
||||
// Grapheme clusters, the unit a soft-keyboard Backspace removes, Claude Code and
|
||||
// Codex delete per DEL, and the local-echo overlay drops per DEL. Code points
|
||||
// stand in where Intl.Segmenter is missing (same rule as terminal-ios-native-input.js).
|
||||
const graphemeSegmenter = (() => {
|
||||
try {
|
||||
return typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'
|
||||
? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
function graphemes(text) {
|
||||
return graphemeSegmenter ? Array.from(graphemeSegmenter.segment(text), (part) => part.segment) : Array.from(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* What turns `previous` into `next`, as a terminal sees it: how many characters to delete from
|
||||
* the END of the line, then what to type. Everything after the common prefix is treated as
|
||||
* replaced, because a terminal can only edit at its cursor. Counts are code points, so an
|
||||
* emoji is one DEL, as it is one backspace.
|
||||
* replaced, because a terminal can only edit at its cursor. Counts are grapheme clusters, so a
|
||||
* red heart, a skin-tone emoji, a flag or a ZWJ family is one DEL, as it is one backspace.
|
||||
*/
|
||||
function editBetween(previous, next) {
|
||||
const a = Array.from(previous);
|
||||
const b = Array.from(next);
|
||||
// A pure append (including a combining mark or tone typed onto the last letter)
|
||||
// is sent as-is: re-typing the extended cluster would make a code-point line
|
||||
// editor (zsh) double the base letter.
|
||||
if (next.startsWith(previous)) return { deleted: 0, inserted: next.slice(previous.length) };
|
||||
const a = graphemes(previous);
|
||||
const b = graphemes(next);
|
||||
let prefix = 0;
|
||||
const max = Math.min(a.length, b.length);
|
||||
while (prefix < max && a[prefix] === b[prefix]) prefix += 1;
|
||||
|
||||
@@ -54,6 +54,7 @@
|
||||
* @dependency constants.js (window.CodemanTerminalFont, window.CodemanFetchDeadline, DEFAULT_SCROLLBACK, TERMINAL_TAIL_SIZE, SHELL_LOAD_BASE_QUERY, SHELL_LOAD_QUERY, TERMINAL_CHUNK_SIZE)
|
||||
* @dependency terminal-ui.js (codemanCurrentXtermTheme, codemanCurrentSkinIsLight, CodemanTerminalInput.shouldSuppressTerminalQueryResponse/isTerminalFocusOrMouseReport/wheelDeltaLines/wheelTicksForGesture/coalesceScrollBytes/sgrWheelReports/pageKeysForGesture, app._shouldForwardWheelToApp/_localScrollbackIsHollow/_terminalViewportAtBottom/_clientPointToCell/_handleDesktopTerminalClick, app.tabAlerts)
|
||||
* @dependency terminal-keycode229-recovery.js (window.CodemanKeyCode229Recovery, optional: absent, xterm's own textarea handling stands)
|
||||
* @dependency terminal-ios-native-input.js (window.CodemanIosNativeInput, optional iOS native editing owner)
|
||||
* @loadorder 7.4 of 16, loaded after terminal-ui.js and before terminal-split.js
|
||||
*/
|
||||
|
||||
@@ -227,6 +228,8 @@
|
||||
// The soft-keyboard controller (terminal-keycode229-recovery.js): created
|
||||
// in connect() once the xterm is open, torn down in destroy().
|
||||
this._keyCode229Recovery = null;
|
||||
this._iosNativeInput = null;
|
||||
this._iosCaretMarker = null;
|
||||
}
|
||||
|
||||
async connect() {
|
||||
@@ -275,7 +278,7 @@
|
||||
this._onFocusIn = () => global.app?._noteFocusedTile?.(this);
|
||||
this.terminal.textarea?.addEventListener('focus', this._onFocusIn);
|
||||
|
||||
this._createKeyCode229Recovery();
|
||||
this._createInputOwner();
|
||||
// The twin of terminal-ui.js's onData gate (initTerminal; keep the two in
|
||||
// step). Canonical xterm data tells the controller this keystroke was
|
||||
// delivered, but not a query reply or a focus/mouse report, which xterm
|
||||
@@ -309,6 +312,7 @@
|
||||
// here too. Ctrl+V goes through the primary pane's paste trap
|
||||
// (image-input.js), aimed at this pane (below).
|
||||
this.terminal.attachCustomKeyEventHandler((ev) => {
|
||||
if (this._iosNativeInput?.keyFilter(ev) === false) return false;
|
||||
// FIRST, above the IME early return below, as in terminal-ui.js: every
|
||||
// keydown settles this pane's pending textarea edit and drains a
|
||||
// pending recovery BEFORE xterm handles the key, so a character an
|
||||
@@ -639,6 +643,68 @@
|
||||
app?._sendInputAsync?.(this.sessionId, data);
|
||||
}
|
||||
|
||||
// iOS owns native textarea edits; other platforms retain the 229 recovery.
|
||||
// Replacing either controller first settles the old tile's pending edit.
|
||||
_createInputOwner() {
|
||||
this._destroyIosNativeInput();
|
||||
this._destroyKeyCode229Recovery();
|
||||
if (!this.terminal) return;
|
||||
const nativeInput = global.CodemanIosNativeInput;
|
||||
if (!nativeInput?.isSupported?.()) {
|
||||
this._createKeyCode229Recovery();
|
||||
return;
|
||||
}
|
||||
this._iosNativeInput = nativeInput.create({
|
||||
terminal: this.terminal,
|
||||
sendTransaction: (ops) => this._sendNativeInputTransaction(ops),
|
||||
isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true,
|
||||
});
|
||||
if (this._iosNativeInput) {
|
||||
// Tiles have no local-echo overlay: resolve only from verified parsed cells.
|
||||
this._iosCaretMarker = nativeInput.attachCaretMarker(this.terminal, this._iosNativeInput);
|
||||
return;
|
||||
}
|
||||
// create() refused (screen reader, missing xterm internals): keep the
|
||||
// soft-keyboard recovery rather than leaving the tile with neither.
|
||||
this._createKeyCode229Recovery();
|
||||
}
|
||||
|
||||
_sendNativeInputTransaction(ops) {
|
||||
const sessionId = this.sessionId;
|
||||
const app = global.app;
|
||||
let ctrlIndex = -1;
|
||||
// Same rule as the primary pane (terminal-ui.js _sendNativeInputTransaction):
|
||||
// the edit's first insertion spends the armed Ctrl whatever its length.
|
||||
// consumeCtrl maps a single character and passes a suggestion or emoji
|
||||
// through unchanged, but it still disarms, so the next `c` stays a `c`.
|
||||
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
|
||||
ctrlIndex = ops.findIndex((data) => data !== '\x7f');
|
||||
if (ctrlIndex === -1 && ops.includes('\x7f')) KeyboardAccessoryBar.clearCtrl?.();
|
||||
}
|
||||
// Keep replacement deletions: Ctrl changes only the insertion, once for
|
||||
// this edit, never once per DEL. Tiles have no local echo to reconcile.
|
||||
const writes = ops.map((data, i) => ({
|
||||
write: i === ctrlIndex ? KeyboardAccessoryBar.consumeCtrl(data) : data,
|
||||
}));
|
||||
if (app?._enqueueInput) app._enqueueInput(sessionId, writes);
|
||||
else for (const { write } of writes) app?._sendInputAsync?.(sessionId, write);
|
||||
if (ctrlIndex !== -1) this._iosNativeInput?.reset('ctrl');
|
||||
}
|
||||
|
||||
_destroyIosNativeInput() {
|
||||
try {
|
||||
this._iosNativeInput?.settle();
|
||||
} finally {
|
||||
try {
|
||||
this._iosNativeInput?.destroy();
|
||||
} finally {
|
||||
this._iosNativeInput = null;
|
||||
this._iosCaretMarker?.();
|
||||
this._iosCaretMarker = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The soft-keyboard controller, the twin of the primary pane's wiring in
|
||||
// terminal-ui.js initTerminal() (keep the two in step); the behaviour lives
|
||||
// once, in terminal-keycode229-recovery.js. Everything it is handed is THIS
|
||||
@@ -1554,6 +1620,8 @@
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (global.app?._focusedTile === this && typeof CjkInput !== 'undefined') CjkInput.flushNow?.();
|
||||
this._destroyIosNativeInput();
|
||||
this._destroyed = true;
|
||||
// Anything still queued for this session stays in the app's queue and is
|
||||
// delivered over HTTP by the redelivery sweep, so closing the pane mid-
|
||||
|
||||
+494
-468
File diff suppressed because it is too large.
Load diff
@@ -25,7 +25,7 @@
|
||||
* @globals {object} VoiceInput
|
||||
*
|
||||
* @dependency mobile-handlers.js (MobileDetection for device checks)
|
||||
* @dependency app.js (uses global `app` for sendInput, showToast, terminal focus)
|
||||
* @dependency app.js (uses global `app` for _sendInputAsync, _enqueueInput, _prepareExternalInput, showToast, terminal focus)
|
||||
* @loadorder 3 of 15 — loaded after mobile-handlers.js, before notification-manager.js
|
||||
*/
|
||||
|
||||
@@ -1071,19 +1071,18 @@ const VoiceInput = {
|
||||
return this._targetSessionId || app.activeSessionId;
|
||||
},
|
||||
|
||||
/**
|
||||
* Send text to the dictation's own session. The active session keeps going
|
||||
* through app.sendInput() exactly as before; any other session goes straight
|
||||
* to the durable queue with the same useMux flag sendInput() passes.
|
||||
*/
|
||||
/** Send only to the captured dictation session, never the current tab. */
|
||||
_sendToTarget(target, text) {
|
||||
if (target === app.activeSessionId) return app.sendInput(text);
|
||||
// Closed while dictating: say so instead of queueing text for a session
|
||||
// that will only answer 404 (and never typing it into some other tab).
|
||||
if (app.sessions && !app.sessions.has(target)) {
|
||||
app.showToast?.('That session has closed; dictation not sent', 'warning');
|
||||
return Promise.resolve();
|
||||
}
|
||||
// Settle the destination's iOS owner, but leave an unsent local-echo draft
|
||||
// in the overlay: flushing it would prepend it to the reviewed dictation.
|
||||
const pane = app._paneForSession?.(target);
|
||||
if (pane) app._prepareExternalInput?.(pane, 'voice-send');
|
||||
app._sendInputAsync(target, text, { useMux: true });
|
||||
return Promise.resolve();
|
||||
},
|
||||
@@ -1098,6 +1097,7 @@ const VoiceInput = {
|
||||
// If a compose overlay is already open, populate its textarea instead of recreating
|
||||
const existingTextarea = document.querySelector('.voice-compose-overlay .paste-textarea');
|
||||
if (existingTextarea) {
|
||||
existingTextarea.closest('.voice-compose-overlay').dataset.targetSessionId = target;
|
||||
existingTextarea.value = trimmed;
|
||||
existingTextarea.focus();
|
||||
existingTextarea.selectionStart = existingTextarea.selectionEnd = trimmed.length;
|
||||
@@ -1113,7 +1113,13 @@ const VoiceInput = {
|
||||
// sees, so it goes straight to the session instead.
|
||||
const isActive = target === app.activeSessionId;
|
||||
const tilesOpen = !!app._tilesOwnTerminal?.();
|
||||
const pane = app._focusedPane?.();
|
||||
if (isActive && !tilesOpen && app._localEchoEnabled && app._localEchoOverlay) {
|
||||
// Focus may have moved to Pane B, but this overlay still belongs to A.
|
||||
const targetPane = pane?.isPrimary && pane.sessionId === target
|
||||
? pane
|
||||
: { isPrimary: true, tile: null, terminal: app.terminal, sessionId: target };
|
||||
app._prepareExternalInput?.(targetPane, 'voice-insert');
|
||||
app._localEchoOverlay.appendText(trimmed);
|
||||
} else {
|
||||
this._sendToTarget(target, trimmed).catch(() => {});
|
||||
@@ -1158,24 +1164,33 @@ const VoiceInput = {
|
||||
this._voiceSendHandler = () => {
|
||||
const target = this._targetSession();
|
||||
if (!target) return;
|
||||
const pane = app._focusedPane?.();
|
||||
const tilesOpen = !!app._tilesOwnTerminal?.();
|
||||
if (target === app.activeSessionId && !tilesOpen) {
|
||||
const targetPane = pane?.isPrimary && pane.sessionId === target
|
||||
? pane
|
||||
: { isPrimary: true, tile: null, terminal: app.terminal, sessionId: target };
|
||||
app._prepareExternalInput?.(targetPane, 'voice-submit');
|
||||
}
|
||||
// Simulate Enter key: if local echo is active, flush its buffer + send \r;
|
||||
// otherwise just send \r directly to the PTY. Both the overlay and the
|
||||
// predictions belong to the ACTIVE session's MAIN terminal, so a
|
||||
// dictation for another session, or for a tile while the grid has the
|
||||
// main terminal parked, just sends its Enter there.
|
||||
if (target !== app.activeSessionId || app._tilesOwnTerminal?.()) {
|
||||
if (target !== app.activeSessionId || tilesOpen) {
|
||||
this._sendToTarget(target, '\r').catch(() => {});
|
||||
} else if (app._localEchoEnabled && app._localEchoOverlay) {
|
||||
const text = app._localEchoOverlay.pendingText || '';
|
||||
app._localEchoOverlay.clear();
|
||||
app._localEchoOverlay.suppressBufferDetection();
|
||||
if (text) app.sendInput(text).catch(() => {});
|
||||
setTimeout(() => app.sendInput('\r').catch(() => {}), 80);
|
||||
const ops = text ? [{ write: text, useMux: true }, { gap: 80 }] : [];
|
||||
ops.push({ write: '\r', useMux: true });
|
||||
app._enqueueInput(target, ops);
|
||||
} else {
|
||||
// Predict-mode sessions (codex) take this branch: the send bypasses
|
||||
// onData, so clear outstanding predictions here (composer will reset)
|
||||
app._predictiveEcho?.clearPredictions();
|
||||
app.sendInput('\r').catch(() => {});
|
||||
app._sendInputAsync(target, '\r', { useMux: true });
|
||||
}
|
||||
// Blink then restore
|
||||
gear.classList.add('voice-send-blink');
|
||||
@@ -1205,6 +1220,7 @@ const VoiceInput = {
|
||||
document.querySelector('.voice-compose-overlay')?.remove();
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'voice-compose-overlay paste-overlay';
|
||||
overlay.dataset.targetSessionId = this._targetSession();
|
||||
overlay.innerHTML = `
|
||||
<div class="paste-dialog">
|
||||
<textarea class="paste-textarea">${text.replace(/</g, '<')}</textarea>
|
||||
@@ -1219,7 +1235,7 @@ const VoiceInput = {
|
||||
const send = () => {
|
||||
const val = textarea.value.trim();
|
||||
overlay.remove();
|
||||
if (val) this._sendToTarget(this._targetSession(), val + '\r').catch(() => {});
|
||||
if (val) this._sendToTarget(overlay.dataset.targetSessionId, val + '\r').catch(() => {});
|
||||
};
|
||||
const cancel = () => overlay.remove();
|
||||
const newInput = () => {
|
||||
|
||||
Reference in new issue
Block a user