{
  lib,
  cfg,
  pkgs,
  config,
  opensessionsCheckout,
  opensessionsCurrent,
  opensessionsRuntimeRoot,
  opensessionsConfigJson,
  ...
}:
{
  home-manager.users.${config.user.name} =
    { lib, ... }:
    {
      home.activation.opensessions-setup = lib.mkIf cfg.opensessions.enable (
        lib.hm.dag.entryAfter [ "writeBoundary" ] ''
          checkout_root="${opensessionsCheckout}"
          current_link="${opensessionsCurrent}"

          ${pkgs.coreutils}/bin/mkdir -p "${opensessionsRuntimeRoot}" "$checkout_root"
          ${pkgs.rsync}/bin/rsync -a --no-perms --delete --exclude node_modules --exclude .git \
            "${pkgs.my.opensessions}/share/opensessions/" \
            "$checkout_root/"

          # Source is copied from the read-only Nix store; make runtime checkout writable.
          ${pkgs.coreutils}/bin/chmod -R u+w "$checkout_root"

          lock_hash_file="$checkout_root/.bun-lock.sha256"
          current_lock_hash=""
          previous_lock_hash=""
          needs_install=0

          if [ -f "$checkout_root/bun.lock" ]; then
            current_lock_hash="$(${pkgs.coreutils}/bin/sha256sum "$checkout_root/bun.lock" | ${pkgs.gawk}/bin/awk '{print $1}')"
            if [ -f "$lock_hash_file" ]; then
              previous_lock_hash="$(${pkgs.coreutils}/bin/cat "$lock_hash_file")"
            fi
          fi

          if [ ! -d "$checkout_root/node_modules" ]; then
            needs_install=1
          elif [ -n "$current_lock_hash" ] && [ "$current_lock_hash" != "$previous_lock_hash" ]; then
            needs_install=1
          fi

          if [ "$needs_install" -eq 1 ]; then
            echo "Bootstrapping opensessions dependencies at $checkout_root..." >&2
            if (cd "$checkout_root" && ${pkgs.bun}/bin/bun install --silent --frozen-lockfile); then
              if [ -n "$current_lock_hash" ]; then
                ${pkgs.coreutils}/bin/printf '%s\n' "$current_lock_hash" > "$lock_hash_file"
              fi
            else
              echo "Warning: bun install failed; opensessions may be incomplete." >&2
            fi
          fi

          ${pkgs.coreutils}/bin/rm -rf "$current_link"
          ${pkgs.coreutils}/bin/ln -s "$checkout_root" "$current_link"
        ''
      );

      # Seed writable opensessions config (only if absent) so UI theme toggles
      # and other runtime preferences can still be persisted by opensessions.
      home.activation.opensessions-config = lib.mkIf cfg.opensessions.enable (
        lib.hm.dag.entryAfter [ "opensessions-setup" ] ''
          config_dir="$HOME/.config/opensessions"
          config_path="$config_dir/config.json"

          if [ ! -f "$config_path" ]; then
            ${pkgs.coreutils}/bin/mkdir -p "$config_dir"
            ${pkgs.coreutils}/bin/printf '%s\n' ${lib.escapeShellArg opensessionsConfigJson} > "$config_path"
          fi
        ''
      );
    };
}
