Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
Seanaye/feat/tauri desktop builds (#4301)
Sean Aye7590479a5210
diff --git a/.github/workflows/build_appimage_on_tag.yml b/.github/workflows/build_appimage_on_tag.ymlnew file mode 100644index 0000000000..41dd9cd34f--- /dev/null+++ b/.github/workflows/build_appimage_on_tag.yml@@ -0,0 +1,132 @@+# DO NOT EDIT — regenerate with `cargo x workflows` (from rust/cloud-storage).+# Source: rust/cloud-storage/tools/xtask/src/workflows/build_appimage_on_tag.rs+name: Build AppImage+'on':+ workflow_call:+ inputs:+ ref:+ description: Git ref to check out and build+ required: true+ type: string+jobs:+ build-appimage:+ name: Build AppImage+ runs-on: namespace-profile-linux-rust-ci+ steps:+ - name: Checkout Repo+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10+ with:+ ref: ${{ inputs.ref }}+ persist-credentials: 'false'+ - name: Mount /nix cache volume+ uses: namespacelabs/nscloud-cache-action@15799a6b54e5765f85b2aac25b3f0df43ed571c0+ with:+ path: /nix+ continue-on-error: true+ - name: Setup Nix+ uses: './.github/actions/setup-nix'+ - name: Configure Cachix fallback+ uses: './.github/actions/setup-cachix'+ with:+ cachix-auth-token: ${{ secrets.CACHIX_AUTH_TOKEN }}+ - id: metadata+ name: Derive artifact metadata+ run: |+ set -euo pipefail+ tag="${RAW_REF#refs/tags/}"+ if [ -z "$tag" ]; then+ tag="${GITHUB_REF_NAME:-untagged}"+ fi+ safe_tag=$(printf '%s' "$tag" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')+ echo "tag=$tag" >> "$GITHUB_OUTPUT"+ echo "safe_tag=$safe_tag" >> "$GITHUB_OUTPUT"+ shell: bash+ env:+ RAW_REF: ${{ inputs.ref }}+ - name: Build AppImage with Nix+ run: |+ set -euo pipefail+ cachix_pid=+ if command -v cachix >/dev/null 2>&1 && [ -n "${CACHIX_CACHE_NAME:-}" ]; then+ cachix watch-store "$CACHIX_CACHE_NAME" >/tmp/cachix-watch-store.log 2>&1 &+ cachix_pid=$!+ trap 'if [ -n "${cachix_pid:-}" ]; then kill "$cachix_pid" 2>/dev/null || true; wait "$cachix_pid" 2>/dev/null || true; fi' EXIT+ fi+ restart_nix_daemon() {+ echo "::warning::Restarting nix-daemon before retrying AppImage build."+ sudo systemctl restart nix-daemon.service 2>/dev/null || true+ sudo pkill -x nix-daemon 2>/dev/null || true+ sudo rm -f /nix/var/nix/daemon-socket/socket+ sudo mkdir -p /nix/var/nix/daemon-socket+ sudo sh -c 'nohup /nix/var/nix/profiles/default/bin/nix-daemon >/tmp/nix-daemon-retry.log 2>&1 &'+ for _ in $(seq 1 30); do+ if sudo test -S /nix/var/nix/daemon-socket/socket; then+ return 0+ fi+ sleep 1+ done+ echo "nix-daemon failed to restart; log follows:" >&2+ sudo cat /tmp/nix-daemon-retry.log >&2 || true+ return 1+ }++ build_appimage() {+ local attempt="$1"+ local -a fallback_args=()+ if [ "$attempt" -eq 3 ]; then+ fallback_args=(--fallback)+ fi++ # Force a hermetic Nix sandbox for linuxdeploy. Namespace's restored+ # Nix daemon can otherwise run unsandboxed under /nix/var/nix/builds,+ # where linuxdeploy sees host libraries/tools and can fail with only+ # `failed to run linuxdeploy` in Tauri's default output.+ nix build \+ "${fallback_args[@]}" \+ --option sandbox true \+ --option sandbox-build-dir /build \+ --option download-attempts 10 \+ --print-build-logs \+ ".#tauri-desktop-appimage"+ }++ for attempt in 1 2 3; do+ if build_appimage "$attempt"; then+ break+ fi+ if [ "$attempt" -eq 3 ]; then+ exit 1+ fi+ echo "::warning::AppImage nix build failed on attempt $attempt; retrying."+ restart_nix_daemon+ sleep $((attempt * 10))+ done+ if command -v cachix >/dev/null 2>&1 && [ -n "${CACHIX_CACHE_NAME:-}" ]; then+ cachix push "$CACHIX_CACHE_NAME" result || echo "::warning::Failed to push AppImage result closure to Cachix."+ fi+ shell: bash+ - name: Collect AppImage artifact+ run: |+ set -euo pipefail+ mkdir -p artifacts+ shopt -s nullglob+ appimages=(result/*.AppImage)+ if [ "${#appimages[@]}" -eq 0 ]; then+ echo "No AppImage files found in nix build result" >&2+ find -L result -maxdepth 2 -type f -print >&2 || true+ exit 1+ fi+ cp -v "${appimages[@]}" artifacts/+ chmod 0755 artifacts/*.AppImage+ (cd artifacts && sha256sum -- *.AppImage > SHA256SUMS)+ shell: bash+ - name: Upload macro-appimage-${{ steps.metadata.outputs.safe_tag }} artifact+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02+ with:+ name: macro-appimage-${{ steps.metadata.outputs.safe_tag }}+ path: artifacts/*+ if-no-files-found: error+ retention-days: '30'+ - name: Teardown Nix+ if: always()+ uses: './.github/actions/teardown-nix'diff --git a/.github/workflows/build_desktop_on_tag.yml b/.github/workflows/build_desktop_on_tag.ymlnew file mode 100644index 0000000000..fb7de0c22d--- /dev/null+++ b/.github/workflows/build_desktop_on_tag.yml@@ -0,0 +1,91 @@+# DO NOT EDIT — regenerate with `cargo x workflows` (from rust/cloud-storage).+# Source: rust/cloud-storage/tools/xtask/src/workflows/build_desktop_on_tag.rs+name: Build Desktop on Tag+'on':+ push:+ tags:+ - v[0-9]*+ create: {}+ workflow_dispatch:+ inputs:+ ref:+ description: Release tag to build (v* or refs/tags/v*). Defaults to the selected protected ref or release tag.+ required: false+ type: string+concurrency:+ group: desktop-${{ inputs.ref || (github.event.ref_type == 'tag' && github.event.ref || github.ref_name) }}+ cancel-in-progress: true+jobs:+ resolve-ref:+ if: github.event_name == 'workflow_dispatch' || github.event_name == 'push' || (github.event_name == 'create' && github.event.ref_type == 'tag')+ name: Resolve build ref+ runs-on: ubuntu-latest+ outputs:+ ref: ${{ steps.resolve.outputs.ref }}+ steps:+ - id: resolve+ name: Resolve ref+ run: |+ set -euo pipefail++ # Resolve the git ref for desktop builds from any trigger type:+ # push (tag) → github.ref+ # create (tag) → github.event.ref+ # workflow_dispatch → inputs.ref (validated) or github.ref (protected)++ case "$EVENT_NAME" in+ push)+ echo "ref=$SELECTED_REF" >> "$GITHUB_OUTPUT"+ ;;+ create)+ if [ "$GITHUB_EVENT_REF_TYPE" != "tag" ]; then+ echo "create event was not a tag; skipping" >&2+ exit 1+ fi+ echo "ref=$GITHUB_EVENT_REF" >> "$GITHUB_OUTPUT"+ ;;+ workflow_dispatch)+ ref="${INPUT_REF:-$SELECTED_REF}"+ if [[ "$ref" =~ ^refs/tags/v[0-9][0-9A-Za-z._-]*$ ]]; then+ echo "ref=$ref" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ if [[ "$ref" =~ ^v[0-9][0-9A-Za-z._-]*$ ]]; then+ echo "ref=refs/tags/$ref" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ if [ -z "$INPUT_REF" ] && [ "$SELECTED_REF_PROTECTED" = "true" ]; then+ echo "ref=$SELECTED_REF" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ echo "Manual desktop builds only allow release tags (v*) or a protected ref." >&2+ exit 1+ ;;+ *)+ echo "Unexpected event: $EVENT_NAME" >&2+ exit 1+ ;;+ esac+ shell: bash+ env:+ EVENT_NAME: ${{ github.event_name }}+ INPUT_REF: ${{ inputs.ref }}+ GITHUB_EVENT_REF: ${{ github.event.ref }}+ GITHUB_EVENT_REF_TYPE: ${{ github.event.ref_type }}+ SELECTED_REF: ${{ github.ref }}+ SELECTED_REF_NAME: ${{ github.ref_name }}+ SELECTED_REF_PROTECTED: ${{ github.ref_protected }}+ build-appimage:+ needs:+ - resolve-ref+ uses: './.github/workflows/build_appimage_on_tag.yml'+ with:+ ref: ${{ needs.resolve-ref.outputs.ref }}+ secrets: inherit+ build-dmg:+ needs:+ - resolve-ref+ uses: './.github/workflows/build_dmg_on_tag.yml'+ with:+ ref: ${{ needs.resolve-ref.outputs.ref }}+ secrets: inheritdiff --git a/.github/workflows/build_dmg_on_tag.yml b/.github/workflows/build_dmg_on_tag.ymlnew file mode 100644index 0000000000..065e8251bb--- /dev/null+++ b/.github/workflows/build_dmg_on_tag.yml@@ -0,0 +1,181 @@+# DO NOT EDIT — regenerate with `cargo x workflows` (from rust/cloud-storage).+# Source: rust/cloud-storage/tools/xtask/src/workflows/build_dmg_on_tag.rs+name: Build macOS DMG+'on':+ workflow_call:+ inputs:+ ref:+ description: Git ref to check out and build+ required: true+ type: string+jobs:+ build-dmg:+ name: Build macOS DMG+ runs-on: macos-15+ steps:+ - name: Checkout Repo+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10+ with:+ ref: ${{ inputs.ref }}+ persist-credentials: 'false'+ - name: Assert arm64 runner+ run: |+ set -euo pipefail+ if [ "$(uname -m)" != "arm64" ]; then+ echo "macOS DMG builds must run on an arm64/aarch64 runner, got $(uname -m)" >&2+ exit 1+ fi+ shell: bash+ - name: Install Nix+ run: |+ set -euo pipefail+ if ! command -v nix >/dev/null 2>&1; then+ curl --http1.1 --retry 5 --retry-delay 5 --retry-all-errors \+ --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | \+ sh -s -- install macos --no-confirm \+ --extra-conf "experimental-features = nix-command flakes" \+ --extra-conf "sandbox = false" \+ --extra-conf "trusted-users = root runner"+ fi+ echo "/nix/var/nix/profiles/default/bin" >> "$GITHUB_PATH"+ echo "NIX_REMOTE=daemon" >> "$GITHUB_ENV"+ export PATH="/nix/var/nix/profiles/default/bin:$PATH"+ export NIX_REMOTE=daemon+ nix --version+ shell: bash+ - name: Configure Cachix fallback+ uses: './.github/actions/setup-cachix'+ with:+ cachix-auth-token: ${{ secrets.CACHIX_AUTH_TOKEN }}+ - name: Configure signing identity+ run: |+ set -euo pipefail+ if [ -z "${MACOS_DEVELOPER_ID_CERTIFICATE_BASE64}" ] || [ -z "${MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD}" ]; then+ echo "Developer ID certificate secrets are not configured; using ad-hoc signing for build validation."+ echo "APPLE_SIGNING_IDENTITY=-" >> "$GITHUB_ENV"+ exit 0+ fi++ certificate_path="$RUNNER_TEMP/developer-id-application.p12"+ printf '%s' "$MACOS_DEVELOPER_ID_CERTIFICATE_BASE64" | base64 --decode > "$certificate_path" 2>/dev/null \+ || printf '%s' "$MACOS_DEVELOPER_ID_CERTIFICATE_BASE64" | base64 -D > "$certificate_path"++ # Nix's macOS daemon builds as _nixbld users, not the runner user.+ # Put the Developer ID identity in the system keychain so codesign can+ # find it from inside the Nix build without embedding certificate+ # secrets into the derivation.+ sudo security import "$certificate_path" \+ -k /Library/Keychains/System.keychain \+ -P "$MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD" \+ -A \+ -T /usr/bin/codesign \+ -T /usr/bin/security+ sudo security set-key-partition-list \+ -S apple-tool:,apple:,codesign: \+ -s \+ -k "" \+ /Library/Keychains/System.keychain || true++ identity=$(security find-identity -v -p codesigning /Library/Keychains/System.keychain \+ | awk -F '"' '/Developer ID Application/ { print $2; exit }')+ if [ -z "$identity" ]; then+ echo "No Developer ID Application identity found in System.keychain" >&2+ security find-identity -v -p codesigning /Library/Keychains/System.keychain >&2 || true+ exit 1+ fi+ echo "APPLE_SIGNING_IDENTITY=$identity" >> "$GITHUB_ENV"+ echo "Using signing identity: $identity"+ shell: bash+ env:+ MACOS_DEVELOPER_ID_CERTIFICATE_BASE64: ${{ secrets.MACOS_DEVELOPER_ID_CERTIFICATE_BASE64 }}+ MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD }}+ - id: metadata+ name: Derive artifact metadata+ run: |+ set -euo pipefail+ tag="${RAW_REF#refs/tags/}"+ if [ -z "$tag" ]; then+ tag="${GITHUB_REF_NAME:-untagged}"+ fi+ safe_tag=$(printf '%s' "$tag" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')+ echo "tag=$tag" >> "$GITHUB_OUTPUT"+ echo "safe_tag=$safe_tag" >> "$GITHUB_OUTPUT"+ shell: bash+ env:+ RAW_REF: ${{ inputs.ref }}+ - name: Build DMG with Nix+ run: |+ set -euo pipefail+ cachix_pid=+ if command -v cachix >/dev/null 2>&1 && [ -n "${CACHIX_CACHE_NAME:-}" ]; then+ cachix watch-store "$CACHIX_CACHE_NAME" >/tmp/cachix-watch-store.log 2>&1 &+ cachix_pid=$!+ trap 'if [ -n "${cachix_pid:-}" ]; then kill "$cachix_pid" 2>/dev/null || true; wait "$cachix_pid" 2>/dev/null || true; fi' EXIT+ fi+ nix build --impure --option sandbox false --print-build-logs ".#packages.aarch64-darwin.tauri-desktop-dmg"+ if command -v cachix >/dev/null 2>&1 && [ -n "${CACHIX_CACHE_NAME:-}" ]; then+ cachix push "$CACHIX_CACHE_NAME" result || echo "::warning::Failed to push DMG result closure to Cachix."+ fi+ shell: bash+ - name: Collect DMG artifact+ run: |+ set -euo pipefail+ mkdir -p artifacts+ shopt -s nullglob+ dmgs=(result/*.dmg)+ if [ "${#dmgs[@]}" -eq 0 ]; then+ echo "No DMG files found in nix build result" >&2+ find -L result -maxdepth 2 -type f -print >&2 || true+ exit 1+ fi+ cp -v "${dmgs[@]}" artifacts/+ shell: bash+ - name: Validate signed DMG+ run: |+ set -euo pipefail+ dmg=$(find artifacts -maxdepth 1 -type f -name '*.dmg' -print -quit)+ if [ -z "$dmg" ]; then+ echo "No DMG found to validate" >&2+ exit 1+ fi+ codesign --verify --strict --verbose=2 "$dmg"++ mount_dir=$(mktemp -d)+ hdiutil attach -readonly -nobrowse -mountpoint "$mount_dir" "$dmg"+ trap 'hdiutil detach "$mount_dir" >/dev/null 2>&1 || true; rmdir "$mount_dir" >/dev/null 2>&1 || true' EXIT+ app=$(find "$mount_dir" -maxdepth 2 -type d -name '*.app' -print -quit)+ if [ -z "$app" ] && [ -d "$mount_dir/Contents" ]; then+ app="$mount_dir"+ fi+ if [ -z "$app" ]; then+ echo "No app bundle found in DMG" >&2+ find "$mount_dir" -maxdepth 2 -print >&2 || true+ exit 1+ fi+ codesign --verify --deep --strict --verbose=2 "$app"++ dylib_refs=$(mktemp)+ search_roots=("$app/Contents/MacOS")+ if [ -d "$app/Contents/Frameworks" ]; then+ search_roots+=("$app/Contents/Frameworks")+ fi+ while IFS= read -r -d '' file; do+ otool -L "$file" 2>/dev/null \+ | awk -v file="$file" 'NR > 1 && $1 ~ "^/nix/store/.*\\.dylib$" { print file ": " $1 }' \+ >> "$dylib_refs" || true+ done < <(find "${search_roots[@]}" -type f -print0)+ if [ -s "$dylib_refs" ]; then+ echo "App bundle contains absolute Nix dylib references:" >&2+ cat "$dylib_refs" >&2+ exit 1+ fi++ (cd artifacts && shasum -a 256 -- *.dmg > SHA256SUMS)+ shell: bash+ - name: Upload macro-dmg-${{ steps.metadata.outputs.safe_tag }} artifact+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02+ with:+ name: macro-dmg-${{ steps.metadata.outputs.safe_tag }}+ path: artifacts/*+ if-no-files-found: error+ retention-days: '30'diff --git a/flake.lock b/flake.lockindex d3230bdfb6..be08a5f44f 100644--- a/flake.lock+++ b/flake.lock@@ -15,6 +15,21 @@"type": "github"}},+ "crane-tauri": {+ "locked": {+ "lastModified": 1781984549,+ "narHash": "sha256-iu/qgh21OB3C7MlI8cMPOltegTc0QTRHhbyqKdy21Yo=",+ "owner": "JPHutchins",+ "repo": "crane-tauri",+ "rev": "072afbfc844bd66f258b8380a5a3161ce9d83b4e",+ "type": "github"+ },+ "original": {+ "owner": "JPHutchins",+ "repo": "crane-tauri",+ "type": "github"+ }+ },"fenix": {"inputs": {"nixpkgs": [@@ -36,6 +51,24 @@"type": "github"}},+ "flake-parts": {+ "inputs": {+ "nixpkgs-lib": "nixpkgs-lib"+ },+ "locked": {+ "lastModified": 1778716662,+ "narHash": "sha256-m1Yf0wZ8j1OHjTc2UwHwyQRSnNeSgLJOd7q5Y45hzi4=",+ "owner": "hercules-ci",+ "repo": "flake-parts",+ "rev": "f7c1a2d347e4c52d5fb8d10cb4d94b5884e546fb",+ "type": "github"+ },+ "original": {+ "owner": "hercules-ci",+ "repo": "flake-parts",+ "type": "github"+ }+ },"flake-utils": {"inputs": {"systems": "systems"@@ -54,6 +87,21 @@"type": "github"}},+ "import-tree": {+ "locked": {+ "lastModified": 1778781969,+ "narHash": "sha256-Jjuz5CmSkur8KvLDoGa+vylEp+RkQtv4mt/qcMznpH0=",+ "owner": "vic",+ "repo": "import-tree",+ "rev": "d321337efd0f23a9eb14a42adb7b2c29313ab274",+ "type": "github"+ },+ "original": {+ "owner": "vic",+ "repo": "import-tree",+ "type": "github"+ }+ },"nixpkgs": {"locked": {"lastModified": 1781577229,@@ -70,32 +118,32 @@"type": "github"}},- "root": {- "inputs": {- "crane": "crane",- "fenix": "fenix",- "flake-utils": "flake-utils",- "nixpkgs": "nixpkgs",- "rs-libreoffice-bindings": "rs-libreoffice-bindings"- }- },- "rs-libreoffice-bindings": {- "flake": false,+ "nixpkgs-lib": {"locked": {- "lastModified": 1777577693,- "narHash": "sha256-lx/AuxPpCarxdDzogkGudCbE4B2OEt5un4s4gIFt1ek=",- "owner": "macro-inc",- "repo": "rs-libreoffice-bindings",- "rev": "056a40ddfac1d9650be30b9f0b4b934e9266c7dc",+ "lastModified": 1777168982,+ "narHash": "sha256-GOkGPcboWE9BmGCRMLX3worL4EMnsnG8MyKmXNeYuhQ=",+ "owner": "nix-community",+ "repo": "nixpkgs.lib",+ "rev": "f5901329dade4a6ea039af1433fb087bd9c1fe14","type": "github"},"original": {- "owner": "macro-inc",- "ref": "dev",- "repo": "rs-libreoffice-bindings",+ "owner": "nix-community",+ "repo": "nixpkgs.lib","type": "github"}},+ "root": {+ "inputs": {+ "crane": "crane",+ "crane-tauri": "crane-tauri",+ "fenix": "fenix",+ "flake-parts": "flake-parts",+ "flake-utils": "flake-utils",+ "import-tree": "import-tree",+ "nixpkgs": "nixpkgs"+ }+ },"rust-analyzer-src": {"flake": false,"locked": {diff --git a/flake.nix b/flake.nixindex 0dceceb252..24aa0fd121 100644--- a/flake.nix+++ b/flake.nix@@ -2,913 +2,14 @@inputs = {nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";flake-utils.url = "github:numtide/flake-utils";+ flake-parts.url = "github:hercules-ci/flake-parts";+ import-tree.url = "github:vic/import-tree";+fenix.url = "github:nix-community/fenix";fenix.inputs.nixpkgs.follows = "nixpkgs";crane.url = "github:ipetkov/crane";- rs-libreoffice-bindings.url = "github:macro-inc/rs-libreoffice-bindings/dev";- rs-libreoffice-bindings.flake = false;+ crane-tauri.url = "github:JPHutchins/crane-tauri";};- outputs =- {- self,- nixpkgs,- flake-utils,- fenix,- crane,- rs-libreoffice-bindings,- }:- flake-utils.lib.eachDefaultSystem (- system:- let- pkgs = import nixpkgs {- system = system;- };- isDarwin = pkgs.stdenv.isDarwin;- isLinux = pkgs.stdenv.isLinux;-- # ── cloud-storage (Rust backend) ──────────────────────────────-- rustToolchain = fenix.packages.${system}.fromToolchainFile {- file = ./rust/rust-toolchain.toml;- sha256 = "sha256-qqF33vNuAdU5vua96VKVIwuc43j4EFeEXbjQ6+l4mO4=";- };-- craneLib = (crane.mkLib pkgs).overrideToolchain rustToolchain;-- libraries =- with pkgs;- [- openssl- openssl.dev- glib- glib.dev- libclang- xz.out- ]- ++ pkgs.lib.optionals isLinux [- glibc.dev- gcc- ]- ++ pkgs.lib.optionals isDarwin [- libiconv- ];-- # Include Cargo sources plus the .sqlx offline query cache.- # rs-libreoffice-bindings lives outside the repo; we import it explicitly- # so the nix sandbox can resolve the path dep in convert_service.- sqlxFilter = path: _type: builtins.match ".*\\.sqlx/.*\\.json$" path != null;- pdfiumFilter = path: _type: builtins.match ".*pdfium-lib/.*\\.(so|dylib)$" path != null;- assetFilter = path: _type: builtins.match ".*\\.(md|html|txt|json|canvas|sql)$" path != null;- binFilter = path: _type: builtins.match ".*\\.bin$" path != null;- srcFilter =- path: type:- (sqlxFilter path type)- || (pdfiumFilter path type)- || (assetFilter path type)- || (binFilter path type)- || (craneLib.filterCargoSources path type);- cloudStorageSrc = pkgs.lib.cleanSourceWith {- src = ./rust/cloud-storage;- filter = srcFilter;- };- cSourceFilter = path: _type: builtins.match ".*\\.(c|h)$" path != null;- libreofficeBindingsSrc = pkgs.lib.cleanSourceWith {- src = rs-libreoffice-bindings;- filter = path: type: (cSourceFilter path type) || (craneLib.filterCargoSources path type);- };- src = pkgs.runCommand "cloud-storage-src" { } ''- cp -rT ${cloudStorageSrc} $out- chmod -R +w $out- cp -rT ${libreofficeBindingsSrc} $out/rs-libreoffice-bindings- '';-- # ── Per-artifact pruned deploy sources ────────────────────────- # .github/workspace-dep-closures.json (generated by `just hakari` via- # rust/cloud-storage/tools/xtask, drift-checked in CI) maps every workspace- # crate to its transitive workspace dependency- # closure. Each deploy leaf builds from a tree where only the crates in- # its closure keep real sources; every other member is reduced to its- # manifest plus a crane stub target. A leaf's store hash then only- # moves when a crate it actually depends on changes — an email-only- # change leaves the other deploy derivations as pure substitutions- # (sticky disk / Cachix) instead of full workspace-subgraph rebuilds.- # Manifest or Cargo.lock changes still invalidate every leaf (the stub- # layer embeds them all); those are the rare structural commits.- #- # Soundness: a stale map fails loud, not silent. A missing closure- # crate means its stub (empty lib) gets compiled and the dependent- # crate fails to resolve its items; a deleted dir fails at eval. CI- # regenerates the map and rejects drift before merge.- workspaceDepClosures =- (builtins.fromJSON (builtins.readFile ./.github/workspace-dep-closures.json)).closures;-- # Manifests + Cargo.lock + stub targets for every member, shared by all- # pruned sources; only changes when a manifest or the lock changes.- deployDummySrc = craneLib.mkDummySrc { inherit src; };-- # Real sources of one workspace crate dir, same filter as the full tree- # (keeps per-crate assets: pdfium blobs, .sql migrations, templates).- crateDirSrc =- dir:- pkgs.lib.cleanSourceWith {- src = ./rust/cloud-storage + "/${dir}";- filter = srcFilter;- name = "crate-${builtins.replaceStrings [ "/" ] [ "-" ] dir}";- };-- # Workspace-root files that crates read across crate boundaries: the- # .sqlx offline cache (sqlx macros resolve it from the workspace root)- # and loose root assets like markdown-golden.1.bin (include_bytes!-ed- # from the documents crate). Included in every pruned source, so a- # sqlx prepare still invalidates all leaves — coarser than ideal, but- # the query-to-crate mapping is not recoverable from the file names.- rootDepsSrc = pkgs.lib.cleanSourceWith {- src = ./rust/cloud-storage;- name = "cloud-storage-root-deps";- filter =- path: type:- let- rel = pkgs.lib.removePrefix ((toString ./rust/cloud-storage) + "/") (toString path);- in- (rel == ".sqlx")- || (pkgs.lib.hasPrefix ".sqlx/" rel)- || (- type == "regular"- && !(pkgs.lib.hasInfix "/" rel)- && ((assetFilter path type) || (binFilter path type))- );- };-- prunedDeploySrc =- pname: rootPackage:- let- # Generator emits dirs sorted, so parents always precede nested- # members and overlays land inside already-materialised parents.- dirs =- workspaceDepClosures.${rootPackage} or (throw (- "No '${rootPackage}' entry in .github/workspace-dep-closures.json; "- + "run `just hakari` from rust/cloud-storage and commit the result."- ));- overlays = pkgs.lib.concatMapStrings (dir: ''- rm -rf "$out/${dir}"- cp -rT ${crateDirSrc dir} "$out/${dir}"- chmod -R +w "$out/${dir}"- '') dirs;- in- pkgs.runCommand "cloud-storage-src-${pname}" { } ''- cp -rT ${deployDummySrc} $out- chmod -R +w $out- cp -rfT ${rootDepsSrc} $out- chmod -R +w $out- ${overlays}- rm -rf $out/rs-libreoffice-bindings- cp -rT ${libreofficeBindingsSrc} $out/rs-libreoffice-bindings- '';-- commonArgs = {- inherit src;- pname = "cloud-storage";- version = "0.1.0";- strictDeps = true;- buildInputs = libraries;- # Cargo/crane need git in the sandbox to fetch git dependencies.- # Without this, CI can fall back to host /usr/lib/git-core helpers,- # which are not ABI-compatible with Nix-provided glibc.- nativeBuildInputs = with pkgs; [ git pkg-config ] ++ pkgs.lib.optionals isLinux [ mold ];- LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";- OPENSSL_NO_VENDOR = "1";- SQLX_OFFLINE = "true";- # Keep vendoring independent of the generated src derivation and pin- # git dependencies so Nix does not fall back to host git helpers in CI.- cargoVendorDir = craneLib.vendorCargoDeps {- src = ./rust/cloud-storage;- cargoLock = ./rust/cloud-storage/Cargo.lock;- outputHashes = {- "git+https://github.com/whutchinson98/jsonwebtoken#c8c0d19511a0e7ba9d456e21437a79d321e99f16" = "sha256-jllT52SAIiNpTPg7Vm3wmT79w/CIz9NnVKM81oQq8dM=";- "git+https://github.com/macro-inc/rig?branch=feat/responses-api-non-strict-tools#6deadfc6f9b432c849ea79733a549f46407530b7" = "sha256-EcmlwqAVXGtbuvozzCOrygoSVipU99mBZK/MrQAIoYg=";- "git+https://github.com/macro-inc/rs-libreoffice-bindings?rev=056a40ddfac1d9650be30b9f0b4b934e9266c7dc#056a40ddfac1d9650be30b9f0b4b934e9266c7dc" = "sha256-lx/AuxPpCarxdDzogkGudCbE4B2OEt5un4s4gIFt1ek=";- };- };- RUSTFLAGS = pkgs.lib.optionalString isLinux "-C link-arg=-fuse-ld=mold";- # Build deps + workspace + bins in dev profile so the test job (which runs- # `cargo nextest` outside the sandbox using the test profile, inheriting dev)- # can reuse the restored target/debug/ instead of recompiling all deps.- CARGO_PROFILE = "dev";- }- // pkgs.lib.optionalAttrs isLinux {- LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libraries}";- BINDGEN_EXTRA_CLANG_ARGS = "-I${pkgs.glibc.dev}/include -I${pkgs.gcc.cc}/lib/gcc/${pkgs.stdenv.hostPlatform.config}/${pkgs.gcc.version}/include";- };-- # Pre-built third-party deps — Cachix caches this; hash is driven by Cargo.lock- # (workspace member sources are stubbed by crane), so it survives most PRs.- # --all-features matches the test job (cargo nextest --all-features) and clippy- # so all consumers share the same dep feature unification.- cargoArtifacts = craneLib.buildDepsOnly (- commonArgs- // {- cargoExtraArgs = "--locked --all-features";- }- );-- # Layered atop cargoArtifacts: pre-compile every workspace lib crate so- # downstream derivations (openApiBins, clippy) inherit a warm target/. The- # hash is per-source so cachix only hits when the SHA matches across CI- # workflows — but since code-check-cloud-storage and web-app-check-main both- # run on the same SHA, whichever finishes first pushes for the other.- workspaceArtifacts = craneLib.cargoBuild (- commonArgs- // {- inherit cargoArtifacts;- pname = "cloud-storage-workspace";- doCheck = false;- doInstallCargoArtifacts = true;- cargoExtraArgs = "--locked --all-features --workspace --lib";- RUSTFLAGS = "-Dwarnings" + pkgs.lib.optionalString isLinux " -C link-arg=-fuse-ld=mold";- RUSTDOCFLAGS = "-Dwarnings";- }- );-- cloudStorageCargoToml = builtins.fromTOML (builtins.readFile ./rust/cloud-storage/Cargo.toml);- cloudStorageWorkspaceMembers =- cloudStorageCargoToml.workspace.members or (throw "rust/cloud-storage/Cargo.toml is missing workspace.members");-- dopplerConfigBinNames =- let- dopplerConfigPath = "src/doppler_config.rs";- matchingDopplerBins =- member:- let- memberDir = ./rust/cloud-storage + "/${member}";- manifestFile = memberDir + "/Cargo.toml";- hasConfig = builtins.pathExists (memberDir + "/src/config.rs");- hasDopplerConfig = builtins.pathExists (memberDir + "/${dopplerConfigPath}");- manifest = builtins.fromTOML (builtins.readFile manifestFile);- matchingBins = builtins.filter (bin: (bin.path or null) == dopplerConfigPath) (manifest.bin or [ ]);- missingNameError =- "cloud-storage workspace member '${member}' has a ${dopplerConfigPath} bin without a name";- matchingBinNames = map (bin: bin.name or (throw missingNameError)) matchingBins;- in- if !hasDopplerConfig then- [ ]- else if !(builtins.pathExists manifestFile) then- throw "cloud-storage workspace member '${member}' has ${dopplerConfigPath} but no Cargo.toml"- else if matchingBinNames == [ ] then- throw (- "cloud-storage workspace member '${member}' has ${dopplerConfigPath} "- + "but no [[bin]] with path = \"${dopplerConfigPath}\""- )- else if !hasConfig then- [ ]- else- matchingBinNames;- in- pkgs.lib.unique (pkgs.lib.concatMap matchingDopplerBins cloudStorageWorkspaceMembers);-- dopplerConfigBinPackages = builtins.listToAttrs (- map (- binName:- pkgs.lib.nameValuePair "doppler-config-bin-${binName}" (- craneLib.buildPackage (- commonArgs- // {- # Reuse the dependency-only layer, then compile only this- # Doppler config binary and the local crates it actually uses.- inherit cargoArtifacts;- pname = "cloud-storage-doppler-config-${binName}";- doCheck = false;- cargoExtraArgs = pkgs.lib.concatStringsSep " " [- "--locked"- "--all-features"- "--bin ${binName}"- ];- }- )- )- ) dopplerConfigBinNames- );-- dopplerConfigBins = pkgs.symlinkJoin {- name = "cloud-storage-doppler-config";- paths = builtins.attrValues dopplerConfigBinPackages;- };-- openApiBins = craneLib.buildPackage (- commonArgs- // {- cargoArtifacts = workspaceArtifacts;- pname = "cloud-storage-openapi";- doCheck = false;- cargoExtraArgs = pkgs.lib.concatStringsSep " " [- "--locked"- "--all-features"- "--bin document_storage_service_openapi"- "--bin properties_service_openapi"- "--bin document_cognition_service_openapi"- "--bin authentication_service_openapi"- "--bin notification_service_openapi"- "--bin static_file_service_openapi"- "--bin connection_gateway_openapi"- "--bin contacts_service_openapi"- "--bin unfurl_service_openapi"- "--bin email_service_openapi"- "--bin search_service_openapi"- "--bin scheduled_action_openapi"- "--bin document_cognition_service_models"- "--bin gen_tool_schemas"- ];- }- );-- # Pre-built nextest archive — packages all compiled test binaries plus their- # metadata into a single tar.zst. CI fetches this archive and runs- # `cargo nextest run --archive-file` outside the sandbox so tests can hit- # postgres/redis services. Built in nix → cached by cachix.- nextestArchive = craneLib.mkCargoDerivation (- commonArgs- // {- cargoArtifacts = workspaceArtifacts;- pname = "cloud-storage-nextest-archive";- doCheck = false;- nativeBuildInputs = commonArgs.nativeBuildInputs or [ ] ++ [ pkgs.cargo-nextest ];- buildPhaseCargoCommand = ''- cargo nextest archive \- --cargo-profile dev \- --locked --all-features \- --workspace --lib --bins --tests \- --archive-file nextest-archive.tar.zst- '';- installPhaseCommand = ''- mkdir -p $out- cp nextest-archive.tar.zst $out/- '';- }- );-- deployServiceBinaryDefinitions = [- {- serviceName = "agent-schedule-service";- packageName = "scheduled_action";- binaries = [ "service" ];- }- {- serviceName = "authentication-service";- packageName = "authentication_service";- binaries = [ "authentication_service" ];- }- {- serviceName = "connection-gateway";- packageName = "connection_gateway";- binaries = [ "connection_gateway_service" ];- }- {- serviceName = "contacts-service";- packageName = "contacts_service";- binaries = [ "contacts_service" ];- }- {- serviceName = "convert-service";- packageName = "convert_service";- binaries = [ "convert_service" ];- }- {- serviceName = "document-cognition-service";- packageName = "document_cognition_service";- binaries = [ "document_cognition_service" ];- }- {- serviceName = "document-storage-service";- packageName = "document_storage_service";- binaries = [ "document_storage_service" ];- }- {- serviceName = "email-service";- packageName = "email_service";- binaries = [- "email_service"- "pubsub_workers"- ];- }- {- serviceName = "image-proxy-service";- packageName = "image_proxy_service";- binaries = [ "image_proxy_service" ];- }- {- serviceName = "mcp-server";- packageName = "mcp_service";- binaries = [ "mcp_service" ];- }- {- serviceName = "notification-service";- packageName = "notification_service";- binaries = [ "notification_service" ];- }- {- serviceName = "search-processing-service";- packageName = "search_processing_service";- binaries = [ "search_processing_service" ];- }- {- serviceName = "static-file-service";- packageName = "static_file_service";- binaries = [ "static_file_service" ];- }- {- serviceName = "unfurl-service";- packageName = "unfurl_service";- binaries = [ "unfurl_service" ];- }- ];-- deployBinaryCargoExtraArgs =- "--locked "- + pkgs.lib.concatMapStringsSep " " (- def:- "--package ${def.packageName} "- + pkgs.lib.concatMapStringsSep " " (binary: "--bin ${binary}") def.binaries- ) deployServiceBinaryDefinitions;-- deployCargoArtifacts = craneLib.buildDepsOnly (- commonArgs- // {- pname = "cloud-storage-deploy-deps";- doCheck = false;- # buildDepsOnly runs a cargo check in buildPhase by default; keep this- # warm artifact to release deps only.- cargoCheckCommand = "true";- cargoExtraArgs = deployBinaryCargoExtraArgs;- CARGO_PROFILE = "release";- }- );-- deployServiceBinaryPackage =- {- serviceName,- packageName,- binaries,- }:- craneLib.buildPackage (- commonArgs- // {- # Pruned source: this derivation only rebuilds when a crate in- # the service's own workspace closure changes.- src = prunedDeploySrc "service-${serviceName}" packageName;- cargoArtifacts = deployCargoArtifacts;- pname = "cloud-storage-${serviceName}-binaries";- doCheck = false;- cargoExtraArgs =- "--locked --package ${packageName} "- + pkgs.lib.concatMapStringsSep " " (binary: "--bin ${binary}") binaries;- CARGO_PROFILE = "release";- installPhaseCommand = ''- mkdir -p $out/bin- for binary in ${pkgs.lib.concatStringsSep " " binaries}; do- cp target/release/$binary $out/bin/$binary- ${pkgs.binutils}/bin/strip $out/bin/$binary || true- done- '';- }- );-- deployServiceBinaryPackages = pkgs.lib.listToAttrs (- map (def: {- name = "deploy-service-binaries-${def.serviceName}";- value = deployServiceBinaryPackage def;- }) deployServiceBinaryDefinitions- );-- # ── Lambda builds (crane + cargo-zigbuild) ─────────────────────- # SPIKE: build a Rust Lambda handler reproducibly under nix/crane so- # lambdas ride the same content-addressed cache as the service binaries- # (nix store + Cachix + sticky disk) instead of a cargo-in-checkout that- # recompiles the workspace every run. cargo-zigbuild pins the Lambda- # glibc via a target *suffix* (no toolchain swap; host triple == lambda- # triple, so no extra rust-std). The binary is renamed `bootstrap` and- # zipped for the provided.al2/al2023 custom runtime.- lambdaTarget = "x86_64-unknown-linux-gnu";- # glibc 2.26 == Amazon Linux 2; forward-compatible with al2023.- lambdaZigTarget = "${lambdaTarget}.2.26";-- callRecordingPreviewFfmpegLayer =- let- ffmpegVersion = "7.0.2";- ffmpegArchive = pkgs.fetchurl {- url = "https://johnvansickle.com/ffmpeg/releases/ffmpeg-${ffmpegVersion}-amd64-static.tar.xz";- hash = "sha256-q9qNd86DCRQfg6uO3wWWg0CHxSRn9rrfN2pqKkyHz2c=";- };- in- pkgs.runCommand "call-recording-preview-ffmpeg-layer"- {- nativeBuildInputs = [- pkgs.coreutils- pkgs.gnutar- pkgs.unzip- pkgs.xz- pkgs.zip- ];- }- ''- set -euo pipefail-- archive_dir="ffmpeg-${ffmpegVersion}-amd64-static"- mkdir -p extract package/bin "$out/call_recording_preview_handler"- tar -xJf ${ffmpegArchive} -C extract \- "$archive_dir/ffmpeg" \- "$archive_dir/ffprobe"- install -m 0755 "extract/$archive_dir/ffmpeg" package/bin/ffmpeg- install -m 0755 "extract/$archive_dir/ffprobe" package/bin/ffprobe- touch -h -d @315532800 package/bin/ffmpeg package/bin/ffprobe-- (- cd package- zip -9 -q -X "$out/call_recording_preview_handler/ffmpeg-layer.zip" bin/ffmpeg bin/ffprobe- )- unzip -tqq "$out/call_recording_preview_handler/ffmpeg-layer.zip" >/dev/null- '';-- lambdaCommonArgs = commonArgs // {- # zig links the final binary (cargo-zigbuild); drop the host-only mold arg.- RUSTFLAGS = "";- CARGO_PROFILE = "release";- # Lambdas don't need max opt; matches the cargo-lambda CI setting.- CARGO_PROFILE_RELEASE_OPT_LEVEL = "2";- # aws-lc-sys (aws-lc-rs / rustls default crypto, pulled via aws-sdk &- # sqlx) has a cc-builder guard that rejects the zig C compiler. Force- # its cmake builder instead, which has no such guard and still compiles- # the C against the zig-pinned glibc. cmake + nasm are its build deps.- AWS_LC_SYS_CMAKE_BUILDER = "1";- nativeBuildInputs = (commonArgs.nativeBuildInputs or [ ]) ++ [- pkgs.cargo-zigbuild- pkgs.zig- pkgs.cmake- pkgs.nasm- ];- # zig needs a writable cache inside the sandbox ($HOME is read-only).- preBuild = ''- export ZIG_GLOBAL_CACHE_DIR="$TMPDIR/zig-cache"- export ZIG_LOCAL_CACHE_DIR="$TMPDIR/zig-cache"- export XDG_CACHE_HOME="$TMPDIR/xdg"-- # Inherited cargoArtifacts can carry CMake configure state- # (CMakeCache.txt / CMakeFiles) from the deps-only layer. Its- # CMAKE_C_COMPILER points at a cargo-zigbuild wrapper script under- # $TMPDIR whose hash-suffixed name need not exist in this sandbox,- # and CMake hard-fails validating a cached compiler that is gone- # ("is not a full path to an existing compiler tool"). Drop the- # configure state so a build-script re-run reconfigures cleanly;- # crates whose fingerprints are clean never read it, so this costs- # nothing on the cached path. (Today aws-lc-sys is the only cmake- # crate in the graph, via AWS_LC_SYS_CMAKE_BUILDER below.)- tdir="''${CARGO_TARGET_DIR:-target}"- if [ -d "$tdir" ]; then- while IFS= read -r -d "" cache; do- dir="$(dirname "$cache")"- echo "purging stale cmake configure state in $dir"- rm -rf "$dir/CMakeFiles" "$cache"- done < <(find "$tdir" -name CMakeCache.txt -print0)- fi- '';- };-- # Every handler deployed as a lambda, read straight from the deploy- # config so the flake never drifts from services-config.json. For every- # handler, crate name == dir name == deploy_lambdas entry.- lambdaNames =- let- cfg = builtins.fromJSON (builtins.readFile ./.github/services-config.json);- in- pkgs.lib.unique (- pkgs.lib.concatMap (svc: svc.deploy_lambdas or [ ]) (pkgs.lib.attrValues cfg.services)- );-- # One shared dep closure for all lambda handlers. Build it with the same- # cargo-zigbuild target used by the final packages; Cargo fingerprints the- # `.2.26` target separately from the plain triple, so warming the plain- # target does not help the deploy builds.- lambdaDeployCargoArtifacts = craneLib.buildDepsOnly (- lambdaCommonArgs- // {- pname = "cloud-storage-lambda-deps";- doCheck = false;- # buildDepsOnly runs a cargo check in buildPhase by default; keep this- # warm artifact to release deps only.- cargoCheckCommand = "true";- cargoBuildCommand = "cargo zigbuild --release";- cargoExtraArgs =- "--locked --target ${lambdaZigTarget} "- + pkgs.lib.concatMapStringsSep " " (n: "--package ${n}") lambdaNames;- }- );-- # bin name == crate name == handler dir name (see per-lambda justfiles).- deployLambdaPackage =- lambdaName:- craneLib.buildPackage (- lambdaCommonArgs- // {- # Pruned source: this derivation only rebuilds when a crate in- # the handler's own workspace closure changes.- src = prunedDeploySrc "lambda-${lambdaName}" lambdaName;- cargoArtifacts = lambdaDeployCargoArtifacts;- pname = "cloud-storage-lambda-${lambdaName}";- doCheck = false;- # cargo-zigbuild links the final binary against the pinned Lambda- # glibc, selected via the `.2.26` target suffix.- cargoBuildCommand = "cargo zigbuild --release";- cargoExtraArgs = "--locked --target ${lambdaZigTarget} --bin ${lambdaName}";- # Emit the Lambda custom-runtime artifact: a zip whose single entry- # is named `bootstrap`, mirroring cargo-lambda's- # target/lambda/<name>/bootstrap.zip layout. zigbuild writes to- # target/<triple>/release (suffix stripped from the dir name).- installPhaseCommand = ''- mkdir -p "$out/${lambdaName}"- cp "target/${lambdaTarget}/release/${lambdaName}" bootstrap- ${pkgs.binutils}/bin/strip bootstrap || true- ${pkgs.zip}/bin/zip -j -X "$out/${lambdaName}/bootstrap.zip" bootstrap- ${pkgs.lib.optionalString (lambdaName == "document_text_extractor") ''- # Mirror the handler justfile's `cargo lambda build --include- # ./pdfium-lib/linux`: at runtime the binary dlopen's- # ./pdfium-lib/linux/libpdfium.so relative to the Lambda task- # root, so the blob has to ride along in bootstrap.zip at that- # same relative path.- ( cd ${lambdaName} && ${pkgs.zip}/bin/zip -r -X "$out/${lambdaName}/bootstrap.zip" pdfium-lib/linux )- ''}- ${pkgs.lib.optionalString (lambdaName == "call_recording_preview_handler") ''- cp "${callRecordingPreviewFfmpegLayer}/${lambdaName}/ffmpeg-layer.zip" "$out/${lambdaName}/ffmpeg-layer.zip"- ''}- '';- }- );-- deployLambdaPackages = pkgs.lib.listToAttrs (- map (n: {- name = "deploy-lambda-${n}";- value = deployLambdaPackage n;- }) lambdaNames- );-- shellTools =- with pkgs;- [- parallel- docker-compose- curl- xz- unzip- zip- cargo-info- cargo-udeps- cargo-lambda- cargo-zigbuild- zig- cmake- nasm- (writeShellScriptBin "rustup" ''- set -euo pipefail- rustc_path="$(${coreutils}/bin/readlink -f "$(command -v rustc)")"- toolchain="$(${coreutils}/bin/basename "$(${coreutils}/bin/dirname "$(${coreutils}/bin/dirname "$rustc_path")")")"- case "$1 $2" in- "toolchain list") echo "$toolchain (default)" ;;- "toolchain add") exit 0 ;;- "target list") echo "x86_64-unknown-linux-gnu (installed)"; echo "aarch64-unknown-linux-gnu"; echo "wasm32-unknown-unknown (installed)" ;;- "target add") exit 0 ;;- "component list") echo "rust-src-x86_64-unknown-linux-gnu (installed)"; echo "clippy-x86_64-unknown-linux-gnu (installed)" ;;- "component add") exit 0 ;;- *) echo "rustup shim only supports commands used by cross" >&2; exit 1 ;;- esac- '')- cargo-cross- cargo-deny- cargo-nextest- cargo-expand- wasm-pack- pkg-config- bacon- just- just-lsp- taplo- bun- pnpm- sqlx-cli- typescript-language-server- nodejs_24- pulumi- pulumiPackages.pulumi-nodejs- doppler- biome- jq- stripe-cli- sccache- rustToolchain- python3- ]- ++ pkgs.lib.optionals isLinux [ mold ];-- # ── js-app (frontend Tauri app) ────────────────────────────────-- # Need allowUnfree + android license for the Android SDK- jsPkgs = import nixpkgs {- inherit system;- config.allowUnfree = true;- config.android_sdk.accept_license = true;- };-- android_sdk = pkgs.lib.optionalAttrs isLinux (- (jsPkgs.androidenv.composeAndroidPackages {- platformVersions = [- "34"- "36"- ];- buildToolsVersions = [- "35.0.0"- ];- ndkVersions = [ "26.3.11579264" ];- includeNDK = true;- useGoogleAPIs = false;- useGoogleTVAddOns = false;- includeEmulator = true;- includeSystemImages = true;- systemImageTypes = [ "google_apis_playstore" ];- abiVersions = [ "x86_64" ];- includeSources = false;- }).androidsdk- );-- jsBasePackages = with jsPkgs; [- curl- wget- pkg-config- just- bun- biome- nodejs_24- typescript-language-server- cargo-tauri- cargo-info- cargo-udeps- pulumi- pulumiPackages.pulumi-nodejs- pulumiPackages.pulumi-aws-native- playwright- playwright-mcp- (- with fenix.packages.${system};- combine (- [- complete.rustc- complete.rust-src- complete.cargo- complete.clippy- complete.rustfmt- complete.rust-analyzer- ]- ++ pkgs.lib.optionals isLinux [- targets.aarch64-linux-android.latest.rust-std- targets.armv7-linux-androideabi.latest.rust-std- targets.i686-linux-android.latest.rust-std- targets.x86_64-linux-android.latest.rust-std- ]- )- )- ];-- jsLinuxPackages = with jsPkgs; [- gst_all_1.gstreamer- gst_all_1.gst-plugins-base- gst_all_1.gst-plugins-good- gst_all_1.gst-plugins-bad- jdk- xdg-utils- ];-- jsPackages = jsBasePackages ++ pkgs.lib.optionals isLinux (jsLinuxPackages ++ [ android_sdk ]);-- jsLinuxLibraries = with jsPkgs; [- gtk3- libsoup_3- webkitgtk_4_1- cairo- gdk-pixbuf- glib- dbus- openssl- librsvg- lsb-release- ];-- jsDarwinLibraries = with jsPkgs; [- openssl- libiconv- ];-- jsLibraries = if isDarwin then jsDarwinLibraries else jsLinuxLibraries;- in- {- checks = {- fmt = craneLib.cargoFmt {- inherit src;- pname = "cloud-storage";- version = "0.1.0";- };- clippy = craneLib.cargoClippy (- commonArgs- // {- cargoArtifacts = workspaceArtifacts;- cargoClippyExtraArgs = "--all-features -- -D warnings";- RUSTDOCFLAGS = "-Dwarnings";- }- );- doppler-config-bins = dopplerConfigBins;- gen-api =- let- openApiFiles = pkgs.lib.cleanSourceWith {- src = ./js/app/packages/service-clients;- filter = path: type: type == "directory" || pkgs.lib.hasSuffix "openapi.json" (baseNameOf path);- };- crateToDir = {- document_storage_service = "service-storage";- properties_service = "service-properties";- document_cognition_service = "service-cognition";- authentication_service = "service-auth";- notification_service = "service-notification";- static_file_service = "service-static-files";- connection_gateway = "service-connection";- contacts_service = "service-contacts";- unfurl_service = "service-unfurl";- email_service = "service-email";- search_service = "service-search";- scheduled_action = "service-scheduled-action";- };- checkScript = pkgs.lib.concatStringsSep "\n" (- pkgs.lib.mapAttrsToList (crate: dir: ''- echo -n "Checking ${dir}/openapi.json ... "- if ! diff \- <("${openApiBins}/bin/${crate}_openapi" | ${pkgs.jq}/bin/jq --sort-keys .) \- <(${pkgs.jq}/bin/jq --sort-keys . < "${openApiFiles}/${dir}/openapi.json"); then- echo "FAIL: run 'bun run gen-api' and commit the result"- exit 1- fi- echo "ok"- '') crateToDir- );- in- pkgs.runCommand "cloud-storage-gen-api-check" { RUST_LOG = "error"; } ''- ${checkScript}- touch $out- '';- };-- packages = {- inherit- cargoArtifacts- callRecordingPreviewFfmpegLayer- workspaceArtifacts- deployCargoArtifacts- lambdaDeployCargoArtifacts- openApiBins- dopplerConfigBins- nextestArchive- ;- default = cargoArtifacts;- }- // dopplerConfigBinPackages- // deployServiceBinaryPackages- // deployLambdaPackages;-- devShells = {- default = pkgs.mkShell (- {- buildInputs = shellTools ++ libraries;- PKG_CONFIG_PATH = "${pkgs.openssl.dev}/lib/pkgconfig";- LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";- RUSTC_WRAPPER = "${pkgs.sccache}/bin/sccache";- # Keep local cargo-lambda builds on the same aws-lc-sys path as- # the Nix lambda derivations. The default cc builder rejects- # cargo-lambda/cargo-zigbuild's Zig cc wrapper.- AWS_LC_SYS_CMAKE_BUILDER = "1";- }- // pkgs.lib.optionalAttrs isLinux {- LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libraries}";- BINDGEN_EXTRA_CLANG_ARGS = "-I${pkgs.glibc.dev}/include -I${pkgs.gcc.cc}/lib/gcc/${pkgs.stdenv.hostPlatform.config}/${pkgs.gcc.version}/include";- }- );- js-app = jsPkgs.mkShell (- {- buildInputs = jsPackages ++ jsLibraries;- PKG_CONFIG_PATH = "${jsPkgs.openssl.dev}/lib/pkgconfig";- }- // pkgs.lib.optionalAttrs isLinux {- LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath jsLibraries}:$LD_LIBRARY_PATH";- XDG_DATA_DIRS = "${jsPkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${jsPkgs.gsettings-desktop-schemas.name}:${jsPkgs.gtk3}/share/gsettings-schemas/${jsPkgs.gtk3.name}:$XDG_DATA_DIRS";- ANDROID_HOME = "${android_sdk}/libexec/android-sdk";- NDK_HOME = "${android_sdk}/libexec/android-sdk/ndk/26.3.11579264";- GRADLE_OPTS = "-Dorg.gradle.project.android.aapt2FromMavenOverride=${android_sdk}/libexec/android-sdk/build-tools/35.0.0/aapt2";- GIO_MODULE_DIR = "${jsPkgs.glib-networking}/lib/gio/modules/";- }- );- };- }- );+ outputs = inputs: inputs.flake-parts.lib.mkFlake { inherit inputs; } (inputs.import-tree ./nix);}diff --git a/js/app/flake.lock b/js/app/flake.lockdeleted file mode 100644index f08a2c9042..0000000000--- a/js/app/flake.lock+++ /dev/null@@ -1,100 +0,0 @@-{- "nodes": {- "fenix": {- "inputs": {- "nixpkgs": [- "nixpkgs"- ],- "rust-analyzer-src": "rust-analyzer-src"- },- "locked": {- "lastModified": 1776240401,- "narHash": "sha256-S9m5SrxUT6dNPZrCscuQR2zLD3QIAlUlvlXchPKBnxs=",- "owner": "nix-community",- "repo": "fenix",- "rev": "a30830ebacdf957690dd8ea9ade9f12809ae0982",- "type": "github"- },- "original": {- "owner": "nix-community",- "repo": "fenix",- "type": "github"- }- },- "flake-utils": {- "inputs": {- "systems": "systems"- },- "locked": {- "lastModified": 1731533236,- "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",- "owner": "numtide",- "repo": "flake-utils",- "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",- "type": "github"- },- "original": {- "owner": "numtide",- "repo": "flake-utils",- "type": "github"- }- },- "nixpkgs": {- "locked": {- "lastModified": 1775710090,- "narHash": "sha256-ar3rofg+awPB8QXDaFJhJ2jJhu+KqN/PRCXeyuXR76E=",- "owner": "NixOS",- "repo": "nixpkgs",- "rev": "4c1018dae018162ec878d42fec712642d214fdfa",- "type": "github"- },- "original": {- "owner": "NixOS",- "ref": "nixos-unstable",- "repo": "nixpkgs",- "type": "github"- }- },- "root": {- "inputs": {- "fenix": "fenix",- "flake-utils": "flake-utils",- "nixpkgs": "nixpkgs"- }- },- "rust-analyzer-src": {- "flake": false,- "locked": {- "lastModified": 1776173606,- "narHash": "sha256-o2ism66hEAnfWZSUMs22KX5zpMZDxS/Bg4N/HcDCkXM=",- "owner": "rust-lang",- "repo": "rust-analyzer",- "rev": "17d028e9d7161cf6ebf21e21d3c4a1835099e039",- "type": "github"- },- "original": {- "owner": "rust-lang",- "ref": "nightly",- "repo": "rust-analyzer",- "type": "github"- }- },- "systems": {- "locked": {- "lastModified": 1681028828,- "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",- "owner": "nix-systems",- "repo": "default",- "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",- "type": "github"- },- "original": {- "owner": "nix-systems",- "repo": "default",- "type": "github"- }- }- },- "root": "root",- "version": 7-}diff --git a/js/app/tauri/src-tauri/tauri.conf.json b/js/app/tauri/src-tauri/tauri.conf.jsonindex aec4c949f2..4526ac5b70 100644--- a/js/app/tauri/src-tauri/tauri.conf.json+++ b/js/app/tauri/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "macro",- "version": "2.0.5",+ "version": "../../packages/app/package.json","identifier": "com.macro.app.prod","build": {"frontendDist": "../../packages/app/dist",diff --git a/nix/cloud-storage.nix b/nix/cloud-storage.nixnew file mode 100644index 0000000000..b1a462d321--- /dev/null+++ b/nix/cloud-storage.nix@@ -0,0 +1,784 @@+{ inputs, ... }:+{+ perSystem =+ { system, ... }:+ let+ inherit (inputs)+ nixpkgs+ fenix+ crane+ ;+ pkgs = import nixpkgs {+ system = system;+ };+ isDarwin = pkgs.stdenv.isDarwin;+ isLinux = pkgs.stdenv.isLinux;++ # ── cloud-storage (Rust backend) ──────────────────────────────++ rustToolchain = fenix.packages.${system}.fromToolchainFile {+ file = ../rust/rust-toolchain.toml;+ sha256 = "sha256-qqF33vNuAdU5vua96VKVIwuc43j4EFeEXbjQ6+l4mO4=";+ };++ craneLib = (crane.mkLib pkgs).overrideToolchain rustToolchain;++ libraries =+ with pkgs;+ [+ openssl+ openssl.dev+ glib+ glib.dev+ libclang+ xz.out+ ]+ ++ pkgs.lib.optionals isLinux [+ glibc.dev+ gcc+ ]+ ++ pkgs.lib.optionals isDarwin [+ libiconv+ ];++ # Include Cargo sources plus the .sqlx offline query cache.+ sqlxFilter = path: _type: builtins.match ".*\\.sqlx/.*\\.json$" path != null;+ pdfiumFilter = path: _type: builtins.match ".*pdfium-lib/.*\\.(so|dylib)$" path != null;+ assetFilter = path: _type: builtins.match ".*\\.(md|html|txt|json|canvas|sql)$" path != null;+ binFilter = path: _type: builtins.match ".*\\.bin$" path != null;+ srcFilter =+ path: type:+ (sqlxFilter path type)+ || (pdfiumFilter path type)+ || (assetFilter path type)+ || (binFilter path type)+ || (craneLib.filterCargoSources path type);+ cloudStorageSrc = pkgs.lib.cleanSourceWith {+ src = ../rust/cloud-storage;+ filter = srcFilter;+ };+ src = cloudStorageSrc;++ # ── Per-artifact pruned deploy sources ────────────────────────+ # .github/workspace-dep-closures.json (generated by `just hakari` via+ # rust/cloud-storage/tools/xtask, drift-checked in CI) maps every workspace+ # crate to its transitive workspace dependency+ # closure. Each deploy leaf builds from a tree where only the crates in+ # its closure keep real sources; every other member is reduced to its+ # manifest plus a crane stub target. A leaf's store hash then only+ # moves when a crate it actually depends on changes — an email-only+ # change leaves the other deploy derivations as pure substitutions+ # (sticky disk / Cachix) instead of full workspace-subgraph rebuilds.+ # Manifest or Cargo.lock changes still invalidate every leaf (the stub+ # layer embeds them all); those are the rare structural commits.+ #+ # Soundness: a stale map fails loud, not silent. A missing closure+ # crate means its stub (empty lib) gets compiled and the dependent+ # crate fails to resolve its items; a deleted dir fails at eval. CI+ # regenerates the map and rejects drift before merge.+ workspaceDepClosures =+ (builtins.fromJSON (builtins.readFile ../.github/workspace-dep-closures.json)).closures;++ # Manifests + Cargo.lock + stub targets for every member, shared by all+ # pruned sources; only changes when a manifest or the lock changes.+ deployDummySrc = craneLib.mkDummySrc { inherit src; };++ # Real sources of one workspace crate dir, same filter as the full tree+ # (keeps per-crate assets: pdfium blobs, .sql migrations, templates).+ crateDirSrc =+ dir:+ pkgs.lib.cleanSourceWith {+ src = ../rust/cloud-storage + "/${dir}";+ filter = srcFilter;+ name = "crate-${builtins.replaceStrings [ "/" ] [ "-" ] dir}";+ };++ # Workspace-root files that crates read across crate boundaries: the+ # .sqlx offline cache (sqlx macros resolve it from the workspace root)+ # and loose root assets like markdown-golden.1.bin (include_bytes!-ed+ # from the documents crate). Included in every pruned source, so a+ # sqlx prepare still invalidates all leaves — coarser than ideal, but+ # the query-to-crate mapping is not recoverable from the file names.+ rootDepsSrc = pkgs.lib.cleanSourceWith {+ src = ../rust/cloud-storage;+ name = "cloud-storage-root-deps";+ filter =+ path: type:+ let+ rel = pkgs.lib.removePrefix ((toString ../rust/cloud-storage) + "/") (toString path);+ in+ (rel == ".sqlx")+ || (pkgs.lib.hasPrefix ".sqlx/" rel)+ || (+ type == "regular"+ && !(pkgs.lib.hasInfix "/" rel)+ && ((assetFilter path type) || (binFilter path type))+ );+ };++ prunedDeploySrc =+ pname: rootPackage:+ let+ # Generator emits dirs sorted, so parents always precede nested+ # members and overlays land inside already-materialised parents.+ dirs =+ workspaceDepClosures.${rootPackage} or (throw (+ "No '${rootPackage}' entry in .github/workspace-dep-closures.json; "+ + "run `just hakari` from rust/cloud-storage and commit the result."+ ));+ overlays = pkgs.lib.concatMapStrings (dir: ''+ rm -rf "$out/${dir}"+ cp -rT ${crateDirSrc dir} "$out/${dir}"+ chmod -R +w "$out/${dir}"+ '') dirs;+ in+ pkgs.runCommand "cloud-storage-src-${pname}" { } ''+ cp -rT ${deployDummySrc} $out+ chmod -R +w $out+ cp -rfT ${rootDepsSrc} $out+ chmod -R +w $out+ ${overlays}+ '';++ commonArgs = {+ inherit src;+ pname = "cloud-storage";+ version = "0.1.0";+ strictDeps = true;+ buildInputs = libraries;+ # Cargo/crane need git in the sandbox to fetch git dependencies.+ # Without this, CI can fall back to host /usr/lib/git-core helpers,+ # which are not ABI-compatible with Nix-provided glibc.+ nativeBuildInputs =+ with pkgs;+ [+ git+ pkg-config+ ]+ ++ pkgs.lib.optionals isLinux [ mold ];+ LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";+ OPENSSL_NO_VENDOR = "1";+ SQLX_OFFLINE = "true";+ # Keep vendoring independent of the generated src derivation and pin+ # git dependencies so Nix does not fall back to host git helpers in CI.+ cargoVendorDir = craneLib.vendorCargoDeps {+ src = ../rust/cloud-storage;+ cargoLock = ../rust/cloud-storage/Cargo.lock;+ outputHashes = {+ "git+https://github.com/whutchinson98/jsonwebtoken#c8c0d19511a0e7ba9d456e21437a79d321e99f16" =+ "sha256-jllT52SAIiNpTPg7Vm3wmT79w/CIz9NnVKM81oQq8dM=";+ "git+https://github.com/macro-inc/rig?branch=feat/responses-api-non-strict-tools#6deadfc6f9b432c849ea79733a549f46407530b7" =+ "sha256-EcmlwqAVXGtbuvozzCOrygoSVipU99mBZK/MrQAIoYg=";+ "git+https://github.com/macro-inc/rs-libreoffice-bindings?rev=056a40ddfac1d9650be30b9f0b4b934e9266c7dc#056a40ddfac1d9650be30b9f0b4b934e9266c7dc" =+ "sha256-lx/AuxPpCarxdDzogkGudCbE4B2OEt5un4s4gIFt1ek=";+ };+ };+ RUSTFLAGS = pkgs.lib.optionalString isLinux "-C link-arg=-fuse-ld=mold";+ # Build deps + workspace + bins in dev profile so the test job (which runs+ # `cargo nextest` outside the sandbox using the test profile, inheriting dev)+ # can reuse the restored target/debug/ instead of recompiling all deps.+ CARGO_PROFILE = "dev";+ }+ // pkgs.lib.optionalAttrs isLinux {+ LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libraries}";+ BINDGEN_EXTRA_CLANG_ARGS = "-I${pkgs.glibc.dev}/include -I${pkgs.gcc.cc}/lib/gcc/${pkgs.stdenv.hostPlatform.config}/${pkgs.gcc.version}/include";+ };++ # Pre-built third-party deps — Cachix caches this; hash is driven by Cargo.lock+ # (workspace member sources are stubbed by crane), so it survives most PRs.+ # --all-features matches the test job (cargo nextest --all-features) and clippy+ # so all consumers share the same dep feature unification.+ cargoArtifacts = craneLib.buildDepsOnly (+ commonArgs+ // {+ cargoExtraArgs = "--locked --all-features";+ }+ );++ # Layered atop cargoArtifacts: pre-compile every workspace lib crate so+ # downstream derivations (openApiBins, clippy) inherit a warm target/. The+ # hash is per-source so cachix only hits when the SHA matches across CI+ # workflows — but since code-check-cloud-storage and web-app-check-main both+ # run on the same SHA, whichever finishes first pushes for the other.+ workspaceArtifacts = craneLib.cargoBuild (+ commonArgs+ // {+ inherit cargoArtifacts;+ pname = "cloud-storage-workspace";+ doCheck = false;+ doInstallCargoArtifacts = true;+ cargoExtraArgs = "--locked --all-features --workspace --lib";+ RUSTFLAGS = "-Dwarnings" + pkgs.lib.optionalString isLinux " -C link-arg=-fuse-ld=mold";+ RUSTDOCFLAGS = "-Dwarnings";+ }+ );++ cloudStorageCargoToml = builtins.fromTOML (builtins.readFile ../rust/cloud-storage/Cargo.toml);+ cloudStorageWorkspaceMembers =+ cloudStorageCargoToml.workspace.members+ or (throw "rust/cloud-storage/Cargo.toml is missing workspace.members");++ dopplerConfigBinNames =+ let+ dopplerConfigPath = "src/doppler_config.rs";+ matchingDopplerBins =+ member:+ let+ memberDir = ../rust/cloud-storage + "/${member}";+ manifestFile = memberDir + "/Cargo.toml";+ hasConfig = builtins.pathExists (memberDir + "/src/config.rs");+ hasDopplerConfig = builtins.pathExists (memberDir + "/${dopplerConfigPath}");+ manifest = builtins.fromTOML (builtins.readFile manifestFile);+ matchingBins = builtins.filter (bin: (bin.path or null) == dopplerConfigPath) (manifest.bin or [ ]);+ missingNameError = "cloud-storage workspace member '${member}' has a ${dopplerConfigPath} bin without a name";+ matchingBinNames = map (bin: bin.name or (throw missingNameError)) matchingBins;+ in+ if !hasDopplerConfig then+ [ ]+ else if !(builtins.pathExists manifestFile) then+ throw "cloud-storage workspace member '${member}' has ${dopplerConfigPath} but no Cargo.toml"+ else if matchingBinNames == [ ] then+ throw (+ "cloud-storage workspace member '${member}' has ${dopplerConfigPath} "+ + "but no [[bin]] with path = \"${dopplerConfigPath}\""+ )+ else if !hasConfig then+ [ ]+ else+ matchingBinNames;+ in+ pkgs.lib.unique (pkgs.lib.concatMap matchingDopplerBins cloudStorageWorkspaceMembers);++ dopplerConfigBinPackages = builtins.listToAttrs (+ map (+ binName:+ pkgs.lib.nameValuePair "doppler-config-bin-${binName}" (+ craneLib.buildPackage (+ commonArgs+ // {+ # Reuse the dependency-only layer, then compile only this+ # Doppler config binary and the local crates it actually uses.+ inherit cargoArtifacts;+ pname = "cloud-storage-doppler-config-${binName}";+ doCheck = false;+ cargoExtraArgs = pkgs.lib.concatStringsSep " " [+ "--locked"+ "--all-features"+ "--bin ${binName}"+ ];+ }+ )+ )+ ) dopplerConfigBinNames+ );++ dopplerConfigBins = pkgs.symlinkJoin {+ name = "cloud-storage-doppler-config";+ paths = builtins.attrValues dopplerConfigBinPackages;+ };++ openApiBins = craneLib.buildPackage (+ commonArgs+ // {+ cargoArtifacts = workspaceArtifacts;+ pname = "cloud-storage-openapi";+ doCheck = false;+ cargoExtraArgs = pkgs.lib.concatStringsSep " " [+ "--locked"+ "--all-features"+ "--bin document_storage_service_openapi"+ "--bin properties_service_openapi"+ "--bin document_cognition_service_openapi"+ "--bin authentication_service_openapi"+ "--bin notification_service_openapi"+ "--bin static_file_service_openapi"+ "--bin connection_gateway_openapi"+ "--bin contacts_service_openapi"+ "--bin unfurl_service_openapi"+ "--bin email_service_openapi"+ "--bin search_service_openapi"+ "--bin scheduled_action_openapi"+ "--bin document_cognition_service_models"+ "--bin gen_tool_schemas"+ ];+ }+ );++ # Pre-built nextest archive — packages all compiled test binaries plus their+ # metadata into a single tar.zst. CI fetches this archive and runs+ # `cargo nextest run --archive-file` outside the sandbox so tests can hit+ # postgres/redis services. Built in nix → cached by cachix.+ nextestArchive = craneLib.mkCargoDerivation (+ commonArgs+ // {+ cargoArtifacts = workspaceArtifacts;+ pname = "cloud-storage-nextest-archive";+ doCheck = false;+ nativeBuildInputs = commonArgs.nativeBuildInputs or [ ] ++ [ pkgs.cargo-nextest ];+ buildPhaseCargoCommand = ''+ cargo nextest archive \+ --cargo-profile dev \+ --locked --all-features \+ --workspace --lib --bins --tests \+ --archive-file nextest-archive.tar.zst+ '';+ installPhaseCommand = ''+ mkdir -p $out+ cp nextest-archive.tar.zst $out/+ '';+ }+ );++ deployServiceBinaryDefinitions = [+ {+ serviceName = "agent-schedule-service";+ packageName = "scheduled_action";+ binaries = [ "service" ];+ }+ {+ serviceName = "authentication-service";+ packageName = "authentication_service";+ binaries = [ "authentication_service" ];+ }+ {+ serviceName = "connection-gateway";+ packageName = "connection_gateway";+ binaries = [ "connection_gateway_service" ];+ }+ {+ serviceName = "contacts-service";+ packageName = "contacts_service";+ binaries = [ "contacts_service" ];+ }+ {+ serviceName = "convert-service";+ packageName = "convert_service";+ binaries = [ "convert_service" ];+ }+ {+ serviceName = "document-cognition-service";+ packageName = "document_cognition_service";+ binaries = [ "document_cognition_service" ];+ }+ {+ serviceName = "document-storage-service";+ packageName = "document_storage_service";+ binaries = [ "document_storage_service" ];+ }+ {+ serviceName = "email-service";+ packageName = "email_service";+ binaries = [+ "email_service"+ "pubsub_workers"+ ];+ }+ {+ serviceName = "image-proxy-service";+ packageName = "image_proxy_service";+ binaries = [ "image_proxy_service" ];+ }+ {+ serviceName = "mcp-server";+ packageName = "mcp_service";+ binaries = [ "mcp_service" ];+ }+ {+ serviceName = "notification-service";+ packageName = "notification_service";+ binaries = [ "notification_service" ];+ }+ {+ serviceName = "search-processing-service";+ packageName = "search_processing_service";+ binaries = [ "search_processing_service" ];+ }+ {+ serviceName = "static-file-service";+ packageName = "static_file_service";+ binaries = [ "static_file_service" ];+ }+ {+ serviceName = "unfurl-service";+ packageName = "unfurl_service";+ binaries = [ "unfurl_service" ];+ }+ ];++ deployBinaryCargoExtraArgs =+ "--locked "+ + pkgs.lib.concatMapStringsSep " " (+ def:+ "--package ${def.packageName} "+ + pkgs.lib.concatMapStringsSep " " (binary: "--bin ${binary}") def.binaries+ ) deployServiceBinaryDefinitions;++ deployCargoArtifacts = craneLib.buildDepsOnly (+ commonArgs+ // {+ pname = "cloud-storage-deploy-deps";+ doCheck = false;+ # buildDepsOnly runs a cargo check in buildPhase by default; keep this+ # warm artifact to release deps only.+ cargoCheckCommand = "true";+ cargoExtraArgs = deployBinaryCargoExtraArgs;+ CARGO_PROFILE = "release";+ }+ );++ deployServiceBinaryPackage =+ {+ serviceName,+ packageName,+ binaries,+ }:+ craneLib.buildPackage (+ commonArgs+ // {+ # Pruned source: this derivation only rebuilds when a crate in+ # the service's own workspace closure changes.+ src = prunedDeploySrc "service-${serviceName}" packageName;+ cargoArtifacts = deployCargoArtifacts;+ pname = "cloud-storage-${serviceName}-binaries";+ doCheck = false;+ cargoExtraArgs =+ "--locked --package ${packageName} "+ + pkgs.lib.concatMapStringsSep " " (binary: "--bin ${binary}") binaries;+ CARGO_PROFILE = "release";+ installPhaseCommand = ''+ mkdir -p $out/bin+ for binary in ${pkgs.lib.concatStringsSep " " binaries}; do+ cp target/release/$binary $out/bin/$binary+ ${pkgs.binutils}/bin/strip $out/bin/$binary || true+ done+ '';+ }+ );++ deployServiceBinaryPackages = pkgs.lib.listToAttrs (+ map (def: {+ name = "deploy-service-binaries-${def.serviceName}";+ value = deployServiceBinaryPackage def;+ }) deployServiceBinaryDefinitions+ );++ # ── Lambda builds (crane + cargo-zigbuild) ─────────────────────+ # SPIKE: build a Rust Lambda handler reproducibly under nix/crane so+ # lambdas ride the same content-addressed cache as the service binaries+ # (nix store + Cachix + sticky disk) instead of a cargo-in-checkout that+ # recompiles the workspace every run. cargo-zigbuild pins the Lambda+ # glibc via a target *suffix* (no toolchain swap; host triple == lambda+ # triple, so no extra rust-std). The binary is renamed `bootstrap` and+ # zipped for the provided.al2/al2023 custom runtime.+ lambdaTarget = "x86_64-unknown-linux-gnu";+ # glibc 2.26 == Amazon Linux 2; forward-compatible with al2023.+ lambdaZigTarget = "${lambdaTarget}.2.26";++ callRecordingPreviewFfmpegLayer =+ let+ ffmpegVersion = "7.0.2";+ ffmpegArchive = pkgs.fetchurl {+ url = "https://johnvansickle.com/ffmpeg/releases/ffmpeg-${ffmpegVersion}-amd64-static.tar.xz";+ hash = "sha256-q9qNd86DCRQfg6uO3wWWg0CHxSRn9rrfN2pqKkyHz2c=";+ };+ in+ pkgs.runCommand "call-recording-preview-ffmpeg-layer"+ {+ nativeBuildInputs = [+ pkgs.coreutils+ pkgs.gnutar+ pkgs.unzip+ pkgs.xz+ pkgs.zip+ ];+ }+ ''+ set -euo pipefail++ archive_dir="ffmpeg-${ffmpegVersion}-amd64-static"+ mkdir -p extract package/bin "$out/call_recording_preview_handler"+ tar -xJf ${ffmpegArchive} -C extract \+ "$archive_dir/ffmpeg" \+ "$archive_dir/ffprobe"+ install -m 0755 "extract/$archive_dir/ffmpeg" package/bin/ffmpeg+ install -m 0755 "extract/$archive_dir/ffprobe" package/bin/ffprobe+ touch -h -d @315532800 package/bin/ffmpeg package/bin/ffprobe++ (+ cd package+ zip -9 -q -X "$out/call_recording_preview_handler/ffmpeg-layer.zip" bin/ffmpeg bin/ffprobe+ )+ unzip -tqq "$out/call_recording_preview_handler/ffmpeg-layer.zip" >/dev/null+ '';++ lambdaCommonArgs = commonArgs // {+ # zig links the final binary (cargo-zigbuild); drop the host-only mold arg.+ RUSTFLAGS = "";+ CARGO_PROFILE = "release";+ # Lambdas don't need max opt; matches the cargo-lambda CI setting.+ CARGO_PROFILE_RELEASE_OPT_LEVEL = "2";+ # aws-lc-sys (aws-lc-rs / rustls default crypto, pulled via aws-sdk &+ # sqlx) has a cc-builder guard that rejects the zig C compiler. Force+ # its cmake builder instead, which has no such guard and still compiles+ # the C against the zig-pinned glibc. cmake + nasm are its build deps.+ AWS_LC_SYS_CMAKE_BUILDER = "1";+ nativeBuildInputs = (commonArgs.nativeBuildInputs or [ ]) ++ [+ pkgs.cargo-zigbuild+ pkgs.zig+ pkgs.cmake+ pkgs.nasm+ ];+ # zig needs a writable cache inside the sandbox ($HOME is read-only).+ preBuild = ''+ export ZIG_GLOBAL_CACHE_DIR="$TMPDIR/zig-cache"+ export ZIG_LOCAL_CACHE_DIR="$TMPDIR/zig-cache"+ export XDG_CACHE_HOME="$TMPDIR/xdg"++ # Inherited cargoArtifacts can carry CMake configure state+ # (CMakeCache.txt / CMakeFiles) from the deps-only layer. Its+ # CMAKE_C_COMPILER points at a cargo-zigbuild wrapper script under+ # $TMPDIR whose hash-suffixed name need not exist in this sandbox,+ # and CMake hard-fails validating a cached compiler that is gone+ # ("is not a full path to an existing compiler tool"). Drop the+ # configure state so a build-script re-run reconfigures cleanly;+ # crates whose fingerprints are clean never read it, so this costs+ # nothing on the cached path. (Today aws-lc-sys is the only cmake+ # crate in the graph, via AWS_LC_SYS_CMAKE_BUILDER below.)+ tdir="''${CARGO_TARGET_DIR:-target}"+ if [ -d "$tdir" ]; then+ while IFS= read -r -d "" cache; do+ dir="$(dirname "$cache")"+ echo "purging stale cmake configure state in $dir"+ rm -rf "$dir/CMakeFiles" "$cache"+ done < <(find "$tdir" -name CMakeCache.txt -print0)+ fi+ '';+ };++ # Every handler deployed as a lambda, read straight from the deploy+ # config so the flake never drifts from services-config.json. For every+ # handler, crate name == dir name == deploy_lambdas entry.+ lambdaNames =+ let+ cfg = builtins.fromJSON (builtins.readFile ../.github/services-config.json);+ in+ pkgs.lib.unique (+ pkgs.lib.concatMap (svc: svc.deploy_lambdas or [ ]) (pkgs.lib.attrValues cfg.services)+ );++ # One shared dep closure for all lambda handlers. Build it with the same+ # cargo-zigbuild target used by the final packages; Cargo fingerprints the+ # `.2.26` target separately from the plain triple, so warming the plain+ # target does not help the deploy builds.+ lambdaDeployCargoArtifacts = craneLib.buildDepsOnly (+ lambdaCommonArgs+ // {+ pname = "cloud-storage-lambda-deps";+ doCheck = false;+ # buildDepsOnly runs a cargo check in buildPhase by default; keep this+ # warm artifact to release deps only.+ cargoCheckCommand = "true";+ cargoBuildCommand = "cargo zigbuild --release";+ cargoExtraArgs =+ "--locked --target ${lambdaZigTarget} "+ + pkgs.lib.concatMapStringsSep " " (n: "--package ${n}") lambdaNames;+ }+ );++ # bin name == crate name == handler dir name (see per-lambda justfiles).+ deployLambdaPackage =+ lambdaName:+ craneLib.buildPackage (+ lambdaCommonArgs+ // {+ # Pruned source: this derivation only rebuilds when a crate in+ # the handler's own workspace closure changes.+ src = prunedDeploySrc "lambda-${lambdaName}" lambdaName;+ cargoArtifacts = lambdaDeployCargoArtifacts;+ pname = "cloud-storage-lambda-${lambdaName}";+ doCheck = false;+ # cargo-zigbuild links the final binary against the pinned Lambda+ # glibc, selected via the `.2.26` target suffix.+ cargoBuildCommand = "cargo zigbuild --release";+ cargoExtraArgs = "--locked --target ${lambdaZigTarget} --bin ${lambdaName}";+ # Emit the Lambda custom-runtime artifact: a zip whose single entry+ # is named `bootstrap`, mirroring cargo-lambda's+ # target/lambda/<name>/bootstrap.zip layout. zigbuild writes to+ # target/<triple>/release (suffix stripped from the dir name).+ installPhaseCommand = ''+ mkdir -p "$out/${lambdaName}"+ cp "target/${lambdaTarget}/release/${lambdaName}" bootstrap+ ${pkgs.binutils}/bin/strip bootstrap || true+ ${pkgs.zip}/bin/zip -j -X "$out/${lambdaName}/bootstrap.zip" bootstrap+ ${pkgs.lib.optionalString (lambdaName == "document_text_extractor") ''+ # Mirror the handler justfile's `cargo lambda build --include+ # ./pdfium-lib/linux`: at runtime the binary dlopen's+ # ./pdfium-lib/linux/libpdfium.so relative to the Lambda task+ # root, so the blob has to ride along in bootstrap.zip at that+ # same relative path.+ ( cd ${lambdaName} && ${pkgs.zip}/bin/zip -r -X "$out/${lambdaName}/bootstrap.zip" pdfium-lib/linux )+ ''}+ ${pkgs.lib.optionalString (lambdaName == "call_recording_preview_handler") ''+ cp "${callRecordingPreviewFfmpegLayer}/${lambdaName}/ffmpeg-layer.zip" "$out/${lambdaName}/ffmpeg-layer.zip"+ ''}+ '';+ }+ );++ deployLambdaPackages = pkgs.lib.listToAttrs (+ map (n: {+ name = "deploy-lambda-${n}";+ value = deployLambdaPackage n;+ }) lambdaNames+ );++ shellTools =+ with pkgs;+ [+ parallel+ docker-compose+ curl+ xz+ unzip+ zip+ cargo-info+ cargo-udeps+ cargo-lambda+ cargo-zigbuild+ zig+ cmake+ nasm+ (writeShellScriptBin "rustup" ''+ set -euo pipefail+ rustc_path="$(${coreutils}/bin/readlink -f "$(command -v rustc)")"+ toolchain="$(${coreutils}/bin/basename "$(${coreutils}/bin/dirname "$(${coreutils}/bin/dirname "$rustc_path")")")"+ case "$1 $2" in+ "toolchain list") echo "$toolchain (default)" ;;+ "toolchain add") exit 0 ;;+ "target list") echo "x86_64-unknown-linux-gnu (installed)"; echo "aarch64-unknown-linux-gnu"; echo "wasm32-unknown-unknown (installed)" ;;+ "target add") exit 0 ;;+ "component list") echo "rust-src-x86_64-unknown-linux-gnu (installed)"; echo "clippy-x86_64-unknown-linux-gnu (installed)" ;;+ "component add") exit 0 ;;+ *) echo "rustup shim only supports commands used by cross" >&2; exit 1 ;;+ esac+ '')+ cargo-cross+ cargo-deny+ cargo-nextest+ cargo-expand+ wasm-pack+ pkg-config+ bacon+ just+ just-lsp+ taplo+ bun+ pnpm+ sqlx-cli+ typescript-language-server+ nodejs_24+ pulumi+ pulumiPackages.pulumi-nodejs+ doppler+ biome+ jq+ stripe-cli+ sccache+ rustToolchain+ python3+ ]+ ++ pkgs.lib.optionals isLinux [ mold ];++ in+ {+ checks = {+ fmt = craneLib.cargoFmt {+ inherit src;+ pname = "cloud-storage";+ version = "0.1.0";+ };+ clippy = craneLib.cargoClippy (+ commonArgs+ // {+ cargoArtifacts = workspaceArtifacts;+ cargoClippyExtraArgs = "--all-features -- -D warnings";+ RUSTDOCFLAGS = "-Dwarnings";+ }+ );+ doppler-config-bins = dopplerConfigBins;+ gen-api =+ let+ openApiFiles = pkgs.lib.cleanSourceWith {+ src = ../js/app/packages/service-clients;+ filter = path: type: type == "directory" || pkgs.lib.hasSuffix "openapi.json" (baseNameOf path);+ };+ crateToDir = {+ document_storage_service = "service-storage";+ properties_service = "service-properties";+ document_cognition_service = "service-cognition";+ authentication_service = "service-auth";+ notification_service = "service-notification";+ static_file_service = "service-static-files";+ connection_gateway = "service-connection";+ contacts_service = "service-contacts";+ unfurl_service = "service-unfurl";+ email_service = "service-email";+ search_service = "service-search";+ scheduled_action = "service-scheduled-action";+ };+ checkScript = pkgs.lib.concatStringsSep "\n" (+ pkgs.lib.mapAttrsToList (crate: dir: ''+ echo -n "Checking ${dir}/openapi.json ... "+ if ! diff \+ <("${openApiBins}/bin/${crate}_openapi" | ${pkgs.jq}/bin/jq --sort-keys .) \+ <(${pkgs.jq}/bin/jq --sort-keys . < "${openApiFiles}/${dir}/openapi.json"); then+ echo "FAIL: run 'bun run gen-api' and commit the result"+ exit 1+ fi+ echo "ok"+ '') crateToDir+ );+ in+ pkgs.runCommand "cloud-storage-gen-api-check" { RUST_LOG = "error"; } ''+ ${checkScript}+ touch $out+ '';+ };++ packages = {+ inherit+ cargoArtifacts+ callRecordingPreviewFfmpegLayer+ workspaceArtifacts+ deployCargoArtifacts+ lambdaDeployCargoArtifacts+ openApiBins+ dopplerConfigBins+ nextestArchive+ ;+ default = cargoArtifacts;+ }+ // dopplerConfigBinPackages+ // deployServiceBinaryPackages+ // deployLambdaPackages;++ devShells = {+ default = pkgs.mkShell (+ {+ buildInputs = shellTools ++ libraries;+ PKG_CONFIG_PATH = "${pkgs.openssl.dev}/lib/pkgconfig";+ LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";+ RUSTC_WRAPPER = "${pkgs.sccache}/bin/sccache";+ # Keep local cargo-lambda builds on the same aws-lc-sys path as+ # the Nix lambda derivations. The default cc builder rejects+ # cargo-lambda/cargo-zigbuild's Zig cc wrapper.+ AWS_LC_SYS_CMAKE_BUILDER = "1";+ }+ // pkgs.lib.optionalAttrs isLinux {+ LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libraries}";+ BINDGEN_EXTRA_CLANG_ARGS = "-I${pkgs.glibc.dev}/include -I${pkgs.gcc.cc}/lib/gcc/${pkgs.stdenv.hostPlatform.config}/${pkgs.gcc.version}/include";+ }+ );+ };+ };+}diff --git a/nix/js-app.nix b/nix/js-app.nixnew file mode 100644index 0000000000..3d0a8d19e6--- /dev/null+++ b/nix/js-app.nix@@ -0,0 +1,156 @@+{ inputs, ... }:+{+ perSystem =+ { system, ... }:+ let+ inherit (inputs)+ nixpkgs+ fenix+ ;+ pkgs = import nixpkgs {+ system = system;+ };+ isDarwin = pkgs.stdenv.isDarwin;+ isLinux = pkgs.stdenv.isLinux;++ # ── js-app (frontend Tauri app) ────────────────────────────────++ # Need allowUnfree + android license for the Android SDK+ jsPkgs = import nixpkgs {+ inherit system;+ config.allowUnfree = true;+ config.android_sdk.accept_license = true;+ };++ android_sdk = pkgs.lib.optionalAttrs isLinux (+ (jsPkgs.androidenv.composeAndroidPackages {+ platformVersions = [+ "34"+ "36"+ ];+ buildToolsVersions = [+ "35.0.0"+ ];+ ndkVersions = [ "26.3.11579264" ];+ includeNDK = true;+ useGoogleAPIs = false;+ useGoogleTVAddOns = false;+ includeEmulator = true;+ includeSystemImages = true;+ systemImageTypes = [ "google_apis_playstore" ];+ abiVersions = [ "x86_64" ];+ includeSources = false;+ }).androidsdk+ );++ jsRustComponents = with fenix.packages.${system}; [+ complete.rustc+ complete.rust-src+ complete.cargo+ complete.clippy+ complete.rustfmt+ complete.rust-analyzer+ ];++ jsRustToolchain = with fenix.packages.${system}; combine jsRustComponents;+ jsAndroidRustToolchain =+ with fenix.packages.${system};+ combine (+ jsRustComponents+ ++ [+ targets.aarch64-linux-android.latest.rust-std+ targets.armv7-linux-androideabi.latest.rust-std+ targets.i686-linux-android.latest.rust-std+ targets.x86_64-linux-android.latest.rust-std+ ]+ );++ jsBasePackages = with jsPkgs; [+ curl+ wget+ pkg-config+ just+ bun+ biome+ nodejs_24+ typescript-language-server+ cargo-tauri+ cargo-info+ cargo-udeps+ pulumi+ pulumiPackages.pulumi-nodejs+ pulumiPackages.pulumi-aws-native+ playwright+ playwright-mcp+ ];++ jsLinuxPackages = with jsPkgs; [+ gst_all_1.gstreamer+ gst_all_1.gst-plugins-base+ gst_all_1.gst-plugins-good+ gst_all_1.gst-plugins-bad+ xdg-utils+ ];++ jsPackages = jsBasePackages ++ [ jsRustToolchain ] ++ pkgs.lib.optionals isLinux jsLinuxPackages;+ jsAndroidPackages =+ jsBasePackages+ ++ [ jsAndroidRustToolchain ]+ ++ pkgs.lib.optionals isLinux (+ jsLinuxPackages+ ++ [+ jsPkgs.jdk+ android_sdk+ ]+ );++ jsLinuxLibraries = with jsPkgs; [+ gtk3+ libsoup_3+ webkitgtk_4_1+ cairo+ gdk-pixbuf+ glib+ dbus+ openssl+ librsvg+ lsb-release+ ];++ jsDarwinLibraries = with jsPkgs; [+ openssl+ libiconv+ ];++ jsLibraries = if isDarwin then jsDarwinLibraries else jsLinuxLibraries;+ jsLinuxShellHook = ''+ export LD_LIBRARY_PATH="${pkgs.lib.makeLibraryPath jsLibraries}''${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"+ export XDG_DATA_DIRS="${jsPkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${jsPkgs.gsettings-desktop-schemas.name}:${jsPkgs.gtk3}/share/gsettings-schemas/${jsPkgs.gtk3.name}''${XDG_DATA_DIRS:+:$XDG_DATA_DIRS}"+ '';+ in+ {+ devShells = {+ js-app = jsPkgs.mkShell (+ {+ buildInputs = jsPackages ++ jsLibraries;+ PKG_CONFIG_PATH = "${jsPkgs.openssl.dev}/lib/pkgconfig";+ }+ // pkgs.lib.optionalAttrs isLinux {+ shellHook = jsLinuxShellHook;+ GIO_MODULE_DIR = "${jsPkgs.glib-networking}/lib/gio/modules/";+ }+ );+ }+ // pkgs.lib.optionalAttrs isLinux {+ js-app-android = jsPkgs.mkShell {+ buildInputs = jsAndroidPackages ++ jsLibraries;+ PKG_CONFIG_PATH = "${jsPkgs.openssl.dev}/lib/pkgconfig";+ shellHook = jsLinuxShellHook;+ ANDROID_HOME = "${android_sdk}/libexec/android-sdk";+ NDK_HOME = "${android_sdk}/libexec/android-sdk/ndk/26.3.11579264";+ GRADLE_OPTS = "-Dorg.gradle.project.android.aapt2FromMavenOverride=${android_sdk}/libexec/android-sdk/build-tools/35.0.0/aapt2";+ GIO_MODULE_DIR = "${jsPkgs.glib-networking}/lib/gio/modules/";+ };+ };+ };+}diff --git a/nix/systems.nix b/nix/systems.nixnew file mode 100644index 0000000000..a6be0cbdfa--- /dev/null+++ b/nix/systems.nix@@ -0,0 +1,4 @@+{ inputs, ... }:+{+ systems = inputs.flake-utils.lib.defaultSystems;+}diff --git a/nix/tauri-desktop.nix b/nix/tauri-desktop.nixnew file mode 100644index 0000000000..83c3e17675--- /dev/null+++ b/nix/tauri-desktop.nix@@ -0,0 +1,691 @@+{ inputs, ... }:+{+ perSystem =+ { system, ... }:+ let+ inherit (inputs)+ nixpkgs+ fenix+ crane+ crane-tauri+ ;+ pkgs = import nixpkgs {+ inherit system;+ config.allowUnfree = true;+ };+ inherit (pkgs) lib;+ isLinux = pkgs.stdenv.hostPlatform.isLinux;+ isX86_64Linux = system == "x86_64-linux";+ isAarch64Darwin = system == "aarch64-darwin";++ appVersion = (builtins.fromJSON (builtins.readFile ../js/app/packages/app/package.json)).version;+ gitRev = inputs.self.shortRev or inputs.self.dirtyShortRev or "unknown";++ rustToolchain = fenix.packages.${system}.fromToolchainFile {+ file = ../rust/rust-toolchain.toml;+ sha256 = "sha256-qqF33vNuAdU5vua96VKVIwuc43j4EFeEXbjQ6+l4mO4=";+ };+ craneLib = (crane.mkLib pkgs).overrideToolchain rustToolchain;++ jsRoot = ../js;+ jsSrc = lib.cleanSourceWith {+ src = jsRoot;+ filter =+ path: type:+ let+ rel = lib.removePrefix ((toString jsRoot) + "/") (toString path);+ in+ !(lib.hasPrefix "node_modules/" rel)+ && !(lib.hasPrefix "app/node_modules/" rel)+ && !(lib.hasPrefix "app/packages/app/dist/" rel)+ && !(lib.hasPrefix "app/tauri/target/" rel)+ && !(lib.hasPrefix "lexical-core/node_modules/" rel)+ && !(lib.hasPrefix "lexical-service/node_modules/" rel)+ && !(lib.hasPrefix "loro-mirror/node_modules/" rel)+ && !(lib.hasInfix "/node_modules/" rel)+ && !(lib.hasInfix "/target/" rel)+ && !(lib.hasInfix "/dist/" rel)+ && rel != "node_modules"+ && rel != "app/node_modules"+ && rel != "app/packages/app/dist"+ && rel != "app/tauri/target";+ };++ bunDeps = pkgs.stdenvNoCC.mkDerivation {+ pname = "macro-js-bun-deps";+ version = appVersion;+ src = jsSrc;++ nativeBuildInputs = with pkgs; [+ bun+ git+ ];++ dontConfigure = true;+ dontBuild = true;+ dontFixup = true;++ installPhase = ''+ runHook preInstall++ export HOME="$TMPDIR"+ export BUN_INSTALL_CACHE_DIR="$TMPDIR/bun-cache"+ bun install --frozen-lockfile --no-progress++ mkdir -p "$out"+ cp -a node_modules "$out/node_modules"++ runHook postInstall+ '';++ outputHashAlgo = "sha256";+ outputHashMode = "recursive";+ outputHash =+ if isAarch64Darwin then+ "sha256-R0C2jkhk/QiS5v5Lm5cLiv3qU/8UzssTF37+8f3wrH4="+ else+ "sha256-iRTxcszsC1TKGV34k2F8cBLW7Lt3FSGIN7smcHrVVkk=";+ };++ frontend = pkgs.stdenvNoCC.mkDerivation {+ pname = "macro-tauri-frontend";+ version = appVersion;+ src = jsSrc;++ nativeBuildInputs = with pkgs; [+ bun+ git+ ];++ dontConfigure = true;++ buildPhase = ''+ runHook preBuild++ export HOME="$TMPDIR"+ cp -a ${bunDeps}/node_modules ./node_modules+ chmod -R u+w ./node_modules++ printf production > app/tauri/src-tauri/.macro-tauri-env+ (+ cd app/packages/app+ MODE=production NODE_ENV=production bun ../../../node_modules/vite/bin/vite.js build -c vite.config.ts+ printf '${appVersion}+${gitRev}\n' > dist/semver.txt+ BUNDLE_BUILD_NUMBER=1 MIN_NATIVE_BUILD=0 bun scripts/write-bundle-manifest.mjs+ )++ runHook postBuild+ '';++ installPhase = ''+ runHook preInstall+ cp -r app/packages/app/dist "$out"+ runHook postInstall+ '';+ };++ tauriCargoVendorDir = craneLib.vendorCargoDeps {+ src = ../js/app/tauri;+ cargoLock = ../js/app/tauri/Cargo.lock;+ outputHashes = {+ "git+https://github.com/macro-inc/tauri-plugins?rev=26537c8a46bb8424f9cf4021d08aa76aa7cd66ef#26537c8a46bb8424f9cf4021d08aa76aa7cd66ef" =+ "sha256-v0Pn8kiRXaczNrFNjXct7yZUQ50qP68l8ivQDumu7Hw=";+ "git+https://github.com/seanaye/plugins-workspace?branch=seanaye%2Ffeat%2Fwebsocket-cookies#c23e1d7b24391a79b5bcfc3df535452c17f1f01c" =+ "sha256-cxxQLB9q/Ajh0YkyyZ0AuLt9Syeq+g7LcSqNr05SDXo=";+ "git+https://github.com/seanaye/plugins-workspace?branch=seanaye/feat/websocket-cookies#c23e1d7b24391a79b5bcfc3df535452c17f1f01c" =+ "sha256-cxxQLB9q/Ajh0YkyyZ0AuLt9Syeq+g7LcSqNr05SDXo=";+ "git+https://github.com/seanaye/tauri?rev=95a7521b#95a7521b8c565cfba568319ddd8ba79c9ce244e2" =+ "sha256-5HamTWAZPtUSWOfP3TgtiqFJvunlPXy9/C0TLHQpXlU=";+ "git+https://github.com/voxelbee/tauri-plugin-virtual-keyboard?branch=main#70e8e8325b5ff7d681ef5f3b996ac083d4fc5a01" =+ "sha256-OdEp5mw0l5Euj0ry7gzNVxdB0jlGUq0N7XINXUhtE+c=";+ };+ };++ tauri = crane-tauri.lib.buildTauriApp { inherit pkgs craneLib; } {+ pname = "macro-tauri-desktop";+ version = appVersion;+ binaryName = "app";+ src = ../js/app/tauri;+ cargoRoot = ../js/app/tauri;+ cargoLock = ../js/app/tauri/Cargo.lock;+ inherit frontend;++ craneArgs.cargoVendorDir = tauriCargoVendorDir;+ craneArgs.postConfigure = ''+ writable_vendor="$TMPDIR/cargo-vendor"+ mkdir -p "$writable_vendor"+ cp -aL ${tauriCargoVendorDir}/. "$writable_vendor/"+ chmod -R u+w "$writable_vendor"+ substituteInPlace .cargo-home/config.toml \+ --replace-fail "${tauriCargoVendorDir}" "$writable_vendor"+ '';+ craneArgs.preBuild = ''+ mkdir -p ../packages/app+ cp ${../js/app/packages/app/package.json} ../packages/app/package.json+ rm -rf ../packages/app/dist+ cp -r ${frontend} ../packages/app/dist+ '';+ };++ wrappedTauriDesktop = pkgs.symlinkJoin {+ name = "macro-tauri-desktop-${appVersion}";+ paths = [ tauri.app ];+ nativeBuildInputs = [ pkgs.makeWrapper ];+ postBuild = ''+ wrapProgram "$out/bin/app" \+ --prefix LD_LIBRARY_PATH : ${+ lib.makeLibraryPath [+ pkgs.webkitgtk_4_1+ pkgs.libsoup_3+ pkgs.gtk3+ pkgs.glib+ pkgs.cairo+ pkgs.pango+ pkgs.gdk-pixbuf+ pkgs.atk+ pkgs.librsvg+ pkgs.libayatana-appindicator+ pkgs.openssl+ ]+ } \+ --prefix XDG_DATA_DIRS : "${pkgs.gsettings-desktop-schemas}/share/gsettings-schemas/${pkgs.gsettings-desktop-schemas.name}:${pkgs.gtk3}/share/gsettings-schemas/${pkgs.gtk3.name}"++ install -Dm0644 ${../js/app/tauri/src-tauri/icons/32x32.png} "$out/share/icons/hicolor/32x32/apps/macro.png"+ install -Dm0644 ${../js/app/tauri/src-tauri/icons/64x64.png} "$out/share/icons/hicolor/64x64/apps/macro.png"+ install -Dm0644 ${../js/app/tauri/src-tauri/icons/128x128.png} "$out/share/icons/hicolor/128x128/apps/macro.png"+ install -Dm0644 ${../js/app/tauri/src-tauri/icons/icon.png} "$out/share/icons/hicolor/256x256/apps/macro.png"+ install -Dm0644 /dev/stdin "$out/share/applications/macro.desktop" <<'EOF'+ [Desktop Entry]+ Type=Application+ Name=Macro+ Exec=app %U+ Icon=macro+ Categories=Office;Utility;+ MimeType=x-scheme-handler/macro;+ EOF+ '';+ meta.mainProgram = "app";+ };++ tauriBundlerSource = pkgs.cargo-tauri.src;+ tauriAppRun = pkgs.fetchurl {+ url = "https://github.com/tauri-apps/binary-releases/releases/download/apprun-old/AppRun-x86_64";+ hash = "sha256-8wFApDoKWeRtshve/fdJuenyxpRukq+rus+YuK5z+08=";+ };+ tauriLinuxdeployWrapper = pkgs.stdenv.mkDerivation {+ pname = "tauri-linuxdeploy-wrapper";+ version = "1";+ dontUnpack = true;+ buildPhase = ''+ cat > linuxdeploy-wrapper.c <<'EOF'+ #include <dirent.h>+ #include <stdio.h>+ #include <stdlib.h>+ #include <string.h>+ #include <unistd.h>++ static int has_suffix(const char *value, const char *suffix) {+ size_t value_len = strlen(value);+ size_t suffix_len = strlen(suffix);+ return value_len >= suffix_len && strcmp(value + value_len - suffix_len, suffix) == 0;+ }++ static void remove_if_exists(const char *path) {+ if (access(path, F_OK) == 0) {+ unlink(path);+ }+ }++ static void sanitize_appdir(const char *appdir) {+ if (appdir == NULL) return;+ DIR *dir = opendir(appdir);+ if (dir == NULL) return;++ size_t appdir_len = strlen(appdir);+ char *dir_icon = malloc(appdir_len + strlen("/.DirIcon") + 1);+ sprintf(dir_icon, "%s/.DirIcon", appdir);+ remove_if_exists(dir_icon);+ free(dir_icon);++ struct dirent *entry;+ while ((entry = readdir(dir)) != NULL) {+ if (has_suffix(entry->d_name, ".desktop")) {+ char *path = malloc(appdir_len + 1 + strlen(entry->d_name) + 1);+ sprintf(path, "%s/%s", appdir, entry->d_name);+ remove_if_exists(path);+ free(path);+ }+ }+ closedir(dir);+ }++ int main(int argc, char **argv) {+ const char *appdir = NULL;+ for (int i = 1; i < argc; i++) {+ if (strcmp(argv[i], "--appdir") == 0 && i + 1 < argc) {+ appdir = argv[i + 1];+ } else if (strncmp(argv[i], "--appdir=", 9) == 0) {+ appdir = argv[i] + 9;+ }+ }+ sanitize_appdir(appdir);++ char *slash = strrchr(argv[0], '/');+ if (slash != NULL) {+ size_t dir_len = (size_t)(slash - argv[0]);+ char *dir = strndup(argv[0], dir_len);+ char *old_path = getenv("PATH");+ const char *nix_ldd_dir = "${pkgs.glibc.bin}/bin";+ size_t path_len = dir_len + 1 + strlen(nix_ldd_dir) + 1 + (old_path ? strlen(old_path) : 0) + 1;+ char *path = malloc(path_len);+ snprintf(path, path_len, "%s:%s:%s", dir, nix_ldd_dir, old_path ? old_path : "");+ setenv("PATH", path, 1);+ }++ char **args = calloc((size_t)argc + 1, sizeof(char *));+ args[0] = "${pkgs.linuxdeploy}/bin/linuxdeploy";+ int out = 1;+ for (int i = 1; i < argc; i++) {+ if (strcmp(argv[i], "--appimage-extract-and-run") == 0) {+ continue;+ }+ if (strcmp(argv[i], "--plugin") == 0 && i + 1 < argc && strcmp(argv[i + 1], "gtk") == 0) {+ i++;+ continue;+ }+ if (strcmp(argv[i], "--plugin=gtk") == 0) {+ continue;+ }+ args[out++] = argv[i];+ }+ args[out] = NULL;+ execv(args[0], args);+ perror("execv linuxdeploy");+ return 127;+ }+ EOF+ $CC linuxdeploy-wrapper.c -o linuxdeploy-x86_64.AppImage+ '';+ installPhase = ''+ install -Dm0755 linuxdeploy-x86_64.AppImage "$out/bin/linuxdeploy-x86_64.AppImage"+ '';+ };+ tauriAppImageRuntime = pkgs.fetchurl {+ # Do not use the mutable "continuous" release: tag-push builds must be reproducible.+ url = "https://github.com/AppImage/type2-runtime/releases/download/20251108/runtime-x86_64";+ hash = "sha256-L8qLRDySUQ8Ug6iD9gBhrQm0a5eLJjHIB82HOkfsJg0=";+ };+ tauriLinuxdeployAppimagePluginSource = pkgs.fetchurl {+ # Do not use the mutable "continuous" release: tag-push builds must be reproducible.+ url = "https://github.com/linuxdeploy/linuxdeploy-plugin-appimage/releases/download/1-alpha-20250213-1/linuxdeploy-plugin-appimage-x86_64.AppImage";+ hash = "sha256-mS1QKiSOFKsYVEjd9vbn0lVYy4TUYjw1TDrzUMJfzLM=";+ };+ tauriLinuxdeployAppimagePluginExtracted = pkgs.appimageTools.extractType2 {+ pname = "linuxdeploy-plugin-appimage";+ version = "1-alpha-20250213-1";+ src = tauriLinuxdeployAppimagePluginSource;+ };+ tauriLinuxdeployAppimagePlugin = pkgs.stdenvNoCC.mkDerivation {+ pname = "linuxdeploy-plugin-appimage-patched";+ version = "1-alpha-20250213-1";+ dontUnpack = true;+ installPhase = ''+ mkdir -p "$out/lib/linuxdeploy-plugin-appimage" "$out/bin"+ cp -a ${tauriLinuxdeployAppimagePluginExtracted}/. "$out/lib/linuxdeploy-plugin-appimage/"+ chmod -R u+w "$out/lib/linuxdeploy-plugin-appimage"+ patchShebangs "$out/lib/linuxdeploy-plugin-appimage"+ printf '%s\n' \+ '#!${pkgs.runtimeShell}' \+ 'exec "'$out'/lib/linuxdeploy-plugin-appimage/AppRun" "$@"' \+ > "$out/bin/linuxdeploy-plugin-appimage.AppImage"+ chmod 0755 "$out/bin/linuxdeploy-plugin-appimage.AppImage"+ '';+ };+ tauriRuntimeLibraries = [+ pkgs.webkitgtk_4_1+ pkgs.libsoup_3+ pkgs.gtk3+ pkgs.glib+ pkgs.cairo+ pkgs.pango+ pkgs.gdk-pixbuf+ pkgs.atk+ pkgs.librsvg+ pkgs.libayatana-appindicator+ pkgs.openssl+ ];+ tauriRuntimeLibraryPath = lib.makeLibraryPath tauriRuntimeLibraries;+ tauriRuntimeClosure = pkgs.closureInfo {+ rootPaths = tauriRuntimeLibraries ++ tauri.commonArgs.buildInputs;+ };+ tauriAppImageConfig = builtins.toJSON {+ build = {+ frontendDist = "${frontend}";+ beforeBuildCommand = "";+ };+ bundle = {+ active = true;+ targets = [ "appimage" ];+ useLocalToolsDir = true;+ linux.appimage.files = {+ "/usr/bin/xdg-mime" = "${pkgs.xdg-utils}/bin/xdg-mime";+ "/usr/bin/xdg-open" = "${pkgs.xdg-utils}/bin/xdg-open";+ };+ };+ };+ tauriDesktopDmgSigningIdentity = builtins.getEnv "APPLE_SIGNING_IDENTITY";+ tauriDesktopDmgConfig = builtins.toJSON (+ lib.recursiveUpdate+ {+ build = {+ frontendDist = "${frontend}";+ beforeBuildCommand = "";+ };+ bundle = {+ active = true;+ targets = [ "app" ];+ };+ }+ (+ lib.optionalAttrs (tauriDesktopDmgSigningIdentity != "") {+ bundle.macOS.signingIdentity = tauriDesktopDmgSigningIdentity;+ }+ )+ );+ tauriDesktopDmg = craneLib.mkCargoDerivation (+ tauri.commonArgs+ // {+ cargoArtifacts = tauri.cargoArtifacts;+ pname = "macro-tauri-desktop-dmg";+ TAURI_CONFIG = tauriDesktopDmgConfig;+ APPLE_SIGNING_IDENTITY = tauriDesktopDmgSigningIdentity;+ nativeBuildInputs = tauri.commonArgs.nativeBuildInputs ++ [ pkgs.cargo-tauri ];+ preBuild = ''+ if [ -z "$APPLE_SIGNING_IDENTITY" ]; then+ echo "APPLE_SIGNING_IDENTITY must be set when building the signed macOS DMG; use nix build --impure." >&2+ exit 1+ fi+ export PATH="$PATH:/usr/bin:/bin:/usr/sbin:/sbin"+ ${tauri.commonArgs.preBuild or ""}+ '';+ buildPhaseCargoCommand = ''+ cargo tauri build --bundles app \+ --features tauri/custom-protocol \+ --config "$TAURI_CONFIG"+ '';+ installPhaseCommand = ''+ export PATH="$PATH:/usr/bin:/bin:/usr/sbin:/sbin"++ appPath=$(find target -type d -path '*/release/bundle/macos/*.app' -print -quit)+ if [ -z "$appPath" ]; then+ echo "failed to locate built macOS app bundle" >&2+ find target -path '*/bundle/*' -print >&2 || true+ exit 1+ fi++ bundle_nix_dylibs() {+ local app="$1"+ local frameworks="$app/Contents/Frameworks"+ mkdir -p "$frameworks"++ local -a queue=()+ while IFS= read -r -d "" mach_o; do+ if otool -hv "$mach_o" >/dev/null 2>&1; then+ queue+=("$mach_o")+ fi+ done < <(find "$app/Contents/MacOS" "$frameworks" -type f -print0)++ local processed="$TMPDIR/bundled-mach-o-files"+ : > "$processed"++ copy_dep() {+ local dep="$1"+ local base+ base=$(basename "$dep")+ local dest="$frameworks/$base"+ if [ ! -e "$dest" ]; then+ echo "Bundling Nix dylib $dep -> $dest" >&2+ cp -L "$dep" "$dest"+ chmod u+w "$dest"+ queue+=("$dest")+ fi+ }++ local i=0+ while [ "$i" -lt "''${#queue[@]}" ]; do+ local binary="''${queue[$i]}"+ i=$((i + 1))++ if grep -Fxq "$binary" "$processed"; then+ continue+ fi+ printf '%s\n' "$binary" >> "$processed"++ chmod u+w "$binary" || true+ local prefix="@loader_path"+ case "$binary" in+ "$app/Contents/MacOS/"*) prefix="@executable_path/../Frameworks" ;;+ *) install_name_tool -id "@loader_path/$(basename "$binary")" "$binary" 2>/dev/null || true ;;+ esac++ local deps+ deps=$(otool -L "$binary" 2>/dev/null | awk 'NR > 1 { print $1 }' | grep '^/nix/store/.*\.dylib$' || true)+ if [ -z "$deps" ]; then+ continue+ fi++ while IFS= read -r dep; do+ [ -n "$dep" ] || continue+ copy_dep "$dep"+ install_name_tool -change "$dep" "$prefix/$(basename "$dep")" "$binary"+ done <<< "$deps"+ done++ local remaining_refs="$TMPDIR/remaining-nix-dylib-refs"+ : > "$remaining_refs"+ while IFS= read -r -d "" file; do+ otool -L "$file" 2>/dev/null \+ | awk -v file="$file" 'NR > 1 && $1 ~ "^/nix/store/.*\\.dylib$" { print file ": " $1 }' \+ >> "$remaining_refs" || true+ done < <(find "$app/Contents/MacOS" "$app/Contents/Frameworks" -type f -print0)++ if [ -s "$remaining_refs" ]; then+ echo "App bundle still contains absolute Nix dylib references:" >&2+ cat "$remaining_refs" >&2+ exit 1+ fi+ }++ sign_darwin_app() {+ local app="$1"+ local -a sign_args=(--force --sign "$APPLE_SIGNING_IDENTITY")+ if [ "$APPLE_SIGNING_IDENTITY" != "-" ]; then+ sign_args+=(--timestamp --options runtime)+ fi++ if [ -d "$app/Contents/Frameworks" ]; then+ while IFS= read -r -d "" file; do+ if otool -hv "$file" >/dev/null 2>&1; then+ codesign "''${sign_args[@]}" "$file"+ fi+ done < <(find "$app/Contents/Frameworks" -type f -print0)+ fi++ codesign "''${sign_args[@]}" --deep "$app"+ codesign --verify --deep --strict --verbose=2 "$app"+ }++ bundle_nix_dylibs "$appPath"+ sign_darwin_app "$appPath"++ mkdir -p "$out"+ dmgPath="$out/Macro-${appVersion}-${system}.dmg"+ hdiutil create \+ -volname "Macro" \+ -srcfolder "$appPath" \+ -ov \+ -format UDZO \+ "$dmgPath"++ if [ "$APPLE_SIGNING_IDENTITY" = "-" ]; then+ codesign --force --sign - "$dmgPath"+ else+ codesign --force --sign "$APPLE_SIGNING_IDENTITY" --timestamp "$dmgPath"+ fi+ codesign --verify --strict --verbose=2 "$dmgPath"+ '';+ doInstallCargoArtifacts = false;+ }+ );++ tauriDesktopAppImage = craneLib.mkCargoDerivation (+ tauri.commonArgs+ // {+ cargoArtifacts = tauri.cargoArtifacts;+ pname = "macro-tauri-desktop-appimage";+ TAURI_CONFIG = tauriAppImageConfig;+ nativeBuildInputs = tauri.commonArgs.nativeBuildInputs ++ [+ pkgs.cargo-tauri+ pkgs.bash+ pkgs.coreutils+ pkgs.diffutils+ pkgs.file+ pkgs.findutils+ pkgs.gawk+ pkgs.gnugrep+ pkgs.gnused+ pkgs.patchelf+ pkgs.which+ ];+ LD_LIBRARY_PATH = tauriRuntimeLibraryPath;+ LDAI_RUNTIME_FILE = tauriAppImageRuntime;+ preBuild = ''+ ${tauri.commonArgs.preBuild or ""}++ runtime_library_path="$(while IFS= read -r store_path; do+ if [ -d "$store_path/lib" ]; then+ printf '%s:' "$store_path/lib"+ fi+ done < ${tauriRuntimeClosure}/store-paths)"+ export LD_LIBRARY_PATH="$runtime_library_path$LD_LIBRARY_PATH"++ mkdir -p target/.tauri+ install -m 0755 ${tauriAppRun} target/.tauri/AppRun-x86_64+ install -m 0755 ${tauriLinuxdeployWrapper}/bin/linuxdeploy-x86_64.AppImage target/.tauri/linuxdeploy-x86_64.AppImage+ install -m 0755 ${tauriLinuxdeployAppimagePlugin}/bin/linuxdeploy-plugin-appimage.AppImage target/.tauri/linuxdeploy-plugin-appimage.AppImage+ install -m 0755 ${tauriBundlerSource}/crates/tauri-bundler/src/bundle/linux/appimage/linuxdeploy-plugin-gtk.sh target/.tauri/linuxdeploy-plugin-gtk.sh+ install -m 0755 ${tauriBundlerSource}/crates/tauri-bundler/src/bundle/linux/appimage/linuxdeploy-plugin-gstreamer.sh target/.tauri/linuxdeploy-plugin-gstreamer.sh+ cat > target/.tauri/ldd <<'EOF'+ #!${pkgs.runtimeShell}+ set -euo pipefail++ binary="''${1:?usage: ldd <elf>}"+ if ! needed=$(patchelf --print-needed "$binary" 2>/dev/null); then+ echo "not a dynamic executable"+ exit 1+ fi++ origin=$(cd "$(dirname "$binary")" && pwd -P)+ rpath=$(patchelf --print-rpath "$binary" 2>/dev/null || true)+ search_path=""+ append_search_path() {+ local path_entry="$1"+ [ -n "$path_entry" ] || return 0+ if [ -z "$search_path" ]; then+ search_path="$path_entry"+ else+ search_path="$search_path:$path_entry"+ fi+ }++ IFS=: read -r -a rpath_entries <<< "$rpath"+ for entry in "''${rpath_entries[@]}"; do+ entry=$(printf '%s' "$entry" | awk -v origin="$origin" '{ gsub(/\$\{ORIGIN\}/, origin); gsub(/\$ORIGIN/, origin); print }')+ append_search_path "$entry"+ done+ append_search_path "''${LD_LIBRARY_PATH:-}"+ append_search_path "/lib"+ append_search_path "/usr/lib"+ append_search_path "/lib64"+ append_search_path "/usr/lib64"++ resolve_needed() {+ local needed_name="$1"+ if [ "''${needed_name#/}" != "$needed_name" ] && [ -e "$needed_name" ]; then+ readlink -f "$needed_name"+ return 0+ fi++ local entry candidate+ IFS=: read -r -a search_entries <<< "$search_path"+ for entry in "''${search_entries[@]}"; do+ [ -n "$entry" ] || continue+ candidate="$entry/$needed_name"+ if [ -e "$candidate" ]; then+ readlink -f "$candidate"+ return 0+ fi+ done++ return 1+ }++ while IFS= read -r needed_name; do+ [ -n "$needed_name" ] || continue+ if resolved=$(resolve_needed "$needed_name"); then+ printf '\t%s => %s (0x0000000000000000)\n' "$needed_name" "$resolved"+ else+ printf '\t%s => not found\n' "$needed_name"+ fi+ done <<< "$needed"+ EOF+ chmod 0755 target/.tauri/ldd+ patchShebangs target/.tauri/*.sh target/.tauri/ldd target/.tauri/linuxdeploy-plugin-appimage.AppImage+ '';+ buildPhaseCargoCommand = ''+ cargo tauri build --verbose --bundles appimage \+ --features tauri/custom-protocol \+ --config "$TAURI_CONFIG"+ '';+ installPhaseCommand = ''+ appimagePath=$(find target -type f -path '*/release/bundle/appimage/*.AppImage' -print -quit)+ if [ -z "$appimagePath" ]; then+ echo "failed to locate built AppImage" >&2+ find target -path '*/bundle/*' -print >&2 || true+ exit 1+ fi++ mkdir -p "$out"+ cp "$appimagePath" "$out/Macro-${appVersion}-${system}.AppImage"+ chmod 0755 "$out/Macro-${appVersion}-${system}.AppImage"+ '';+ doInstallCargoArtifacts = false;+ }+ );+ in+ {+ apps = lib.optionalAttrs isLinux {+ tauri-desktop = {+ type = "app";+ program = "${wrappedTauriDesktop}/bin/app";+ meta.description = "Run the Macro Tauri desktop app";+ };+ };++ packages =+ lib.optionalAttrs isLinux {+ tauri-frontend = frontend;+ tauri-desktop = wrappedTauriDesktop;+ tauri-desktop-unwrapped = tauri.app;+ tauri-desktop-cargo-artifacts = tauri.cargoArtifacts;+ }+ // lib.optionalAttrs isX86_64Linux {+ tauri-desktop-appimage = tauriDesktopAppImage;+ }+ // lib.optionalAttrs isAarch64Darwin {+ tauri-frontend = frontend;+ tauri-desktop-dmg = tauriDesktopDmg;+ tauri-desktop-cargo-artifacts = tauri.cargoArtifacts;+ };+ };+}diff --git a/rust/cloud-storage/tools/xtask/src/workflows/build_appimage_on_tag.rs b/rust/cloud-storage/tools/xtask/src/workflows/build_appimage_on_tag.rsnew file mode 100644index 0000000000..8b2a6275fd--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/workflows/build_appimage_on_tag.rs@@ -0,0 +1,57 @@+//! `Build AppImage` — reusable workflow that builds the Tauri desktop AppImage+//! via Nix. Called from [`super::build_desktop_on_tag`].++use gh_workflow::{Event, Job, Run, Step, Workflow, WorkflowCall, WorkflowCallInput};++use crate::workflows::{runners, steps};++/// Tag pattern for desktop release builds (CalVer: `v2026.6.23.1`).+/// Shared with the DMG workflow and the parent orchestrator.+pub const DESKTOP_TAG_PATTERN: &str = "v[0-9]*";++/// Build the reusable workflow.+pub fn build_appimage() -> Workflow {+ Workflow::new("Build AppImage")+ .on(+ Event::default().workflow_call(WorkflowCall::default().add_input(+ "ref",+ WorkflowCallInput {+ description: "Git ref to check out and build".into(),+ required: true,+ input_type: "string".into(),+ default: None,+ },+ )),+ )+ .add_job("build-appimage", build_appimage_job())+}++fn build_appimage_job() -> Job {+ Job::default()+ .name("Build AppImage")+ .runs_on(runners::Runner::LinuxRustCi.to_string())+ .add_step(steps::checkout_ref("${{ inputs.ref }}"))+ .add_step(steps::mount_nix_cache_volume())+ .add_step(steps::setup_nix())+ .add_step(steps::setup_cachix())+ .add_step(steps::derive_artifact_metadata("${{ inputs.ref }}"))+ .add_step(nix_build_appimage())+ .add_step(collect_appimage())+ .add_step(steps::upload_artifact(+ "macro-appimage-${{ steps.metadata.outputs.safe_tag }}",+ "artifacts/*",+ ))+ .add_step(steps::teardown_nix())+}++fn nix_build_appimage() -> Step<Run> {+ Step::new("Build AppImage with Nix")+ .run(include_str!("scripts/build_appimage.sh"))+ .shell("bash")+}++fn collect_appimage() -> Step<Run> {+ Step::new("Collect AppImage artifact")+ .run(include_str!("scripts/collect_appimage.sh"))+ .shell("bash")+}diff --git a/rust/cloud-storage/tools/xtask/src/workflows/build_desktop_on_tag.rs b/rust/cloud-storage/tools/xtask/src/workflows/build_desktop_on_tag.rsnew file mode 100644index 0000000000..a09c0cee6e--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/workflows/build_desktop_on_tag.rs@@ -0,0 +1,88 @@+//! `Build Desktop on Tag` — orchestrator workflow that triggers AppImage and DMG+//! builds in parallel when a release tag is pushed. Also supports manual+//! dispatch. Generated into `build_desktop_on_tag.yml`.+//!+//! The actual build logic lives in the reusable workflows defined in+//! [`super::build_appimage_on_tag`] and [`super::build_dmg_on_tag`].+//!+//! This workflow is rendered by hand because `gh-workflow` 0.8's `Job` struct+//! cannot represent reusable-workflow calling jobs (`with:` ++//! `secrets: inherit`), and we don't want to add a direct YAML serializer+//! dependency to `xtask` just for this one workflow.++use crate::workflows::build_appimage_on_tag;++/// Build the workflow YAML body.+pub fn build_desktop_on_tag() -> String {+ format!(+ indoc::indoc! {r#"+ name: Build Desktop on Tag+ 'on':+ push:+ tags:+ - {desktop_tag_pattern}+ create: {{}}+ workflow_dispatch:+ inputs:+ ref:+ description: Release tag to build (v* or refs/tags/v*). Defaults to the selected protected ref or release tag.+ required: false+ type: string+ concurrency:+ group: desktop-${{{{ inputs.ref || (github.event.ref_type == 'tag' && github.event.ref || github.ref_name) }}}}+ cancel-in-progress: true+ jobs:+ resolve-ref:+ if: github.event_name == 'workflow_dispatch' || github.event_name == 'push' || (github.event_name == 'create' && github.event.ref_type == 'tag')+ name: Resolve build ref+ runs-on: ubuntu-latest+ outputs:+ ref: ${{{{ steps.resolve.outputs.ref }}}}+ steps:+ - id: resolve+ name: Resolve ref+ run: |+ {resolve_ref_script}+ shell: bash+ env:+ EVENT_NAME: ${{{{ github.event_name }}}}+ INPUT_REF: ${{{{ inputs.ref }}}}+ GITHUB_EVENT_REF: ${{{{ github.event.ref }}}}+ GITHUB_EVENT_REF_TYPE: ${{{{ github.event.ref_type }}}}+ SELECTED_REF: ${{{{ github.ref }}}}+ SELECTED_REF_NAME: ${{{{ github.ref_name }}}}+ SELECTED_REF_PROTECTED: ${{{{ github.ref_protected }}}}+ build-appimage:+ needs:+ - resolve-ref+ uses: './.github/workflows/build_appimage_on_tag.yml'+ with:+ ref: ${{{{ needs.resolve-ref.outputs.ref }}}}+ secrets: inherit+ build-dmg:+ needs:+ - resolve-ref+ uses: './.github/workflows/build_dmg_on_tag.yml'+ with:+ ref: ${{{{ needs.resolve-ref.outputs.ref }}}}+ secrets: inherit+ "#},+ desktop_tag_pattern = build_appimage_on_tag::DESKTOP_TAG_PATTERN,+ resolve_ref_script = indent(include_str!("scripts/resolve_desktop_ref.sh"), 8),+ )+}++fn indent(value: &str, spaces: usize) -> String {+ let prefix = " ".repeat(spaces);+ value+ .lines()+ .map(|line| {+ if line.is_empty() {+ String::new()+ } else {+ format!("{prefix}{line}")+ }+ })+ .collect::<Vec<_>>()+ .join("\n")+}diff --git a/rust/cloud-storage/tools/xtask/src/workflows/build_dmg_on_tag.rs b/rust/cloud-storage/tools/xtask/src/workflows/build_dmg_on_tag.rsnew file mode 100644index 0000000000..7e7c36b5ab--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/workflows/build_dmg_on_tag.rs@@ -0,0 +1,92 @@+//! `Build macOS DMG` — reusable workflow that builds the Tauri desktop DMG via+//! Nix. Called from [`super::build_desktop_on_tag`].++use gh_workflow::{Event, Job, Run, Step, Workflow, WorkflowCall, WorkflowCallInput};++use crate::workflows::{steps, vars};++/// Build the reusable workflow.+pub fn build_dmg() -> Workflow {+ Workflow::new("Build macOS DMG")+ .on(+ Event::default().workflow_call(WorkflowCall::default().add_input(+ "ref",+ WorkflowCallInput {+ description: "Git ref to check out and build".into(),+ required: true,+ input_type: "string".into(),+ default: None,+ },+ )),+ )+ .add_job("build-dmg", build_dmg_job())+}++fn build_dmg_job() -> Job {+ Job::default()+ .name("Build macOS DMG")+ .runs_on("macos-15")+ .add_step(steps::checkout_ref("${{ inputs.ref }}"))+ .add_step(assert_arm64())+ .add_step(install_nix_macos())+ .add_step(steps::setup_cachix())+ .add_step(configure_signing_identity())+ .add_step(steps::derive_artifact_metadata("${{ inputs.ref }}"))+ .add_step(nix_build_dmg())+ .add_step(collect_dmg())+ .add_step(validate_signed_dmg())+ .add_step(steps::upload_artifact(+ "macro-dmg-${{ steps.metadata.outputs.safe_tag }}",+ "artifacts/*",+ ))+}++fn assert_arm64() -> Step<Run> {+ Step::new("Assert arm64 runner")+ .run(indoc::indoc! {r#"+ set -euo pipefail+ if [ "$(uname -m)" != "arm64" ]; then+ echo "macOS DMG builds must run on an arm64/aarch64 runner, got $(uname -m)" >&2+ exit 1+ fi+ "#})+ .shell("bash")+}++fn install_nix_macos() -> Step<Run> {+ Step::new("Install Nix")+ .run(include_str!("scripts/install_nix_macos.sh"))+ .shell("bash")+}++fn configure_signing_identity() -> Step<Run> {+ Step::new("Configure signing identity")+ .run(include_str!("scripts/configure_signing_identity.sh"))+ .shell("bash")+ .add_env((+ "MACOS_DEVELOPER_ID_CERTIFICATE_BASE64",+ vars::MACOS_DEVELOPER_ID_CERTIFICATE_BASE64,+ ))+ .add_env((+ "MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD",+ vars::MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD,+ ))+}++fn nix_build_dmg() -> Step<Run> {+ Step::new("Build DMG with Nix")+ .run(include_str!("scripts/build_dmg.sh"))+ .shell("bash")+}++fn collect_dmg() -> Step<Run> {+ Step::new("Collect DMG artifact")+ .run(include_str!("scripts/collect_dmg.sh"))+ .shell("bash")+}++fn validate_signed_dmg() -> Step<Run> {+ Step::new("Validate signed DMG")+ .run(include_str!("scripts/validate_signed_dmg.sh"))+ .shell("bash")+}diff --git a/rust/cloud-storage/tools/xtask/src/workflows/mod.rs b/rust/cloud-storage/tools/xtask/src/workflows/mod.rsindex 5b058d45bd..9c6b00f9bb 100644--- a/rust/cloud-storage/tools/xtask/src/workflows/mod.rs+++ b/rust/cloud-storage/tools/xtask/src/workflows/mod.rs@@ -9,6 +9,9 @@//! files — [`runners`] (runner labels), [`vars`] (env / secrets / concurrency),//! and [`steps`] (reusable step + job helpers).+mod build_appimage_on_tag;+mod build_desktop_on_tag;+mod build_dmg_on_tag;mod check_generated;mod code_check_cloud_storage;mod runners;@@ -27,8 +30,8 @@ use gh_workflow::Workflow;/// checks key on a job *name*, not the filename, so renaming files is safe.)struct WorkflowFile {slug: &'static str,- /// Builds the workflow definition.- build: fn() -> Workflow,+ /// Produces the YAML body for this workflow.+ render_yaml: fn() -> Result<String>,}impl WorkflowFile {@@ -38,15 +41,32 @@ impl WorkflowFile {}}+/// Render a `gh_workflow::Workflow` to YAML. Used by most workflow modules.+fn render_gh_workflow(build: fn() -> Workflow) -> impl Fn() -> Result<String> {+ move || build().to_string().map_err(|e| anyhow::anyhow!("{e:?}"))+}+/// Every workflow we generate. Add new workflows here.const WORKFLOWS: &[WorkflowFile] = &[+ WorkflowFile {+ slug: "build_appimage_on_tag",+ render_yaml: || render_gh_workflow(build_appimage_on_tag::build_appimage)(),+ },+ WorkflowFile {+ slug: "build_dmg_on_tag",+ render_yaml: || render_gh_workflow(build_dmg_on_tag::build_dmg)(),+ },+ WorkflowFile {+ slug: "build_desktop_on_tag",+ render_yaml: || Ok(build_desktop_on_tag::build_desktop_on_tag()),+ },WorkflowFile {slug: "code_check_cloud_storage",- build: code_check_cloud_storage::code_check_cloud_storage,+ render_yaml: || render_gh_workflow(code_check_cloud_storage::code_check_cloud_storage)(),},WorkflowFile {slug: "check_generated",- build: check_generated::check_generated_workflows,+ render_yaml: || render_gh_workflow(check_generated::check_generated_workflows)(),},];@@ -86,9 +106,8 @@ pub fn check() -> Result<()> {/// Serialize a workflow to YAML and prepend the "do not edit" header.fn render(workflow: &WorkflowFile) -> Result<String> {- let yaml = (workflow.build)()- .to_string()- .map_err(|e| anyhow::anyhow!("serializing {}: {e:?}", workflow.file_name()))?;+ let yaml = (workflow.render_yaml)()+ .with_context(|| format!("serializing {}", workflow.file_name()))?;Ok(format!("{}{yaml}", disclaimer(workflow.slug)))}diff --git a/rust/cloud-storage/tools/xtask/src/workflows/scripts/build_appimage.sh b/rust/cloud-storage/tools/xtask/src/workflows/scripts/build_appimage.shnew file mode 100644index 0000000000..654483696b--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/workflows/scripts/build_appimage.sh@@ -0,0 +1,59 @@+set -euo pipefail+cachix_pid=+if command -v cachix >/dev/null 2>&1 && [ -n "${CACHIX_CACHE_NAME:-}" ]; then+ cachix watch-store "$CACHIX_CACHE_NAME" >/tmp/cachix-watch-store.log 2>&1 &+ cachix_pid=$!+ trap 'if [ -n "${cachix_pid:-}" ]; then kill "$cachix_pid" 2>/dev/null || true; wait "$cachix_pid" 2>/dev/null || true; fi' EXIT+fi+restart_nix_daemon() {+ echo "::warning::Restarting nix-daemon before retrying AppImage build."+ sudo systemctl restart nix-daemon.service 2>/dev/null || true+ sudo pkill -x nix-daemon 2>/dev/null || true+ sudo rm -f /nix/var/nix/daemon-socket/socket+ sudo mkdir -p /nix/var/nix/daemon-socket+ sudo sh -c 'nohup /nix/var/nix/profiles/default/bin/nix-daemon >/tmp/nix-daemon-retry.log 2>&1 &'+ for _ in $(seq 1 30); do+ if sudo test -S /nix/var/nix/daemon-socket/socket; then+ return 0+ fi+ sleep 1+ done+ echo "nix-daemon failed to restart; log follows:" >&2+ sudo cat /tmp/nix-daemon-retry.log >&2 || true+ return 1+}++build_appimage() {+ local attempt="$1"+ local -a fallback_args=()+ if [ "$attempt" -eq 3 ]; then+ fallback_args=(--fallback)+ fi++ # Force a hermetic Nix sandbox for linuxdeploy. Namespace's restored+ # Nix daemon can otherwise run unsandboxed under /nix/var/nix/builds,+ # where linuxdeploy sees host libraries/tools and can fail with only+ # `failed to run linuxdeploy` in Tauri's default output.+ nix build \+ "${fallback_args[@]}" \+ --option sandbox true \+ --option sandbox-build-dir /build \+ --option download-attempts 10 \+ --print-build-logs \+ ".#tauri-desktop-appimage"+}++for attempt in 1 2 3; do+ if build_appimage "$attempt"; then+ break+ fi+ if [ "$attempt" -eq 3 ]; then+ exit 1+ fi+ echo "::warning::AppImage nix build failed on attempt $attempt; retrying."+ restart_nix_daemon+ sleep $((attempt * 10))+done+if command -v cachix >/dev/null 2>&1 && [ -n "${CACHIX_CACHE_NAME:-}" ]; then+ cachix push "$CACHIX_CACHE_NAME" result || echo "::warning::Failed to push AppImage result closure to Cachix."+fidiff --git a/rust/cloud-storage/tools/xtask/src/workflows/scripts/build_dmg.sh b/rust/cloud-storage/tools/xtask/src/workflows/scripts/build_dmg.shnew file mode 100644index 0000000000..f2aded86ab--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/workflows/scripts/build_dmg.sh@@ -0,0 +1,11 @@+set -euo pipefail+cachix_pid=+if command -v cachix >/dev/null 2>&1 && [ -n "${CACHIX_CACHE_NAME:-}" ]; then+ cachix watch-store "$CACHIX_CACHE_NAME" >/tmp/cachix-watch-store.log 2>&1 &+ cachix_pid=$!+ trap 'if [ -n "${cachix_pid:-}" ]; then kill "$cachix_pid" 2>/dev/null || true; wait "$cachix_pid" 2>/dev/null || true; fi' EXIT+fi+nix build --impure --option sandbox false --print-build-logs ".#packages.aarch64-darwin.tauri-desktop-dmg"+if command -v cachix >/dev/null 2>&1 && [ -n "${CACHIX_CACHE_NAME:-}" ]; then+ cachix push "$CACHIX_CACHE_NAME" result || echo "::warning::Failed to push DMG result closure to Cachix."+fidiff --git a/rust/cloud-storage/tools/xtask/src/workflows/scripts/collect_appimage.sh b/rust/cloud-storage/tools/xtask/src/workflows/scripts/collect_appimage.shnew file mode 100644index 0000000000..60a139810f--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/workflows/scripts/collect_appimage.sh@@ -0,0 +1,12 @@+set -euo pipefail+mkdir -p artifacts+shopt -s nullglob+appimages=(result/*.AppImage)+if [ "${#appimages[@]}" -eq 0 ]; then+ echo "No AppImage files found in nix build result" >&2+ find -L result -maxdepth 2 -type f -print >&2 || true+ exit 1+fi+cp -v "${appimages[@]}" artifacts/+chmod 0755 artifacts/*.AppImage+(cd artifacts && sha256sum -- *.AppImage > SHA256SUMS)diff --git a/rust/cloud-storage/tools/xtask/src/workflows/scripts/collect_dmg.sh b/rust/cloud-storage/tools/xtask/src/workflows/scripts/collect_dmg.shnew file mode 100644index 0000000000..069f8826a1--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/workflows/scripts/collect_dmg.sh@@ -0,0 +1,10 @@+set -euo pipefail+mkdir -p artifacts+shopt -s nullglob+dmgs=(result/*.dmg)+if [ "${#dmgs[@]}" -eq 0 ]; then+ echo "No DMG files found in nix build result" >&2+ find -L result -maxdepth 2 -type f -print >&2 || true+ exit 1+fi+cp -v "${dmgs[@]}" artifacts/diff --git a/rust/cloud-storage/tools/xtask/src/workflows/scripts/configure_signing_identity.sh b/rust/cloud-storage/tools/xtask/src/workflows/scripts/configure_signing_identity.shnew file mode 100644index 0000000000..56ba56d067--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/workflows/scripts/configure_signing_identity.sh@@ -0,0 +1,36 @@+set -euo pipefail+if [ -z "${MACOS_DEVELOPER_ID_CERTIFICATE_BASE64}" ] || [ -z "${MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD}" ]; then+ echo "Developer ID certificate secrets are not configured; using ad-hoc signing for build validation."+ echo "APPLE_SIGNING_IDENTITY=-" >> "$GITHUB_ENV"+ exit 0+fi++certificate_path="$RUNNER_TEMP/developer-id-application.p12"+printf '%s' "$MACOS_DEVELOPER_ID_CERTIFICATE_BASE64" | base64 --decode > "$certificate_path" 2>/dev/null \+ || printf '%s' "$MACOS_DEVELOPER_ID_CERTIFICATE_BASE64" | base64 -D > "$certificate_path"++# Nix's macOS daemon builds as _nixbld users, not the runner user.+# Put the Developer ID identity in the system keychain so codesign can+# find it from inside the Nix build without embedding certificate+# secrets into the derivation.+sudo security import "$certificate_path" \+ -k /Library/Keychains/System.keychain \+ -P "$MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD" \+ -A \+ -T /usr/bin/codesign \+ -T /usr/bin/security+sudo security set-key-partition-list \+ -S apple-tool:,apple:,codesign: \+ -s \+ -k "" \+ /Library/Keychains/System.keychain || true++identity=$(security find-identity -v -p codesigning /Library/Keychains/System.keychain \+ | awk -F '"' '/Developer ID Application/ { print $2; exit }')+if [ -z "$identity" ]; then+ echo "No Developer ID Application identity found in System.keychain" >&2+ security find-identity -v -p codesigning /Library/Keychains/System.keychain >&2 || true+ exit 1+fi+echo "APPLE_SIGNING_IDENTITY=$identity" >> "$GITHUB_ENV"+echo "Using signing identity: $identity"diff --git a/rust/cloud-storage/tools/xtask/src/workflows/scripts/install_nix_macos.sh b/rust/cloud-storage/tools/xtask/src/workflows/scripts/install_nix_macos.shnew file mode 100644index 0000000000..75ec8319eb--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/workflows/scripts/install_nix_macos.sh@@ -0,0 +1,14 @@+set -euo pipefail+if ! command -v nix >/dev/null 2>&1; then+ curl --http1.1 --retry 5 --retry-delay 5 --retry-all-errors \+ --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | \+ sh -s -- install macos --no-confirm \+ --extra-conf "experimental-features = nix-command flakes" \+ --extra-conf "sandbox = false" \+ --extra-conf "trusted-users = root runner"+fi+echo "/nix/var/nix/profiles/default/bin" >> "$GITHUB_PATH"+echo "NIX_REMOTE=daemon" >> "$GITHUB_ENV"+export PATH="/nix/var/nix/profiles/default/bin:$PATH"+export NIX_REMOTE=daemon+nix --versiondiff --git a/rust/cloud-storage/tools/xtask/src/workflows/scripts/resolve_desktop_ref.sh b/rust/cloud-storage/tools/xtask/src/workflows/scripts/resolve_desktop_ref.shnew file mode 100644index 0000000000..4488146c89--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/workflows/scripts/resolve_desktop_ref.sh@@ -0,0 +1,40 @@+set -euo pipefail++# Resolve the git ref for desktop builds from any trigger type:+# push (tag) → github.ref+# create (tag) → github.event.ref+# workflow_dispatch → inputs.ref (validated) or github.ref (protected)++case "$EVENT_NAME" in+ push)+ echo "ref=$SELECTED_REF" >> "$GITHUB_OUTPUT"+ ;;+ create)+ if [ "$GITHUB_EVENT_REF_TYPE" != "tag" ]; then+ echo "create event was not a tag; skipping" >&2+ exit 1+ fi+ echo "ref=$GITHUB_EVENT_REF" >> "$GITHUB_OUTPUT"+ ;;+ workflow_dispatch)+ ref="${INPUT_REF:-$SELECTED_REF}"+ if [[ "$ref" =~ ^refs/tags/v[0-9][0-9A-Za-z._-]*$ ]]; then+ echo "ref=$ref" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ if [[ "$ref" =~ ^v[0-9][0-9A-Za-z._-]*$ ]]; then+ echo "ref=refs/tags/$ref" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ if [ -z "$INPUT_REF" ] && [ "$SELECTED_REF_PROTECTED" = "true" ]; then+ echo "ref=$SELECTED_REF" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ echo "Manual desktop builds only allow release tags (v*) or a protected ref." >&2+ exit 1+ ;;+ *)+ echo "Unexpected event: $EVENT_NAME" >&2+ exit 1+ ;;+esacdiff --git a/rust/cloud-storage/tools/xtask/src/workflows/scripts/validate_signed_dmg.sh b/rust/cloud-storage/tools/xtask/src/workflows/scripts/validate_signed_dmg.shnew file mode 100644index 0000000000..80766f44aa--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/workflows/scripts/validate_signed_dmg.sh@@ -0,0 +1,39 @@+set -euo pipefail+dmg=$(find artifacts -maxdepth 1 -type f -name '*.dmg' -print -quit)+if [ -z "$dmg" ]; then+ echo "No DMG found to validate" >&2+ exit 1+fi+codesign --verify --strict --verbose=2 "$dmg"++mount_dir=$(mktemp -d)+hdiutil attach -readonly -nobrowse -mountpoint "$mount_dir" "$dmg"+trap 'hdiutil detach "$mount_dir" >/dev/null 2>&1 || true; rmdir "$mount_dir" >/dev/null 2>&1 || true' EXIT+app=$(find "$mount_dir" -maxdepth 2 -type d -name '*.app' -print -quit)+if [ -z "$app" ] && [ -d "$mount_dir/Contents" ]; then+ app="$mount_dir"+fi+if [ -z "$app" ]; then+ echo "No app bundle found in DMG" >&2+ find "$mount_dir" -maxdepth 2 -print >&2 || true+ exit 1+fi+codesign --verify --deep --strict --verbose=2 "$app"++dylib_refs=$(mktemp)+search_roots=("$app/Contents/MacOS")+if [ -d "$app/Contents/Frameworks" ]; then+ search_roots+=("$app/Contents/Frameworks")+fi+while IFS= read -r -d '' file; do+ otool -L "$file" 2>/dev/null \+ | awk -v file="$file" 'NR > 1 && $1 ~ "^/nix/store/.*\\.dylib$" { print file ": " $1 }' \+ >> "$dylib_refs" || true+done < <(find "${search_roots[@]}" -type f -print0)+if [ -s "$dylib_refs" ]; then+ echo "App bundle contains absolute Nix dylib references:" >&2+ cat "$dylib_refs" >&2+ exit 1+fi++(cd artifacts && shasum -a 256 -- *.dmg > SHA256SUMS)diff --git a/rust/cloud-storage/tools/xtask/src/workflows/steps.rs b/rust/cloud-storage/tools/xtask/src/workflows/steps.rsindex d35ac07ed3..0b93646cc6 100644--- a/rust/cloud-storage/tools/xtask/src/workflows/steps.rs+++ b/rust/cloud-storage/tools/xtask/src/workflows/steps.rs@@ -121,3 +121,80 @@ pub fn gated_job() -> Job {"needs.path-check.outputs.should_run == 'true' && github.event.pull_request.draft == false",))}++// ---------------------------------------------------------------------------+// Desktop (AppImage / DMG) shared steps+// ---------------------------------------------------------------------------++/// `actions/checkout` with a dynamic ref (for tag-triggered builds). Uses the+/// same pinned SHA as [`checkout`].+pub fn checkout_ref(ref_expr: &str) -> Step<Use> {+ Step::new("Checkout Repo")+ .uses(+ "actions",+ "checkout",+ "df4cb1c069e1874edd31b4311f1884172cec0e10",+ ) // v6+ .add_with(("ref", ref_expr))+ .add_with(("persist-credentials", false))+}++/// Mount only the `/nix` store cache volume (no cargo/sccache). Used by the+/// desktop builds that delegate entirely to Nix.+pub fn mount_nix_cache_volume() -> Step<Use> {+ Step::new("Mount /nix cache volume")+ .uses(+ "namespacelabs",+ "nscloud-cache-action",+ "15799a6b54e5765f85b2aac25b3f0df43ed571c0", // v1.4.3+ )+ .add_with(("path", "/nix"))+ .continue_on_error(true)+}++/// Configure Cachix (without entering a dev shell).+pub fn setup_cachix() -> Step<Use> {+ uses_local(+ "Configure Cachix fallback",+ "./.github/actions/setup-cachix",+ )+ .add_with(("cachix-auth-token", vars::CACHIX_AUTH_TOKEN))+}++/// Derive a safe tag name from the git ref for use in artifact names.+pub fn derive_artifact_metadata(raw_ref_expr: &str) -> Step<Run> {+ Step::new("Derive artifact metadata")+ .run(indoc::indoc! {r#"+ set -euo pipefail+ tag="${RAW_REF#refs/tags/}"+ if [ -z "$tag" ]; then+ tag="${GITHUB_REF_NAME:-untagged}"+ fi+ safe_tag=$(printf '%s' "$tag" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')+ echo "tag=$tag" >> "$GITHUB_OUTPUT"+ echo "safe_tag=$safe_tag" >> "$GITHUB_OUTPUT"+ "#})+ .id("metadata")+ .shell("bash")+ .add_env(("RAW_REF", raw_ref_expr))+}++/// Upload build artifacts via `actions/upload-artifact`, pinned.+pub fn upload_artifact(name: &str, path: &str) -> Step<Use> {+ Step::new(format!("Upload {name} artifact"))+ .uses(+ "actions",+ "upload-artifact",+ "ea165f8d65b6e75b540449e92b4886f43607fa02",+ ) // v4+ .add_with(("name", name))+ .add_with(("path", path))+ .add_with(("if-no-files-found", "error"))+ .add_with(("retention-days", 30))+}++/// Teardown Nix (always runs).+pub fn teardown_nix() -> Step<Use> {+ uses_local("Teardown Nix", "./.github/actions/teardown-nix")+ .if_condition(Expression::new("always()"))+}diff --git a/rust/cloud-storage/tools/xtask/src/workflows/vars.rs b/rust/cloud-storage/tools/xtask/src/workflows/vars.rsindex 5567bea1a2..3509a5f697 100644--- a/rust/cloud-storage/tools/xtask/src/workflows/vars.rs+++ b/rust/cloud-storage/tools/xtask/src/workflows/vars.rs@@ -13,6 +13,8 @@ macro_rules! secret {secret!(CACHIX_AUTH_TOKEN);secret!(DOPPLER_TOKEN);+secret!(MACOS_DEVELOPER_ID_CERTIFICATE_BASE64);+secret!(MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD);/// Nextest thread count for the test job. Tuned for the previous/// `linux-extra-beefy` runner; revisit if `namespace-profile-linux-mid` is