mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-30 16:39:33 +01:00
fix(tui): take the window size back when the attached terminal is used
`codeman tui` sets `window-size latest` for an attach, but a browser tab
that opens or resizes the same session mid-attach makes Codeman run
`resize-window`, which puts the window back on `manual` at the browser's
size. The terminal then showed a phone-sized pane, and typing or pasting
changed nothing until a detach and a fresh attach.
The attach now sets a per-session `client-active[91]` hook on every
session it dresses. It runs `set-window-option window-size latest` only
for the TUI's own client (`#{client_tty}`), so typing, pasting or
resizing the terminal hands the window back to it, the way plain tmux
follows whoever used it last. `restore()` removes the hooks before the
window sizes are put back, and only while they still name this tty.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5548c17c4a
commit
ba61cfe4e6
8 files changed
+480
-1
No files matched your search
@@ -676,6 +676,8 @@ describe('attach switch keys stay on the TUI client', () => {
|
||||
order.push('follow');
|
||||
return true;
|
||||
},
|
||||
armFollowTyping: async () => true,
|
||||
disarmFollowTyping: async () => undefined,
|
||||
restoreWindowSizing: async () => true,
|
||||
} as unknown as TuiClient;
|
||||
|
||||
@@ -726,6 +728,82 @@ describe('attach switch keys stay on the TUI client', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('attach takes the window back from a browser when the terminal is used', () => {
|
||||
/** Records the sizing calls in order; everything else is a no-op. */
|
||||
function sizingFake(armResult = true) {
|
||||
const calls: string[] = [];
|
||||
const client = {
|
||||
readPrefixKey: async () => 'C-b',
|
||||
readDetachKey: async () => 'd',
|
||||
readPrefixBinding: async () => null,
|
||||
bindDetachKey: async () => true,
|
||||
unbindDetachKey: async () => true,
|
||||
armTuiSwitchGuard: async () => true,
|
||||
disarmTuiSwitchGuard: async () => undefined,
|
||||
bindSwitchKey: async () => true,
|
||||
unbindSwitchKey: async () => undefined,
|
||||
readSessionOptions: async () => null,
|
||||
applySessionOptions: async () => true,
|
||||
restoreSessionOptions: async () => undefined,
|
||||
readWindowSizing: async () => ({ cols: 60, rows: 30, mode: 'manual' }),
|
||||
presizeWindow: async () => true,
|
||||
followAttachingClient: async (muxName: string) => {
|
||||
calls.push(`follow ${muxName}`);
|
||||
return true;
|
||||
},
|
||||
armFollowTyping: async (muxName: string, tty: string) => {
|
||||
calls.push(`arm ${muxName} ${tty}`);
|
||||
return armResult;
|
||||
},
|
||||
disarmFollowTyping: async (muxName: string, tty: string) => {
|
||||
calls.push(`disarm ${muxName} ${tty}`);
|
||||
},
|
||||
restoreWindowSizing: async (muxName: string) => {
|
||||
calls.push(`size ${muxName}`);
|
||||
},
|
||||
} as unknown as TuiClient;
|
||||
return { client, calls };
|
||||
}
|
||||
|
||||
const tabs = [
|
||||
{ index: 1, label: 'w1', active: true, muxName: 'codeman-aaaa1111' },
|
||||
{ index: 2, label: 'w2', active: false, muxName: 'codeman-bbbb2222' },
|
||||
];
|
||||
|
||||
it('arms the hook on every session the strip can reach, and drops it before the size is put back', async () => {
|
||||
const { client, calls } = sizingFake();
|
||||
const handoff = await beginAttachHandoff(client, 'codeman-aaaa1111', 'w1', tabs, 200, 50, '/dev/pts/4');
|
||||
// Alt+2 lands in the second session, and a phone can pin that one too.
|
||||
expect(calls).toEqual([
|
||||
'follow codeman-aaaa1111',
|
||||
'arm codeman-aaaa1111 /dev/pts/4',
|
||||
'arm codeman-bbbb2222 /dev/pts/4',
|
||||
]);
|
||||
|
||||
calls.length = 0;
|
||||
await handoff.restore();
|
||||
// Disarmed first: the size restore re-pins the browser's authority, and
|
||||
// a hook still armed after it could hand the window back to a reused pty.
|
||||
expect(calls).toEqual([
|
||||
'disarm codeman-aaaa1111 /dev/pts/4',
|
||||
'disarm codeman-bbbb2222 /dev/pts/4',
|
||||
'size codeman-aaaa1111',
|
||||
'size codeman-bbbb2222',
|
||||
]);
|
||||
});
|
||||
|
||||
it('arms nothing without a tty to guard on, and disarms only what it armed', async () => {
|
||||
const bare = sizingFake();
|
||||
await (await beginAttachHandoff(bare.client, 'codeman-aaaa1111', 'w1', tabs, 200, 50, null)).restore();
|
||||
expect(bare.calls.filter((call) => call.startsWith('arm') || call.startsWith('disarm'))).toEqual([]);
|
||||
|
||||
// A session whose hook slot is the user's (arm answered false) is not disarmed.
|
||||
const refused = sizingFake(false);
|
||||
await (await beginAttachHandoff(refused.client, 'codeman-aaaa1111', 'w1', tabs, 200, 50, '/dev/pts/4')).restore();
|
||||
expect(refused.calls.filter((call) => call.startsWith('disarm'))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('naming a session the TUI starts', () => {
|
||||
it("follows the web UI's w<n>-<case> convention", () => {
|
||||
expect(nextSessionName('mirofish', [])).toBe('w1-mirofish');
|
||||
|
||||
@@ -29,6 +29,9 @@ import {
|
||||
tuiSwitchBindingTty,
|
||||
tuiSwitchAttachHook,
|
||||
tuiSwitchGuard,
|
||||
tuiFollowTypingHook,
|
||||
tuiFollowTypingHookTty,
|
||||
TUI_FOLLOW_TYPING_HOOK,
|
||||
isTuiClientTty,
|
||||
ATTACH_BANNER_MARKER,
|
||||
parseTmuxSessionList,
|
||||
@@ -519,6 +522,90 @@ 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);
|
||||
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([]);
|
||||
|
||||
const dead = hookClient(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();
|
||||
});
|
||||
});
|
||||
|
||||
describe('attach window sizing', () => {
|
||||
/** A client that only ever needs its injected exec: none of this talks to a server. */
|
||||
function sizingClient(exec: TuiExecFile): TuiClient {
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* @fileoverview A `codeman tui` attach takes the window size back when you type
|
||||
* in it, after a browser tab re-pinned the window to its own size.
|
||||
*
|
||||
* 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`.
|
||||
*
|
||||
* Port: N/A (no server)
|
||||
*/
|
||||
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';
|
||||
|
||||
const hasTmux = (() => {
|
||||
try {
|
||||
execSync('tmux -V', { stdio: 'ignore' });
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
// `client-active` exists from tmux 3.3. An older tmux refuses the hook, and
|
||||
// armFollowTyping() answers false there, which the unit tests cover.
|
||||
const version = /tmux (?:next-)?([0-9]+)\.([0-9]+)/.exec(execSync('tmux -V', { encoding: 'utf8' }));
|
||||
if (!version) return false;
|
||||
const major = Number(version[1]);
|
||||
const minor = Number(version[2]);
|
||||
return major > 3 || (major === 3 && minor >= 3);
|
||||
})();
|
||||
|
||||
describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => {
|
||||
const socket = `codeman-tui-follow-${process.pid}`;
|
||||
const alpha = 'codeman-aaaa3333';
|
||||
const run = (args: readonly string[]): string =>
|
||||
execFileSync('tmux', ['-L', socket, '-f', '/dev/null', ...args], {
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
const client = new TuiClient({ socket });
|
||||
const clients: pty.IPty[] = [];
|
||||
|
||||
function attach(cols: number, rows: number): pty.IPty {
|
||||
const env = { ...process.env } as Record<string, string>;
|
||||
delete env.TMUX;
|
||||
const term = pty.spawn('tmux', ['-L', socket, '-f', '/dev/null', 'attach-session', '-t', alpha], {
|
||||
name: 'xterm-256color',
|
||||
cols,
|
||||
rows,
|
||||
env,
|
||||
});
|
||||
term.onData(() => {
|
||||
/* drain, so tmux never blocks on a full pty */
|
||||
});
|
||||
clients.push(term);
|
||||
return term;
|
||||
}
|
||||
|
||||
/** The tty tmux reports for a client, found by its pid (portable: macOS has no /proc). */
|
||||
function ttyOf(term: pty.IPty): string {
|
||||
for (const line of run(['list-clients', '-F', '#{client_pid}\t#{client_tty}']).split('\n')) {
|
||||
const [pid, tty] = line.trim().split('\t');
|
||||
if (pid === String(term.pid) && tty) return tty;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function windowSize(): string {
|
||||
return run(['display-message', '-p', '-t', alpha, '#{window_width}x#{window_height} #{window-size}']).trim();
|
||||
}
|
||||
|
||||
function hooks(): string {
|
||||
return run(['show-hooks', '-t', alpha]);
|
||||
}
|
||||
|
||||
async function waitFor(check: () => boolean, ms = 4000): Promise<boolean> {
|
||||
const deadline = Date.now() + ms;
|
||||
while (Date.now() < deadline) {
|
||||
if (check()) return true;
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
}
|
||||
return check();
|
||||
}
|
||||
|
||||
/**
|
||||
* Codeman's web resize, as `Session.resize()` does it: the tab's attach
|
||||
* client's pty, then `TmuxManager.resizeWindow()`'s `resize-window`.
|
||||
*/
|
||||
async function browserResize(term: pty.IPty, cols: number, rows: number): Promise<void> {
|
||||
term.resize(cols, rows);
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
run(['resize-window', '-t', alpha, '-x', String(cols), '-y', String(rows)]);
|
||||
}
|
||||
|
||||
afterAll(() => {
|
||||
for (const term of clients) term.kill();
|
||||
let socketPath = '';
|
||||
try {
|
||||
socketPath = run(['display-message', '-p', '#{socket_path}']).trim();
|
||||
run(['kill-server']);
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
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 () => {
|
||||
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']);
|
||||
|
||||
const tui = attach(200, 50);
|
||||
let tuiTty = '';
|
||||
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);
|
||||
expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true);
|
||||
|
||||
// A phone opens the session: its client attaches and Codeman pins the window.
|
||||
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');
|
||||
|
||||
// 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.
|
||||
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);
|
||||
|
||||
// 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');
|
||||
tui.write('a');
|
||||
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]);
|
||||
expect(tuiTty).not.toBe('');
|
||||
|
||||
// Another tty's restore leaves this attach's hook alone (pts/4 vs pts/41 included).
|
||||
await client.disarmFollowTyping(alpha, `${tuiTty}1`);
|
||||
expect(hooks()).toContain(TUI_FOLLOW_TYPING_HOOK);
|
||||
|
||||
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');
|
||||
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']);
|
||||
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]);
|
||||
|
||||
// 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);
|
||||
expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true);
|
||||
expect(hooks()).toContain(`#{client_tty},${tuiTty}}`);
|
||||
expect(hooks()).not.toContain(`#{client_tty},${tuiTty}1}`);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user