diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..77bd808 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,99 @@ +# Pushing a tag like v0.1.0 builds a binary per platform, runs each on its own OS, and +# publishes them as a GitHub Release for install.sh and `t3tui upgrade`. Run it by hand +# to build and check the binaries without releasing them. +name: Release + +on: + push: + tags: ["v*"] + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.4 + - name: Check the tag matches package.json + if: startsWith(github.ref, 'refs/tags/') + run: | + version=$(jq -r .version package.json) + [ "$GITHUB_REF_NAME" = "v$version" ] || { echo "tag $GITHUB_REF_NAME doesn't match package.json version $version"; exit 1; } + # Every platform's OpenTUI package, so one machine can compile them all. + - run: bun install --frozen-lockfile --os='*' --cpu='*' + - run: bun run typecheck + - run: bun run lint + - run: bun test + - run: bun run compile linux-x64 linux-arm64 darwin-x64 darwin-arm64 + - name: Compress and checksum + working-directory: release + run: | + gzip -9 t3tui-* + sha256sum t3tui-*.gz > SHA256SUMS + - uses: actions/upload-artifact@v4 + with: + name: release + path: release/ + if-no-files-found: error + + smoke: + needs: build + strategy: + fail-fast: false + matrix: + include: + - { runner: ubuntu-24.04, target: linux-x64 } + - { runner: ubuntu-24.04-arm, target: linux-arm64 } + - { runner: macos-15-intel, target: darwin-x64 } + - { runner: macos-15, target: darwin-arm64 } + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/download-artifact@v4 + with: + name: release + - run: gunzip -c t3tui-${{ matrix.target }}.gz > t3tui && chmod +x t3tui && ./t3tui version + # The dashboard loads OpenTUI's native library. With no server it should keep retrying, not exit. + - name: Open the dashboard + env: + T3TUI_SERVER: http://127.0.0.1:9 + TERM: xterm-256color + run: | + # script gives it a terminal; the sleep holds script's input open so it doesn't hang up. + if [ "$RUNNER_OS" = macOS ]; then (sleep 60 | script -q out.txt ./t3tui >/dev/null) & else (sleep 60 | script -qec ./t3tui out.txt >/dev/null) & fi + sleep 5 + kill -0 $! || { cat out.txt; echo "t3tui exited early"; exit 1; } + grep -q "Waiting for threads" out.txt || { cat out.txt; echo "the dashboard didn't draw"; exit 1; } + kill $! + + release: + if: startsWith(github.ref, 'refs/tags/') + needs: smoke + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: release + path: release + - name: Publish + env: + GH_TOKEN: ${{ github.token }} + run: | + commit=$(git rev-parse HEAD:vendor/t3code) + t3code=$(git ls-remote --tags https://github.com/pingdotgg/t3code.git | awk -v c="$commit" '$1 == c { sub("refs/tags/", "", $2); print $2; exit }') + cat > notes.md <&2 + exit 1 +} + +case $(uname -s) in + Linux) os=linux ;; + Darwin) os=darwin ;; + *) fail "no release for $(uname -s); build from source instead: https://github.com/$repo#build-from-source" ;; +esac +case $(uname -m) in + x86_64 | amd64) arch=x64 ;; + aarch64 | arm64) arch=arm64 ;; + *) fail "no release for $(uname -m); build from source instead: https://github.com/$repo#build-from-source" ;; +esac +# A shell under Rosetta reports x86_64 on Apple silicon; the native binary is the better fit. +if [ "$os" = darwin ] && [ "$arch" = x64 ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null)" = 1 ]; then + arch=arm64 +fi +if [ "$os" = linux ] && ldd --version 2>&1 | grep -qi musl; then + fail "the releases need glibc, and this system uses musl; build from source instead: https://github.com/$repo#build-from-source" +fi + +file="t3tui-$os-$arch.gz" +if [ -n "${T3TUI_VERSION:-}" ]; then + base="https://github.com/$repo/releases/download/v${T3TUI_VERSION#v}" +else + base="https://github.com/$repo/releases/latest/download" +fi + +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +echo "Downloading $file..." +curl -fL --progress-bar -o "$tmp/$file" "$base/$file" || fail "couldn't download $base/$file" +curl -fsSL -o "$tmp/SHA256SUMS" "$base/SHA256SUMS" || fail "couldn't download $base/SHA256SUMS" + +expected=$(awk -v f="$file" '$2 == f { print $1 }' "$tmp/SHA256SUMS") +if command -v sha256sum >/dev/null 2>&1; then + actual=$(sha256sum "$tmp/$file" | awk '{ print $1 }') +else + actual=$(shasum -a 256 "$tmp/$file" | awk '{ print $1 }') +fi +[ -n "$expected" ] && [ "$expected" = "$actual" ] || fail "$file doesn't match its checksum; nothing was installed" + +gunzip "$tmp/$file" +chmod 755 "$tmp/t3tui-$os-$arch" +mkdir -p "$dir" +mv "$tmp/t3tui-$os-$arch" "$dir/t3tui" +echo "Installed $("$dir/t3tui" version) to $dir/t3tui" + +case ":$PATH:" in + *":$dir:"*) ;; + *) echo "$dir isn't on your PATH. Add it, e.g. in your shell's rc file: export PATH=\"$dir:\$PATH\"" ;; +esac diff --git a/package.json b/package.json index 9bc5b06..eee43db 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "scripts": { "dev": "bun run src/bin.ts", "build": "bun run scripts/build.ts", + "compile": "bun run scripts/compile.ts", "typecheck": "tsc --noEmit", "lint": "biome lint src test", "test": "bun test", diff --git a/scripts/compile.ts b/scripts/compile.ts new file mode 100644 index 0000000..2110039 --- /dev/null +++ b/scripts/compile.ts @@ -0,0 +1,32 @@ +// Compiles t3tui into one executable per platform, with Bun's runtime and OpenTUI's native +// library inside, so users need neither Bun nor a checkout. Usage: +// bun run compile [linux-x64 linux-arm64 darwin-x64 darwin-arm64] +// With no targets it builds for this machine. Binaries land in release/t3tui--. +// Cross-compiling needs every platform's OpenTUI package: bun install --os='*' --cpu='*' +import { $ } from "bun"; +import { existsSync } from "node:fs"; +import { mkdir } from "node:fs/promises"; +import { join } from "node:path"; + +const TARGETS = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64"]; +// Every native package OpenTUI might import. Each binary keeps only its own platform's. +const NATIVE = [...TARGETS, "linux-x64-musl", "linux-arm64-musl", "win32-x64", "win32-arm64"].map((t) => `@opentui/core-${t}`); + +const root = join(import.meta.dir, ".."); +const outdir = join(root, "release"); +const targets = process.argv.slice(2); +if (targets.length === 0) targets.push(`${process.platform}-${process.arch}`); +for (const target of targets) { + if (!TARGETS.includes(target)) throw new Error(`unknown target ${target}; expected one of ${TARGETS.join(", ")}`); + if (!existsSync(join(root, "node_modules/@opentui", `core-${target}`))) { + throw new Error(`@opentui/core-${target} isn't installed; run bun install --os='*' --cpu='*'`); + } +} + +await mkdir(outdir, { recursive: true }); +for (const target of targets) { + const outfile = join(outdir, `t3tui-${target}`); + const external = NATIVE.filter((name) => name !== `@opentui/core-${target}`).flatMap((name) => ["--external", name]); + // OpenTUI starts its syntax highlighter from parser.worker.js, so it's compiled in as a second entrypoint. + await $`bun build --compile --minify --target=bun-${target} ${external} ${join(root, "src/bin.ts")} ${join(root, "node_modules/@opentui/core/parser.worker.js")} --outfile ${outfile}`.cwd(root); +} diff --git a/src/bin.ts b/src/bin.ts index a08591b..9286504 100755 --- a/src/bin.ts +++ b/src/bin.ts @@ -3,6 +3,7 @@ import type { OrchestrationV2ShellSnapshot, ThreadId } from "@t3tools/contracts" import { migrateConfigDir } from "./client/auth.ts"; import { T3Session } from "./client/session.ts"; +import { isCompiled, upgrade, VERSION } from "./upgrade.ts"; import { findThread, lastActivity, relativeTime, rowTime, shortId, statusLabel, threadRows } from "./model/threads.ts"; const USAGE = `t3tui: a terminal client for T3 Code @@ -13,6 +14,8 @@ usage: t3tui list [--json] print threads and exit t3tui tmux [--watch] [--session ] mirror active threads into tmux windows (default session: t3tui) + t3tui upgrade replace this binary with the latest release + t3tui version t3tui help env: @@ -35,6 +38,13 @@ async function main(argv: string[]) { return list(rest.includes("--json")); case "tmux": return tmuxCommand(rest); + case "upgrade": + return upgrade(); + case "version": + case "--version": + case "-v": + console.log(`t3tui ${VERSION}`); + return; case "help": case "--help": case "-h": @@ -83,7 +93,8 @@ async function tmuxCommand(args: string[]) { const sessionFlag = args.indexOf("--session"); const name = sessionFlag >= 0 ? args[sessionFlag + 1] : "t3tui"; if (!name) return fail("usage: t3tui tmux [--watch] [--session ]"); - const options = { session: name, t3tui: [process.execPath, import.meta.path] }; + // A compiled binary is t3tui by itself; otherwise it's Bun running this file. + const options = { session: name, t3tui: isCompiled() ? [process.execPath] : [process.execPath, import.meta.path] }; const { session, snapshot } = await connectedSession(); const { opened } = await syncTmux(snapshot, options); console.log(`tmux session "${name}" is in sync (${opened} new window${opened === 1 ? "" : "s"}). Attach with: tmux attach -t ${name}`); diff --git a/src/upgrade.ts b/src/upgrade.ts new file mode 100644 index 0000000..bab1cf3 --- /dev/null +++ b/src/upgrade.ts @@ -0,0 +1,70 @@ +// `t3tui upgrade`: replaces a released binary with the latest release's. +import { chmod, rename, rm } from "node:fs/promises"; +import { realpathSync } from "node:fs"; + +import { version } from "../package.json" with { type: "json" }; + +export const VERSION = version; +const REPO = "callumalpass/t3tui"; + +/** A compiled binary runs its code from Bun's embedded filesystem. */ +export function isCompiled(): boolean { + return import.meta.path.startsWith("/$bunfs/"); +} + +/** The release asset for this machine, e.g. t3tui-linux-x64. */ +export function assetName(platform: string = process.platform, arch: string = process.arch): string { + return `t3tui-${platform}-${arch}`; +} + +/** Finds an asset's hash in a sha256sum listing. */ +export function checksumFor(sums: string, file: string): string | undefined { + for (const line of sums.split("\n")) { + const [hash, name] = line.trim().split(/\s+\*?/); + if (name === file) return hash; + } + return undefined; +} + +export async function upgrade(): Promise { + if (!isCompiled()) { + console.log("t3tui is running from source. Update it with: git pull --recurse-submodules && bun install"); + return; + } + const latest = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, { headers: { accept: "application/vnd.github+json" } }); + if (latest.status === 404) throw new Error("No t3tui release has been published yet."); + if (!latest.ok) throw new Error(`Couldn't check for a new release (GitHub answered ${latest.status}).`); + const tag = ((await latest.json()) as { tag_name: string }).tag_name; + if (tag === `v${VERSION}`) { + console.log(`t3tui ${VERSION} is the latest release.`); + return; + } + const file = `${assetName()}.gz`; + const base = `https://github.com/${REPO}/releases/download/${tag}`; + const [archive, sums] = await Promise.all([download(`${base}/${file}`), download(`${base}/SHA256SUMS`)]); + const expected = checksumFor(new TextDecoder().decode(sums), file); + if (!expected) throw new Error(`Release ${tag} has no ${file}.`); + const actual = new Bun.CryptoHasher("sha256").update(archive).digest("hex"); + if (actual !== expected) throw new Error(`The downloaded ${file} doesn't match its checksum; nothing was changed.`); + + // Renaming over the running binary is safe: the running process keeps the old file open. + const target = realpathSync(process.execPath); + const temporary = `${target}.upgrade-${process.pid}`; + try { + await Bun.write(temporary, Bun.gunzipSync(archive)); + await chmod(temporary, 0o755); + await rename(temporary, target); + } catch (error) { + await rm(temporary, { force: true }); + const code = (error as NodeJS.ErrnoException).code; + if (code === "EACCES" || code === "EPERM") throw new Error(`Can't write ${target}. Rerun with permission to replace it (e.g. sudo t3tui upgrade).`); + throw error; + } + console.log(`t3tui ${VERSION} → ${tag.replace(/^v/, "")}`); +} + +async function download(url: string): Promise> { + const response = await fetch(url); + if (!response.ok) throw new Error(`Couldn't download ${url} (${response.status}).`); + return new Uint8Array(await response.arrayBuffer()); +} diff --git a/test/upgrade.test.ts b/test/upgrade.test.ts new file mode 100644 index 0000000..2873cf2 --- /dev/null +++ b/test/upgrade.test.ts @@ -0,0 +1,18 @@ +import { expect, test } from "bun:test"; + +import { assetName, checksumFor, isCompiled } from "../src/upgrade.ts"; + +test("names the release asset for a platform", () => { + expect(assetName("darwin", "arm64")).toBe("t3tui-darwin-arm64"); +}); + +test("reads a hash from a sha256sum listing", () => { + const sums = "aaa t3tui-linux-x64.gz\nbbb *t3tui-darwin-arm64.gz\n"; + expect(checksumFor(sums, "t3tui-linux-x64.gz")).toBe("aaa"); + expect(checksumFor(sums, "t3tui-darwin-arm64.gz")).toBe("bbb"); + expect(checksumFor(sums, "t3tui-linux-arm64.gz")).toBeUndefined(); +}); + +test("knows it's running from source", () => { + expect(isCompiled()).toBe(false); +});