fix(tui): keep the window following the client used last, forced resizes included

A browser that opens a session sends a forced resize at its current size.
Its pty does not change, so tmux keeps the TUI's client as the latest one
and `client-active` never fires again, while Codeman's `resize-window`
still pins the window to `manual` at the browser's size. Typing in the
terminal then did nothing, which is the bug this branch fixes.

An `after-resize-window[91]` hook now puts `latest` back after Codeman's
resize, so tmux keeps deciding by the client used last; `client-active[91]`
stays for Codeman's own attach (`setManualWindowSize()`), which sets
`manual` without a resize.

The owner's tty moves into the session option `@codeman-tui-follow`, and
both hook commands are constants that read it, so no tty is interpolated
into a hook and hooks whose owner is gone do nothing. restore() and the
startup sweep drop the owner first, then our hooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kamil KaliszandClaude Opus 5.5 committed 2026-11-24 18:39:54 +01:00
1 parent d387cf8cdb
commit dbf545ce8f
7 files changed
+344 -301

No files matched your search

+126 -126
View File
@@ -29,9 +29,9 @@ import {
tuiSwitchBindingTty,
tuiSwitchAttachHook,
tuiSwitchGuard,
tuiFollowTypingHook,
tuiFollowTypingHookTty,
TUI_FOLLOW_TYPING_HOOK,
parseFollowHooks,
TUI_FOLLOW_HOOKS,
TUI_FOLLOW_OWNER,
isTuiClientTty,
ATTACH_BANNER_MARKER,
parseTmuxSessionList,
@@ -522,87 +522,134 @@ describe('degraded-mode tmux enumeration', () => {
});
});
describe('the follow-typing hook', () => {
function hookClient(exec: TuiExecFile): TuiClient {
return new TuiClient({ baseUrl, socket: 'codeman-beta', exec });
}
const line = (tty: string): string => `${TUI_FOLLOW_TYPING_HOOK} ${tuiFollowTypingHook(tty)}`;
it('reads its own tty back out of the closed form, and nothing else', () => {
expect(tuiFollowTypingHookTty(line('/dev/pts/4'))).toBe('/dev/pts/4');
expect(tuiFollowTypingHookTty(line('/dev/ttys033'))).toBe('/dev/ttys033');
expect(tuiFollowTypingHookTty(line('/dev/pts/41'))).toBe('/dev/pts/41');
// The user's own hook at the same index, or at another one, is not ours.
expect(tuiFollowTypingHookTty(`${TUI_FOLLOW_TYPING_HOOK} display-message mine`)).toBeNull();
expect(tuiFollowTypingHookTty(`client-active[0] ${tuiFollowTypingHook('/dev/pts/4')}`)).toBeNull();
expect(tuiFollowTypingHookTty('')).toBeNull();
});
it('arms with an argv array on the session, after checking the slot is free', async () => {
const calls: Array<readonly string[]> = [];
const client = hookClient(async (_file, args) => {
calls.push(args);
return { stdout: 'client-attached[90] something else\n', stderr: '' };
});
await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(true);
expect(calls).toEqual([
['-L', 'codeman-beta', 'show-hooks', '-t', 'codeman-1a2b3c4d'],
[
'-L',
'codeman-beta',
'set-hook',
'-t',
'codeman-1a2b3c4d',
'client-active[91]',
'if-shell -F "#{==:#{client_tty},/dev/pts/4}" "set-window-option window-size latest"',
],
]);
});
it('leaves a hook of the user at its index alone', async () => {
const calls: Array<readonly string[]> = [];
const client = hookClient(async (_file, args) => {
calls.push(args);
return { stdout: `${TUI_FOLLOW_TYPING_HOOK} display-message mine\n`, stderr: '' };
});
await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false);
await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4');
expect(calls.every((args) => args[2] === 'show-hooks')).toBe(true);
});
it('disarms only while the hook still names this tty', async () => {
let stored = line('/dev/pts/41');
const calls: Array<readonly string[]> = [];
const client = hookClient(async (_file, args) => {
calls.push(args);
return { stdout: `${stored}\n`, stderr: '' };
});
// pts/4 is a prefix of pts/41: that hook is another TUI's.
await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4');
expect(calls.map((args) => args[2])).toEqual(['show-hooks']);
stored = line('/dev/pts/4');
calls.length = 0;
await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4');
expect(calls[1]).toEqual(['-L', 'codeman-beta', 'set-hook', '-u', '-t', 'codeman-1a2b3c4d', 'client-active[91]']);
});
it('refuses names and ttys it must not interpolate, and swallows a dead tmux', async () => {
const calls: Array<readonly string[]> = [];
const client = hookClient(async (_file, args) => {
calls.push(args);
describe('the follow hooks', () => {
/**
* A fake tmux holding one session's options and hooks, so arm, disarm and
* the sweep run against state rather than a script of canned answers.
*/
function fakeTmux(initial: { owner?: string; hooks?: Record<string, string>; clients?: string[] } = {}) {
const state = { owner: initial.owner ?? null, hooks: { ...(initial.hooks ?? {}) } as Record<string, string> };
const writes: string[] = [];
const exec: TuiExecFile = async (_file, args) => {
const verb = args[2];
if (verb === 'list-sessions') return { stdout: 'codeman-1a2b3c4d\n', stderr: '' };
if (verb === 'list-clients') return { stdout: (initial.clients ?? []).join('\n'), stderr: '' };
if (verb === 'show-options') {
return {
stdout: state.owner ? `${TUI_FOLLOW_OWNER} ${state.owner}\nstatus off\n` : 'status off\n',
stderr: '',
};
}
if (verb === 'show-hooks') {
const lines = Object.entries(state.hooks).map(([name, command]) => `${name} ${command}`);
return { stdout: lines.join('\n'), stderr: '' };
}
writes.push(args.slice(2).join(' '));
if (verb === 'set-option' && args.includes('-u')) state.owner = null;
else if (verb === 'set-option') state.owner = args[args.length - 1] ?? null;
else if (verb === 'set-hook' && args.includes('-u')) delete state.hooks[args[args.length - 1] ?? ''];
else if (verb === 'set-hook') state.hooks[args[args.length - 2] ?? ''] = args[args.length - 1] ?? '';
return { stdout: '', stderr: '' };
});
await expect(client.armFollowTyping('other-session', '/dev/pts/4')).resolves.toBe(false);
await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4"; kill-server; "')).resolves.toBe(false);
await client.disarmFollowTyping('codeman-ssh-prod', '/dev/pts/4');
expect(calls).toEqual([]);
};
return { client: new TuiClient({ baseUrl, socket: 'codeman-beta', exec }), state, writes };
}
const dead = hookClient(async () => {
throw new Error('no server running on /tmp/tmux-1000/codeman-beta');
it('builds constant commands that read the owner option, with no -t and no tty in them', () => {
expect(Object.keys(TUI_FOLLOW_HOOKS)).toEqual(['client-active[91]', 'after-resize-window[91]']);
for (const command of Object.values(TUI_FOLLOW_HOOKS)) {
expect(command).toContain(`#{${TUI_FOLLOW_OWNER}}`);
expect(command).toContain('"set-window-option window-size latest"');
// tmux parses a hook command when it is set: an unquoted #{...} after -t is a comment.
expect(command).not.toContain('-t ');
expect(command).not.toContain('/dev/');
}
// client-active acts only for the owner's client.
expect(TUI_FOLLOW_HOOKS['client-active[91]']).toContain(`#{==:#{client_tty},#{${TUI_FOLLOW_OWNER}}}`);
});
it('tells our hooks from the user ones at the same index', () => {
const ours = Object.entries(TUI_FOLLOW_HOOKS).map(([name, command]) => `${name} ${command}`);
expect(parseFollowHooks(ours.join('\n'))).toEqual({
'client-active[91]': 'ours',
'after-resize-window[91]': 'ours',
});
expect(parseFollowHooks('client-active[91] display-message mine\nclient-active[0] x')).toEqual({
'client-active[91]': 'theirs',
});
expect(parseFollowHooks('client-active\nafter-resize-window\n')).toEqual({});
});
it('arms the owner before the hooks, and disarms the owner first', async () => {
const { client, state, writes } = fakeTmux();
await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(true);
expect(writes).toEqual([
`set-option -t codeman-1a2b3c4d ${TUI_FOLLOW_OWNER} /dev/pts/4`,
`set-hook -t codeman-1a2b3c4d client-active[91] ${TUI_FOLLOW_HOOKS['client-active[91]']}`,
`set-hook -t codeman-1a2b3c4d after-resize-window[91] ${TUI_FOLLOW_HOOKS['after-resize-window[91]']}`,
]);
writes.length = 0;
await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4');
// Owner first: from that moment both hooks are inert, even if a removal fails.
expect(writes).toEqual([
`set-option -u -t codeman-1a2b3c4d ${TUI_FOLLOW_OWNER}`,
'set-hook -u -t codeman-1a2b3c4d client-active[91]',
'set-hook -u -t codeman-1a2b3c4d after-resize-window[91]',
]);
expect(state).toEqual({ owner: null, hooks: {} });
});
it('installs nothing over a hook of the user, and never removes one', async () => {
const { client, state, writes } = fakeTmux({ hooks: { 'after-resize-window[91]': 'display-message mine' } });
await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false);
expect(writes).toEqual([]);
// Even with an owner recorded (a TUI killed before restore), the user's hook stays.
state.owner = '/dev/pts/4';
await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4');
expect(state.hooks).toEqual({ 'after-resize-window[91]': 'display-message mine' });
});
it('leaves the session to a second TUI that took it over', async () => {
const { client, state } = fakeTmux();
await client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4');
await client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/41');
// pts/4 is a prefix of pts/41, and its restore must not take pts/41's hooks.
await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4');
expect(state.owner).toBe('/dev/pts/41');
expect(Object.keys(state.hooks)).toHaveLength(2);
});
it('sweeps an owner with no live client, and never a live one or its own', async () => {
const dead = fakeTmux({ owner: '/dev/pts/7', hooks: { ...TUI_FOLLOW_HOOKS }, clients: ['/dev/pts/2'] });
await expect(dead.client.clearLeakedFollowTyping(null)).resolves.toBe(1);
expect(dead.state).toEqual({ owner: null, hooks: {} });
const live = fakeTmux({ owner: '/dev/pts/8', hooks: { ...TUI_FOLLOW_HOOKS }, clients: ['/dev/pts/8'] });
await expect(live.client.clearLeakedFollowTyping(null)).resolves.toBe(0);
expect(live.state.owner).toBe('/dev/pts/8');
// An Enter pressed before the sweep finished: armed, not yet a client.
const own = fakeTmux({ owner: '/dev/pts/7', hooks: { ...TUI_FOLLOW_HOOKS } });
await expect(own.client.clearLeakedFollowTyping('/dev/pts/7')).resolves.toBe(0);
expect(own.state.owner).toBe('/dev/pts/7');
});
it('refuses names and ttys it must not pass on, and swallows a dead tmux', async () => {
const { client, writes } = fakeTmux();
await expect(client.armFollowTyping('other-session', '/dev/pts/4')).resolves.toBe(false);
await expect(client.armFollowTyping('codeman-1a2b3c4d', '/tmp/not-a-tty')).resolves.toBe(false);
await client.disarmFollowTyping('codeman-ssh-prod', '/dev/pts/4');
expect(writes).toEqual([]);
const dead = new TuiClient({
baseUrl,
socket: 'codeman-beta',
exec: async () => {
throw new Error('no server running on /tmp/tmux-1000/codeman-beta');
},
});
await expect(dead.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false);
await expect(dead.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBeUndefined();
await expect(dead.clearLeakedFollowTyping(null)).resolves.toBe(0);
});
});
@@ -897,53 +944,6 @@ describe('TuiClient.clearLeakedAttachBanners', () => {
});
});
describe('TuiClient.clearLeakedFollowTyping', () => {
const ours = (tty: string): string => `${TUI_FOLLOW_TYPING_HOOK} ${tuiFollowTypingHook(tty)}`;
function sweeper(hooks: Record<string, string>, clients: string[]): { client: TuiClient; unset: string[] } {
const unset: string[] = [];
const exec: TuiExecFile = async (_file, args) => {
if (args.includes('list-sessions')) return { stdout: Object.keys(hooks).join('\n'), stderr: '' };
if (args.includes('list-clients')) return { stdout: clients.join('\n'), stderr: '' };
if (args.includes('show-hooks')) return { stdout: hooks[args[args.indexOf('-t') + 1] ?? ''] ?? '', stderr: '' };
if (args.includes('set-hook')) unset.push(args[args.indexOf('-t') + 1] ?? '');
return { stdout: '', stderr: '' };
};
return { client: new TuiClient({ baseUrl, socket: 'codeman-beta', exec }), unset };
}
it('removes ours for a tty with no live client, and nothing else', async () => {
const { client, unset } = sweeper(
{
// A TUI killed mid-attach (window closed, SSH dropped).
'codeman-aaaa1111': ours('/dev/pts/7'),
// A second TUI attached right now.
'codeman-bbbb2222': ours('/dev/pts/8'),
// The user's own hook at that index.
'codeman-cccc3333': `${TUI_FOLLOW_TYPING_HOOK} display-message mine`,
'codeman-dddd4444': '',
},
['/dev/pts/8', '/dev/pts/2']
);
expect(await client.clearLeakedFollowTyping(null)).toBe(1);
expect(unset).toEqual(['codeman-aaaa1111']);
});
it("never sweeps this terminal's own hook, which an early Enter may have armed already", async () => {
const { client, unset } = sweeper({ 'codeman-aaaa1111': ours('/dev/pts/7') }, []);
expect(await client.clearLeakedFollowTyping('/dev/pts/7')).toBe(0);
expect(unset).toEqual([]);
});
it('reports nothing rather than throwing when there is no tmux server', async () => {
const exec: TuiExecFile = async () => {
throw new Error('no server running on /tmp/tmux-1000/codeman-beta');
};
const client = new TuiClient({ baseUrl, socket: 'codeman-beta', exec });
await expect(client.clearLeakedFollowTyping(null)).resolves.toBe(0);
});
});
describe('parseDetachKey', () => {
// Verbatim from `tmux -L codeman list-keys -T prefix` on tmux 3.4, trimmed to
// the two lines that matter. They differ only by case, which is the whole
+67 -46
View File
@@ -5,8 +5,9 @@
* Against a real tmux on a private socket (never Codeman's). Two attach clients
* on ptys: one is the TUI's terminal, the other is what a browser tab is (one
* `tmux attach-session` per session, sized by Codeman). The browser's resize is
* what `TmuxManager.resizeWindow()` runs: `resize-window -x -y`, which puts the
* window on `manual`.
* what `Session.resize()` does: resize its client's pty, then
* `TmuxManager.resizeWindow()`'s `resize-window -x -y`, which puts the window
* on `manual`.
*
* Port: N/A (no server)
*/
@@ -14,7 +15,7 @@ import { afterAll, describe, expect, it } from 'vitest';
import { execFileSync, execSync } from 'node:child_process';
import { rmSync } from 'node:fs';
import * as pty from 'node-pty';
import { TUI_FOLLOW_TYPING_HOOK, TuiClient } from '../../src/tui/tui-client.js';
import { TUI_FOLLOW_HOOKS, TUI_FOLLOW_OWNER, TuiClient } from '../../src/tui/tui-client.js';
const hasTmux = (() => {
try {
@@ -106,7 +107,7 @@ describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => {
if (socketPath.endsWith(`/${socket}`)) rmSync(socketPath, { force: true });
});
it('gives the window back to the TUI terminal on its next keystroke, and only to that terminal', async () => {
it('follows whichever client was used last, the TUI terminal included', async () => {
run(['new-session', '-d', '-s', alpha, '-x', '120', '-y', '40', 'cat']);
run(['set-option', '-g', 'status', 'off']);
run(['set-window-option', '-t', alpha, 'window-size', 'manual']);
@@ -116,72 +117,92 @@ describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => {
expect(await waitFor(() => (tuiTty = ttyOf(tui)) !== '')).toBe(true);
expect(await client.followAttachingClient(alpha)).toBe(true);
expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true);
expect(hooks()).toContain(TUI_FOLLOW_TYPING_HOOK);
// The closed form, which disarm and re-arm match on.
expect(hooks()).toContain(`#{client_tty},${tuiTty}}`);
// Set on the session, not the server: no other session gets it.
expect(run(['show-hooks', '-g'])).not.toContain(TUI_FOLLOW_TYPING_HOOK);
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) expect(hooks()).toContain(name);
expect(run(['show-options', '-t', alpha])).toContain(`${TUI_FOLLOW_OWNER} ${tuiTty}`);
// Set on the session, not the server: no other session gets them.
expect(run(['show-hooks', '-g'])).not.toContain('[91]');
expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true);
// A phone opens the session: its client attaches and Codeman pins the window.
// A phone opens the session: Codeman's client attaches and is resized to it.
const browser = attach(60, 30);
expect(await waitFor(() => ttyOf(browser) !== '')).toBe(true);
run(['resize-window', '-t', alpha, '-x', '60', '-y', '30']);
expect(windowSize()).toBe('60x30 manual');
await browserResize(browser, 61, 30);
expect(windowSize()).toBe('61x30 latest');
// Typing in the browser tab is Codeman's business, not the hook's.
browser.write('b');
await new Promise((resolve) => setTimeout(resolve, 300));
expect(windowSize()).toBe('60x30 manual');
// Typing in the TUI terminal takes it back. This is the bug: without the
// hook the window stayed 60x30 manual here for the rest of the attach.
// The bug: without the hooks the window stayed 61x30 manual here, and
// typing in the terminal changed nothing for the rest of the attach.
tui.write('a');
expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true);
// Resizing the TUI terminal is using it too: tmux makes the resized client
// the latest one, so the hook fires without a keystroke (measured on 3.8).
await browserResize(browser, 62, 30);
expect(windowSize()).toBe('62x30 manual');
tui.resize(150, 45);
expect(await waitFor(() => windowSize() === '150x45 latest')).toBe(true);
// A browser opening a session sends a FORCED resize at its current size.
// Its pty does not change, so tmux keeps the terminal as the latest client
// and the window stays where the user is typing.
await browserResize(browser, 61, 30);
expect(windowSize()).toBe('200x50 latest');
// The browser resizing its client makes THAT client the latest one, so
// the TUI's next keystroke is a change of client and fires the hook again.
await browserResize(browser, 62, 31);
expect(windowSize()).toBe('62x31 manual');
// Typing in the browser tab gives the window to the tab...
browser.write('b');
expect(await waitFor(() => windowSize() === '61x30 latest')).toBe(true);
// ...and typing in the terminal takes it back.
tui.write('a');
expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true);
// Codeman's own attach (`setManualWindowSize()`) sets manual with no resize.
browser.write('b');
expect(await waitFor(() => windowSize() === '61x30 latest')).toBe(true);
run(['set-window-option', '-t', alpha, 'window-size', 'manual']);
tui.write('a');
expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true);
// Resizing the terminal is using it too.
browser.write('b');
expect(await waitFor(() => windowSize() === '61x30 latest')).toBe(true);
tui.resize(150, 45);
expect(await waitFor(() => windowSize() === '150x45 latest')).toBe(true);
});
it('disarms only its own hook, and never replaces one of the user', async () => {
const tuiTty = ttyOf(clients[0]);
it('stops when disarmed, leaves a second TUI and the user alone', async () => {
const [tui, browser] = clients;
const tuiTty = ttyOf(tui);
expect(tuiTty).not.toBe('');
// Another tty's restore leaves this attach's hook alone (pts/4 vs pts/41 included).
// Another tty's restore leaves this attach armed (pts/4 vs pts/41 included).
await client.disarmFollowTyping(alpha, `${tuiTty}1`);
expect(hooks()).toContain(TUI_FOLLOW_TYPING_HOOK);
expect(run(['show-options', '-t', alpha])).toContain(TUI_FOLLOW_OWNER);
await client.disarmFollowTyping(alpha, tuiTty);
expect(hooks()).not.toContain(TUI_FOLLOW_TYPING_HOOK);
// Disarmed means the next keystroke changes nothing.
await browserResize(clients[1], 64, 30);
clients[0].write('a');
expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER);
expect(hooks()).not.toContain('[91]');
// Disarmed: Codeman's resize pins the window again, and typing changes nothing.
await browserResize(browser, 64, 30);
expect(windowSize()).toBe('64x30 manual');
tui.write('a');
await new Promise((resolve) => setTimeout(resolve, 300));
expect(windowSize()).toBe('64x30 manual');
// A hook of the user's own at that index is never overwritten.
run(['set-hook', '-t', alpha, TUI_FOLLOW_TYPING_HOOK, 'display-message mine']);
// Hooks left without an owner (a removal that failed) do nothing.
for (const [name, command] of Object.entries(TUI_FOLLOW_HOOKS)) run(['set-hook', '-t', alpha, name, command]);
await browserResize(browser, 65, 30);
tui.write('a');
await new Promise((resolve) => setTimeout(resolve, 300));
expect(windowSize()).toBe('65x30 manual');
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) run(['set-hook', '-u', '-t', alpha, name]);
// A hook of the user's own at either index is never overwritten.
run(['set-hook', '-t', alpha, 'after-resize-window[91]', 'display-message mine']);
expect(await client.armFollowTyping(alpha, tuiTty)).toBe(false);
expect(hooks()).toContain('display-message mine');
await client.disarmFollowTyping(alpha, tuiTty);
expect(hooks()).toContain('display-message mine');
run(['set-hook', '-u', '-t', alpha, TUI_FOLLOW_TYPING_HOOK]);
expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER);
run(['set-hook', '-u', '-t', alpha, 'after-resize-window[91]']);
// One of ours for a stale tty (a TUI killed before its restore) is taken over.
expect(await client.armFollowTyping(alpha, `${tuiTty}1`)).toBe(true);
// A leaked owner (a TUI killed mid-attach) is swept once its client is gone.
expect(await client.armFollowTyping(alpha, '/dev/ttys999')).toBe(true);
expect(await client.clearLeakedFollowTyping(null)).toBe(1);
expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER);
expect(hooks()).not.toContain('[91]');
// A live one is not.
expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true);
expect(hooks()).toContain(`#{client_tty},${tuiTty}}`);
expect(hooks()).not.toContain(`#{client_tty},${tuiTty}1}`);
expect(await client.clearLeakedFollowTyping(null)).toBe(0);
expect(run(['show-options', '-t', alpha])).toContain(`${TUI_FOLLOW_OWNER} ${tuiTty}`);
});
});