Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

perf(desktop): speed up desktop release packaging and CI workflow

Dongdong Chen2250edda3870
diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml
index a0ddd870..04a1108d 100644
--- a/.github/workflows/desktop-release.yml
+++ b/.github/workflows/desktop-release.yml
@@ -81,10 +81,16 @@ jobs:
include:
- target: darwin-arm64
installer: macos-arm64.dmg
+ docker_image: dmgtool
+ docker_file: apps/desktop/packaging/mac/Dockerfile
- target: linux-x64
installer: linux-x64.tar.gz
+ docker_image: ""
+ docker_file: ""
- target: win32-x64
installer: windows-x64-setup.exe
+ docker_image: wintool
+ docker_file: apps/desktop/packaging/win/Dockerfile
env:
DESKTOP_VERSION: ${{ needs.prepare.outputs.version }}
RELEASE_OUT: ${{ github.workspace }}/.linger-runtime/desktop-release
@@ -93,27 +99,65 @@ jobs:
# A target's build holds the bundled runtime, its archive and the
# package at once; the runner image's SDKs leave too little room.
- name: Free disk space
- run: sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL
+ run: >-
+ sudo bash -c
+ 'rm -rf /usr/share/dotnet & rm -rf /usr/local/lib/android & rm -rf /opt/ghc & rm -rf /opt/hostedtoolcache/CodeQL & wait'
- uses: actions/checkout@v4
+ - id: versions
+ shell: bash
+ run: |
+ echo "node=$(tr -d '[:space:]' <.node-version)" >>"$GITHUB_OUTPUT"
+ echo "go=$(sed -n 's/^go //p' apps/teamhub/go.mod)" >>"$GITHUB_OUTPUT"
+ - uses: actions/cache@v4
+ with:
+ path: ${{ runner.tool_cache }}/node/${{ steps.versions.outputs.node }}
+ key: toolcache-node-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.node }}
+ - uses: actions/cache@v4
+ with:
+ path: ${{ runner.tool_cache }}/go/${{ steps.versions.outputs.go }}
+ key: toolcache-go-${{ runner.os }}-${{ runner.arch }}-${{ steps.versions.outputs.go }}
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version-file: .node-version
cache: pnpm
+ # Cache GOMODCACHE once across targets and GOCACHE per target so cross-
+ # compiled stdlib and TeamHub packages stay warm for darwin-arm64 and win32-x64.
- uses: actions/setup-go@v5
with:
go-version-file: apps/teamhub/go.mod
- cache-dependency-path: |
- apps/teamhub/go.sum
- apps/computer/local-daemon/go.sum
- contracts/generated/go/go.sum
+ cache: false
+ - uses: actions/cache@v4
+ with:
+ path: ~/go/pkg/mod
+ key: desktop-gomod-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('apps/teamhub/go.sum', 'apps/computer/local-daemon/go.sum', 'contracts/generated/go/go.sum') }}
+ restore-keys: desktop-gomod-${{ runner.os }}-${{ runner.arch }}-
+ - uses: actions/cache@v4
+ with:
+ path: ~/.cache/go-build
+ key: desktop-gobuild-${{ matrix.target }}-${{ steps.versions.outputs.go }}-${{ hashFiles('apps/teamhub/go.sum', 'apps/computer/local-daemon/go.sum', 'contracts/generated/go/go.sum') }}
+ restore-keys: desktop-gobuild-${{ matrix.target }}-${{ steps.versions.outputs.go }}-
- run: pnpm install --frozen-lockfile
- # Electron zips that package.py downloads, keyed by the pinned version.
+ # Pinned binary downloads reused across releases: Electron, Cua driver,
+ # native PostgreSQL + voice tools, and the pinned Node.js distribution.
- uses: actions/cache@v4
with:
- path: ~/.cache/linger-desktop
- key: electron-${{ matrix.target }}-${{ hashFiles('apps/desktop/package.json') }}
- restore-keys: electron-${{ matrix.target }}-
+ path: |
+ ~/.cache/linger-desktop
+ ~/.cache/linger-computer-tools
+ ${{ env.LINGER_NATIVE_POSTGRES_DIR }}
+ .linger-runtime/node-distributions
+ key: desktop-downloads-${{ matrix.target }}-${{ hashFiles('apps/desktop/package.json', 'apps/desktop/distribution/*.json', 'scripts/local-computer-node-distributions.mjs', 'apps/computer/scripts/bundle-computer-tools.mjs') }}
+ restore-keys: desktop-downloads-${{ matrix.target }}-
+ - id: docker-cache
+ if: matrix.docker_image != ''
+ uses: actions/cache@v4
+ with:
+ path: ~/.cache/linger-docker/${{ matrix.docker_image }}.tar
+ key: desktop-docker-${{ matrix.docker_image }}-${{ hashFiles(matrix.docker_file) }}
+ - name: Load cached Docker image
+ if: matrix.docker_image != '' && steps.docker-cache.outputs.cache-hit == 'true'
+ run: docker load -i ~/.cache/linger-docker/${{ matrix.docker_image }}.tar
- name: Install rcodesign
if: matrix.target == 'darwin-arm64'
shell: bash
@@ -127,7 +171,14 @@ jobs:
echo "RCODESIGN=$RUNNER_TEMP/$name/rcodesign" >>"$GITHUB_ENV"
- name: Install osslsigncode
if: matrix.target == 'win32-x64'
- run: sudo apt-get update -q && sudo apt-get install -y -q osslsigncode
+ env:
+ WINDOWS_SIGNING_P12_BASE64: ${{ secrets.WINDOWS_SIGNING_P12_BASE64 }}
+ run: |
+ if [ -z "$WINDOWS_SIGNING_P12_BASE64" ]; then
+ echo "Skipping osslsigncode install: WINDOWS_SIGNING_P12_BASE64 is not set."
+ exit 0
+ fi
+ sudo apt-get update -q && sudo apt-get install -y -q osslsigncode
# Optional signing material goes to files only rcodesign, openssl and
# osslsigncode read; each is skipped when its secret is empty.
- name: Write signing files
@@ -171,6 +222,11 @@ jobs:
run: |
cd "$RELEASE_OUT/assets"
sha256sum "Linger-$DESKTOP_VERSION-windows-x64-setup.exe" > windows-setup.sha256
+ - name: Save Docker image for cache
+ if: matrix.docker_image != '' && steps.docker-cache.outputs.cache-hit != 'true'
+ run: |
+ mkdir -p ~/.cache/linger-docker
+ docker save -o ~/.cache/linger-docker/${{ matrix.docker_image }}.tar ${{ matrix.docker_image }}
- name: Remove signing files
if: always()
run: rm -rf "$RUNNER_TEMP/signing"
diff --git a/apps/desktop/build.mjs b/apps/desktop/build.mjs
index a4cc69d8..13d1c21e 100644
--- a/apps/desktop/build.mjs
+++ b/apps/desktop/build.mjs
@@ -240,7 +240,13 @@ const teamhubTargets = daemonTargets.filter((target) =>
const runtimeTargets = daemonTargets.filter((target) =>
RUNTIME_TARGETS.includes(target),
);
-if (sourceArchive && (teamhubTargets.length || runtimeTargets.length)) {
+// Run the independent packaging build steps concurrently across available cores:
+// native TeamHub binaries, Native runtime services, teamhub CLI, and the Go
+// daemon + Computer tools (sequenced so buildDaemon finishes clearing
+// dist/computer before stageDesktopComputerTools links into it).
+const buildNativeOutputs = async () => {
+ if (!sourceArchive || (!teamhubTargets.length && !runtimeTargets.length))
+ return;
let archive = bundledSource;
const work = archive
? undefined
@@ -261,34 +267,41 @@ if (sourceArchive && (teamhubTargets.length || runtimeTargets.length)) {
);
await writeFile(archive, bytes);
}
- for (const target of teamhubTargets) {
- const manifest = await buildTeamhub(target, archive);
- console.log(
- `TeamHub binaries for ${target} from ${manifest.sourceCommit.slice(0, 12)}`,
- );
- }
- for (const target of runtimeTargets) {
- const manifest = await buildRuntime(target, archive);
- console.log(
- `Native runtime for ${target} from ${manifest.sourceCommit.slice(0, 12)}: ${manifest.layout === "directory" ? "a folder" : `${manifest.archive.bytes} bytes`}`,
- );
- }
+ await Promise.all([
+ (async () => {
+ for (const target of teamhubTargets) {
+ const manifest = await buildTeamhub(target, archive);
+ console.log(
+ `TeamHub binaries for ${target} from ${manifest.sourceCommit.slice(0, 12)}`,
+ );
+ }
+ })(),
+ (async () => {
+ for (const target of runtimeTargets) {
+ const manifest = await buildRuntime(target, archive);
+ console.log(
+ `Native runtime for ${target} from ${manifest.sourceCommit.slice(0, 12)}: ${manifest.layout === "directory" ? "a folder" : `${manifest.archive.bytes} bytes`}`,
+ );
+ }
+ })(),
+ ]);
} finally {
if (work) await rm(work, { recursive: true, force: true });
}
-}
+};
// The teamhub CLI that runtimes use to reply, built from the same checkout as
// the server so their API versions match (as the Go daemon bundles it). The
// launcher runs it with the app's own Node, so the computer needs no Node.
-await run(
- "../teamhub-cli/scripts/build-cli.mjs",
- ["--outdir", "dist/teamhub-cli"],
- "teamhub CLI build failed",
-);
-await writeFile(
- "dist/teamhub-cli/teamhub",
- `#!/bin/sh
+const buildTeamhubCli = async () => {
+ await run(
+ "../teamhub-cli/scripts/build-cli.mjs",
+ ["--outdir", "dist/teamhub-cli"],
+ "teamhub CLI build failed",
+ );
+ await writeFile(
+ "dist/teamhub-cli/teamhub",
+ `#!/bin/sh
# Runs the bundled teamhub CLI with the Node built into Linger.
dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
app="$dir/../../../../MacOS/Linger"
@@ -297,26 +310,35 @@ app="$dir/../../../../MacOS/Linger"
[ -x "$app" ] || app="\${LINGER_NODE:-node}"
ELECTRON_RUN_AS_NODE=1 exec "$app" --use-env-proxy "$dir/teamhub.js" "$@"
`,
- { mode: 0o755 },
-);
-// The same for cmd and PowerShell on Windows, which run `teamhub.cmd`; Git
-// Bash takes the script above. The Computer's live voice cards start the app
-// at this relative path directly (cardCLIProgram in the local daemon's
-// playground_tools.go), so a layout change updates both.
-await writeFile(
- "dist/teamhub-cli/teamhub.cmd",
- `@echo off\r
+ { mode: 0o755 },
+ );
+ // The same for cmd and PowerShell on Windows, which run `teamhub.cmd`; Git
+ // Bash takes the script above. The Computer's live voice cards start the app
+ // at this relative path directly (cardCLIProgram in the local daemon's
+ // playground_tools.go), so a layout change updates both.
+ await writeFile(
+ "dist/teamhub-cli/teamhub.cmd",
+ `@echo off\r
setlocal\r
set "app=%~dp0..\\..\\..\\..\\Linger.exe"\r
if not exist "%app%" set "app=node"\r
set ELECTRON_RUN_AS_NODE=1\r
"%app%" --use-env-proxy "%~dp0teamhub.js" %*\r
`,
-);
+ );
+};
// The Go Local Computer daemon (dist/computer/<platform>-<arch>/) for each
// target, and the browser and computer-control tools it loads
// (dist/computer-tools/<platform>-<arch>/). Without the tools the daemon runs
// but offers Agents no browser or computer use.
-await buildDaemon(daemonTargets);
-await stageDesktopComputerTools(daemonTargets);
+const buildDaemonAndTools = async () => {
+ await buildDaemon(daemonTargets);
+ await stageDesktopComputerTools(daemonTargets);
+};
+
+await Promise.all([
+ buildNativeOutputs(),
+ buildTeamhubCli(),
+ buildDaemonAndTools(),
+]);
diff --git a/apps/desktop/packaging/archive.py b/apps/desktop/packaging/archive.py
new file mode 100644
index 00000000..6dccebd9
--- /dev/null
+++ b/apps/desktop/packaging/archive.py
@@ -0,0 +1,49 @@
+"""Shared archive and digest helpers for desktop packaging scripts."""
+import hashlib
+import os
+import shutil
+import subprocess
+import tarfile
+
+
+def sha256(path):
+ """Streaming SHA-256 hex digest of a file."""
+ digest = hashlib.sha256()
+ with open(path, "rb") as source:
+ for chunk in iter(lambda: source.read(1 << 20), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _owned_by_root(info):
+ info.uid = info.gid = 0
+ info.uname = info.gname = "root"
+ return info
+
+
+def tar_gz(src_dir, name, output, root_owner=False):
+ """Packs src_dir/name into output as a .tar.gz, using pigz when available."""
+ pigz = shutil.which("pigz")
+ tar_bin = shutil.which("tar")
+ if pigz and tar_bin:
+ cmd = [tar_bin]
+ if root_owner:
+ cmd += ["--owner=0", "--group=0", "--numeric-owner"]
+ cmd += ["-C", src_dir, "-cf", "-", name]
+ with open(output, "wb") as out:
+ tar_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+ pigz_proc = subprocess.Popen([pigz, "-6"], stdin=tar_proc.stdout, stdout=out)
+ tar_proc.stdout.close()
+ pigz_rc = pigz_proc.wait()
+ tar_rc = tar_proc.wait()
+ if tar_rc != 0:
+ raise subprocess.CalledProcessError(tar_rc, "tar")
+ if pigz_rc != 0:
+ raise subprocess.CalledProcessError(pigz_rc, "pigz")
+ return
+ with tarfile.open(output, "w:gz") as archive:
+ archive.add(
+ os.path.join(src_dir, name),
+ arcname=name,
+ filter=_owned_by_root if root_owner else None,
+ )
diff --git a/apps/desktop/packaging/computer_tools_test.py b/apps/desktop/packaging/computer_tools_test.py
index 45f4d755..4471793d 100644
--- a/apps/desktop/packaging/computer_tools_test.py
+++ b/apps/desktop/packaging/computer_tools_test.py
@@ -14,6 +14,7 @@ import tempfile
import unittest
import zipfile
+import archive
import computer_tools
HERE = os.path.dirname(os.path.abspath(__file__))
@@ -191,5 +192,32 @@ class MacSigningTest(unittest.TestCase):
args[args.index("--exclude") + 1])
+class ArchiveHelperTest(unittest.TestCase):
+ def setUp(self):
+ self.root = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, self.root)
+
+ def test_tar_gz_preserves_symlinks_and_applies_root_owner_option(self):
+ bundle = os.path.join(self.root, "Linger")
+ os.makedirs(bundle)
+ file_path = os.path.join(bundle, "hello.txt")
+ with open(file_path, "wb") as out:
+ out.write(b"linger\n")
+ os.symlink("hello.txt", os.path.join(bundle, "link.txt"))
+
+ owned = os.path.join(self.root, "owned.tar.gz")
+ archive.tar_gz(self.root, "Linger", owned, root_owner=True)
+ with tarfile.open(owned, "r:gz") as tf:
+ members = {m.name: m for m in tf.getmembers()}
+ self.assertEqual(members["Linger/hello.txt"].uid, 0)
+ self.assertEqual(members["Linger/hello.txt"].gid, 0)
+ self.assertTrue(members["Linger/link.txt"].issym())
+ self.assertEqual(members["Linger/link.txt"].linkname, "hello.txt")
+
+ plain = os.path.join(self.root, "plain.tar.gz")
+ archive.tar_gz(self.root, "Linger", plain)
+ self.assertEqual(archive.sha256(plain), sha256(plain))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/apps/desktop/packaging/linux/package.py b/apps/desktop/packaging/linux/package.py
index f9198ec2..fc606296 100644
--- a/apps/desktop/packaging/linux/package.py
+++ b/apps/desktop/packaging/linux/package.py
@@ -18,12 +18,10 @@ runtime and the bundled PostgreSQL need glibc 2.35 or newer (Ubuntu 22.04,
Debian 12); on an older system the desktop installs Native from the network.
"""
import argparse
-import hashlib
import json
import os
import shutil
import sys
-import tarfile
import tempfile
import urllib.request
import zipfile
@@ -31,6 +29,7 @@ import zipfile
HERE = os.path.dirname(os.path.abspath(__file__))
DESKTOP = os.path.dirname(os.path.dirname(HERE))
sys.path.insert(0, os.path.dirname(HERE))
+from archive import sha256, tar_gz # noqa: E402
import computer_tools # noqa: E402
from native_bundle import check_runtime, check_teamhub # noqa: E402
@@ -84,20 +83,6 @@ def stage_app(version, electron_version, root, cache):
os.rename(os.path.join(root, "electron"), os.path.join(root, "linger"))
-def owned_by_root(info):
- info.uid = info.gid = 0
- info.uname = info.gname = "root"
- return info
-
-
-def sha256(path):
- digest = hashlib.sha256()
- with open(path, "rb") as source:
- for chunk in iter(lambda: source.read(1 << 20), b""):
- digest.update(chunk)
- return digest.hexdigest()
-
-
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--out", default=os.path.join(DESKTOP, "out"))
@@ -119,10 +104,9 @@ def main():
root = os.path.join(workdir, name)
stage_app(version, electron_version, root, args.cache)
output = os.path.join(args.out, f"{name}.tar.gz")
- with tarfile.open(output, "w:gz") as archive:
- archive.add(root, arcname=name, filter=owned_by_root)
+ tar_gz(workdir, name, output, root_owner=True)
computer_tools.check_archive(output, f"{name}/resources/", TARGET)
- print(f"{output} {os.path.getsize(output)} sha256={sha256(output)}")
+ print(f"{output} {os.path.getsize(output)} sha256={sha256(output)}", flush=True)
finally:
shutil.rmtree(workdir, ignore_errors=True)
diff --git a/apps/desktop/packaging/mac/Dockerfile b/apps/desktop/packaging/mac/Dockerfile
index 09de9717..ba9c27bf 100644
--- a/apps/desktop/packaging/mac/Dockerfile
+++ b/apps/desktop/packaging/mac/Dockerfile
@@ -1,5 +1,9 @@
+FROM ubuntu:24.04 AS build
+RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates cmake make gcc g++ zlib1g-dev libbz2-dev libssl-dev && rm -rf /var/lib/apt/lists/*
+RUN git clone --depth 1 https://github.com/mozilla/libdmg-hfsplus /src && cd /src && cmake -B build -DCMAKE_BUILD_TYPE=Release . && make -C build -j8
+
FROM ubuntu:24.04
-RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates cmake make gcc g++ zlib1g-dev libbz2-dev libssl-dev hfsprogs imagemagick python3 python3-pip && rm -rf /var/lib/apt/lists/*
-RUN git clone --depth 1 https://github.com/mozilla/libdmg-hfsplus /src && cd /src && cmake -B build . && make -C build -j8 && cp build/dmg/dmg build/hfs/hfsplus /usr/local/bin/
+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates hfsprogs libbz2-1.0 libssl3t64 python3 python3-pip zlib1g && rm -rf /var/lib/apt/lists/*
+COPY --from=build /src/build/dmg/dmg /src/build/hfs/hfsplus /usr/local/bin/
# dsstore.py writes the Finder layout for each volume name.
-RUN pip install --break-system-packages ds_store==1.3.3 mac_alias==2.2.3
+RUN pip install --no-cache-dir --break-system-packages ds_store==1.3.3 mac_alias==2.2.3
diff --git a/apps/desktop/packaging/mac/package.py b/apps/desktop/packaging/mac/package.py
index 95d4755d..7d407285 100644
--- a/apps/desktop/packaging/mac/package.py
+++ b/apps/desktop/packaging/mac/package.py
@@ -39,7 +39,7 @@ signed app the installed app replaces itself with. The release's signed
manifest lists it (scripts/ci/desktop-release.sh manifest).
"""
import argparse
-import hashlib
+from concurrent.futures import ThreadPoolExecutor
import json
import os
import plistlib
@@ -48,7 +48,6 @@ import shutil
import stat
import subprocess
import sys
-import tarfile
import tempfile
import urllib.request
import zipfile
@@ -56,6 +55,7 @@ import zipfile
HERE = os.path.dirname(os.path.abspath(__file__))
DESKTOP = os.path.dirname(os.path.dirname(HERE))
sys.path.insert(0, os.path.dirname(HERE))
+from archive import sha256, tar_gz # noqa: E402
import computer_tools # noqa: E402
from native_bundle import check_runtime, check_teamhub, refresh # noqa: E402
BUNDLE_ID = "com.simplexai.linger.desktop.preview"
@@ -326,26 +326,26 @@ def build_dmg(stage, workdir, output, volume_name):
out.truncate(size * 2 + 128 * 1024 * 1024)
for asset in ("background.tiff", "dsstore.py"):
shutil.copy(os.path.join(HERE, asset), os.path.join(workdir, asset))
- dmgtool(workdir, "python3", "dsstore.py", "DS_Store", volume_name)
- dmgtool(workdir, "mkfs.hfsplus", "-v", volume_name, "vol.hfs")
- # The Finder layout in DS_Store points at the background by catalog ID,
- # so /.background and its image must be the first items (IDs 16 and 17).
- dmgtool(workdir, "hfsplus", "vol.hfs", "mkdir", "/.background")
- dmgtool(workdir, "hfsplus", "vol.hfs", "add", "background.tiff", "/.background/background.tiff")
- # Keep the bundle's symlinks (framework Versions/Current, Applications).
- dmgtool(workdir, "sh", "-c", "hfsplus -s clone_link vol.hfs addall stage > /dev/null")
- dmgtool(workdir, "hfsplus", "vol.hfs", "add", "DS_Store", "/.DS_Store")
- dmgtool(workdir, "dmg", "dmg", "vol.hfs", "out.dmg")
+ # Run the HFS+ and UDIF steps in one container invocation. The Finder
+ # layout in DS_Store points at the background by catalog ID, so /.background
+ # and its image must be the first items (IDs 16 and 17).
+ script = (
+ 'python3 dsstore.py DS_Store "$1" && '
+ 'mkfs.hfsplus -v "$1" vol.hfs && '
+ 'hfsplus vol.hfs mkdir /.background && '
+ 'hfsplus vol.hfs add background.tiff /.background/background.tiff && '
+ 'hfsplus -s clone_link vol.hfs addall stage > /dev/null && '
+ 'hfsplus vol.hfs add DS_Store /.DS_Store && '
+ 'dmg dmg vol.hfs out.dmg'
+ )
+ dmgtool(workdir, "sh", "-ec", script, "_", volume_name)
shutil.move(os.path.join(workdir, "out.dmg"), output)
def update_archive(app, output):
"""The signed bundle as Linger.app/ in a tar.gz; tar keeps its symlinks."""
- with tarfile.open(output, "w:gz") as archive:
- archive.add(app, arcname="Linger.app")
- with open(output, "rb") as source:
- digest = hashlib.sha256(source.read()).hexdigest()
- print(f"{output} {os.path.getsize(output)} sha256={digest}")
+ tar_gz(os.path.dirname(app), os.path.basename(app), output)
+ print(f"{output} {os.path.getsize(output)} sha256={sha256(output)}", flush=True)
def main():
@@ -384,16 +384,26 @@ def main():
signing.notarize(app)
computer_tools.check(os.path.join(app, RESOURCES), f"darwin-{arch}")
output = os.path.join(args.out, f"Linger-{version}-{arch}.dmg")
- build_dmg(stage, workdir, output, f"Linger {version}")
- signing.sign_dmg(output)
- signing.notarize(output)
- with open(output, "rb") as dmg:
- digest = hashlib.sha256(dmg.read()).hexdigest()
- print(f"{output} {os.path.getsize(output)} sha256={digest}")
- if args.update_archive:
+
+ def make_dmg():
+ build_dmg(stage, workdir, output, f"Linger {version}")
+ signing.sign_dmg(output)
+ signing.notarize(output)
+ print(f"{output} {os.path.getsize(output)} sha256={sha256(output)}", flush=True)
+
+ def make_update():
archive = os.path.join(args.out, f"Linger-{version}-{arch}.app.tar.gz")
update_archive(app, archive)
computer_tools.check_archive(archive, "Linger.app/Contents/Resources/", f"darwin-{arch}")
+
+ if args.update_archive:
+ # Both only read the signed, stapled bundle.
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ futures = [pool.submit(make_dmg), pool.submit(make_update)]
+ for future in futures:
+ future.result()
+ else:
+ make_dmg()
finally:
shutil.rmtree(workdir, ignore_errors=True)
diff --git a/apps/desktop/packaging/native_bundle.py b/apps/desktop/packaging/native_bundle.py
index 863601ba..133dc058 100644
--- a/apps/desktop/packaging/native_bundle.py
+++ b/apps/desktop/packaging/native_bundle.py
@@ -6,25 +6,18 @@ match their manifests and that package; scripts/build-teamhub.mjs and
scripts/build-native-runtime.mjs write them. Every package script runs these
before staging the app.
"""
-import hashlib
import json
import os
import sys
+from archive import sha256
+
DESKTOP = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
NATIVE = os.path.join(DESKTOP, "dist", "installer", "native")
SOURCE = os.path.join(DESKTOP, "dist", "installer", "source")
TEAMHUB_COMMANDS = ("teamhub", "migrate", "account")
-def sha256(path):
- digest = hashlib.sha256()
- with open(path, "rb") as source:
- for chunk in iter(lambda: source.read(1 << 20), b""):
- digest.update(chunk)
- return digest.hexdigest()
-
-
def matches(path, item):
return os.path.isfile(path) and os.path.getsize(path) == item["bytes"] and sha256(path) == item["sha256"]
diff --git a/apps/desktop/packaging/win/Dockerfile b/apps/desktop/packaging/win/Dockerfile
index 829e4f83..32cc5272 100644
--- a/apps/desktop/packaging/win/Dockerfile
+++ b/apps/desktop/packaging/win/Dockerfile
@@ -1,5 +1,5 @@
FROM ubuntu:24.04
-RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates nsis imagemagick nodejs npm && rm -rf /var/lib/apt/lists/*
+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates nsis nodejs npm && rm -rf /var/lib/apt/lists/*
# resources.mjs writes the icon and version into Linger.exe.
RUN npm install -g [email protected] && npm cache clean --force
ENV NODE_PATH=/usr/local/lib/node_modules
diff --git a/apps/desktop/packaging/win/installer.nsi b/apps/desktop/packaging/win/installer.nsi
index 3b7b18cc..775ab958 100644
--- a/apps/desktop/packaging/win/installer.nsi
+++ b/apps/desktop/packaging/win/installer.nsi
@@ -19,7 +19,11 @@ InstallDirRegKey HKCU "${UNINSTALL_KEY}" "InstallLocation"
!define APP_ID "com.simplexai.linger.desktop.preview"
!define RUN_KEY "Software\Microsoft\Windows\CurrentVersion\Run"
RequestExecutionLevel user
-SetCompressor /SOLID lzma
+; Use zlib without datablock deduplication: single-threaded LZMA spends
+; minutes re-compressing bundled archives, and datablock optimization scans
+; quadratically across the thousands of files in computer-tools.
+SetCompressor zlib
+SetDatablockOptimize off
VIProductVersion "${NUMERIC_VERSION}.0"
VIAddVersionKey "ProductName" "Linger"
diff --git a/apps/desktop/packaging/win/package.py b/apps/desktop/packaging/win/package.py
index 7f17920e..769e1b64 100644
--- a/apps/desktop/packaging/win/package.py
+++ b/apps/desktop/packaging/win/package.py
@@ -26,7 +26,7 @@ TeamHub binaries and the Native runtime build.mjs built from it must be there
and match their manifests and that package (../native_bundle.py).
"""
import argparse
-import hashlib
+from concurrent.futures import ThreadPoolExecutor
import json
import os
import shutil
@@ -39,6 +39,7 @@ import zipfile
HERE = os.path.dirname(os.path.abspath(__file__))
DESKTOP = os.path.dirname(os.path.dirname(HERE))
sys.path.insert(0, os.path.dirname(HERE))
+from archive import sha256 # noqa: E402
import computer_tools # noqa: E402
from native_bundle import check_runtime, check_teamhub # noqa: E402
DAEMON = os.path.join(DESKTOP, "dist", "computer", "win32-x64", "linger-computer-daemon.exe")
@@ -119,21 +120,30 @@ def build_setup(workdir, version, output):
shutil.move(os.path.join(workdir, "Linger-setup.exe"), output)
+# Extensions already compressed with high-entropy formats; storing them skips
+# wasted DEFLATE work without growing the archive.
+PRECOMPRESSED_EXTENSIONS = (".gz", ".tgz", ".zst", ".zip", ".xz", ".bz2", ".png", ".woff2")
+
+
def build_zip(stage, output):
with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive:
for root, _, files in os.walk(stage):
for name in sorted(files):
path = os.path.join(root, name)
- archive.write(path, os.path.join("Linger", os.path.relpath(path, stage)))
-
-
-def sha256(path):
- with open(path, "rb") as source:
- return hashlib.sha256(source.read()).hexdigest()
+ compress_type = (
+ zipfile.ZIP_STORED
+ if name.lower().endswith(PRECOMPRESSED_EXTENSIONS)
+ else zipfile.ZIP_DEFLATED
+ )
+ archive.write(
+ path,
+ os.path.join("Linger", os.path.relpath(path, stage)),
+ compress_type=compress_type,
+ )
def report(path):
- print(f"{path} {os.path.getsize(path)} sha256={sha256(path)}")
+ print(f"{path} {os.path.getsize(path)} sha256={sha256(path)}", flush=True)
def main():
@@ -155,12 +165,22 @@ def main():
try:
stage = stage_app(version, electron_version, workdir, args.cache)
setup = os.path.join(args.out, f"Linger-{version}-x64-setup.exe")
- build_setup(workdir, version, setup)
- report(setup)
archive = os.path.join(args.out, f"Linger-{version}-x64.zip")
- build_zip(stage, archive)
- computer_tools.check_archive(archive, "Linger/resources/", "win32-x64")
- report(archive)
+
+ def make_setup():
+ build_setup(workdir, version, setup)
+ report(setup)
+
+ def make_zip():
+ build_zip(stage, archive)
+ computer_tools.check_archive(archive, "Linger/resources/", "win32-x64")
+ report(archive)
+
+ # Both read the finalized stage folder and write distinct outputs.
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ futures = [pool.submit(make_setup), pool.submit(make_zip)]
+ for future in futures:
+ future.result()
finally:
shutil.rmtree(workdir, ignore_errors=True)
diff --git a/apps/desktop/scripts/build-daemon.mjs b/apps/desktop/scripts/build-daemon.mjs
index 05b40c64..254a40a6 100644
--- a/apps/desktop/scripts/build-daemon.mjs
+++ b/apps/desktop/scripts/build-daemon.mjs
@@ -5,7 +5,7 @@
// node scripts/build-daemon.mjs [--target darwin-arm64 ...] [--all]
//
// Without a target it builds for this machine.
-import { spawnSync } from "node:child_process";
+import { spawn } from "node:child_process";
import { readFile, rm } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -29,6 +29,18 @@ export const daemonFileName = (target) =>
? "linger-computer-daemon.exe"
: "linger-computer-daemon";
+export function run(command, args, options = {}) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, args, { stdio: "inherit", ...options });
+ child.once("error", reject);
+ child.once("close", (code) =>
+ code === 0
+ ? resolve()
+ : reject(new Error(`${command} ${args.join(" ")} failed (${code})`)),
+ );
+ });
+}
+
export const buildDaemon = async (targets) => {
const { version } = JSON.parse(
await readFile(path.join(desktop, "../computer/package.json"), "utf8"),
@@ -37,41 +49,42 @@ export const buildDaemon = async (targets) => {
recursive: true,
force: true,
});
- for (const target of targets) {
- const go = DAEMON_TARGETS[target];
- if (!go) throw new Error(`Unknown daemon target ${target}`);
- const output = path.join(
- desktop,
- "dist/computer",
- target,
- daemonFileName(target),
- );
- const compiled = spawnSync(
- "go",
- [
- "build",
- "-trimpath",
- "-ldflags",
- `-s -w -X github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/transport.ReleaseVersion=${version}`,
- "-o",
- output,
- "./cmd/linger-computer-daemon",
- ],
- {
- cwd: localDaemon,
- env: {
- ...process.env,
- CGO_ENABLED: "0",
- GOOS: go.goos,
- GOARCH: go.goarch,
+ await Promise.all(
+ targets.map(async (target) => {
+ const go = DAEMON_TARGETS[target];
+ if (!go) throw new Error(`Unknown daemon target ${target}`);
+ const output = path.join(
+ desktop,
+ "dist/computer",
+ target,
+ daemonFileName(target),
+ );
+ await run(
+ "go",
+ [
+ "build",
+ "-trimpath",
+ "-ldflags",
+ `-s -w -X github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/transport.ReleaseVersion=${version}`,
+ "-o",
+ output,
+ "./cmd/linger-computer-daemon",
+ ],
+ {
+ cwd: localDaemon,
+ env: {
+ ...process.env,
+ CGO_ENABLED: "0",
+ GOOS: go.goos,
+ GOARCH: go.goarch,
+ },
},
- stdio: "inherit",
- },
- );
- if (compiled.error) throw compiled.error;
- if (compiled.status !== 0)
- throw new Error(`Go build of the daemon for ${target} failed`);
- }
+ ).catch((error) => {
+ if (error?.code === "ENOENT") throw error;
+ throw new Error(`Go build of the daemon for ${target} failed`);
+ });
+ }),
+ );
};
if (process.argv[1] === fileURLToPath(import.meta.url)) {
diff --git a/apps/desktop/scripts/build-native-runtime.mjs b/apps/desktop/scripts/build-native-runtime.mjs
index 197fbbfe..886bc4ef 100644
--- a/apps/desktop/scripts/build-native-runtime.mjs
+++ b/apps/desktop/scripts/build-native-runtime.mjs
@@ -19,7 +19,6 @@
// (RUNTIME_LAYOUTS); packaging/mac/package.py signs them.
//
// node scripts/build-native-runtime.mjs --target win32-x64 --source linger-<label>.tar.gz
-import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { createReadStream, createWriteStream, existsSync } from "node:fs";
import {
@@ -34,7 +33,7 @@ import {
writeFile,
} from "node:fs/promises";
import { builtinModules } from "node:module";
-import { tmpdir } from "node:os";
+import { availableParallelism, tmpdir } from "node:os";
import path from "node:path";
import { pipeline } from "node:stream/promises";
import { fileURLToPath } from "node:url";
@@ -43,10 +42,11 @@ import zlib, { createZstdCompress } from "node:zlib";
import { build } from "esbuild";
import {
+ ensureNodeRuntimeArchive,
NODE_RUNTIME_RELEASES,
NODE_RUNTIME_VERSION,
- nodeRuntimeDownloadUrls,
} from "../../../scripts/local-computer-node-distributions.mjs";
+import { run } from "./build-daemon.mjs";
import { bundleNodeServices } from "./bundle-node-services.mjs";
import { sourceCommit } from "./build-teamhub.mjs";
@@ -124,13 +124,6 @@ const sha256File = async (file) => {
return hash.digest("hex");
};
-const run = (command, args, options = {}) => {
- const result = spawnSync(command, args, { stdio: "inherit", ...options });
- if (result.error) throw result.error;
- if (result.status !== 0)
- throw new Error(`${command} ${args.join(" ")} failed (${result.status})`);
-};
-
const packageName = (specifier) =>
specifier
.split("/")
@@ -262,47 +255,31 @@ async function listFiles(root) {
return files;
}
-// Node archives already downloaded by an earlier build; they are checked
-// against the pinned sha256 like a download.
-const nodeCache = path.join(desktop, "node_modules/.cache/linger-node");
+// Shared with scripts/prepare-local-computer-release.mjs so both the Native
+// runtime and Computer tools reuse one pinned Node.js download per target.
+const nodeCache = path.join(
+ desktop,
+ "../../.linger-runtime/node-distributions",
+);
async function downloadNode(target, output) {
const release = NODE_RUNTIME_RELEASES[target];
const file = path.join(output, release.archive);
- const cached = path.join(nodeCache, release.archive);
- if (existsSync(cached) && (await sha256File(cached)) === release.sha256) {
- await cp(cached, file);
- return {
- version: NODE_RUNTIME_VERSION,
- file: release.archive,
- sha256: release.sha256,
- bytes: (await stat(file)).size,
- };
- }
- for (const url of nodeRuntimeDownloadUrls(release.archive)) {
- const response = await fetch(url).catch(() => undefined);
- if (!response?.ok) continue;
- await writeFile(file, Buffer.from(await response.arrayBuffer()));
- if ((await sha256File(file)) !== release.sha256) continue;
- await mkdir(nodeCache, { recursive: true });
- await cp(file, cached);
- return {
- version: NODE_RUNTIME_VERSION,
- file: release.archive,
- sha256: release.sha256,
- bytes: (await stat(file)).size,
- };
- }
- throw new Error(
- `Could not download ${release.archive} with its pinned sha256`,
- );
+ const cached = await ensureNodeRuntimeArchive(target, nodeCache);
+ await cp(cached, file);
+ return {
+ version: NODE_RUNTIME_VERSION,
+ file: release.archive,
+ sha256: release.sha256,
+ bytes: (await stat(file)).size,
+ };
}
// bin/node and the license from a Node.js release tar.gz, into `output`/node.
async function unpackNode(archive, output, work) {
const unpacked = path.join(work, "node-release");
await mkdir(unpacked);
- run("tar", ["-xzf", archive, "-C", unpacked, "--strip-components=1"]);
+ await run("tar", ["-xzf", archive, "-C", unpacked, "--strip-components=1"]);
const node = path.join(output, NODE_DIRECTORY);
await mkdir(path.join(node, "bin"), { recursive: true });
await cp(path.join(unpacked, "bin/node"), path.join(node, "bin/node"));
@@ -384,7 +361,7 @@ export async function buildRuntime(
const services = path.join(root, "node-services");
const web = path.join(root, "web");
await mkdir(source);
- run("tar", ["-xzf", archive, "-C", source, "--strip-components=1"]);
+ await run("tar", ["-xzf", archive, "-C", source, "--strip-components=1"]);
await timed("install", () =>
run(
"pnpm",
@@ -402,93 +379,106 @@ export async function buildRuntime(
{ cwd: source },
),
);
- await timed("web", async () => {
- run("pnpm", ["--filter", "@linger/web", "build:assets"], {
- cwd: source,
- });
- // The precompressed twins halve Web's share of the package and save
- // nothing on loopback; the host serves the plain file without them.
- await cp(path.join(source, "apps/web/dist"), path.join(web, "dist"), {
- recursive: true,
- filter: (file) =>
- !/\.(?:gz|br)$/.test(file) ||
- !existsSync(file.replace(/\.(?:gz|br)$/, "")),
- });
- await build({
- absWorkingDir: path.join(source, "apps/web"),
- entryPoints: [path.join(source, "apps/web/static-host.mjs")],
- outfile: path.join(web, "static-host.mjs"),
- bundle: true,
- platform: "node",
- format: "esm",
- target: "node26",
- logLevel: "warning",
- });
- });
- const bundled = await timed("node-services", async () => {
- const result = await bundleNodeServices(source, services);
- await cp(
- path.join(source, "apps/node-services/prompts"),
- path.join(services, "prompts"),
- { recursive: true },
- );
- await writeFile(
- path.join(services, "package.json"),
- JSON.stringify(
- { name: "@linger/node-services", private: true, type: "module" },
- null,
- 2,
- ),
- );
- return result;
- });
- const packages = await timed("externals", async () => {
- const deployed = path.join(work, "deploy");
- run(
- "pnpm",
- [
- "--filter",
- "@linger/node-services",
- "deploy",
- "--config.inject-workspace-packages=true",
- "--config.node-linker=hoisted",
- "--prod",
- // Every native package here ships prebuilt per platform.
- "--ignore-scripts",
- `--os=${platform.os}`,
- `--cpu=${platform.cpu}`,
- ...(platform.libc ? [`--libc=${platform.libc}`] : []),
- deployed,
- ],
- { cwd: source },
- );
- const builtins = new Set(builtinModules);
- const roots = new Set(RUNTIME_PACKAGES);
- for (const specifier of bundled.imports) {
- const name = packageName(specifier);
- if (!builtins.has(name) && !OPTIONAL_IMPORTS.has(name)) roots.add(name);
- }
- const copied = await copyExternals(
- deployed,
- services,
- [...roots].sort(),
- modelPackageGroup,
- );
- await writeFile(
- path.join(services, "models.json"),
- JSON.stringify(
- modelPackages(
- await readFile(path.join(source, "pnpm-lock.yaml"), "utf8"),
- copied.excluded,
- ),
- null,
- 2,
- ),
- );
- return copied;
- });
+ const [, { bundled, packages }, downloadedNode] = await Promise.all([
+ timed("web", async () => {
+ const webSource = path.join(source, "apps/web");
+ // Forward --skip-precompress to build:assets so Web keeps one build
+ // recipe while skipping .gz/.br twins the loopback host does not serve.
+ await run(
+ "pnpm",
+ [
+ "--filter",
+ "@linger/web",
+ "run",
+ "build:assets",
+ "--skip-precompress",
+ ],
+ { cwd: source },
+ );
+ await cp(path.join(webSource, "dist"), path.join(web, "dist"), {
+ recursive: true,
+ });
+ await build({
+ absWorkingDir: webSource,
+ entryPoints: [path.join(webSource, "static-host.mjs")],
+ outfile: path.join(web, "static-host.mjs"),
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ target: "node26",
+ logLevel: "warning",
+ });
+ }),
+ (async () => {
+ const bundledResult = await timed("node-services", async () => {
+ const result = await bundleNodeServices(source, services);
+ await cp(
+ path.join(source, "apps/node-services/prompts"),
+ path.join(services, "prompts"),
+ { recursive: true },
+ );
+ await writeFile(
+ path.join(services, "package.json"),
+ JSON.stringify(
+ { name: "@linger/node-services", private: true, type: "module" },
+ null,
+ 2,
+ ),
+ );
+ return result;
+ });
+ const packagesResult = await timed("externals", async () => {
+ const deployed = path.join(work, "deploy");
+ await run(
+ "pnpm",
+ [
+ "--filter",
+ "@linger/node-services",
+ "deploy",
+ "--config.inject-workspace-packages=true",
+ "--config.node-linker=hoisted",
+ "--prod",
+ // Every native package here ships prebuilt per platform.
+ "--ignore-scripts",
+ `--os=${platform.os}`,
+ `--cpu=${platform.cpu}`,
+ ...(platform.libc ? [`--libc=${platform.libc}`] : []),
+ deployed,
+ ],
+ { cwd: source },
+ );
+ const builtins = new Set(builtinModules);
+ const roots = new Set(RUNTIME_PACKAGES);
+ for (const specifier of bundledResult.imports) {
+ const name = packageName(specifier);
+ if (!builtins.has(name) && !OPTIONAL_IMPORTS.has(name))
+ roots.add(name);
+ }
+ const copied = await copyExternals(
+ deployed,
+ services,
+ [...roots].sort(),
+ modelPackageGroup,
+ );
+ await writeFile(
+ path.join(services, "models.json"),
+ JSON.stringify(
+ modelPackages(
+ await readFile(path.join(source, "pnpm-lock.yaml"), "utf8"),
+ copied.excluded,
+ ),
+ null,
+ 2,
+ ),
+ );
+ return copied;
+ });
+ return { bundled: bundledResult, packages: packagesResult };
+ })(),
+ timed("node", () => downloadNode(target, output)),
+ ]);
const layout = RUNTIME_LAYOUTS[target];
- let node = await timed("node", () => downloadNode(target, output));
+ let node = downloadedNode;
await timed("archive", async () => {
const files = await listFiles(root);
await writeFile(
@@ -506,7 +496,7 @@ export async function buildRuntime(
),
);
if (layout === "directory") return;
- run("tar", [
+ await run("tar", [
"--sort=name",
"--format=posix",
"--owner=0",
@@ -527,6 +517,10 @@ export async function buildRuntime(
params: {
[zlib.constants.ZSTD_c_compressionLevel]: 12,
[zlib.constants.ZSTD_c_windowLog]: 24,
+ [zlib.constants.ZSTD_c_nbWorkers]: Math.min(
+ availableParallelism(),
+ 4,
+ ),
},
}),
createWriteStream(path.join(output, RUNTIME_ARCHIVE)),
diff --git a/apps/desktop/scripts/build-teamhub.mjs b/apps/desktop/scripts/build-teamhub.mjs
index cc400a07..553ef5df 100644
--- a/apps/desktop/scripts/build-teamhub.mjs
+++ b/apps/desktop/scripts/build-teamhub.mjs
@@ -5,7 +5,7 @@
// source, so Native there needs no Go toolchain, module download or compile.
//
// node scripts/build-teamhub.mjs --target win32-x64 --source linger-<label>.tar.gz
-import { spawnSync } from "node:child_process";
+import { spawn } from "node:child_process";
import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import {
@@ -21,7 +21,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { createGunzip } from "node:zlib";
-import { DAEMON_TARGETS } from "./build-daemon.mjs";
+import { DAEMON_TARGETS, run } from "./build-daemon.mjs";
const desktop = fileURLToPath(new URL("../", import.meta.url));
@@ -39,6 +39,25 @@ const sha256File = async (file) => {
return hash.digest("hex");
};
+const capture = (command, args, options = {}) =>
+ new Promise((resolve, reject) => {
+ const child = spawn(command, args, {
+ stdio: ["ignore", "pipe", "inherit"],
+ ...options,
+ });
+ let stdout = "";
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (chunk) => {
+ stdout += chunk;
+ });
+ child.once("error", reject);
+ child.once("close", (code) =>
+ code === 0
+ ? resolve(stdout)
+ : reject(new Error(`${command} ${args.join(" ")} failed (${code})`)),
+ );
+ });
+
// The commit `git archive` records in the package's first (pax) header.
export async function sourceCommit(archive) {
const stream = createReadStream(archive).pipe(createGunzip());
@@ -98,12 +117,15 @@ export async function buildTeamhub(
const work = await mkdtemp(path.join(tmpdir(), "linger-teamhub-"));
try {
// The package holds one folder, `<name>-<label>/`.
- const unpacked = spawnSync(
- "tar",
- ["-xzf", archive, "-C", work, "--strip-components=1"],
- { stdio: "inherit" },
- );
- if (unpacked.status !== 0) throw new Error(`Could not unpack ${archive}`);
+ await run("tar", [
+ "-xzf",
+ archive,
+ "-C",
+ work,
+ "--strip-components=1",
+ ]).catch(() => {
+ throw new Error(`Could not unpack ${archive}`);
+ });
const teamhub = path.join(work, "apps/teamhub");
const env = {
...process.env,
@@ -114,16 +136,15 @@ export async function buildTeamhub(
.filter(Boolean)
.join(" "),
};
- const version = spawnSync("go", ["env", "GOVERSION"], {
+ const version = await capture("go", ["env", "GOVERSION"], {
cwd: teamhub,
env,
- encoding: "utf8",
+ }).catch(() => {
+ throw new Error("go env GOVERSION failed");
});
- if (version.status !== 0) throw new Error("go env GOVERSION failed");
- const binaries = {};
- for (const command of COMMANDS) {
+ const buildCommand = async (command) => {
const file = go.goos === "windows" ? `${command}.exe` : command;
- const compiled = spawnSync(
+ await run(
"go",
[
"build",
@@ -134,17 +155,26 @@ export async function buildTeamhub(
path.join(output, file),
`./cmd/${command}`,
],
- { cwd: teamhub, env, stdio: "inherit" },
- );
- if (compiled.error) throw compiled.error;
- if (compiled.status !== 0)
+ { cwd: teamhub, env },
+ ).catch((error) => {
+ if (error?.code === "ENOENT") throw error;
throw new Error(`Go build of ${command} for ${target} failed`);
- binaries[command] = {
- file,
- sha256: await sha256File(path.join(output, file)),
- bytes: (await stat(path.join(output, file))).size,
- };
- }
+ });
+ return [
+ command,
+ {
+ file,
+ sha256: await sha256File(path.join(output, file)),
+ bytes: (await stat(path.join(output, file))).size,
+ },
+ ];
+ };
+ // Build the primary binary first so shared packages populate GOCACHE once,
+ // then link the companion commands concurrently.
+ const [first, ...rest] = COMMANDS;
+ const firstEntry = await buildCommand(first);
+ const restEntries = await Promise.all(rest.map(buildCommand));
+ const binaries = Object.fromEntries([firstEntry, ...restEntries]);
await writeFile(
path.join(output, "manifest.json"),
JSON.stringify(
@@ -152,7 +182,7 @@ export async function buildTeamhub(
target,
sourceCommit: commit,
sourceArchiveSha256,
- goVersion: version.stdout.trim().replace(/^go/, ""),
+ goVersion: version.trim().replace(/^go/, ""),
binaries,
},
null,
diff --git a/apps/desktop/scripts/bundle-node-services.mjs b/apps/desktop/scripts/bundle-node-services.mjs
index ba98a415..856f73ef 100644
--- a/apps/desktop/scripts/bundle-node-services.mjs
+++ b/apps/desktop/scripts/bundle-node-services.mjs
@@ -89,30 +89,26 @@ export async function bundleNodeServices(repo, output) {
bundle(repo, output, entry, outputFile, {
LINGER_PACKAGE_ROOT: JSON.stringify(packageRootFrom(outputFile)),
});
- for (const entry of NODE_SERVICES_ENTRIES)
- record(
- await nodeServices(
- `apps/node-services/src/${entry}.ts`,
- `dist/${entry}.js`,
- ),
- );
- for (const entry of VOICE_ENTRIES)
- record(
- await bundle(
+ const metafiles = await Promise.all([
+ ...NODE_SERVICES_ENTRIES.map((entry) =>
+ nodeServices(`apps/node-services/src/${entry}.ts`, `dist/${entry}.js`),
+ ),
+ ...VOICE_ENTRIES.map((entry) =>
+ bundle(
repo,
output,
`apps/voice-runtime/src/${entry}.ts`,
`node_modules/@linger/voice-runtime/dist/${entry}.js`,
),
- );
- // Waits for TeamHub and restarts the service after a crash, as in
- // development (scripts/dev-supervisor.ts --compiled).
- record(
- await nodeServices(
+ ),
+ // Waits for TeamHub and restarts the service after a crash, as in
+ // development (scripts/dev-supervisor.ts --compiled).
+ nodeServices(
"apps/node-services/scripts/dev-supervisor.ts",
"dist/supervisor.js",
),
- );
+ ]);
+ for (const metafile of metafiles) record(metafile);
const worker = "src/agent/observability/agent-log-file-worker.mjs";
await mkdir(path.join(output, "dist/agent/observability"), {
recursive: true,
diff --git a/apps/web/build-assets.mjs b/apps/web/build-assets.mjs
index 643ab0a3..7b28f8ee 100644
--- a/apps/web/build-assets.mjs
+++ b/apps/web/build-assets.mjs
@@ -31,6 +31,7 @@ export const webInitialJavaScriptBudget = {
export async function prepareProductionAssets({
budget = webInitialJavaScriptBudget,
+ precompress = true,
root,
}) {
const outputRoot = resolve(root);
@@ -39,7 +40,12 @@ export async function prepareProductionAssets({
);
const initialFiles = resolveInitialJavaScriptFiles(manifest);
const productionJavaScriptFiles = resolveProductionJavaScriptFiles(manifest);
- const compressedAssets = await precompressStaticAssets(outputRoot);
+ const filesToCompress = precompress
+ ? await listCompressibleFiles(outputRoot)
+ : initialFiles.map((file) => join(outputRoot, file));
+ const compressedAssets = await compressAssets(outputRoot, filesToCompress, {
+ write: precompress,
+ });
const initialJavaScript = await measureInitialJavaScript(
outputRoot,
initialFiles,
@@ -50,7 +56,7 @@ export async function prepareProductionAssets({
assertWithinBudget(initialJavaScript, budget);
return {
- compressedAssetCount: compressedAssets.size,
+ compressedAssetCount: precompress ? compressedAssets.size : 0,
initialJavaScript: {
brotliBytes: initialJavaScript.brotliBytes,
files: initialFiles,
@@ -102,8 +108,7 @@ function resolveInitialJavaScriptFiles(manifest) {
return files;
}
-async function precompressStaticAssets(root) {
- const sourceFiles = await listCompressibleFiles(root);
+async function compressAssets(root, sourceFiles, { write }) {
const compressedAssets = new Map();
await Promise.all(
@@ -123,14 +128,16 @@ async function precompressStaticAssets(root) {
gzipBytes: Math.min(source.length, gzipped.length),
};
- await Promise.all([
- brotli.length < source.length
- ? writeFile(`${absolutePath}.br`, brotli)
- : undefined,
- gzipped.length < source.length
- ? writeFile(`${absolutePath}.gz`, gzipped)
- : undefined,
- ]);
+ if (write) {
+ await Promise.all([
+ brotli.length < source.length
+ ? writeFile(`${absolutePath}.br`, brotli)
+ : undefined,
+ gzipped.length < source.length
+ ? writeFile(`${absolutePath}.gz`, gzipped)
+ : undefined,
+ ]);
+ }
compressedAssets.set(relativePath, variants);
}),
);
@@ -249,7 +256,10 @@ function printReport(result) {
}
if (isMainModule()) {
- prepareProductionAssets({ root: process.argv[2] ?? "dist" })
+ const args = process.argv.slice(2);
+ const precompress = !args.includes("--skip-precompress");
+ const root = args.find((arg) => !arg.startsWith("--")) ?? "dist";
+ prepareProductionAssets({ precompress, root })
.then(printReport)
.catch((error) => {
process.stderr.write(
diff --git a/apps/web/src/test/build-assets.test.ts b/apps/web/src/test/build-assets.test.ts
index ffc115d6..c932cce5 100644
--- a/apps/web/src/test/build-assets.test.ts
+++ b/apps/web/src/test/build-assets.test.ts
@@ -104,6 +104,31 @@ describe("Web production build assets", () => {
}),
).rejects.toThrow(/React development bundle/i);
});
+
+ it("enforces the budget and React check without writing precompressed twins when precompress is false", async () => {
+ const fixture = await createBuildFixture();
+
+ const result = await prepareProductionAssets({
+ budget: {
+ brotliBytes: 10_000,
+ gzipBytes: 10_000,
+ minifiedBytes: 10_000,
+ },
+ precompress: false,
+ root: fixture.root,
+ });
+
+ expect(result.compressedAssetCount).toBe(0);
+ expect(result.initialJavaScript.brotliBytes).toBeLessThan(
+ result.initialJavaScript.minifiedBytes,
+ );
+ await expect(
+ readFile(join(fixture.root, "assets", "entry.js.br")),
+ ).rejects.toMatchObject({ code: "ENOENT" });
+ await expect(
+ readFile(join(fixture.root, "assets", "dynamic.js.gz")),
+ ).rejects.toMatchObject({ code: "ENOENT" });
+ });
});
async function createBuildFixture({
diff --git a/scripts/ci/desktop-release.sh b/scripts/ci/desktop-release.sh
index 385a4a49..44e3f9fd 100755
--- a/scripts/ci/desktop-release.sh
+++ b/scripts/ci/desktop-release.sh
@@ -206,9 +206,20 @@ cmd_compile() {
)
}
+ensure_docker_image() {
+ local tag="$1" dir="$2" sha current
+ sha="$(sha256_of "$dir/Dockerfile")"
+ current="$(docker image inspect --format '{{index .Config.Labels "linger.dockerfile.sha256"}}' "$tag" 2>/dev/null || true)"
+ if [[ "$current" == "$sha" ]]; then
+ echo "desktop-release: reusing cached Docker image $tag"
+ return 0
+ fi
+ docker build -q --label "linger.dockerfile.sha256=$sha" -t "$tag" "$dir" >/dev/null
+}
+
package_darwin() {
local version="$1" pkg="$2" assets="$3" args=()
- docker build -q -t dmgtool "$desktop/packaging/mac" >/dev/null
+ ensure_docker_image dmgtool "$desktop/packaging/mac"
args+=(--arch arm64 --rcodesign "${RCODESIGN:-rcodesign}" --out "$pkg")
if [[ -n "${MACOS_DEVELOPER_ID_P12:-}" ]]; then
args+=(--developer-id "$MACOS_DEVELOPER_ID_P12" --developer-id-password "${MACOS_DEVELOPER_ID_PASSWORD_FILE:?MACOS_DEVELOPER_ID_PASSWORD_FILE is required with MACOS_DEVELOPER_ID_P12}")
@@ -231,7 +242,7 @@ package_linux() {
package_windows() {
local version="$1" pkg="$2" assets="$3" setup
- docker build -q -t wintool "$desktop/packaging/win" >/dev/null
+ ensure_docker_image wintool "$desktop/packaging/win"
(cd "$desktop" && python3 packaging/win/package.py --out "$pkg")
setup="$pkg/Linger-$version-x64-setup.exe"
if [[ -n "${WINDOWS_SIGNING_P12:-}" ]]; then