Architecture · November 2026

Close the window, update the app, keep every terminal: Fibo’s background host and terminal handover

A terminal that lives in the window process takes its running agent down when the window closes or the app updates. Fibo keeps terminals in a long-running host, fibo serve; on an update the old host passes each PTY file descriptor and a screen snapshot to the new host over SCM_RIGHTS, and any failure before the new host answers "taken" leaves the old one serving. Being long-running brings its own problems: one lock, one failed sendmsg, or how the host was started, affects every terminal at once.

What Fibo is: a native desktop workbench for coding agents such as Claude Code and Codex, open source (MIT). The release build is for macOS; Windows and Ubuntu have previews. Install: download the DMG, or brew install --cask majiayu000/tap/fibo. The previous posts covered terminals on other machines and pasting screenshots over ssh; this one is about what both rest on: where the terminals live.
Window Old host New host 0 START host runs other code: start fibo serve --takeover 1 PREPARE Hello + Handoff drain input, lock every terminal terminal list + a screen snapshot each 2 READY READY, then the PTY master fds (SCM_RIGHTS) restore screens, open the DB listen on .sock-start, unpublished Fails before here: the new host hangs up, the old one resumes input and keeps serving 3 COMMIT ACK "taken" old host exit(0), no signal to any program 4 SERVING wait for host.lock to be released .sock-start → workbench.sock window reconnects to the new build A failure here drops the terminals, so every check that can run earlier runs before COMMIT
The four phases of one handover. Until the new host answers "taken", the old host still holds every terminal and any failure falls back to it; after that the old host exits and the new one serves.

01 Why terminals live outside the window

An ordinary terminal app holds each terminal's PTY master itself. When the app quits, the master closes, the kernel sends SIGHUP to the processes in that terminal, and the shell exits with the Claude Code inside it. An agent half an hour into a task is gone because someone closed the wrong window or installed an update.

Fibo keeps terminals in a long-running background process, fibo serve. When the window process fibo-app starts and finds no host, it starts one: setsid detaches it from the window's session, stdin goes to null, stderr goes to host.log. From then on the window talks to the host over one Unix socket (workbench.sock) and holds no PTY at all. The screen state lives in the host too: the host parses output with libghostty-vt, and a window that connects first receives a snapshot of the screen, then the changes.

What happensTerminal inside the window processFibo: terminal inside fibo serve
Close the window, quit the appmaster closes, SIGHUP, agent exitshost unaffected; reopening shows the snapshot and carries on
App crashessamesame
Update the appquits first, so samea new host takes every terminal over (next section), pids unchanged
The host itself exitsn/aevery terminal goes. So the host must try hard not to exit (section 05)
Rebootall goneterminal processes gone too; interrupted sessions can be resumed as the same conversation

A reopened window first greets the host (Hello), and the host reports a fingerprint of its program file: an FNV-1a hash of its bytes plus its length. If that matches the host program shipped next to the window, the window just connects. If not, the host is running old code, and there are two ways forward: stop it and start a new one, which ends every terminal, or have a new host take the terminals over. Fibo takes the second.

02 Handover: four phases, split at "taken"

For terminals to survive, the new host has to get the same PTY master, not open a new one. The standard Unix way to pass a file descriptor between processes is an SCM_RIGHTS control message on a Unix socket: the kernel creates a descriptor in the receiving process that refers to the same open file. The old host sends each terminal's master fd, the new host reads and writes through it, and the shell and agent notice nothing.

The fd alone is not enough. What is on screen, where the cursor is, the terminal title: those live in the old host's memory, so the old host also sends a screen snapshot. The hard part is ordering: when may the old host let go? Too early, and if the new host fails to start, nobody holds the terminals. Fibo's rule is item 5 of docs/plan.md: a two-phase handover, Prepare → READY → COMMIT → SERVING; on any failure before READY the old host keeps serving. In code the dividing line is one frame from the new host, ACK "taken".

