mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-30 16:39:33 +01:00
Merge #853: fix(tui): the attached terminal takes the window size back after a browser resized it
This commit is contained in:
commit
f2c03e6bf3
10 files changed
+1026
-39
No files matched your search
+36
-3
@@ -5696,13 +5696,46 @@ export class Session extends EventEmitter {
|
||||
this._guardedGeometryRevision++;
|
||||
this._ptyCols = cols;
|
||||
this._ptyRows = rows;
|
||||
if (!IS_TEST_MODE && this._mux && this._muxSession) {
|
||||
this._mux.resizeWindow?.(this._muxSession.muxName, cols, rows);
|
||||
// ⚠️ A forced resize at an unchanged size is a device asking for the pane
|
||||
// back (the Redraw button, a closing pop-out window, the split pane). An
|
||||
// unchanged pty sends tmux no SIGWINCH, so tmux never counts this client
|
||||
// as the one used last, and while a `codeman tui` attach keeps the window
|
||||
// on `latest`, its follow hook (TUI_FOLLOW_HOOKS) hands the window back
|
||||
// to that terminal at its next key. A one-row nudge first makes this
|
||||
// client the latest one, as a real resize does. Under `manual` with no
|
||||
// attach the window ignores the client's pty, so the agent sees nothing.
|
||||
if (!dimsChanged && rows > 1) {
|
||||
this.nudgeThenResize(cols, rows);
|
||||
return;
|
||||
}
|
||||
this.ptyProcess.resize(cols, rows);
|
||||
this.applyResize(cols, rows);
|
||||
}
|
||||
}
|
||||
|
||||
/** How long tmux gets to read the nudged size before the real one. */
|
||||
static readonly FORCED_RESIZE_NUDGE_MS = 60;
|
||||
|
||||
private applyResize(cols: number, rows: number): void {
|
||||
if (!IS_TEST_MODE && this._mux && this._muxSession) {
|
||||
this._mux.resizeWindow?.(this._muxSession.muxName, cols, rows);
|
||||
}
|
||||
this.ptyProcess?.resize(cols, rows);
|
||||
}
|
||||
|
||||
private nudgeThenResize(cols: number, rows: number): void {
|
||||
const revision = this._guardedGeometryRevision;
|
||||
this.ptyProcess?.resize(cols, rows - 1);
|
||||
const timer = setTimeout(() => {
|
||||
// A newer resize won: it set its own size, so this one has nothing left to do.
|
||||
if (revision !== this._guardedGeometryRevision || !this.ptyProcess) return;
|
||||
// The pane moves a second time, so guarded input read between the two
|
||||
// must see a new revision too.
|
||||
this._guardedGeometryRevision++;
|
||||
this.applyResize(cols, rows);
|
||||
}, Session.FORCED_RESIZE_NUDGE_MS);
|
||||
timer.unref?.();
|
||||
}
|
||||
|
||||
// Legacy method for compatibility with session-manager
|
||||
async start(): Promise<void> {
|
||||
this._status = 'idle';
|
||||
|
||||
@@ -638,10 +638,15 @@ export async function beginAttachHandoff(
|
||||
const banner = bannerFor(muxName, label);
|
||||
const dressed: Array<{ muxName: string; options: TuiSessionOptions }> = [];
|
||||
const resized: Array<{ muxName: string; sizing: TuiWindowSizing }> = [];
|
||||
const followTyping: string[] = [];
|
||||
const targets = new Map<string, string>([[muxName, label]]);
|
||||
for (const tab of tabs.slice(0, 9)) {
|
||||
if (tab.muxName && !targets.has(tab.muxName)) targets.set(tab.muxName, tab.label);
|
||||
}
|
||||
// A follow hook a killed TUI left behind would undo the presize below, so
|
||||
// leaks go first. The dashboard also sweeps at startup; this covers
|
||||
// `codeman tui <n>`, which has no dashboard.
|
||||
await client.clearLeakedFollowTyping().catch(() => 0);
|
||||
for (const [target, targetLabel] of targets) {
|
||||
const snapshot = await client.readSessionOptions(target, Object.keys(banner));
|
||||
if (snapshot) dressed.push({ muxName: target, options: snapshot });
|
||||
@@ -659,6 +664,16 @@ export async function beginAttachHandoff(
|
||||
// let the session we are actually opening follow the terminal live.
|
||||
if (cols && rows && rows > 1) await client.presizeWindow(target, cols, rows - 1);
|
||||
if (target === muxName) await client.followAttachingClient(target);
|
||||
// ⚠️ `latest` does not hold for the whole attach. A browser that opens or
|
||||
// resizes this session mid-attach goes through Codeman's `resize-window`,
|
||||
// which puts the window back on `manual` at the BROWSER's size: a phone
|
||||
// opening it left the terminal showing a phone-sized pane, and typing or
|
||||
// pasting here changed nothing until a detach and a fresh attach. The
|
||||
// follow hook (TUI_FOLLOW_HOOKS) puts `latest` back when this terminal is
|
||||
// used again, so the window follows whichever client was used last. It
|
||||
// needs the tty to name its owner, like the switch keys, so without one
|
||||
// the attach keeps the old behaviour.
|
||||
if (guarded && (await client.armFollowTyping(target, tty as string))) followTyping.push(target);
|
||||
}
|
||||
// ⚠️ Armed LAST, as the final tmux call before the caller's `spawnSync`. The
|
||||
// hook is one-shot for this tty, so a TUI killed between arming and attaching
|
||||
@@ -676,6 +691,9 @@ export async function beginAttachHandoff(
|
||||
if (tty && isTuiClientTty(tty)) await client.disarmTuiSwitchGuard(tty);
|
||||
if (oneKey) await client.unbindDetachKey(ONE_KEY_DETACH, 'root');
|
||||
if (claimed && alias) await client.unbindDetachKey(alias);
|
||||
// The follow hook before the size, so nothing of this attach acts on
|
||||
// the window once the restore below has re-pinned the browser's size.
|
||||
for (const target of followTyping) await client.disarmFollowTyping(target, tty as string);
|
||||
// Options first, then the size: dropping the status bar gives its row
|
||||
// back to the pane, and the resize is what re-pins the browser's
|
||||
// authority over the window.
|
||||
@@ -1265,6 +1283,7 @@ class TuiApp {
|
||||
// Fire and forget: a bar stranded by a previous run is cosmetic, so it must
|
||||
// never delay the first frame or fail a start.
|
||||
void this.client.clearLeakedAttachBanners().catch(() => undefined);
|
||||
void this.client.clearLeakedFollowTyping().catch(() => undefined);
|
||||
|
||||
return new Promise<number>((resolve) => {
|
||||
this.resolveExit = resolve;
|
||||
|
||||
@@ -507,6 +507,113 @@ export function tuiSwitchAttachHook(tty: string): string {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Session option naming the tty of the `codeman tui` attach that owns the
|
||||
* window size of this session. The follow hook below reads it, so a hook whose
|
||||
* owner is gone does nothing.
|
||||
*/
|
||||
export const TUI_FOLLOW_OWNER = '@codeman-tui-follow';
|
||||
|
||||
/**
|
||||
* Session option holding the pid of the `codeman tui` process that set
|
||||
* `TUI_FOLLOW_OWNER`. The startup sweep reads it to tell a leak from a live
|
||||
* attach. A tty cannot do that: Linux hands out the lowest free pty, so a new
|
||||
* terminal (or a browser tab's attach client) usually gets the number of the
|
||||
* one that just closed.
|
||||
*/
|
||||
export const TUI_FOLLOW_PID = '@codeman-tui-follow-pid';
|
||||
|
||||
/** The event `TUI_FOLLOW_HOOKS` hooks, without its index. */
|
||||
const FOLLOW_HOOK_EVENT = 'client-active';
|
||||
|
||||
/**
|
||||
* The session hook that keeps a window following the attach's terminal, the
|
||||
* way plain tmux follows whichever client was used last.
|
||||
*
|
||||
* Why it is needed: the attach sets `window-size latest`, but Codeman's web
|
||||
* resize (`resizeWindow()` in tmux-manager.ts) runs `resize-window`, and
|
||||
* Codeman's own attach (`setManualWindowSize()`) sets `manual`. Either puts
|
||||
* the window back on `manual` at the browser's size. A phone opening the
|
||||
* session mid-attach therefore pinned the window to the phone, and typing or
|
||||
* pasting in the terminal changed nothing until a detach and a fresh attach.
|
||||
*
|
||||
* `client-active[91]` puts `latest` back when the TUI's own client becomes the
|
||||
* latest one again: typing, pasting or resizing the terminal after another
|
||||
* client was used (measured on tmux 3.8). A browser resize makes the tab's
|
||||
* client the latest one, because Codeman resizes that client's pty first. A
|
||||
* forced resize at an unchanged size (the browser's Redraw, a closing pop-out
|
||||
* window, the split pane) would not, so `Session.resize()` nudges the pty
|
||||
* there; see its comment. The window then stays on `manual` at the browser's
|
||||
* size until the terminal is used again.
|
||||
*
|
||||
* Cost: the first browser resize after the terminal was used changes the
|
||||
* agent's height twice where master changes it once. The window is on
|
||||
* `latest` then, so the tab's pty resize moves it (one row short, for the
|
||||
* attach's status bar), and `resize-window` moves it again. Later resizes
|
||||
* from the same tab find the window on `manual` and cost one change, as
|
||||
* without an attach. Height changes cost Claude's inline renderer transcript
|
||||
* lines (#672). A second hook on `after-resize-window` used to keep the
|
||||
* window on `latest` through every browser resize, which cost three.
|
||||
*
|
||||
* Indexed so it does not replace a user's own hook, next to the switch
|
||||
* guard's `[90]`, and set per session (`set-hook -t`), never globally.
|
||||
*
|
||||
* ⚠️ Constant string: the tty is read from `TUI_FOLLOW_OWNER` when the hook
|
||||
* runs, never interpolated. And no `-t` on `set-window-option`: tmux parses a
|
||||
* hook's command when the hook is set, and an unquoted `#{session_name}`
|
||||
* there starts a comment (measured: "-t expects an argument"). Without `-t`
|
||||
* the command targets the window the hook fired for.
|
||||
*/
|
||||
export const TUI_FOLLOW_HOOKS: Readonly<Record<string, string>> = {
|
||||
[`${FOLLOW_HOOK_EVENT}[91]`]: `if-shell -F "#{==:#{client_tty},#{${TUI_FOLLOW_OWNER}}}" "set-window-option window-size latest"`,
|
||||
};
|
||||
|
||||
/** What `show-hooks` lists for one follow hook. */
|
||||
export interface FollowHookState {
|
||||
/** Our index: `ours`, `theirs` (a hook of the user's), or absent. */
|
||||
slot?: 'ours' | 'theirs';
|
||||
/** Entries at any other index of the same event. */
|
||||
others: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* For each follow hook name, what a `show-hooks` listing holds for its event:
|
||||
* our index and how many other entries there are.
|
||||
*/
|
||||
export function parseFollowHooks(stdout: string): Record<string, FollowHookState> {
|
||||
const found: Record<string, FollowHookState> = {};
|
||||
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) found[name] = { others: 0 };
|
||||
for (const line of stdout.split('\n')) {
|
||||
const text = line.trim();
|
||||
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) {
|
||||
const event = name.slice(0, name.indexOf('['));
|
||||
if (text.startsWith(`${name} `)) {
|
||||
found[name].slot = text.includes(`#{${TUI_FOLLOW_OWNER}}`) ? 'ours' : 'theirs';
|
||||
} else if (text.startsWith(`${event}[`)) {
|
||||
found[name].others += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Between the global and the session listing in one `show-hooks` read. */
|
||||
const FOLLOW_READ_SPLIT = '@@codeman-follow-split@@';
|
||||
|
||||
/** Sessions this process armed, by socket: the sweep never takes them for a leak. */
|
||||
const armedHere = new Set<string>();
|
||||
|
||||
/** True when `pid` is a process of this user other than this one. */
|
||||
function isOtherLiveProcess(pid: number): boolean {
|
||||
if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid) return false;
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (err) {
|
||||
return (err as NodeJS.ErrnoException).code === 'EPERM';
|
||||
}
|
||||
}
|
||||
|
||||
const LEGACY_TUI_SWITCH = /^switch-client -t (\S+?)(?: \\; set-window-option -t \1 window-size latest)?$/;
|
||||
|
||||
/**
|
||||
@@ -1172,6 +1279,211 @@ export class TuiClient {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make one session's window follow this terminal for the attach: record the
|
||||
* tty and this process as the owner, then install `TUI_FOLLOW_HOOKS`. Best
|
||||
* effort, like the rest of the attach dressing: false leaves the attach as it
|
||||
* was before the hook existed (the window follows the terminal until the web
|
||||
* UI resizes it).
|
||||
*
|
||||
* Nothing is installed when the user has a hook of their own at our index,
|
||||
* or a GLOBAL hook on the same event: a session-level array hides the global
|
||||
* one for that session (measured: a global hook stopped firing during the
|
||||
* attach). An owner already recorded is replaced: it is a TUI killed before
|
||||
* its restore, or a second TUI on the same session, and the newest attach is
|
||||
* the one in front of the user.
|
||||
*
|
||||
* One tmux call reads, one writes, so nine tabs stay quick to attach.
|
||||
*
|
||||
* ⚠️ A half-done arm is undone before answering false, because `restore()`
|
||||
* only disarms what armed. tmux before 3.3 has no `client-active` hook, so
|
||||
* there the owner is set and the hook is refused; left alone, the owner
|
||||
* would stay on the session for good.
|
||||
*/
|
||||
async armFollowTyping(muxName: string, clientTty: string): Promise<boolean> {
|
||||
if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return false;
|
||||
try {
|
||||
const { global, session } = await this.readFollowHooks(muxName);
|
||||
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) {
|
||||
if (session[name].slot === 'theirs') return false;
|
||||
if (global[name].slot !== undefined || global[name].others > 0) return false;
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
// Recorded before the first write, so a sweep running concurrently (it is
|
||||
// fire-and-forget at startup) never takes this arm for a leak.
|
||||
armedHere.add(this.armedKey(muxName));
|
||||
const args = [
|
||||
'set-option',
|
||||
'-t',
|
||||
muxName,
|
||||
TUI_FOLLOW_OWNER,
|
||||
clientTty,
|
||||
';',
|
||||
'set-option',
|
||||
'-t',
|
||||
muxName,
|
||||
TUI_FOLLOW_PID,
|
||||
String(process.pid),
|
||||
];
|
||||
for (const [name, command] of Object.entries(TUI_FOLLOW_HOOKS)) {
|
||||
args.push(';', 'set-hook', '-t', muxName, name, command);
|
||||
}
|
||||
try {
|
||||
await this.exec('tmux', ['-L', this.socket, ...args]);
|
||||
return true;
|
||||
} catch {
|
||||
armedHere.delete(this.armedKey(muxName));
|
||||
try {
|
||||
await this.dropFollowTyping(muxName);
|
||||
} catch {
|
||||
/* the session is gone, or tmux is: nothing is left to undo then */
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Undo `armFollowTyping`, but only while this tty is still the owner: a
|
||||
* second TUI that attached later owns the session now.
|
||||
*/
|
||||
async disarmFollowTyping(muxName: string, clientTty: string): Promise<void> {
|
||||
if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return;
|
||||
try {
|
||||
const { stdout } = await this.exec('tmux', [
|
||||
'-L',
|
||||
this.socket,
|
||||
'show-options',
|
||||
'-t',
|
||||
muxName,
|
||||
';',
|
||||
'show-hooks',
|
||||
'-t',
|
||||
muxName,
|
||||
]);
|
||||
// Hook lines never start with `@`, so the option parse ignores them.
|
||||
if (parseSessionOptions(stdout, [TUI_FOLLOW_OWNER])[TUI_FOLLOW_OWNER] !== clientTty) return;
|
||||
await this.dropFollowTyping(muxName, parseFollowHooks(stdout));
|
||||
} catch {
|
||||
/* the session may be gone (the user exited the agent from inside the attach) */
|
||||
} finally {
|
||||
armedHere.delete(this.armedKey(muxName));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove follow hooks a previous TUI never got to take down.
|
||||
*
|
||||
* Same leak as the banners: a terminal that dies while attached (a closed
|
||||
* window, a dropped SSH) never reaches `restore()`, and its owner stays
|
||||
* recorded, so the window followed whatever client a pty reusing that
|
||||
* number belonged to. Left alone the hook also undoes `presizeWindow()` on
|
||||
* the next attach.
|
||||
*
|
||||
* A session is left alone when this process armed it, or when the pid
|
||||
* recorded with the owner is another live process (a second TUI mid-attach).
|
||||
* Everything else with an owner is a leak, whatever its tty: Linux reuses
|
||||
* pty numbers, so a tty proves nothing.
|
||||
*
|
||||
* Runs at TUI startup and again before each attach dresses its sessions, so
|
||||
* `codeman tui <n>` gets it too. One tmux call lists every owner.
|
||||
*/
|
||||
async clearLeakedFollowTyping(): Promise<number> {
|
||||
let rows: string[];
|
||||
try {
|
||||
const { stdout } = await this.exec('tmux', [
|
||||
'-L',
|
||||
this.socket,
|
||||
'list-sessions',
|
||||
'-F',
|
||||
`#{session_name}\t#{${TUI_FOLLOW_OWNER}}\t#{${TUI_FOLLOW_PID}}`,
|
||||
]);
|
||||
rows = stdout.split('\n');
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
let cleared = 0;
|
||||
for (const row of rows) {
|
||||
const [name = '', owner = '', pid = ''] = row.trim().split('\t');
|
||||
if (!MUX_NAME_PATTERN.test(name) || !owner) continue;
|
||||
if (armedHere.has(this.armedKey(name))) continue;
|
||||
if (isOtherLiveProcess(Number(pid))) continue;
|
||||
try {
|
||||
await this.dropFollowTyping(name);
|
||||
cleared += 1;
|
||||
} catch {
|
||||
/* the session went away mid-sweep */
|
||||
}
|
||||
}
|
||||
return cleared;
|
||||
}
|
||||
|
||||
private armedKey(muxName: string): string {
|
||||
return `${this.socket}\0${muxName}`;
|
||||
}
|
||||
|
||||
/** The global and the session hook listings, in one tmux call. */
|
||||
private async readFollowHooks(
|
||||
muxName: string
|
||||
): Promise<{ global: Record<string, FollowHookState>; session: Record<string, FollowHookState> }> {
|
||||
const { stdout } = await this.exec('tmux', [
|
||||
'-L',
|
||||
this.socket,
|
||||
'show-hooks',
|
||||
'-g',
|
||||
';',
|
||||
'display-message',
|
||||
'-p',
|
||||
'-t',
|
||||
muxName,
|
||||
FOLLOW_READ_SPLIT,
|
||||
';',
|
||||
'show-hooks',
|
||||
'-t',
|
||||
muxName,
|
||||
]);
|
||||
const split = stdout.indexOf(FOLLOW_READ_SPLIT);
|
||||
if (split === -1) throw new Error('unexpected show-hooks output');
|
||||
return {
|
||||
global: parseFollowHooks(stdout.slice(0, split)),
|
||||
session: parseFollowHooks(stdout.slice(split + FOLLOW_READ_SPLIT.length)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Owner first (the hook is inert from then on), then our hook, in one call.
|
||||
*
|
||||
* ⚠️ When ours is the only entry of the event, the whole session array is
|
||||
* unset, not just our index: `set-hook -u` on one index leaves an empty
|
||||
* session-level array, which keeps hiding the user's global hook for that
|
||||
* event (measured on tmux 3.8). `restoreSessionOptions()` documents the
|
||||
* same trap for `status-format[0]`.
|
||||
*/
|
||||
private async dropFollowTyping(muxName: string, known?: Record<string, FollowHookState>): Promise<void> {
|
||||
const hooks = known ?? (await this.readFollowHooks(muxName)).session;
|
||||
const args = [
|
||||
'set-option',
|
||||
'-u',
|
||||
'-t',
|
||||
muxName,
|
||||
TUI_FOLLOW_OWNER,
|
||||
';',
|
||||
'set-option',
|
||||
'-u',
|
||||
'-t',
|
||||
muxName,
|
||||
TUI_FOLLOW_PID,
|
||||
];
|
||||
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) {
|
||||
const state = hooks[name];
|
||||
if (state.slot !== 'ours') continue;
|
||||
const event = name.slice(0, name.indexOf('['));
|
||||
args.push(';', 'set-hook', '-u', '-t', muxName, state.others === 0 ? event : name);
|
||||
}
|
||||
await this.exec('tmux', ['-L', this.socket, ...args]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Give back a switch key, but only while it is still one of ours.
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user