Tmux control mode empty begin/end behavior
Yes, it's true. When tmux control mode starts, it always sends an empty %begin/%end pair for the initial command.
Here's the flow:
Initial command is dispatched in server-client.c#L3502-3504 — when a control client connects, its startup command (e.g.,
attachornew-session) is queuedEvery command fires guards in cmd-queue.c#L619 and L678-679:
cmdq_guard(item, "begin", flags); // at start // ...execute command... cmdq_guard(item, "end", flags); // at end (or "error" on failure)cmdq_guardwrites the control message in cmd-queue.c#L825-833:if (c != NULL && (c->flags & CLIENT_CONTROL)) control_write(c, "%%%s %ld %u %d", guard, t, number, flags);
Since the initial startup command (typically new-session or attach-session) produces no output, control clients see:
%begin <timestamp> <number> <flags>
%end <timestamp> <number> <flags>
Yes, always. The %begin/%end wraps the command execution, and %session-changed is sent during execution (inside the guards).
The sequence is:
cmdq_guard(item, "begin", flags)→ sends%begin- Command runs (e.g.,
attach-session) - Inside command:
server_client_set_session()→ callsnotify_client("client-session-changed")→ sends%session-changed cmdq_guard(item, "end", flags)→ sends%end
So the output order is:
%begin <t> <n> <f>
%session-changed $<id> <name>
%end <t> <n> <f>
The %session-changed is always between the begin/end guards of the attach/new-session command.
Yes, exactly. notify_client queues the notification via cmdq_append(NULL, ...) at notify.c#L226.
The key line is:
cmdq_append(NULL, cmdq_get_callback(notify_callback, ne));
This appends to the global command queue (first arg is NULL), not the client's queue. The notify_callback that actually sends %session-changed runs after the current command completes.
So the actual order is:
%begin ...
%end ...
%session-changed ...
The notification is deferred, not immediate.
The callbacks are executed in the server main loop at server.c#L264-277:
static int
server_loop(void)
{
do {
items = cmdq_next(NULL); // global queue
TAILQ_FOREACH(c, &clients, entry) {
if (c->flags & CLIENT_IDENTIFIED)
items += cmdq_next(c); // per-client queues
}
} while (items != 0);
...
}
Then cmdq_next() at cmd-queue.c#L730-808 processes items:
switch (item->type) {
case CMDQ_COMMAND:
retval = cmdq_fire_command(item); // runs actual commands
break;
case CMDQ_CALLBACK:
retval = cmdq_fire_callback(item); // runs callbacks like notify_callback
break;
}
Since notify_client() appends to the global queue (cmdq_append(NULL, ...)), the notification callback runs on the next iteration of the do/while loop—after the client's command (with its %begin/%end) has already completed.