PhaseWho does whatTimeoutA failure here
0 StartThe window starts a new host with --takeover; the new host first checks that workbench.sock and .sock-start are this user's sockets or absentwindow waits 20 snew host exits; the window says the new host could not take the terminals and the old host keeps running
1 PrepareThe new host connects and sends Hello, Handoff. The old host waits until each terminal's accepted input is written, locks every terminal, and sends the terminal list and a screen snapshot eachinput drain 10 s; new host reads for 15 sconnection drops, the old host unlocks and keeps serving
2 READYEach snapshot ends with a READY frame; one last message carries every master fd via SCM_RIGHTS. The new host restores screens, opens the database, listens on .sock-start (not yet public)sending fds 10 sthe new host hangs up without an ACK; the old host sees it, resumes input, keeps serving
3 COMMITThe new host answers ACK "taken"; the old host calls exit(0) and signals none of the programsold host waits 10 s for the ACKno ACK means no handover; the old host keeps serving
4 SERVINGThe new host waits for the old one to release host.lock, starts each terminal's read and write threads, renames .sock-start to workbench.socklock wait 10 sterminals drop. Only the lock wait, thread starts and one rename are left here

The old host's side, simplified (error handling trimmed):

// old host: with every terminal locked, send snapshots, then the fds
send(&mut stream, CONTROL, &Reply::Handoff { terminals })?;
for (_, live) in held.iter_mut() {
    for chunk in live.vt.snapshot()?.chunks(MAX_FRAME - 1) {
        write_frame(&mut stream, SNAPSHOT, chunk)?;
    }
    write_frame(&mut stream, READY, &[])?;
}
term::send_masters(&stream, &masters)?;          // SCM_RIGHTS
match read_frame(&mut stream) {
    Ok((ACK, taken)) if taken == b"taken" => std::process::exit(0),
    other => Err(io::Error::other(format!(
        "handoff not confirmed, still serving: {other:?}"))),
}

A few details:

