mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-30 16:39:33 +01:00
fix(tui): Redraw wins, leaks are told by process, detach unsets the whole hook array
Review follow-up on the follow-typing attach. - Redraw (and every forced resize at an unchanged size) handed the window back to the terminal: an unchanged pty sends tmux no SIGWINCH, so the terminal stayed the latest client and the after-resize-window hook undid the resize-window. Session.resize() now nudges the pty one row first (FORCED_RESIZE_NUDGE_MS), then applies the size, so tmux counts the tab as the client used last; the second move bumps the guarded geometry revision too. Under manual with no attach the agent sees no change. - With the nudge, client-active[91] alone covers every case, so the after-resize-window hook is gone. It kept latest through every browser resize and cost the agent three height changes per resize; now the first resize after the terminal was used costs two and later ones one. The cost is stated next to the hook. - The leak sweep matched owners by tty, and Linux hands the next terminal the pty that just closed, so the common leak was never swept. The arm now records the TUI's pid (@codeman-tui-follow-pid), and the sweep keeps only sessions this process armed (a Set filled before the first write) or whose pid is another live process. One list-sessions call reads every owner. It also runs before each attach dresses its sessions, so `codeman tui <n>` gets it and a leaked hook cannot undo presizeWindow(). - `set-hook -u` on our index left an empty session-level array, which hides the user's global hook on that event. Disarm unsets the whole event when ours is its only entry, and arm refuses while the user has a global client-active hook. - Arm and disarm are one tmux call to read and one to write (`;` lists). - Docs: the "forced resize when a browser opens a session" wording was wrong (selectSession sends no force; only Redraw, a closing pop-out and the split pane do), fixed in tui-client.ts, docs/tui.md and the invariants, whose paragraph now stands on its own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9753ca9d70
commit
70ee1312d4
10 files changed
+569
-225
No files matched your search
@@ -624,6 +624,7 @@ describe('the way out when F1 is taken, on a socket with no detach key', () => {
|
||||
restoreSessionOptions: async () => true,
|
||||
readWindowSizing: async () => null,
|
||||
presizeWindow: async () => true,
|
||||
clearLeakedFollowTyping: async () => 0,
|
||||
followAttachingClient: async () => true,
|
||||
restoreWindowSizing: async () => true,
|
||||
} as unknown as TuiClient;
|
||||
@@ -672,6 +673,7 @@ describe('attach switch keys stay on the TUI client', () => {
|
||||
restoreSessionOptions: async () => true,
|
||||
readWindowSizing: async () => null,
|
||||
presizeWindow: async () => true,
|
||||
clearLeakedFollowTyping: async () => 0,
|
||||
followAttachingClient: async () => {
|
||||
order.push('follow');
|
||||
return true;
|
||||
@@ -747,6 +749,10 @@ describe('attach takes the window back from a browser when the terminal is used'
|
||||
restoreSessionOptions: async () => undefined,
|
||||
readWindowSizing: async () => ({ cols: 60, rows: 30, mode: 'manual' }),
|
||||
presizeWindow: async () => true,
|
||||
clearLeakedFollowTyping: async () => {
|
||||
calls.push('sweep');
|
||||
return 0;
|
||||
},
|
||||
followAttachingClient: async (muxName: string) => {
|
||||
calls.push(`follow ${muxName}`);
|
||||
return true;
|
||||
@@ -773,8 +779,10 @@ describe('attach takes the window back from a browser when the terminal is used'
|
||||
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');
|
||||
// Leaks first, so a killed TUI's hook cannot undo the presize. Then
|
||||
// Alt+2 lands in the second session, and a phone can pin that one too.
|
||||
expect(calls).toEqual([
|
||||
'sweep',
|
||||
'follow codeman-aaaa1111',
|
||||
'arm codeman-aaaa1111 /dev/pts/4',
|
||||
'arm codeman-bbbb2222 /dev/pts/4',
|
||||
|
||||
+150
-75
@@ -32,6 +32,7 @@ import {
|
||||
parseFollowHooks,
|
||||
TUI_FOLLOW_HOOKS,
|
||||
TUI_FOLLOW_OWNER,
|
||||
TUI_FOLLOW_PID,
|
||||
isTuiClientTty,
|
||||
ATTACH_BANNER_MARKER,
|
||||
parseTmuxSessionList,
|
||||
@@ -523,126 +524,200 @@ describe('degraded-mode tmux enumeration', () => {
|
||||
});
|
||||
|
||||
describe('the follow hooks', () => {
|
||||
const HOOK = 'client-active[91]';
|
||||
let sockets = 0;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* A fake tmux holding one session's options and hooks plus the global hooks,
|
||||
* so arm, disarm and the sweep run against state rather than canned answers.
|
||||
* It splits each call at `;` like tmux does. Every fake gets its own socket,
|
||||
* because the "armed by this process" record is keyed by socket.
|
||||
*/
|
||||
function fakeTmux(
|
||||
initial: { owner?: string; hooks?: Record<string, string>; clients?: string[]; refuseHook?: string } = {}
|
||||
initial: {
|
||||
owner?: string;
|
||||
pid?: string;
|
||||
hooks?: Record<string, string>;
|
||||
global?: Record<string, string>;
|
||||
refuseHook?: 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: '' };
|
||||
}
|
||||
if (verb === 'set-hook' && !args.includes('-u') && args.includes(initial.refuseHook ?? '\0')) {
|
||||
throw new Error(`invalid option: ${initial.refuseHook}`);
|
||||
}
|
||||
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: '' };
|
||||
const state = {
|
||||
owner: initial.owner ?? null,
|
||||
pid: initial.pid ?? null,
|
||||
hooks: { ...(initial.hooks ?? {}) } as Record<string, string>,
|
||||
/** Events left with an empty session array (what `set-hook -u name[i]` leaves). */
|
||||
empty: [] as string[],
|
||||
};
|
||||
return { client: new TuiClient({ baseUrl, socket: 'codeman-beta', exec }), state, writes };
|
||||
const calls: string[][] = [];
|
||||
const writes: string[] = [];
|
||||
const session = 'codeman-1a2b3c4d';
|
||||
const listHooks = (hooks: Record<string, string>, empty: string[]) =>
|
||||
[...Object.entries(hooks).map(([name, command]) => `${name} ${command}`), ...empty].join('\n') + '\n';
|
||||
const run = (cmd: string[]): string => {
|
||||
const [verb] = cmd;
|
||||
if (verb === 'list-sessions') return `${session}\t${state.owner ?? ''}\t${state.pid ?? ''}\n`;
|
||||
if (verb === 'display-message') return `${cmd[cmd.length - 1]}\n`;
|
||||
if (verb === 'show-hooks' && cmd.includes('-g')) return listHooks(initial.global ?? {}, []);
|
||||
if (verb === 'show-hooks') return listHooks(state.hooks, state.empty);
|
||||
if (verb === 'show-options') {
|
||||
const lines = ['status off'];
|
||||
if (state.owner) lines.unshift(`${TUI_FOLLOW_OWNER} ${state.owner}`);
|
||||
if (state.pid) lines.unshift(`${TUI_FOLLOW_PID} ${state.pid}`);
|
||||
return lines.join('\n') + '\n';
|
||||
}
|
||||
const unset = cmd.includes('-u');
|
||||
const key = unset ? cmd[cmd.length - 1] : cmd[cmd.length - 2];
|
||||
if (verb === 'set-option' && key === TUI_FOLLOW_OWNER) state.owner = unset ? null : cmd[cmd.length - 1];
|
||||
else if (verb === 'set-option' && key === TUI_FOLLOW_PID) state.pid = unset ? null : cmd[cmd.length - 1];
|
||||
else if (verb === 'set-hook' && !unset) {
|
||||
if (key === initial.refuseHook) throw new Error(`invalid option: ${key}`);
|
||||
state.hooks[key] = cmd[cmd.length - 1];
|
||||
state.empty = state.empty.filter((event) => !key.startsWith(`${event}[`));
|
||||
} else if (verb === 'set-hook' && key.includes('[')) {
|
||||
delete state.hooks[key];
|
||||
const event = key.slice(0, key.indexOf('['));
|
||||
if (!Object.keys(state.hooks).some((name) => name.startsWith(`${event}[`)) && !state.empty.includes(event)) {
|
||||
state.empty.push(event);
|
||||
}
|
||||
} else if (verb === 'set-hook') {
|
||||
for (const name of Object.keys(state.hooks)) if (name.startsWith(`${key}[`)) delete state.hooks[name];
|
||||
state.empty = state.empty.filter((event) => event !== key);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
const exec: TuiExecFile = async (_file, args) => {
|
||||
calls.push([...args]);
|
||||
const commands: string[][] = [[]];
|
||||
for (const arg of args.slice(2)) {
|
||||
if (arg === ';') commands.push([]);
|
||||
else commands[commands.length - 1].push(arg);
|
||||
}
|
||||
if (commands.some((cmd) => cmd[0]?.startsWith('set-'))) writes.push(args.slice(2).join(' '));
|
||||
let stdout = '';
|
||||
for (const cmd of commands) stdout += run(cmd);
|
||||
return { stdout, stderr: '' };
|
||||
};
|
||||
sockets += 1;
|
||||
return { client: new TuiClient({ baseUrl, socket: `codeman-follow-${sockets}`, exec }), state, calls, writes };
|
||||
}
|
||||
|
||||
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('builds a constant command that reads the owner option, with no -t and no tty in it', () => {
|
||||
expect(Object.keys(TUI_FOLLOW_HOOKS)).toEqual([HOOK]);
|
||||
const command = TUI_FOLLOW_HOOKS[HOOK];
|
||||
// Acts only for the owner's client.
|
||||
expect(command).toContain(`#{==:#{client_tty},#{${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/');
|
||||
});
|
||||
|
||||
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',
|
||||
it('tells our hook from the user ones, and counts the other entries of the event', () => {
|
||||
expect(parseFollowHooks(`${HOOK} ${TUI_FOLLOW_HOOKS[HOOK]}\n`)).toEqual({ [HOOK]: { slot: 'ours', others: 0 } });
|
||||
expect(parseFollowHooks('client-active[91] display-message mine\nclient-active[0] x\n')).toEqual({
|
||||
[HOOK]: { slot: 'theirs', others: 1 },
|
||||
});
|
||||
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({});
|
||||
// An empty session array (what `set-hook -u name[i]` leaves) is no entry.
|
||||
expect(parseFollowHooks('client-active\nafter-resize-window[2] y\n')).toEqual({ [HOOK]: { others: 0 } });
|
||||
});
|
||||
|
||||
it('arms the owner before the hooks, and disarms the owner first', async () => {
|
||||
it('arms in one write, owner and pid first, and disarms in one, 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]']}`,
|
||||
`set-option -t codeman-1a2b3c4d ${TUI_FOLLOW_OWNER} /dev/pts/4 ; ` +
|
||||
`set-option -t codeman-1a2b3c4d ${TUI_FOLLOW_PID} ${process.pid} ; ` +
|
||||
`set-hook -t codeman-1a2b3c4d ${HOOK} ${TUI_FOLLOW_HOOKS[HOOK]}`,
|
||||
]);
|
||||
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.
|
||||
// The whole array goes when ours was its only entry: an empty one would keep
|
||||
// hiding a global hook on the event.
|
||||
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]',
|
||||
`set-option -u -t codeman-1a2b3c4d ${TUI_FOLLOW_OWNER} ; ` +
|
||||
`set-option -u -t codeman-1a2b3c4d ${TUI_FOLLOW_PID} ; ` +
|
||||
'set-hook -u -t codeman-1a2b3c4d client-active',
|
||||
]);
|
||||
expect(state).toEqual({ owner: null, hooks: {} });
|
||||
expect(state).toEqual({ owner: null, pid: null, hooks: {}, empty: [] });
|
||||
});
|
||||
|
||||
it('takes one tmux call to read and one to write, per arm and per disarm', async () => {
|
||||
const { client, calls } = fakeTmux();
|
||||
await client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4');
|
||||
expect(calls).toHaveLength(2);
|
||||
calls.length = 0;
|
||||
await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4');
|
||||
expect(calls).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('removes only our index when the user has another entry on the event', async () => {
|
||||
const { client, state } = fakeTmux({ hooks: { 'client-active[3]': 'display-message mine' } });
|
||||
await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(true);
|
||||
await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4');
|
||||
expect(state.hooks).toEqual({ 'client-active[3]': 'display-message mine' });
|
||||
});
|
||||
|
||||
it('undoes a half-done arm, as on a tmux without client-active (before 3.3)', async () => {
|
||||
const { client, state } = fakeTmux({ refuseHook: 'client-active[91]' });
|
||||
const { client, state } = fakeTmux({ refuseHook: HOOK });
|
||||
await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false);
|
||||
// restore() disarms only what armed, so nothing may be left behind here.
|
||||
expect(state).toEqual({ owner: null, hooks: {} });
|
||||
expect(state).toEqual({ owner: null, pid: null, hooks: {}, empty: [] });
|
||||
});
|
||||
|
||||
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' } });
|
||||
const { client, state, writes } = fakeTmux({ hooks: { [HOOK]: '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' });
|
||||
expect(state.hooks).toEqual({ [HOOK]: 'display-message mine' });
|
||||
});
|
||||
|
||||
it('installs nothing while the user has a global hook on the event, which a session array would hide', async () => {
|
||||
for (const global of [{ 'client-active[0]': 'display-message g' }, { [HOOK]: 'display-message g' }]) {
|
||||
const { client, writes } = fakeTmux({ global });
|
||||
await expect(client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/4')).resolves.toBe(false);
|
||||
expect(writes).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
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.
|
||||
state.owner = '/dev/pts/41';
|
||||
// pts/4 is a prefix of pts/41, and its restore must not take pts/41's hook.
|
||||
await client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/4');
|
||||
expect(state.owner).toBe('/dev/pts/41');
|
||||
expect(Object.keys(state.hooks)).toHaveLength(2);
|
||||
expect(Object.keys(state.hooks)).toEqual([HOOK]);
|
||||
});
|
||||
|
||||
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: {} });
|
||||
it('sweeps by process, never by tty: a dead pid goes, a live one and this process stay', async () => {
|
||||
const hooks = { ...TUI_FOLLOW_HOOKS };
|
||||
// The pty number came back to a live terminal; the pid says it is a leak.
|
||||
const dead = fakeTmux({ owner: '/dev/pts/7', pid: String(2 ** 22 + 1), hooks });
|
||||
await expect(dead.client.clearLeakedFollowTyping()).resolves.toBe(1);
|
||||
expect(dead.state).toEqual({ owner: null, pid: null, hooks: {}, empty: [] });
|
||||
|
||||
const live = fakeTmux({ owner: '/dev/pts/8', hooks: { ...TUI_FOLLOW_HOOKS }, clients: ['/dev/pts/8'] });
|
||||
await expect(live.client.clearLeakedFollowTyping(null)).resolves.toBe(0);
|
||||
// An owner with no pid at all is a leak too (nothing can vouch for it).
|
||||
const nopid = fakeTmux({ owner: '/dev/pts/7', hooks });
|
||||
await expect(nopid.client.clearLeakedFollowTyping()).resolves.toBe(1);
|
||||
|
||||
// A second TUI mid-attach: another live process.
|
||||
const live = fakeTmux({ owner: '/dev/pts/8', pid: String(process.ppid), hooks });
|
||||
await expect(live.client.clearLeakedFollowTyping()).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);
|
||||
// This process's own arm (an Enter pressed before the startup sweep ended).
|
||||
const own = fakeTmux();
|
||||
await own.client.armFollowTyping('codeman-1a2b3c4d', '/dev/pts/7');
|
||||
await expect(own.client.clearLeakedFollowTyping()).resolves.toBe(0);
|
||||
expect(own.state.owner).toBe('/dev/pts/7');
|
||||
// Once disarmed it is no longer ours, so a copy left behind would be swept.
|
||||
await own.client.disarmFollowTyping('codeman-1a2b3c4d', '/dev/pts/7');
|
||||
Object.assign(own.state, { owner: '/dev/pts/7', pid: String(process.pid), hooks: { ...hooks } });
|
||||
await expect(own.client.clearLeakedFollowTyping()).resolves.toBe(1);
|
||||
});
|
||||
|
||||
it('refuses names and ttys it must not pass on, and swallows a dead tmux', async () => {
|
||||
@@ -661,7 +736,7 @@ describe('the follow hooks', () => {
|
||||
});
|
||||
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);
|
||||
await expect(dead.clearLeakedFollowTyping()).resolves.toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -15,7 +15,8 @@ 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_HOOKS, TUI_FOLLOW_OWNER, TuiClient } from '../../src/tui/tui-client.js';
|
||||
import { TUI_FOLLOW_HOOKS, TUI_FOLLOW_OWNER, TUI_FOLLOW_PID, TuiClient } from '../../src/tui/tui-client.js';
|
||||
import { Session } from '../../src/session.js';
|
||||
|
||||
const hasTmux = (() => {
|
||||
try {
|
||||
@@ -95,6 +96,17 @@ describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => {
|
||||
run(['resize-window', '-t', alpha, '-x', String(cols), '-y', String(rows)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A forced resize at the tab's current size (Redraw), as `Session.resize()`
|
||||
* does it: a one-row nudge of the tab's pty, then the real size and the
|
||||
* `resize-window`.
|
||||
*/
|
||||
async function browserRedraw(term: pty.IPty, cols: number, rows: number): Promise<void> {
|
||||
term.resize(cols, rows - 1);
|
||||
await new Promise((resolve) => setTimeout(resolve, Session.FORCED_RESIZE_NUDGE_MS));
|
||||
await browserResize(term, cols, rows);
|
||||
}
|
||||
|
||||
afterAll(() => {
|
||||
for (const term of clients) term.kill();
|
||||
let socketPath = '';
|
||||
@@ -127,18 +139,19 @@ describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => {
|
||||
const browser = attach(60, 30);
|
||||
expect(await waitFor(() => ttyOf(browser) !== '')).toBe(true);
|
||||
await browserResize(browser, 61, 30);
|
||||
expect(windowSize()).toBe('61x30 latest');
|
||||
expect(windowSize()).toBe('61x30 manual');
|
||||
|
||||
// The bug: without the hooks the window stayed 61x30 manual here, and
|
||||
// typing in the terminal changed nothing for the rest of the attach.
|
||||
// The bug: without the hook the window stayed 61x30 manual from here on,
|
||||
// and typing in the terminal changed nothing for the rest of the attach.
|
||||
tui.write('a');
|
||||
expect(await waitFor(() => windowSize() === '200x50 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's Redraw is a FORCED resize at its current size: the user
|
||||
// asking for the pane back. It wins, and the terminal's next key takes it back.
|
||||
await browserRedraw(browser, 61, 30);
|
||||
expect(windowSize()).toBe('61x30 manual');
|
||||
tui.write('a');
|
||||
expect(await waitFor(() => windowSize() === '200x50 latest')).toBe(true);
|
||||
|
||||
// Typing in the browser tab gives the window to the tab...
|
||||
browser.write('b');
|
||||
@@ -188,21 +201,51 @@ describe.skipIf(!hasTmux)('TUI attach follows the terminal you type in', () => {
|
||||
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']);
|
||||
// A hook of the user's own at our index is never overwritten.
|
||||
run(['set-hook', '-t', alpha, 'client-active[91]', 'display-message mine']);
|
||||
expect(await client.armFollowTyping(alpha, tuiTty)).toBe(false);
|
||||
expect(hooks()).toContain('display-message mine');
|
||||
expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER);
|
||||
run(['set-hook', '-u', '-t', alpha, 'after-resize-window[91]']);
|
||||
run(['set-hook', '-u', '-t', alpha, 'client-active']);
|
||||
|
||||
// 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);
|
||||
// Nor is a global one hidden: a session-level array would stop it firing here.
|
||||
run(['set-hook', '-g', 'client-active', 'display-message global']);
|
||||
expect(await client.armFollowTyping(alpha, tuiTty)).toBe(false);
|
||||
expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER);
|
||||
expect(hooks()).not.toContain('[91]');
|
||||
// A live one is not.
|
||||
run(['set-hook', '-gu', 'client-active']);
|
||||
|
||||
// Disarm removes the whole session array when ours was its only entry: an
|
||||
// empty array left behind would keep hiding a global hook on the event.
|
||||
expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true);
|
||||
expect(await client.clearLeakedFollowTyping(null)).toBe(0);
|
||||
await client.disarmFollowTyping(alpha, tuiTty);
|
||||
expect(hooks()).not.toMatch(/^client-active/m);
|
||||
// A user's own entry on the same event stays, and so does its array.
|
||||
run(['set-hook', '-t', alpha, 'client-active[3]', 'display-message mine']);
|
||||
expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true);
|
||||
await client.disarmFollowTyping(alpha, tuiTty);
|
||||
expect(hooks()).toContain('client-active[3] display-message mine');
|
||||
expect(hooks()).not.toContain('[91]');
|
||||
run(['set-hook', '-u', '-t', alpha, 'client-active']);
|
||||
|
||||
// A leak is told by its process, never its tty: Linux hands the next
|
||||
// terminal the pty that just closed, so here the leaked owner's tty is the
|
||||
// live TUI's own, and the dead pid still marks it as a leak.
|
||||
const leak = (tty: string, pid: number) => {
|
||||
run(['set-option', '-t', alpha, TUI_FOLLOW_OWNER, tty]);
|
||||
run(['set-option', '-t', alpha, TUI_FOLLOW_PID, String(pid)]);
|
||||
for (const [name, command] of Object.entries(TUI_FOLLOW_HOOKS)) run(['set-hook', '-t', alpha, name, command]);
|
||||
};
|
||||
leak(tuiTty, 2 ** 22 + 1);
|
||||
expect(await client.clearLeakedFollowTyping()).toBe(1);
|
||||
expect(run(['show-options', '-t', alpha])).not.toContain(TUI_FOLLOW_OWNER);
|
||||
expect(hooks()).not.toMatch(/^client-active/m);
|
||||
// Another live process (a second TUI mid-attach) keeps its arm.
|
||||
leak('/dev/ttys998', tui.pid);
|
||||
expect(await client.clearLeakedFollowTyping()).toBe(0);
|
||||
expect(run(['show-options', '-t', alpha])).toContain(`${TUI_FOLLOW_OWNER} /dev/ttys998`);
|
||||
// So does this process's own arm, whatever its tty.
|
||||
expect(await client.armFollowTyping(alpha, tuiTty)).toBe(true);
|
||||
expect(await client.clearLeakedFollowTyping()).toBe(0);
|
||||
expect(run(['show-options', '-t', alpha])).toContain(`${TUI_FOLLOW_OWNER} ${tuiTty}`);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user