Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(tmux): bundle a static tmux in the macOS app as the last-resort fallback
enesaf9ad14c0806
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 83c209346..a183f8146 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -33,6 +33,21 @@ jobs:- name: Install dependenciesrun: npm ci+ # The bundled tmux (resources/bin/tmux → <app>/Contents/Resources/bin/tmux via the mac+ # extraResources entry). Without a tmux on the machine the app silently degrades to plain+ # shells — no persistence across restarts, no mobile attach, and a park/dispose kills the+ # agent CLI instead of detaching a client (issue #126). Shipping one removes that for the+ # tmux-less; the SYSTEM tmux still takes precedence at runtime (see findTmux).+ #+ # A SEPARATE STEP, before electron-builder, on purpose: a missing extraResources source is+ # only a WARNING to electron-builder, so a failure folded into the release command could+ # publish a DMG with no tmux in it and nobody would notice. Here a build failure fails the+ # job. Idempotent — a rerun with the binary already present is a no-op, so the retry loop in+ # the next step costs nothing. Needs only the Xcode command line tools (curl/cc/lipo/make);+ # no autoconf, no Homebrew, no npm deps.+ - name: Build bundled tmux (universal, static libevent)+ run: node scripts/build-tmux.mjs+- name: Build, sign & notarizerun: |printf '%s' "$APPLE_API_KEY_B64" | base64 --decode > "$RUNNER_TEMP/notary-key.p8"diff --git a/.gitignore b/.gitignoreindex bbedf1e36..2fae415ae 100644--- a/.gitignore+++ b/.gitignore@@ -9,6 +9,10 @@ dist/build/icon.png+# bundled tmux — a ~2MB universal binary, built by scripts/build-tmux.mjs (the source of truth)+# and copied into the app by electron-builder's mac extraResources. Never committed.+/resources/bin/+.playwright-mcp/# concurrent-session worktrees / local agent statediff --git a/README.md b/README.mdindex 87d7b9845..1ed0bb10a 100644--- a/README.md+++ b/README.md@@ -129,7 +129,9 @@ opencode / custom) · 📝 **Sticky note** (link to an agent as context) · 🗂- **Session continuity (tmux)** — terminals keep running across node remounts *and* fullapp restarts, including live processes; machine reboots restore scrollback and resume- agent sessions (`claude --resume`).+ agent sessions (`claude --resume`). The macOS app **ships its own tmux**, so this works+ with nothing installed; a tmux already on your system is always used in preference to it,+ and terminals opened before an upgrade stay as they were until you refresh the node.- **Talk to your terminal** — on-device Whisper dictation (⌘⇧D): speak, review, send.- **Agent superpowers** — **context links** so agent nodes read each other's transcriptson demand; Claude-only **branch a conversation** and **managed accounts** for several@@ -208,7 +210,9 @@ detects your platform. Everything is also listed at## 🛠 Build from sourceRequires Node.js 20+ on macOS or Linux (tmux recommended — it's what makes sessions-survive restarts).+survive restarts). A source checkout does **not** carry the bundled tmux: run+`node scripts/build-tmux.mjs` once on macOS to build it into `resources/bin/tmux` (the+release job does this automatically), or just install tmux yourself.```bashnpm install # deps + rebuilds node-pty against Electron's ABI (postinstall)diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdindex d86eb9f1a..26bd96182 100644--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@ -20,10 +20,24 @@ nodeterm's license.| @anthropic-ai/claude-agent-sdk | © Anthropic PBC, proprietary (see the package's LICENSE.md) || ws | MIT || tweetnacl | Unlicense (public domain) |+| tmux (macOS builds only) | ISC |+| libevent (macOS builds only, linked statically into tmux) | BSD-3-Clause |Full license texts are available in each package's directory under`node_modules/`, and from the projects' upstream repositories.+## Bundled tmux (macOS)++The macOS app ships a copy of [tmux](https://github.com/tmux/tmux) at+`nodeterm.app/Contents/Resources/bin/tmux`, statically linked against+[libevent](https://github.com/libevent/libevent). It is used **only** when the+machine has no tmux of its own — a tmux found anywhere on the system takes+precedence — so that terminals keep their sessions across restarts. Neither+project is modified; `scripts/build-tmux.mjs` builds the pinned upstream release+tarballs unchanged. Their license texts are in `resources/licenses/`+(`tmux-COPYING.txt`, `libevent-LICENSE.txt`), refreshed from the tarballs by that+same script.+## Trademarks"Claude" and "Claude Code" are trademarks of Anthropic, PBC. The Claude Codediff --git a/package.json b/package.jsonindex 544a8c094..5b733e672 100644--- a/package.json+++ b/package.json@@ -76,6 +76,16 @@"entitlements": "build/entitlements.mac.plist","entitlementsInherit": "build/entitlements.mac.plist","notarize": true,+ "extraResources": [+ {+ "from": "resources/bin/tmux",+ "to": "bin/tmux"+ },+ {+ "from": "resources/licenses",+ "to": "licenses"+ }+ ],"extendInfo": {"NSMicrophoneUsageDescription": "nodeterm uses the microphone so you can dictate into your terminals."},diff --git a/resources/licenses/libevent-LICENSE.txt b/resources/licenses/libevent-LICENSE.txtnew file mode 100644index 000000000..402ca5089--- /dev/null+++ b/resources/licenses/libevent-LICENSE.txt@@ -0,0 +1,99 @@+Libevent is available for use under the following license, commonly known+as the 3-clause (or "modified") BSD license:++==============================+Copyright (c) 2000-2007 Niels Provos <[email protected]>+Copyright (c) 2007-2012 Niels Provos and Nick Mathewson++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions+are met:+1. Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.+2. Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in the+ documentation and/or other materials provided with the distribution.+3. The name of the author may not be used to endorse or promote products+ derived from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.+IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+==============================++Portions of Libevent are based on works by others, also made available by+them under the three-clause BSD license above. The copyright notices are+available in the corresponding source files; the license is as above. Here's+a list:++log.c:+ Copyright (c) 2000 Dug Song <[email protected]>+ Copyright (c) 1993 The Regents of the University of California.++strlcpy.c:+ Copyright (c) 1998 Todd C. Miller <[email protected]>++win32select.c:+ Copyright (c) 2003 Michael A. Davis <[email protected]>++evport.c:+ Copyright (c) 2007 Sun Microsystems++ht-internal.h:+ Copyright (c) 2002 Christopher Clark++minheap-internal.h:+ Copyright (c) 2006 Maxim Yegorushkin <[email protected]>++==============================++The arc4module is available under the following, sometimes called the+"OpenBSD" license:++ Copyright (c) 1996, David Mazieres <[email protected]>+ Copyright (c) 2008, Damien Miller <[email protected]>++ Permission to use, copy, modify, and distribute this software for any+ purpose with or without fee is hereby granted, provided that the above+ copyright notice and this permission notice appear in all copies.++ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.++==============================++The Windows timer code is based on code from libutp, which is+distributed under this license, sometimes called the "MIT" license.+++Copyright (c) 2010 BitTorrent, Inc.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.diff --git a/resources/licenses/tmux-COPYING.txt b/resources/licenses/tmux-COPYING.txtnew file mode 100644index 000000000..8c3c99511--- /dev/null+++ b/resources/licenses/tmux-COPYING.txt@@ -0,0 +1,13 @@+Copyright (c) Various Authors++Permission to use, copy, modify, and distribute this software for any+purpose with or without fee is hereby granted, provided that the above+copyright notice and this permission notice appear in all copies.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING+OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.diff --git a/scripts/build-tmux.mjs b/scripts/build-tmux.mjsnew file mode 100644index 000000000..cc545207f--- /dev/null+++ b/scripts/build-tmux.mjs@@ -0,0 +1,340 @@+#!/usr/bin/env node+/**+ * Build the BUNDLED tmux that ships inside the macOS app (`<app>/Contents/Resources/bin/tmux`).+ *+ * WHY: without tmux on the machine the app silently degrades to a plain shell — terminals don't+ * survive a restart, the mobile companion can't attach, and a park/offscreen dispose kills the+ * shell AND whatever agent CLI is running in it instead of merely detaching a client (issue #126).+ * A tmux-less user could only fix that by installing tmux themselves. Shipping one removes the+ * whole failure class from the default install.+ *+ * PRECEDENCE (see src/core/tmux-hint.ts `bundledTmuxPath` and pty-manager's `findTmux`): the+ * SYSTEM tmux still wins; this binary is the LAST candidate. A tmux client must be able to talk to+ * the tmux SERVER already running on the user's machine, and pairing a newer bundled client with an+ * older running server fails outright ("server version is too old"). System-first means existing+ * tmux users see literally no change; the bundle only rescues the population that had none.+ *+ * The OUTPUT (resources/bin/tmux) is gitignored — this script is the source of truth. The release+ * job runs it before electron-builder, which copies it in via `extraResources`.+ *+ * Shape of the build: static libevent (so the app never depends on a Homebrew dylib that isn't+ * there), ncurses taken dynamically from macOS itself (/usr/lib/libncurses.dylib ships with the+ * OS — vendoring terminfo would be a second, larger problem), one `lipo` pass to make the two+ * arch builds universal. No npm dependencies on purpose: node stdlib + the system curl/cc/lipo,+ * so the release runner needs nothing installed beyond the Xcode command line tools.+ *+ * Usage: node scripts/build-tmux.mjs [--force] [--verbose]+ */++import { execFileSync } from 'node:child_process'+import crypto from 'node:crypto'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++// ── Pins ────────────────────────────────────────────────────────────────────────────────────────+// Exact upstream releases, with the sha256 of each official tarball. Pinned rather than "latest"+// so a release build is reproducible and a compromised/rewritten upstream asset fails the build+// instead of shipping. Bump deliberately: change the version AND the hash together (recompute with+// `shasum -a 256 <tarball>` from the GitHub release page).+const TMUX_VERSION = '3.7b'+const TMUX_SHA256 = '87f2e99e3b685973f2ca002ffd6ed7e51a5744f7009daae5a15670b6d532db96'+const TMUX_URL = `https://github.com/tmux/tmux/releases/download/${TMUX_VERSION}/tmux-${TMUX_VERSION}.tar.gz`++// libevent 2.1.13-stable is the current 2.1.x; it carries the 2026-07 security fixes (evhttp+// request smuggling, evtag OOB read, evbuffer dangling pointer). tmux only uses libevent_core,+// but the pin still tracks the fixed release.+const LIBEVENT_VERSION = '2.1.13-stable'+const LIBEVENT_SHA256 = 'f7e9383b8c0baa81b687e5b5eecc01beefaf1b19b64151d95ed61647fe7a315c'+const LIBEVENT_URL = `https://github.com/libevent/libevent/releases/download/release-${LIBEVENT_VERSION}/libevent-${LIBEVENT_VERSION}.tar.gz`++/** Slices in the universal output, with the deployment target each is built against.+ * arm64 cannot go below 11.0 (Apple Silicon did not exist before it); 10.15 keeps the Intel+ * slice usable on every macOS the Intel app build still supports. */+const ARCHS = [+ { arch: 'arm64', triple: 'aarch64-apple-darwin', minOs: '11.0' },+ { arch: 'x86_64', triple: 'x86_64-apple-darwin', minOs: '10.15' }+]++const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')+const outDir = path.join(repoRoot, 'resources', 'bin')+const outFile = path.join(outDir, 'tmux')+const licenseDir = path.join(repoRoot, 'resources', 'licenses')+/** Written next to the binary; its exact content is the "is the output already the pinned build?"+ * test, so bumping a version above automatically invalidates a stale binary. */+const markerFile = path.join(outDir, '.tmux-build-version')+const MARKER = `tmux-${TMUX_VERSION} libevent-${LIBEVENT_VERSION} universal(${ARCHS.map((a) => a.arch).join('+')})\n`++const force = process.argv.includes('--force')+const verbose = process.argv.includes('--verbose')++function log(msg) {+ console.log(`[build-tmux] ${msg}`)+}++/** Run a command, failing loudly. Output is swallowed unless --verbose (a configure+make pair is+ * thousands of lines of noise); on failure the tail of the captured output is printed, which is+ * the part that says why. */+function run(cmd, args, opts = {}) {+ try {+ return execFileSync(cmd, args, {+ stdio: verbose ? 'inherit' : 'pipe',+ encoding: 'utf8',+ ...opts+ })+ } catch (err) {+ const out = `${err.stdout ?? ''}${err.stderr ?? ''}`+ if (out) console.error(out.split('\n').slice(-40).join('\n'))+ throw new Error(`${cmd} ${args.join(' ')} failed (exit ${err.status})`)+ }+}++/** Capture stdout of a command that is expected to succeed (verification steps). */+function capture(cmd, args, opts = {}) {+ return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], ...opts })+}++function download(url, dest, expectedSha256) {+ log(`downloading ${path.basename(dest)}`)+ // --fail so an HTML error page never lands on disk as a "tarball"; -L follows the GitHub+ // release redirect to the asset CDN.+ run('curl', ['--fail', '--location', '--silent', '--show-error', '--output', dest, url])+ const actual = crypto.createHash('sha256').update(fs.readFileSync(dest)).digest('hex')+ if (actual !== expectedSha256) {+ throw new Error(+ `sha256 mismatch for ${url}\n expected ${expectedSha256}\n actual ${actual}\n` ++ 'Refusing to build. Either the pin is stale (bump the constant deliberately) or the ' ++ 'asset changed under us.'+ )+ }+ log(`verified sha256 ${actual.slice(0, 16)}… ok`)+}++/**+ * Build libevent (static only) and then tmux against it, for ONE arch. Returns the path of the+ * single-arch tmux binary.+ *+ * The cross slice (whichever arch is not this machine's) is configured with `--host`, which puts+ * autoconf in cross-compile mode so it never tries to RUN a test binary — the release runner is+ * an Apple Silicon Mac that may not have Rosetta installed. tmux's three AC_RUN_IFELSE probes+ * (strtonum / reallocarray / recallocarray) all fall back to tmux's own compat implementations+ * when cross-compiling, which is the correct, portable answer anyway.+ */+function buildArch({ arch, triple, minOs }, work, tarballs) {+ // A FRESH extraction per arch, never a copy of one tree: `tar` restores the archive's mtimes,+ // and automake's maintainer rules compare configure.ac against configure. A recursive copy+ // rewrites those timestamps and the build then tries to re-run autoconf — which is not+ // installed on this machine or (deliberately) required on the release runner.+ const stage = path.join(work, `build-${arch}`)+ fs.mkdirSync(stage, { recursive: true })+ run('tar', ['-xzf', tarballs.libevent, '-C', stage])+ run('tar', ['-xzf', tarballs.tmux, '-C', stage])+ const evDir = path.join(stage, `libevent-${LIBEVENT_VERSION}`)+ const tmuxDir = path.join(stage, `tmux-${TMUX_VERSION}`)++ const prefix = path.join(work, `prefix-${arch}`)+ const flags = `-arch ${arch} -mmacosx-version-min=${minOs}`+ const cross = arch !== (process.arch === 'arm64' ? 'arm64' : 'x86_64')+ const env = {+ ...process.env,+ CFLAGS: `${flags} -O2`,+ LDFLAGS: flags,+ // Hard off. If the runner happens to have pkg-config + a Homebrew libevent/ncurses installed,+ // tmux's configure would prefer those .pc files and link the bundled binary against+ // /opt/homebrew dylibs that do not exist on a user's machine. Without pkg-config configure+ // falls through to AC_SEARCH_LIBS, which sees only what our LDFLAGS point at (our static+ // libevent) plus the system libraries. The `otool -L` assertion at the end is the backstop.+ PKG_CONFIG: '/usr/bin/false',+ MACOSX_DEPLOYMENT_TARGET: minOs+ }+ const hostArg = cross ? [`--host=${triple}`] : []++ log(`building libevent (${arch})…`)+ run(+ './configure',+ [+ `--prefix=${prefix}`,+ '--disable-shared',+ '--enable-static',+ '--with-pic',+ // tmux needs libevent_core only; everything else is dead weight in the binary and extra+ // ways for the build to need a dependency the runner doesn't have (openssl, mbedtls).+ '--disable-openssl',+ '--disable-mbedtls',+ '--disable-samples',+ '--disable-libevent-regress',+ '--disable-debug-mode',+ ...hostArg+ ],+ { cwd: evDir, env }+ )+ run('make', [`-j${os.cpus().length}`], { cwd: evDir, env })+ run('make', ['install'], { cwd: evDir, env })++ log(`building tmux (${arch})…`)+ // Point tmux at OUR libevent and nothing else: only the static .a lives in that prefix, so the+ // link is static with no -static flag and no chance of picking up a system libevent.dylib.+ const tmuxEnv = {+ ...env,+ CPPFLAGS: `-I${path.join(prefix, 'include')}`,+ LDFLAGS: `${flags} -L${path.join(prefix, 'lib')}`+ }+ run(+ './configure',+ [+ `--prefix=${prefix}`,+ // Deliberately OFF — and it must be stated explicitly, because tmux 3.7's configure REFUSES+ // to guess on macOS. Upstream recommends --enable-utf8proc there ("macOS library support for+ // Unicode is very poor, particularly for complex codepoints like emojis"), and the cost of+ // saying no is that wide-character widths come from macOS's own wcwidth: emoji-heavy TUIs+ // (the agent CLIs) can mis-wrap. The trade taken here is minimalism — utf8proc would be a+ // third vendored library to download, pin, cross-build and license — against a rendering+ // nicety, for a binary that only ever runs when the machine has NO tmux at all. Revisit by+ // flipping this to --enable-utf8proc plus a static utf8proc slice per arch.+ '--disable-utf8proc',+ ...hostArg+ ],+ { cwd: tmuxDir, env: tmuxEnv }+ )+ run('make', [`-j${os.cpus().length}`], { cwd: tmuxDir, env: tmuxEnv })++ const bin = path.join(work, `tmux-bin-${arch}`)+ fs.copyFileSync(path.join(tmuxDir, 'tmux'), bin)+ return bin+}++/** Copy the upstream license texts next to the binary's notices. tmux is ISC, libevent BSD-3 —+ * both require the notice to travel with a redistributed binary, and these are tracked in git+ * (unlike resources/bin) so the repo carries them even when nobody has run this script. */+function writeLicenses(sources) {+ fs.mkdirSync(licenseDir, { recursive: true })+ fs.copyFileSync(path.join(sources.tmux, 'COPYING'), path.join(licenseDir, 'tmux-COPYING.txt'))+ fs.copyFileSync(+ path.join(sources.libevent, 'LICENSE'),+ path.join(licenseDir, 'libevent-LICENSE.txt')+ )+ log(`licenses refreshed in ${path.relative(repoRoot, licenseDir)}/`)+}++/** Every dylib the binary loads must come from macOS itself; anything under /opt/homebrew or+ * /usr/local would be missing on a user's machine and the bundled tmux would fail to exec —+ * the exact silent-degradation this whole feature removes. */+function assertNoForeignDylibs(file) {+ // On a universal binary otool prints one "<file> (architecture x86_64):" header per slice at+ // column 0 and each dependency INDENTED — so match the indented lines only, or the file's own+ // path reads as a dependency.+ const deps = [+ ...new Set(+ capture('otool', ['-L', file])+ .split('\n')+ .filter((l) => /^\s+\S+\s+\(compatibility version/.test(l))+ .map((l) => l.trim().split(' ')[0])+ )+ ]+ if (!deps.length) throw new Error(`otool -L reported no dependencies for ${file}`)+ const foreign = deps.filter((d) => !d.startsWith('/usr/lib/') && !d.startsWith('/System/'))+ if (foreign.length) {+ throw new Error(+ `bundled tmux links non-system libraries: ${foreign.join(', ')}\n` ++ 'Those will not exist on a user machine. Check that PKG_CONFIG was disabled and that ' ++ 'libevent built static.'+ )+ }+ log(`dylib deps are all system: ${deps.join(', ')}`)+}++/** End-to-end proof that the binary actually runs a server: start one on a THROWAWAY socket,+ * list it, kill it. Never touches the app's own `node-terminal` socket. */+function smokeTest(file) {+ const sock = `nodeterm-bundle-test-${process.pid}`+ const tmux = (...args) =>+ capture(file, ['-L', sock, '-f', '/dev/null', ...args], { env: { ...process.env, TMUX: '' } })+ try {+ tmux('new-session', '-d', '-s', 'smoke')+ const sessions = tmux('list-sessions')+ if (!/^smoke:/m.test(sessions)) throw new Error(`unexpected list-sessions output: ${sessions}`)+ log(`smoke: server started on -L ${sock}, list-sessions → ${sessions.trim()}`)+ } finally {+ try {+ capture(file, ['-L', sock, 'kill-server'])+ } catch {+ // no server to kill (the start itself failed) — the real error is already propagating+ }+ }+}++function main() {+ if (process.platform !== 'darwin') {+ // The bundled binary is a macOS artifact by design: the Linux packages and the Server Edition+ // install tmux from the distro, where it is one `apt-get install` away and already expected.+ log(`nothing to do on ${process.platform} — the bundled tmux is a macOS-only artifact`)+ return+ }++ if (!force && fs.existsSync(outFile) && readMarker() === MARKER) {+ log(`up to date: ${path.relative(repoRoot, outFile)} is already ${MARKER.trim()} (--force to rebuild)`)+ return+ }++ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-tmux-'))+ try {+ const tmuxTar = path.join(work, `tmux-${TMUX_VERSION}.tar.gz`)+ const evTar = path.join(work, `libevent-${LIBEVENT_VERSION}.tar.gz`)+ download(TMUX_URL, tmuxTar, TMUX_SHA256)+ download(LIBEVENT_URL, evTar, LIBEVENT_SHA256)+ const tarballs = { tmux: tmuxTar, libevent: evTar }++ // One extra extraction, purely to lift the two license texts out of the pinned tarballs.+ const licenseSrc = path.join(work, 'licenses-src')+ fs.mkdirSync(licenseSrc, { recursive: true })+ run('tar', ['-xzf', tmuxTar, '-C', licenseSrc, `tmux-${TMUX_VERSION}/COPYING`])+ run('tar', ['-xzf', evTar, '-C', licenseSrc, `libevent-${LIBEVENT_VERSION}/LICENSE`])+ writeLicenses({+ tmux: path.join(licenseSrc, `tmux-${TMUX_VERSION}`),+ libevent: path.join(licenseSrc, `libevent-${LIBEVENT_VERSION}`)+ })++ const slices = ARCHS.map((a) => buildArch(a, work, tarballs))++ fs.mkdirSync(outDir, { recursive: true })+ // Write the marker only after the binary is in place and verified, so an interrupted run+ // leaves a "not built" state rather than a stale binary that claims to be current.+ fs.rmSync(markerFile, { force: true })+ run('lipo', ['-create', '-output', outFile, ...slices])+ run('strip', ['-S', '-x', outFile])+ fs.chmodSync(outFile, 0o755)++ log(`file: ${capture('file', [outFile]).trim()}`)+ log(`lipo: ${capture('lipo', ['-info', outFile]).trim()}`)+ const missing = ARCHS.map((a) => a.arch).filter(+ (a) => !capture('lipo', ['-info', outFile]).includes(a)+ )+ if (missing.length) throw new Error(`universal binary is missing slices: ${missing.join(', ')}`)+ assertNoForeignDylibs(outFile)++ // -V runs the NATIVE slice; the cross slice is verified structurally (lipo/otool) because the+ // runner may have no Rosetta to execute it with.+ const version = capture(outFile, ['-V']).trim()+ if (version !== `tmux ${TMUX_VERSION}`) {+ throw new Error(`built binary reports "${version}", expected "tmux ${TMUX_VERSION}"`)+ }+ log(`version: ${version}`)+ smokeTest(outFile)++ fs.writeFileSync(markerFile, MARKER)+ log(`done → ${path.relative(repoRoot, outFile)}`)+ } finally {+ fs.rmSync(work, { recursive: true, force: true })+ }+}++function readMarker() {+ try {+ return fs.readFileSync(markerFile, 'utf8')+ } catch {+ return null+ }+}++main()diff --git a/src/core/platform.ts b/src/core/platform.tsindex 35824b1c9..1268d5ac9 100644--- a/src/core/platform.ts+++ b/src/core/platform.ts@@ -8,6 +8,11 @@ export interface CorePlatform {readonly userDataDir: stringreadonly appVersion: stringreadonly isPackaged: boolean+ /** Electron's `process.resourcesPath` — `<app>/Contents/Resources` in a packaged build, where+ * extraResources (today: the bundled tmux, see tmux-hint.ts `bundledTmuxPath`) land. OPTIONAL+ * because it is an Electron notion: the Server Edition has no such directory and simply omits+ * it, which is also how src/core stays Electron-free (no-electron.test.ts). */+ readonly resourcesPath?: string/** Register a request/response RPC handler (Electron: ipcMain.handle, event stripped). */handle(channel: string, fn: (...args: any[]) => unknown): void/** Register a fire-and-forget handler (Electron: ipcMain.on, event stripped). */diff --git a/src/core/pty-bundled-tmux.test.ts b/src/core/pty-bundled-tmux.test.tsnew file mode 100644index 000000000..cc3765d7c--- /dev/null+++ b/src/core/pty-bundled-tmux.test.ts@@ -0,0 +1,86 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import fs from 'fs'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'++/**+ * THE BUNDLED tmux, AND WHY IT IS LAST.+ *+ * The macOS app ships its own static tmux (scripts/build-tmux.mjs → resources/bin/tmux →+ * `<app>/Contents/Resources/bin/tmux`) so a machine with no tmux is no longer dropped into the+ * silent plain-shell fallback (issue #126). But it is appended AFTER every system candidate, and+ * that order is the whole design: a tmux client attaches to a tmux SERVER that outlives the app,+ * started by whatever tmux the user installed. Choosing our binary over theirs could hand a new+ * client to an old running server ("server version is too old"). System-first ⇒ existing tmux+ * users see zero change; the bundle only rescues the tmux-less.+ */++const probe = vi.hoisted(() => ({ shellPath: undefined as string | undefined }))+vi.mock('./exec-path', () => ({+ resolveShellPath: () => Promise.resolve(probe.shellPath ?? null),+ shellPathNow: () => probe.shellPath,+ findInPathString: (bin: string, pathStr: string | null | undefined) =>+ pathStr === '/opt/weird/bin' ? `/opt/weird/bin/${bin}` : null,+ findExecutableSync: () => null+}))+vi.mock('node-pty', () => ({ spawn: () => ({ onData: () => {}, onExit: () => {}, kill: () => {} }) }))++const RESOURCES = '/Applications/nodeterm.app/Contents/Resources'+const BUNDLED = `${RESOURCES}/bin/tmux`++/** A manager booted with `existsSync` answering true for exactly `present`. */+async function bootWith(present: string[], resourcesPath?: string) {+ initPlatform(fakePlatform(resourcesPath ? { resourcesPath } : {}))+ vi.spyOn(fs, 'existsSync').mockImplementation((p) => present.includes(String(p)))+ // ensureTmux writes the generated tmux.conf into userDataDir; the fake's dir does not exist.+ vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})+ const { PtyManager } = await import('./pty-manager')+ const mgr = new PtyManager()+ mgr.init(() => ({ tmuxEnabled: true, tmuxScrollback: 10_000 }) as never)+ return mgr+}++describe('bundled tmux in findTmux', () => {+ beforeEach(() => {+ probe.shellPath = undefined+ })+ afterEach(() => {+ vi.restoreAllMocks()+ resetPlatformForTests()+ })++ it('the system tmux still wins when both exist', async () => {+ const mgr = await bootWith(['/opt/homebrew/bin/tmux', BUNDLED], RESOURCES)+ expect(mgr.getTmuxBin()).toBe('/opt/homebrew/bin/tmux')+ })++ it('a tmux only the login-shell PATH knows about also outranks the bundled one', async () => {+ probe.shellPath = '/opt/weird/bin'+ const mgr = await bootWith([BUNDLED], RESOURCES)+ expect(mgr.getTmuxBin()).toBe('/opt/weird/bin/tmux')+ })++ it('falls back to the bundled binary when the machine has no tmux at all', async () => {+ const mgr = await bootWith([BUNDLED], RESOURCES)+ expect(mgr.getTmuxBin()).toBe(BUNDLED)+ })++ it('makes the tmux-missing banner unreachable on a packaged macOS build', async () => {+ // The banner is driven by tmuxStatus().available, which is just "did findTmux resolve" — so+ // shipping the binary retires the banner for packaged macOS without touching its copy.+ const mgr = await bootWith([BUNDLED], RESOURCES)+ expect(mgr.tmuxStatus().available).toBe(true)+ })++ it('keeps the banner for the cases that still have no tmux (dev without the artifact, Linux)', async () => {+ // No packaged Resources dir, and no `resources/bin/tmux` under the repo root either.+ const mgr = await bootWith([])+ expect(mgr.getTmuxBin()).toBeNull()+ expect(mgr.tmuxStatus().available).toBe(false)+ })++ it('dev run: picks up the artifact scripts/build-tmux.mjs left under the repo root', async () => {+ const mgr = await bootWith([`${process.cwd()}/resources/bin/tmux`])+ expect(mgr.getTmuxBin()).toBe(`${process.cwd()}/resources/bin/tmux`)+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 5ab3cb56d..04bcf5966 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -16,7 +16,7 @@ import {type Settings,type TmuxStatus} from '../shared/types'-import { findCommand, findFixedTmux, tmuxInstall } from './tmux-hint'+import { bundledTmuxPath, findCommand, findFixedTmux, tmuxInstall } from './tmux-hint'import { hookServer, PERM_WAIT_SECS_DEFAULT } from './agents/hook-server'import {probeSaysAbsent,@@ -161,8 +161,15 @@ bind -T copy-mode-vi TripleClick1Pane send-keys -X select-line \\; send-keys -X* fallback here was a SYNC login-shell `command -v tmux` — sourcing the profile (nvm/conda:* 100-800ms) on the main thread, re-triggered every 3s by the tmux-missing banner's install poll,* freezing all windows and IPC each time. Now it walks a fixed candidate list- * (`tmuxCandidatePaths` — Homebrew, MacPorts, Nix, Linuxbrew, the distro paths) and then the- * cached login-shell PATH.+ * (`tmuxCandidatePaths` — Homebrew, MacPorts, Nix, Linuxbrew, the distro paths), then the+ * cached login-shell PATH, and only THEN the tmux the macOS app bundles.+ *+ * THE BUNDLED COPY IS DELIBERATELY LAST. A tmux client attaches to a tmux SERVER that outlives the+ * app and was started by whatever tmux the user has installed; preferring our binary could pair a+ * new client with their old running server, which upstream refuses ("server version is too old").+ * System-first means every user who already has tmux sees zero change, and the bundle only rescues+ * the population that had none — where there is no server to be incompatible with. See+ * `bundledTmuxPath` in tmux-hint.ts and scripts/build-tmux.mjs.** BEFORE THAT ASYNC PATH PROBE SETTLES, a tmux living ONLY on the user's shell PATH is still* invisible, and a session spawned in that window silently becomes a plain shell with no@@ -173,7 +180,7 @@ bind -T copy-mode-vi TripleClick1Pane send-keys -X select-line \\; send-keys -X* process into a tmux pane); its recovery is the node's own Refresh/respawn, which re-creates it* through the now-resolved tmux.*/-function findTmux(): string | null {+function findTmux(resourcesPath?: string): string | null {// BOTH lookups inside the guard: `os.homedir()` throws the same SystemError as `userInfo()` when// there is no passwd entry and no $HOME (some containers), and a thrown probe here would take// out tmux discovery entirely — degrading a machine that HAS tmux to the plain-shell fallback,@@ -189,7 +196,16 @@ function findTmux(): string | null {}const fixed = findFixedTmux((p) => fs.existsSync(p), home, user)if (fixed) return fixed- return findInPathString('tmux', shellPathNow() ?? process.env.PATH)+ const onPath = findInPathString('tmux', shellPathNow() ?? process.env.PATH)+ if (onPath) return onPath+ // Last: the binary the macOS app ships. `process.cwd()` is the repo root under+ // `electron-vite dev`, which is where scripts/build-tmux.mjs writes its artifact; in a packaged+ // app it is meaningless and simply misses.+ return bundledTmuxPath({+ resourcesPath,+ repoRoot: process.cwd(),+ exists: (p) => fs.existsSync(p)+ })}/** Resolve an absolute ssh path (GUI apps don't inherit the shell PATH). */@@ -1150,7 +1166,10 @@ export class PtyManager {* No-op while tmux is already resolved or before init() provided settings. */ensureTmux(): void {if (this.tmuxPath || !this.getSettings) return- const found = findTmux()+ // platform() is safe past the guard above: getSettings is only set by init(), which the shell+ // calls after initPlatform(). resourcesPath is undefined on the Server Edition, so the bundled+ // candidate is simply absent there (Linux keeps system-tmux-only).+ const found = findTmux(platform().resourcesPath)if (!found) returnthis.confPath = path.join(platform().userDataDir, 'tmux.conf')try {diff --git a/src/core/tmux-hint.test.ts b/src/core/tmux-hint.test.tsindex 5ad018160..01adeb0e9 100644--- a/src/core/tmux-hint.test.ts+++ b/src/core/tmux-hint.test.ts@@ -1,5 +1,11 @@import { describe, it, expect } from 'vitest'-import { findCommand, findFixedTmux, tmuxCandidatePaths, tmuxInstall } from './tmux-hint'+import {+ bundledTmuxPath,+ findCommand,+ findFixedTmux,+ tmuxCandidatePaths,+ tmuxInstall+} from './tmux-hint'describe('tmuxInstall', () => {it('darwin with brew: one-click brew install', () => {@@ -94,3 +100,51 @@ describe('tmuxCandidatePaths / findFixedTmux', () => {expect(findFixedTmux(exists, '/Users/dev', 'dev')).toBe('/usr/bin/tmux')})})++describe('bundledTmuxPath', () => {+ const PACKAGED = '/Applications/nodeterm.app/Contents/Resources'++ it('packaged: resolves <Resources>/bin/tmux when the shipped binary is there', () => {+ expect(+ bundledTmuxPath({+ resourcesPath: PACKAGED,+ repoRoot: '/Users/dev/nodeterm',+ exists: (p) => p === `${PACKAGED}/bin/tmux`+ })+ ).toBe(`${PACKAGED}/bin/tmux`)+ })++ it('dev: falls back to the repo artifact when the Electron Resources dir has no tmux', () => {+ // In `electron-vite dev` process.resourcesPath points INSIDE node_modules/electron — it never+ // holds our binary, so a dev run must find the one scripts/build-tmux.mjs produced instead.+ const seen: string[] = []+ const found = bundledTmuxPath({+ resourcesPath: '/repo/node_modules/electron/dist/Electron.app/Contents/Resources',+ repoRoot: '/repo',+ exists: (p) => (seen.push(p), p === '/repo/resources/bin/tmux')+ })+ expect(found).toBe('/repo/resources/bin/tmux')+ // Packaged location is still probed FIRST — the dev path is the fallback, not the other way.+ expect(seen[0]).toBe(+ '/repo/node_modules/electron/dist/Electron.app/Contents/Resources/bin/tmux'+ )+ })++ it('neither present: null — a checkout that never ran the build script behaves exactly as before', () => {+ expect(+ bundledTmuxPath({ resourcesPath: PACKAGED, repoRoot: '/repo', exists: () => false })+ ).toBeNull()+ // Server Edition / any shell with neither a Resources dir nor a repo root: nothing to offer.+ expect(bundledTmuxPath({ exists: () => true })).toBeNull()+ })++ it('treats a throwing exists as "not here" rather than failing the whole probe', () => {+ const exists = (p: string): boolean => {+ if (p.startsWith(PACKAGED)) throw new Error('EPERM')+ return p === '/repo/resources/bin/tmux'+ }+ expect(bundledTmuxPath({ resourcesPath: PACKAGED, repoRoot: '/repo', exists })).toBe(+ '/repo/resources/bin/tmux'+ )+ })+})diff --git a/src/core/tmux-hint.ts b/src/core/tmux-hint.tsindex 014535458..a3b6a31e8 100644--- a/src/core/tmux-hint.ts+++ b/src/core/tmux-hint.ts@@ -107,6 +107,47 @@ export function findFixedTmux(return null}+/**+ * The tmux nodeterm SHIPS (macOS only — `scripts/build-tmux.mjs` builds a static universal binary+ * into `resources/bin/tmux`, and electron-builder copies it to `<app>/Contents/Resources/bin/tmux`+ * via extraResources). Returns the packaged copy if it is there, else the dev artifact under the+ * repo root, else null — a checkout that never ran the build script behaves exactly as before.+ *+ * WHY IT IS THE LAST RESORT and not the first (`findTmux` appends it after every system path):+ * a tmux CLIENT talks to a tmux SERVER that may already be running on this machine — started by+ * whatever tmux the user has installed, and outliving the app by design. Preferring our own binary+ * would pair a client we chose with a server we did not, which upstream rejects outright when the+ * protocol differs ("server version is too old"). System-first means every user who already has+ * tmux sees literally zero change in behavior; the bundled copy exists solely for the population+ * that has none, where there is no server to be incompatible with.+ *+ * `resourcesPath` is Electron's `process.resourcesPath`, injected through CorePlatform — src/core+ * must stay Electron-free (see no-electron.test.ts), and the Server Edition supplies neither it nor+ * a repo root, so this correctly returns null there (Linux keeps system-tmux-only).+ *+ * `exists` is injected (fs.existsSync in production) so the walk stays pure; a throwing `exists`+ * reads as "not here", never as a failed probe.+ */+export function bundledTmuxPath(opts: {+ /** Electron's process.resourcesPath — `<app>/Contents/Resources` in a packaged build. */+ resourcesPath?: string | null+ /** Repo root for a dev run (process.cwd() under `electron-vite dev`). */+ repoRoot?: string | null+ exists: (path: string) => boolean+}): string | null {+ const candidates: string[] = []+ if (opts.resourcesPath) candidates.push(`${opts.resourcesPath}/bin/tmux`)+ if (opts.repoRoot) candidates.push(`${opts.repoRoot}/resources/bin/tmux`)+ for (const candidate of candidates) {+ try {+ if (opts.exists(candidate)) return candidate+ } catch {+ // unreadable — keep looking+ }+ }+ return null+}+/** Is `name` on the process PATH or in the common bin dirs? `exists` is injected (fs.existsSync* in production) so the lookup stays pure and testable. */export function findCommand(diff --git a/src/main/platform-electron.ts b/src/main/platform-electron.tsindex b511cab97..38aca57e7 100644--- a/src/main/platform-electron.ts+++ b/src/main/platform-electron.ts@@ -68,6 +68,11 @@ export function electronPlatform(): ElectronPlatform {get isPackaged() {return app.isPackaged},+ // `<app>/Contents/Resources` when packaged; node_modules/electron/…/Resources in dev (which is+ // why bundledTmuxPath falls back to the repo's own resources/bin).+ get resourcesPath() {+ return process.resourcesPath+ },// The ipcMain half of each registration is UNCHANGED — the local window's call is bit-identical// to what it was before the table existed (same event-stripping, same sender id).handle: (ch, fn) => {