Three fault-injection tests guard the failure paths, each with a real fibo serve and real PTYs: an ordinary file where .sock-start goes (the new host must fail and the old host's shell must still be alive); a malformed table planted in the database (the new host errors before the ACK and the old terminal still takes input and prints output); a proxy that flips the first byte of a snapshot (the new host must not ACK).

From the record: one update on 11-03 handed over 8 terminals with their pids unchanged (docs/plan.md). Windows' ConPTY cannot pass a running console, so CAN_HAND_OVER is false there: while terminals run, the window keeps using the old host and shows "host update · restart", leaving the timing to the person (PR #230). The Ubuntu preview uses the same handover code as macOS and the Linux CI runs these tests, but no update has been handed over on a real Linux desktop yet.

03 Self-update takes the same road

The in-app updater only swaps the app bundle; it does not reimplement the handover (docs/decisions/2026-11-08-self-update.md). In order:

So one self-update has two fall-back points: the bundle swap relies on renames, and the original bundle is whole until a rename succeeds; the terminals rely on the ACK, and the old host holds them until then. The two never need to be one transaction.

04 sendmsg with descriptors can fail with EMSGSIZE

After an update on 11-03, the new window came up blank. The old host was still serving and every terminal was there, so it only looked like a window problem. The cause: the sendmsg carrying the fds had returned Message too long. The failure came before the ACK, the fallback worked as designed, and the new host never started.

It comes from macOS Unix sockets. A blocking sender writing ordinary data waits when the peer's buffer is full; a message carrying SCM_RIGHTS that meets an almost-full buffer does not wait, it returns EMSGSIZE at once. During a handover the fd message goes right after the snapshots, which had just filled the buffer the new host had not yet read. The fix (edc88987) treats EMSGSIZE, ENOBUFS and EWOULDBLOCK as "no room yet": retry every 10 ms for up to 10 s. The regression test leaves 8192 bytes unread, then sends an fd; it failed every time before the fix.

Measured 11-28: the edge is not 8192 but 8192 minus the control message

The commit says the peer's buffer held "exactly a full buffer" of 8192 bytes. We measured the edge more finely with a small program on macOS 27.2 (net.local.stream.sendspace is 8192): a socketpair of blocking stream Unix sockets, N bytes written and left unread, then a sendmsg of 1 byte plus 1 fd, with the reader starting to read after 300 ms. Each value was run 5 times with the same result.

Unread bytes Nsendmsg with 1 fd1 byte, no fd
0 to 8175succeeds at oncesucceeds at once
8176blocks about 300 ms until the reader drains, then succeedssucceeds at once
8177 to 8192EMSGSIZE at once (Message too long)succeeds (blocks about 300 ms at 8192)

8192 − 8176 = 16, exactly the size of a one-fd control message, CMSG_SPACE(4). With more fds, the first failing value moves down as the control message grows, every time at 8192 − CMSG_SPACE(4n) + 1:

fds in one messageCMSG_SPACEEMSGSIZE from this many unread bytes
1168177
2208173
4288165
8448149
200 (Fibo's limit)8127381

The pattern looks like this: if the free space fits the control message but not the data, the send waits; if it cannot even fit the control message, the send fails. We did not check this against the kernel source; it is measured behaviour only. It explains why the bug is rare: snapshots run from a few KB to tens of KB and the new host reads as they arrive, so it shows up only when, at the moment the fd message goes out, fewer than 16 bytes (for one terminal) are free. More terminals mean a bigger control message and a wider window. The test program, simplified:

import os, socket, threading, time

def trial(unread, nfds):
    a, b = socket.socketpair()              # blocking stream Unix sockets
    r, w = os.pipe()
    def reader():                           # the new host: reads after 300 ms
        time.sleep(0.3)
        got = 0
        while got < unread:
            got += len(b.recv(unread - got))
        socket.recv_fds(b, 1, nfds)
    t = threading.Thread(target=reader); t.start()
    a.sendall(b"\x07" * unread)             # the snapshot, still unread
    try:
        socket.send_fds(a, [b"\x01"], [r] * nfds)
        result = "ok"
    except OSError as e:
        result = os.strerror(e.errno)       # Message too long
        a.shutdown(socket.SHUT_WR)
    t.join()
    return result

The same day turned up another property of SCM_RIGHTS: a sender's fd may have FD_CLOEXEC set, but the receiver's new fd does not (measured 11-28: 1 on the way out, 0 on arrival), and macOS has no MSG_CMSG_CLOEXEC like Linux. Left alone, every program the new host starts afterwards inherits every old terminal's master: it can type into other terminals, and if the new host crashes the old terminals never get the hangup. The fix sets fcntl(fd, F_SETFD, FD_CLOEXEC) on each one received (24656b96).

05 What a long-running host ran into

Once the host is long-running, each of its mistakes is multiplied by "every terminal". These are the problems tied to the long-running host or the handover that were fixed between 11-03 and 11-24:

SymptomRoot causeWhy it was hard to findFixSource
Blank new window after an updatesendmsg with fds returns EMSGSIZE near a full bufferthe fallback worked, the old host kept serving, only the blank window was lefttreat it as no room yet, retry up to 10 sedc88987
Programs the new host starts hold every old terminal's masterSCM_RIGHTS drops FD_CLOEXECno error anywhereset it on each fd received24656b96
New host says taken, then fails; every terminal hangs up while the app says the old host is finesocket and database checks ran after the ACKonly when a plain file sits where the socket goes, or the database will not opencheck before the ACKbf7f2639
Old host's relay connection alive 6 hours after an updateprocess::exit runs no destructors, so the child gets no termination signalits parent becomes 1, nobody sees it; when it reconnects it may knock the new host's link offthe child checks its parent every second and exits when it changes50e09bf8
Windows update stuck at "the new host could not take the terminals"handoff hard-coded to trueonly on a real Windows machineuse the platform's CAN_HAND_OVER#230
The old host acknowledged a handover with a 64 KiB paste still being writtenthe handover locked terminals without waiting for accepted inputthe paste has to coincide with an update; found by comparison on a real local PTYwait for accepted input first, with locks released while waiting#480
Dropped keys, red "input queue full"the host took a global lock for every keythe lock was held 0.2–0.37 s only every few secondsqueue by bytes and merge, receive keys without the lock#371
A long paste stops at 1022 byteswriting input and reading output share one terminal lockonly when a program redraws while receiving long inputone writer thread per terminal, no lock held while writing#443
New Claude sessions show Not logged inthe host was started inside SSHenvironment variables all correct; quitting and reopening the app does nothingthe host checks how it was started; the window can restart it properly#368
One failed accept ends the host and hangs up every terminalone ? in the main loopfound in a code review, never seen happenlog, pause 100 ms, try again#557

The first four were direct commits from 11-03 to 11-05, without PR numbers. #480 is about the handover itself; #371, #443 and #368 are not handover bugs but come from "one process serves every terminal", covered in the next two sections.

06 One lock, every terminal's input

Dropped keys (#371)

The window used to give each key one slot in a queue and drop keys once 128 slots were full. On the host, each key meant taking the terminal lock to write it to the PTY, then the global lock to note "the user is answering", and only then reading the next key. Every few seconds session matching held the global lock for 0.2–0.37 s; when the program in the terminal was not reading input, the PTY write waited too. Together they filled the window's 128 slots.

We did not just raise 128: the host would still take a lock per key and drop later. Instead the window and host share a byte queue: adjacent input merges into one item (up to 16 KiB each), a new window size replaces a queued one, mouse reports are dropped when there is a backlog, and only a backlog past the limit (1 MiB in the window, 4 MiB in the host) is refused. The host's socket-reading thread only enqueues; writing the PTY and taking the global lock happen on another thread, once per batch.

A long paste cut short (#443)

On macOS each terminal's input queue holds about 1 KB. A program busy redrawing (Codex with its spinner, say) only comes back to read input once its own output has been taken, while the host held the terminal lock the whole time it wrote input, and reading output needs that lock. Each waited on the other until the write timed out after 5 s, with only the first 1022 bytes of the paste in. The reproduction used a single-threaded redrawing program modelled on Codex: with 4000 bytes pasted, the program's output was stuck for 5.0 s and the send failed after 5.2 s.

Two alternatives were considered: dropping the lock during the write and adding a separate write lock fails the same way, since the output thread answering terminal queries would wait on that write lock; a longer timeout only makes the stall longer. The fix is one input-writing thread per terminal, writing in order, with callers queueing and waiting outside the lock.

3000 KEYS, PROGRAM NOT READING FOR 3 S (#371 REGRESSION TEST) Before 3.0 s, test fails After < 1.5 s (test limit), passes 4000-BYTE PASTE INTO A REDRAWING PROGRAM (#443) Before fails at 5.2 s, 1022 bytes in After 28 ms, all 4000 bytes (measured 11-28) scale: 100 px = 1 s
The before numbers come from the PR descriptions and tests; the after 28 ms was measured on 11-28 by running paste_into_busy_program locally (debug build; 28 ms direct and 29 ms through an attached pane). The 3000-key test only asserts a limit and prints no time, so only the limit is shown.

What both share: when one process serves every terminal, anything slow done under a lock stalls not one terminal but all of them. Since #371 the rule is "never write a PTY under a lock"; the handover must lock every terminal, so #480 first waits for input to drain, with the locks released meanwhile so output keeps flowing.

07 The host inherits whoever started it

On 11-16 an update was pushed to a computer from another Mac over SSH, with env -i … nohup fibo serve --takeover &. The handover itself worked, but every Claude opened in Fibo afterwards showed Not logged in. The environment had been wiped; the trouble was in what env -i cannot wipe:

InheritedWhat it decidesStarted inside SSHStarted with a shell's &Cleared by env -i?How Fibo checks
Environment variablesPATH, locale and so onSSH's setthat shell'syesnot checked
Login (audit) sessionwhether the login keychain is readable: Claude's sign-in, gh, git over https, code signing, plugin secretsa remote session, not readablefollows that shellnoaudit session flags
nice valuescheduling priority of every terminalalso +5 when the command uses &zsh adds 5 by default; a normal user cannot undo itno (measured 11-28: still 5)reads the nice value
Responsible process for privacy permissionswhose name system prompts show, whose permissions applysshdthat terminal appnothe system’s responsible-process call

Two things make it worse. Every terminal the host opens inherits these from the host, and a handover does not change them: terminals the new host took over stay in their original session. And a reopened window simply reuses a host of the same build (the fingerprint check in section 01), so quitting and reopening the app fixed nothing; at the time, the window's "restart host" button only appeared when the builds differed. The repair repeated the mistake once: restarting the host from a terminal with & brought in nice 5 and made that terminal app the responsible process.

#368: the host reads these three at start (the remote and graphic-session flags from getaudit_addr, getpriority, and responsibility_get_pid_responsible_for_pid), writes them to host.log, and hands them to the window in the greeting. The window only offers what a restart would fix (issues the host has and the window itself does not): the status bar shows the reason and "restart host", which goes through --takeover so no terminal ends; if the window itself was started from SSH, it says to reopen it from the Dock. The right way to update remotely went into docs/lessons.md: quit the old app by pid, then open the new bundle and let the window start the host. These three checks exist only on macOS so far; other platforms report nothing.

Without Fibo, keeping terminals alive past the window: tmux works the same way; sessions live in the tmux server and the terminal window is only a client.

tmux new -s work          # open a session, run the agent in it
# press Ctrl-b then d to detach; closing the terminal window is fine
tmux attach -t work       # reattach later

The tmux server is a long-running process too, so the table above applies. Measured 11-28: a server started from zsh with tmux new-session -d … & runs at nice 5; started directly, 0; with setopt NO_BG_NICE before the &, also 0. So start the first tmux server in the foreground, from a terminal in the local graphical session, not inside SSH or with &.

Limits: what we have not tested

Summary: three practices