Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(tui): mouse wheel scrolling and tab clicks, only inside the alternate screen (#197)

Abdurrahman Fakhrul8fb1f1b44d4c
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 068f40d8..ee217024 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,7 +8,8 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
-- `tui` a transcript viewport with a scrollbar, so the alternate screen has a reason
+- `tui` mouse wheel scrolling and tab clicks, only inside the alternate screen
+- `tui` a transcript viewport with a scrollbar, so the alternate screen has a reason (#193)
- `tui` an alternate screen behind a flag, with teardown on every exit path (#192)
- `tui` a tab row and a footer that stay put, painted through the frame writer (#191)
- `tui` a transcript model, because scrollback is the only transcript that exists (#187)
diff --git a/docs/TUI-RENDERER-PLAN.md b/docs/TUI-RENDERER-PLAN.md
index b8c2f33b..15212a3a 100644
--- a/docs/TUI-RENDERER-PLAN.md
+++ b/docs/TUI-RENDERER-PLAN.md
@@ -594,7 +594,7 @@ those two, and mouse/scrollbar/splits are additive after M5.
| M4 | Chrome and tabs as a bottom block | DONE | PR #191; chromeLines and tabs switch; composer 216 lines |
| M5 | Alternate screen behind a flag, with teardown | DONE | PR #192; default off; teardown on exit, signals, execve, spawnSync |
| M6 | Transcript viewport and scrollbar | DONE | PR #193; 2000-line cap, follow mode, PgUp/PgDn/Ctrl+G/End, entrypoint 218 to 196 lines |
-| M7 | Mouse | NOT STARTED | needs the owner's selection policy |
+| M7 | Mouse | DONE | SGR 1000/1006 extended mode, wheel scrolls viewport, tab clicks switch session |
| M8 | Split panes, then flip the alt screen default | NOT STARTED | needs M6 and M7 |
Adjacent work that landed while this plan was being executed, and belongs to the same goal:
diff --git a/scripts/mso-agent-chrome.mjs b/scripts/mso-agent-chrome.mjs
index 3e790c00..60207d67 100644
--- a/scripts/mso-agent-chrome.mjs
+++ b/scripts/mso-agent-chrome.mjs
@@ -2,18 +2,24 @@ import { cellWidth, clean, fitCells } from "./tui/cells.mjs";
import { composerFooter } from "./mso-agent-layout.mjs";
/**
- * Formats a single physical row containing session tabs.
- * Active session is marked with a bullet and undimmed; inactive tabs are dimmed.
- * When tabs exceed available width, excess items are dropped from the middle and
- * replaced with a visible +N marker so the row never wraps and breaks row arithmetic.
- *
- * @param {Array<any>} sessions
- * @param {string|number|null} [activeId]
- * @param {{ colors?: any, width?: number }} [options]
- * @returns {string}
+ * Formats a single physical row containing session tabs and performs hit testing.
+ * Extracted layout model ensures tabRow and tabAtPoint stay in exact agreement.
*/
-export function tabRow(sessions, activeId = null, { colors = {}, width = 80 } = {}) {
- if (!Array.isArray(sessions) || sessions.length === 0) return "";
+function makeSegments(itemsList) {
+ let col = 0;
+ const segments = [];
+ for (const it of itemsList) {
+ if (!it) continue;
+ segments.push({ type: it.type || "tab", id: it.id, start: col, end: col + it.width, styled: it.styled });
+ col += it.width + 2;
+ }
+ return segments;
+}
+
+export function tabLayout(sessions, activeId = null, { colors = {}, width = 80 } = {}) {
+ if (!Array.isArray(sessions) || sessions.length === 0) {
+ return { segments: [], maxWidth: Math.max(1, Number(width) || 80) };
+ }
const maxWidth = Math.max(1, Number(width) || 80);
const sep = " ";
@@ -29,15 +35,13 @@ export function tabRow(sessions, activeId = null, { colors = {}, width = 80 } =
const isActive = activeId != null && (String(activeId) === id || String(activeId).replace(/^@/, "") === name);
const marker = isActive ? "● " : "";
const plainText = `${marker}@${name}`;
- const styled = isActive
- ? `${cBold}${cBlue}${marker}@${name}${cReset}`
- : `${cDim}@${name}${cReset}`;
+ const styled = isActive ? `${cBold}${cBlue}${marker}@${name}${cReset}` : `${cDim}@${name}${cReset}`;
return { id, name, isActive, plainText, styled, width: cellWidth(plainText) };
});
const fullPlain = items.map((it) => it.plainText).join(sep);
if (cellWidth(fullPlain) <= maxWidth) {
- return items.map((it) => it.styled).join(sep);
+ return { segments: makeSegments(items), maxWidth };
}
// Dropping from the middle keeps both endpoints visible while indicating hidden tabs.
@@ -47,6 +51,7 @@ export function tabRow(sessions, activeId = null, { colors = {}, width = 80 } =
const kept = items.length - dropped;
const markerText = `+${dropped}`;
const markerStyled = `${cDim}${markerText}${cReset}`;
+ const markerWidth = cellWidth(markerText);
// Candidate splits between left and right items.
// When an active tab exists, prefer splits that preserve the active tab.
@@ -56,11 +61,9 @@ export function tabRow(sessions, activeId = null, { colors = {}, width = 80 } =
const preservesActive = activeIdx < 0 || activeIdx < l || r > (items.length - 1 - activeIdx);
if (preservesActive) candidateSplits.push(l);
}
- // Fall back to all splits if none could preserve active with this kept count.
if (candidateSplits.length === 0) {
for (let l = 0; l <= kept; l++) candidateSplits.push(l);
}
- // Sort by proximity to balanced halves to drop symmetrically from the middle.
candidateSplits.sort((a, b) => Math.abs(a - kept / 2) - Math.abs(b - kept / 2));
for (const leftCount of candidateSplits) {
@@ -75,19 +78,52 @@ export function tabRow(sessions, activeId = null, { colors = {}, width = 80 } =
].filter(Boolean).join(sep);
if (cellWidth(candidatePlain) <= maxWidth) {
- const candidateStyled = [
- ...leftItems.map((it) => it.styled),
- markerStyled,
- ...rightItems.map((it) => it.styled),
- ].filter(Boolean).join(sep);
- return candidateStyled;
+ const marker = { type: "marker", text: markerText, styled: markerStyled, width: markerWidth };
+ return { segments: makeSegments([...leftItems, marker, ...rightItems]), maxWidth };
}
}
}
// Fallback for extremely constrained terminal widths: show single active or first tab truncated.
const fallbackItem = activeIdx >= 0 ? items[activeIdx] : items[0];
- return fitCells(fallbackItem.styled, maxWidth, { pad: false });
+ const truncatedStyled = fitCells(fallbackItem.styled, maxWidth, { pad: false });
+ return {
+ segments: [{ type: "tab", id: fallbackItem.id, start: 0, end: Math.min(fallbackItem.width, maxWidth), styled: truncatedStyled }],
+ maxWidth,
+ };
+}
+
+/**
+ * One physical row of session tabs. The active tab is undimmed and bulleted; when the tabs do not
+ * fit, the middle is dropped with a +N marker rather than wrapping, because a wrapped tab row
+ * breaks the reserved-row arithmetic the composer depends on.
+ *
+ * @param {Array<any>} sessions
+ * @param {string|number|null} [activeId]
+ * @param {{ colors?: any, width?: number }} [options]
+ * @returns {string}
+ */
+export function tabRow(sessions, activeId = null, options = {}) {
+ const { segments } = tabLayout(sessions, activeId, options);
+ return segments.map((s) => s.styled).join(" ");
+}
+
+/**
+ * @param {Array<any>} sessions
+ * @param {string|number|null} [activeId]
+ * @param {any} [point]
+ * @param {any} [options]
+ * @returns {string|null}
+ */
+export function tabAtPoint(sessions, activeId = null, point = {}, options = {}) {
+ const opts = typeof point === "object" && point !== null ? point : options;
+ const x = typeof point === "number" ? point : Number(opts?.x) || 0;
+ const y = typeof opts?.y === "number" ? opts.y : 0;
+ const tabRowY = typeof opts?.tabRow === "number" ? opts.tabRow : (typeof opts?.row === "number" ? opts.row : 0);
+ if (y !== tabRowY) return null;
+ const { segments } = tabLayout(sessions, activeId, opts);
+ const hit = segments.find((s) => s.type === "tab" && x >= s.start && x < s.end);
+ return hit ? hit.id : null;
}
/**
diff --git a/scripts/mso-agent-cmd-session.mjs b/scripts/mso-agent-cmd-session.mjs
index 9ec1d900..ea7d264d 100644
--- a/scripts/mso-agent-cmd-session.mjs
+++ b/scripts/mso-agent-cmd-session.mjs
@@ -28,6 +28,15 @@ export async function handleTodos(ctx, args = []) {
return "handled";
}
+// Reuses the existing resume path and clears cached todos so the status
+// chip never reflects a different session after switching.
+export async function switchToSession(rl, session, sessionId) {
+ if (!sessionId) return false;
+ await resumeInto(rl, session, sessionId);
+ clearTodos();
+ return true;
+}
+
export async function handleTabs(ctx, args = []) {
const { rl, session, C: colors = C } = ctx;
const rows = visibleSessionRows(await listCliSessions(20));
@@ -51,10 +60,7 @@ export async function handleTabs(ctx, args = []) {
console.log(`could not resolve session: ${args.join(" ")}`);
return "handled";
}
- // Reuses the existing resume path and clears cached todos so the status
- // chip never reflects a different session after switching.
- await resumeInto(rl, session, target.id);
- clearTodos();
+ await switchToSession(rl, session, target.id);
return "refresh";
}
diff --git a/scripts/mso-agent-mouse.mjs b/scripts/mso-agent-mouse.mjs
new file mode 100644
index 00000000..0f6527ef
--- /dev/null
+++ b/scripts/mso-agent-mouse.mjs
@@ -0,0 +1,164 @@
+import { getAllLines } from "./mso-agent-viewport.mjs";
+
+// SGR extended mouse reporting sequences. Normal 1000 mode reports button press and release;
+// 1006 extended mode reports coordinates beyond column 223 using decimal SGR encoding.
+export const MOUSE_ON = "\x1b[?1000h\x1b[?1006h";
+export const MOUSE_OFF = "\x1b[?1006l\x1b[?1000l";
+
+// Tracks active outputs currently configured for mouse reporting.
+const activeOutputs = new Set();
+
+/**
+ * Enables SGR mouse reporting idempotently on the output stream.
+ * Suppresses write errors so failing streams do not throw.
+ *
+ * @param {any} output
+ * @returns {boolean}
+ */
+export function enableMouse(output) {
+ if (!output || typeof output.write !== "function") return false;
+ if (activeOutputs.has(output)) return false;
+ try {
+ output.write(MOUSE_ON);
+ activeOutputs.add(output);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Disables SGR mouse reporting idempotently on the output stream.
+ * Tolerant of partial writes and does not throw when write fails.
+ *
+ * @param {any} [output]
+ * @returns {boolean}
+ */
+export function disableMouse(output) {
+ if (output) {
+ if (!activeOutputs.has(output)) return false;
+ activeOutputs.delete(output);
+ if (typeof output.write !== "function") return false;
+ try {
+ output.write(MOUSE_OFF);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ if (activeOutputs.size === 0) return false;
+ let disabled = false;
+ for (const stream of [...activeOutputs]) {
+ activeOutputs.delete(stream);
+ if (typeof stream?.write === "function") {
+ try {
+ stream.write(MOUSE_OFF);
+ disabled = true;
+ } catch {
+ // Suppress write errors to allow remaining teardown to complete.
+ }
+ }
+ }
+ return disabled;
+}
+
+/**
+ * Parses an input chunk containing SGR mouse sequences (\x1b[<CB;Cx;Cy[Mm]).
+ * Returns an array of parsed mouse event objects, or [] if no sequence is found.
+ *
+ * @param {any} chunk
+ * @returns {Array<{ kind: "wheel" | "click" | "release" | "other", button: string, x: number, y: number, shift: boolean, alt: boolean, ctrl: boolean }>}
+ */
+export function parseMouseChunk(chunk) {
+ if (chunk == null) return [];
+ const raw = typeof chunk === "string" ? chunk : (Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk));
+ if (!raw.includes("\x1b[<")) return [];
+
+ const events = [];
+ const regex = /\x1b\[<(\d+);(\d+);(\d+)([Mm])/g;
+ let match;
+
+ while ((match = regex.exec(raw)) !== null) {
+ const code = Number.parseInt(match[1], 10);
+ const rawX = Number.parseInt(match[2], 10);
+ const rawY = Number.parseInt(match[3], 10);
+ const finalChar = match[4];
+
+ if (Number.isNaN(code) || Number.isNaN(rawX) || Number.isNaN(rawY)) continue;
+
+ // Coordinates are 1-based as the terminal sends them; converted to 0-based rows/columns here.
+ const x = Math.max(0, rawX - 1);
+ const y = Math.max(0, rawY - 1);
+
+ const shift = Boolean(code & 4);
+ const alt = Boolean(code & 8);
+ const ctrl = Boolean(code & 16);
+
+ const isWheel = (code & 64) !== 0;
+
+ let kind = "other";
+ let button = "unknown";
+
+ if (isWheel) {
+ kind = "wheel";
+ const dir = code & 3;
+ if (dir === 0) button = "up";
+ else if (dir === 1) button = "down";
+ else if (dir === 2) button = "left";
+ else if (dir === 3) button = "right";
+ } else if (finalChar === "m") {
+ kind = "release";
+ const btn = code & 3;
+ if (btn === 0) button = "left";
+ else if (btn === 1) button = "middle";
+ else if (btn === 2) button = "right";
+ else button = "release";
+ } else if ((code & 32) !== 0) {
+ kind = "other";
+ button = "motion";
+ } else {
+ kind = "click";
+ const btn = code & 3;
+ if (btn === 0) button = "left";
+ else if (btn === 1) button = "middle";
+ else if (btn === 2) button = "right";
+ else button = "unknown";
+ }
+
+ events.push({ kind, button, x, y, shift, alt, ctrl });
+ }
+
+ return events;
+}
+
+/**
+ * Handles mouse wheel scrolling for the transcript viewport.
+ * Wheel up scrolls up by 3 lines; wheel down scrolls down by 3 lines.
+ * Returns true when the event was consumed.
+ *
+ * @param {any} scroll
+ * @param {any} event
+ * @param {{ rows?: number, onScroll?: (offset: number) => void }} [options]
+ * @returns {boolean}
+ */
+export function handleMouse(scroll, event, { rows, onScroll } = {}) {
+ if (!scroll || !event || event.kind !== "wheel") return false;
+
+ if (event.button === "up") {
+ const maxOffset = Array.isArray(scroll?.lines) && scroll.lines.length > 0
+ ? Math.max(0, getAllLines(scroll).length - Math.max(1, Number(rows ?? scroll.rows) || 1))
+ : Number.POSITIVE_INFINITY;
+ scroll.offset = Math.min(maxOffset, (scroll.offset || 0) + 3);
+ if (typeof onScroll === "function") onScroll(scroll.offset);
+ return true;
+ }
+
+ if (event.button === "down") {
+ scroll.offset = Math.max(0, (scroll.offset || 0) - 3);
+ if (typeof onScroll === "function") onScroll(scroll.offset);
+ return true;
+ }
+
+ return false;
+}
diff --git a/scripts/mso-agent-mouse.test.ts b/scripts/mso-agent-mouse.test.ts
new file mode 100644
index 00000000..8fd081a3
--- /dev/null
+++ b/scripts/mso-agent-mouse.test.ts
@@ -0,0 +1,176 @@
+import { EventEmitter } from "node:events";
+import { describe, expect, it } from "vitest";
+import { tabAtPoint, tabRow } from "./mso-agent-chrome.mjs";
+import {
+ disableMouse,
+ enableMouse,
+ handleMouse,
+ MOUSE_OFF,
+ MOUSE_ON,
+ parseMouseChunk,
+} from "./mso-agent-mouse.mjs";
+import { mountScreenLoop } from "./mso-agent-screen-loop.mjs";
+
+class FakeOutput extends EventEmitter {
+ isTTY = true;
+ columns = 80;
+ rows = 24;
+ chunks: string[] = [];
+ write(str: string) {
+ this.chunks.push(String(str));
+ return true;
+ }
+}
+
+describe("MSO Agent TUI mouse support", () => {
+ it("parse a press, a release, a wheel up and a wheel down", () => {
+ // Left button press at col 10, row 5 (1-based from terminal)
+ const press = parseMouseChunk("\x1b[<0;10;5M");
+ expect(press).toHaveLength(1);
+ expect(press[0]).toEqual({
+ kind: "click", button: "left", x: 9, y: 4, shift: false, alt: false, ctrl: false,
+ });
+
+ // Left button release at col 10, row 5
+ const release = parseMouseChunk("\x1b[<0;10;5m");
+ expect(release).toHaveLength(1);
+ expect(release[0]).toEqual({
+ kind: "release", button: "left", x: 9, y: 4, shift: false, alt: false, ctrl: false,
+ });
+
+ // Wheel up at col 20, row 15
+ const wheelUp = parseMouseChunk("\x1b[<64;20;15M");
+ expect(wheelUp).toHaveLength(1);
+ expect(wheelUp[0]).toEqual({
+ kind: "wheel", button: "up", x: 19, y: 14, shift: false, alt: false, ctrl: false,
+ });
+
+ // Wheel down at col 20, row 15
+ const wheelDown = parseMouseChunk("\x1b[<65;20;15M");
+ expect(wheelDown).toHaveLength(1);
+ expect(wheelDown[0]).toEqual({
+ kind: "wheel", button: "down", x: 19, y: 14, shift: false, alt: false, ctrl: false,
+ });
+ });
+
+ it("a chunk with two sequences returns two events", () => {
+ const chunk = "\x1b[<0;10;5M\x1b[<0;10;5m";
+ const events = parseMouseChunk(chunk);
+ expect(events).toHaveLength(2);
+ expect(events[0].kind).toBe("click");
+ expect(events[1].kind).toBe("release");
+ });
+
+ it("a non-mouse chunk returns []", () => {
+ expect(parseMouseChunk("plain user text")).toEqual([]);
+ expect(parseMouseChunk("\x1b[A")).toEqual([]);
+ expect(parseMouseChunk("")).toEqual([]);
+ });
+
+ it("a malformed sequence does not throw", () => {
+ expect(() => parseMouseChunk("\x1b[<not;a;numberM")).not.toThrow();
+ expect(parseMouseChunk("\x1b[<not;a;numberM")).toEqual([]);
+ expect(() => parseMouseChunk(null as never)).not.toThrow();
+ expect(parseMouseChunk(null as never)).toEqual([]);
+ });
+
+ it("wheel up and wheel down each move the offset by 3 and are consumed", () => {
+ const scroll = { offset: 0 };
+ const upConsumed = handleMouse(scroll, { kind: "wheel", button: "up" });
+ expect(upConsumed).toBe(true);
+ expect(scroll.offset).toBe(3);
+
+ const downConsumed = handleMouse(scroll, { kind: "wheel", button: "down" });
+ expect(downConsumed).toBe(true);
+ expect(scroll.offset).toBe(0);
+
+ // Non-wheel event must not be consumed or alter offset
+ const clickConsumed = handleMouse(scroll, { kind: "click", button: "left" });
+ expect(clickConsumed).toBe(false);
+ expect(scroll.offset).toBe(0);
+ });
+
+ it("the tab hit test returns the correct session id for a click on each tab of a 3-tab row including the +N case", () => {
+ const sessions = [
+ { id: "s1", name: "alpha" },
+ { id: "s2", name: "beta" },
+ { id: "s3", name: "gamma" },
+ ];
+
+ // Width 20 forces middle tab to be dropped with +1 marker: "● @alpha +1 @gamma"
+ const rendered = tabRow(sessions, "s1", { width: 20 });
+ expect(rendered).toBe("● @alpha +1 @gamma");
+
+ // Click on visible tab 1 (@alpha: cols 0-7) returns s1
+ expect(tabAtPoint(sessions, "s1", { x: 0, y: 0, width: 20 })).toBe("s1");
+ expect(tabAtPoint(sessions, "s1", { x: 7, y: 0, width: 20 })).toBe("s1");
+
+ // Click on visible tab 3 (@gamma: cols 14-19) returns s3
+ expect(tabAtPoint(sessions, "s1", { x: 14, y: 0, width: 20 })).toBe("s3");
+ expect(tabAtPoint(sessions, "s1", { x: 19, y: 0, width: 20 })).toBe("s3");
+
+ // Clicking each position of the +1 marker (cols 10 and 11) returns null
+ expect(tabAtPoint(sessions, "s1", { x: 10, y: 0, width: 20 })).toBe(null);
+ expect(tabAtPoint(sessions, "s1", { x: 11, y: 0, width: 20 })).toBe(null);
+
+ // Separators (cols 8-9 and 12-13) return null
+ expect(tabAtPoint(sessions, "s1", { x: 8, y: 0, width: 20 })).toBe(null);
+ expect(tabAtPoint(sessions, "s1", { x: 13, y: 0, width: 20 })).toBe(null);
+ });
+
+ it("a click below the tab row returns null", () => {
+ const sessions = [{ id: "s1", name: "main" }];
+ // Tab row is at y: 0; click at y: 1 is below the tab row
+ expect(tabAtPoint(sessions, "s1", { x: 2, y: 1, tabRow: 0 })).toBe(null);
+ expect(tabAtPoint(sessions, "s1", { x: 2, y: 5, tabRow: 2 })).toBe(null);
+ });
+
+ it("disabled mode writes nothing", () => {
+ const output = new FakeOutput();
+ const session = { agentSession: { id: "s1", name: "test" }, history: [] };
+ const loop = mountScreenLoop({ enabled: false, session, output });
+
+ expect(loop.active).toBe(false);
+ expect(output.chunks).toHaveLength(0);
+
+ loop.paint();
+ loop.sync();
+ loop.follow();
+ loop.dispose();
+
+ expect(output.chunks).toHaveLength(0);
+ });
+
+ it("enableMouse and disableMouse are idempotent and write expected escape codes", () => {
+ const output = new FakeOutput();
+ expect(enableMouse(output)).toBe(true);
+ expect(output.chunks).toEqual([MOUSE_ON]);
+
+ // Second call is a no-op
+ expect(enableMouse(output)).toBe(false);
+ expect(output.chunks).toEqual([MOUSE_ON]);
+
+ // Disable writes MOUSE_OFF
+ expect(disableMouse(output)).toBe(true);
+ expect(output.chunks).toEqual([MOUSE_ON, MOUSE_OFF]);
+
+ // Second disable is a no-op
+ expect(disableMouse(output)).toBe(false);
+ expect(output.chunks).toEqual([MOUSE_ON, MOUSE_OFF]);
+ });
+
+ it("dispose disables mouse reporting and restores input.emit", () => {
+ const output = new FakeOutput();
+ const input = new EventEmitter();
+ const originalEmit = input.emit;
+ const session = { agentSession: { id: "s1", name: "test" }, history: [] };
+
+ const loop = mountScreenLoop({ enabled: true, session, output, input });
+ expect(output.chunks[0]).toBe(MOUSE_ON);
+ expect(input.emit).not.toBe(originalEmit);
+
+ loop.dispose();
+ expect(input.emit).toBe(originalEmit);
+ expect(output.chunks).toContain(MOUSE_OFF);
+ });
+});
diff --git a/scripts/mso-agent-screen-loop.mjs b/scripts/mso-agent-screen-loop.mjs
index 2e5d6ab0..64613b72 100644
--- a/scripts/mso-agent-screen-loop.mjs
+++ b/scripts/mso-agent-screen-loop.mjs
@@ -1,6 +1,7 @@
import process from "node:process";
-import { chromeLines } from "./mso-agent-chrome.mjs";
+import { chromeLines, tabAtPoint } from "./mso-agent-chrome.mjs";
import { composerSeparator } from "./mso-agent-layout.mjs";
+import { disableMouse, enableMouse, handleMouse, parseMouseChunk } from "./mso-agent-mouse.mjs";
import { writeFrame } from "./mso-agent-screen.mjs";
import { transcriptLines } from "./mso-agent-transcript.mjs";
import {
@@ -18,8 +19,8 @@ import { renderViewport } from "./mso-agent-viewport-render.mjs";
const PROMPT_ROWS = 3;
/**
- * Owns the alternate-screen panel: the transcript viewport, its chrome, and the key interception
- * that scrolls it. Everything here is inert when the alternate screen is off, so the inline path
+ * Owns the alternate-screen panel: the transcript viewport, its chrome, and key and mouse
+ * interception. Everything here is inert when the alternate screen is off, so the inline path
* keeps running exactly as it did before this module existed.
*
* @param {{
@@ -29,6 +30,7 @@ const PROMPT_ROWS = 3;
* input?: any,
* colors?: any,
* getSessions?: () => Array<any>,
+ * onTabClick?: (sessionId: string) => void | Promise<void>,
* }} options
*/
export function mountScreenLoop({
@@ -38,6 +40,7 @@ export function mountScreenLoop({
input = process.stdin,
colors = {},
getSessions = () => [],
+ onTabClick,
} = {}) {
if (!enabled || !session) {
return {
@@ -49,6 +52,15 @@ export function mountScreenLoop({
};
}
+ enableMouse(output);
+
+ const onTeardown = () => { disableMouse(output); };
+ const detach = (target, event, listener) => {
+ if (typeof target?.off === "function") target.off(event, listener);
+ else if (typeof target?.removeListener === "function") target.removeListener(event, listener);
+ };
+ ["exit", "SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => process.on?.(sig, onTeardown));
+
const viewport = createViewport({ rows: output.rows || 24 });
let painted = [];
let keysPatched = false;
@@ -66,9 +78,12 @@ export function mountScreenLoop({
rows: null,
});
const separator = composerSeparator(session, colors, cols);
+ const hasSep = typeof separator === "string" && separator.length > 0;
// The separator belongs to the panel in this mode; the composer is told to draw none.
- const panel = [typeof separator === "string" ? separator : "", ...chrome].filter((line) => line.length > 0);
- return { cols, rows, panel, viewRows: Math.max(0, rows - panel.length - PROMPT_ROWS) };
+ const panel = [hasSep ? separator : "", ...chrome].filter((line) => line.length > 0);
+ const viewRows = Math.max(0, rows - panel.length - PROMPT_ROWS);
+ const tabRowY = viewRows + (hasSep ? 1 : 0);
+ return { cols, rows, panel, viewRows, tabRowY };
};
// Repaints from the top of the screen and leaves the cursor where the composer expects to start,
@@ -104,16 +119,58 @@ export function mountScreenLoop({
};
output.on?.("resize", onResize);
+ const dispatchMouse = (event) => {
+ if (!event) return false;
+ if (event.kind === "wheel") {
+ if (handleMouse(viewport, event, { rows: geometry().viewRows })) { paint(); return true; }
+ return false;
+ }
+ if (event.kind === "click") {
+ const { cols, tabRowY } = geometry();
+ if (event.y === tabRowY) {
+ const targetId = tabAtPoint(getSessions(), session?.agentSession?.id, { x: event.x, y: event.y, width: cols, tabRow: tabRowY });
+ if (targetId && typeof onTabClick === "function") {
+ Promise.resolve(onTabClick(targetId)).then(paint).catch(() => {});
+ return true;
+ }
+ }
+ return true;
+ }
+ return false;
+ };
+
// readline emits keypress on stdin, and the composer is one of its listeners. Intercepting emit
- // is the only way to consume a key before the composer acts on it without growing the composer,
- // which sits at its line ceiling.
+ // is the only way to consume keys and mouse sequences before the composer acts on them without
+ // growing the composer, which sits at its line ceiling.
originalEmit = input.emit;
if (typeof originalEmit === "function") {
keysPatched = true;
input.emit = function patchedEmit(event, ...args) {
- if (event === "keypress" && args[1] && handleViewportKey(viewport, args[1], { rows: geometry().viewRows })) {
- paint();
- return true;
+ if (event === "data" && args[0]) {
+ const chunk = typeof args[0] === "string" ? args[0] : (args[0] instanceof Buffer ? args[0].toString("utf8") : "");
+ if (chunk.includes("\x1b[<")) {
+ const events = parseMouseChunk(chunk);
+ if (events.length > 0) {
+ for (const ev of events) dispatchMouse(ev);
+ const stripped = chunk.replace(/\x1b\[<\d+;\d+;\d+[Mm]/g, "");
+ if (!stripped) return true;
+ args[0] = typeof args[0] === "string" ? stripped : Buffer.from(stripped, "utf8");
+ }
+ }
+ }
+ if (event === "keypress") {
+ const seq = args[1]?.sequence || (typeof args[0] === "string" ? args[0] : "");
+ if (typeof seq === "string" && seq.startsWith("\x1b[<")) {
+ const events = parseMouseChunk(seq);
+ if (events.length > 0) {
+ for (const ev of events) dispatchMouse(ev);
+ return true;
+ }
+ }
+ if (args[1] && handleViewportKey(viewport, args[1], { rows: geometry().viewRows })) {
+ paint();
+ return true;
+ }
}
return Reflect.apply(originalEmit, this, [event, ...args]);
};
@@ -128,8 +185,10 @@ export function mountScreenLoop({
sync,
follow: () => resetFollow(viewport),
dispose() {
+ ["exit", "SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => detach(process, sig, onTeardown));
output.off?.("resize", onResize);
if (keysPatched) input.emit = originalEmit;
+ disableMouse(output);
if (session.streamSink) delete session.streamSink;
// The panel owns the whole screen, so the inline transcript is repainted once on the way out
// instead of leaving the alternate buffer's last frame on screen.
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index 6eaca6da..c5f5ed89 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -21,6 +21,7 @@ import { pendingImageBlock } from "./mso-agent-image.mjs";
import { altScreenRequested, startAltScreen } from "./mso-agent-altscreen.mjs";
import { visibleSessionRows } from "./mso-agent-sessions.mjs";
import { chromeLines } from "./mso-agent-chrome.mjs";
+import { switchToSession } from "./mso-agent-cmd-session.mjs";
async function main() {
const argv = process.argv.slice(2);
@@ -64,7 +65,21 @@ async function main() {
const refreshSessions = () => { listCliSessions(20).then((rows) => { recentSessions = visibleSessionRows(rows); }).catch(() => {}); };
refreshSessions();
const chromeFooter = () => chromeLines({ session, sessions: recentSessions, activeId: session?.agentSession?.id, colors: C, width: process.stdout.columns, rows: process.stdout.rows });
- const screenLoop = mountScreenLoop({ session, enabled: altScreen.ok, output: process.stdout, input: process.stdin, colors: C, getSessions: () => recentSessions });
+ const screenLoop = mountScreenLoop({
+ session,
+ enabled: altScreen.ok,
+ output: process.stdout,
+ input: process.stdin,
+ colors: C,
+ getSessions: () => recentSessions,
+ onTabClick: async (targetId) => {
+ if (!targetId || targetId === session?.agentSession?.id) return;
+ await switchToSession(rl, session, targetId);
+ if (localBridge) await localBridge.syncSession();
+ refreshSessions();
+ screenLoop.sync();
+ },
+ });
rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C, onToggleStatusBar: () => { session.statusBar = !session.statusBar; screenLoop.paint(); } }); syncPromptHistory(rl, session);
let inboundRequestQueued = false;
localBridge = new LocalAgentBridge({