diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e657d801a..f380400e72 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,6 +29,7 @@ jobs: execution: ${{ steps.groups.outputs.execution }} web: ${{ steps.groups.outputs.web }} scripts: ${{ steps.groups.outputs.scripts }} + macos_scripts: ${{ steps.groups.outputs.macos_scripts }} dependencies: ${{ steps.groups.outputs.dependencies }} steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -142,11 +143,15 @@ jobs: if: >- needs.changes.outputs.rust == 'true' || needs.changes.outputs.xtask == 'true' || needs.changes.outputs.scripts == 'true' - # PR runners must be isolated from release credentials and private networks. - runs-on: [self-hosted, macOS, ARM64] + name: verify (${{ matrix.platform }}) + strategy: + fail-fast: false + matrix: + platform: ${{ fromJSON(github.event_name == 'pull_request' && '["linux"]' || github.event_name == 'push' && '["macos"]' || '["linux","macos"]') }} + runs-on: ${{ matrix.platform == 'linux' && fromJSON('["self-hosted","linux","x64","dim-verify"]') || fromJSON('["self-hosted","macOS","ARM64"]') }} timeout-minutes: 75 env: - CARGO_BUILD_JOBS: "4" + CARGO_BUILD_JOBS: ${{ matrix.platform == 'linux' && '8' || '4' }} CARGO_INCREMENTAL: "0" CARGO_TARGET_DIR: ${{ github.workspace }}/target RUSTC_WRAPPER: "" @@ -158,6 +163,19 @@ jobs: with: node-version-file: .node-version package-manager-cache: false + - uses: actions-rust-lang/setup-rust-toolchain@c8ff772090ab9d00f7f7bd7b388f3c3032282e3b + if: runner.os == 'Linux' + with: + cache: false + build-warnings: "" + - name: Report Linux host support + if: runner.os == 'Linux' + shell: bash + run: | + echo "CPUs: $(nproc)" + grep -E 'MemTotal|MemAvailable' /proc/meminfo + # Without a working bubblewrap the confined process tests return without running. + bwrap --ro-bind / / true - name: Build and lint the Rust workspace if: needs.changes.outputs.rust == 'true' shell: bash @@ -264,10 +282,17 @@ jobs: set -euo pipefail # The Python of `py:` rows: a relocatable CPython, pinned by hash, so the # self-hosted runner needs neither a system Python 3.10+ nor sudo. - python_build="cpython-3.12.15+20261003-aarch64-apple-darwin-install_only.tar.gz" + if [[ "$RUNNER_OS" == Linux ]]; then + python_target=x86_64-unknown-linux-gnu + python_sha256=f937814031eab4698ca6d07ec606ede1825768f3f3e99af76d9db3900bee03c5 + else + python_target=aarch64-apple-darwin + python_sha256=316a463172740e71d8dca1f2730784e325f3f720941137b5d674d5801a632213 + fi + python_build="cpython-3.12.15+20261003-${python_target}-install_only.tar.gz" curl -fsSL -o "$RUNNER_TEMP/python.tar.gz" \ "https://github.com/astral-sh/python-build-standalone/releases/download/20261003/${python_build/+/%2B}" - echo "316a463172740e71d8dca1f2730784e325f3f720941137b5d674d5801a632213 $RUNNER_TEMP/python.tar.gz" | shasum -a 256 -c - + echo "$python_sha256 $RUNNER_TEMP/python.tar.gz" | shasum -a 256 -c - rm -rf "$RUNNER_TEMP/python" runtime/.venv tar -xzf "$RUNNER_TEMP/python.tar.gz" -C "$RUNNER_TEMP" "$RUNNER_TEMP/python/bin/python3" -m venv runtime/.venv @@ -280,6 +305,32 @@ jobs: - name: Verify downloaded Node runtime if: needs.changes.outputs.node == 'true' && github.event_name != 'pull_request' run: node scripts/run-rust-test.mjs target/test-artifacts.jsonl transport_flow runtime_manager::runtime_switches_from_system_to_downloaded_node --ignored --exact + macos-native: + needs: changes + if: github.event_name == 'pull_request' && (needs.changes.outputs.rust == 'true' || needs.changes.outputs.macos_scripts == 'true') + runs-on: [self-hosted, macOS, ARM64] + timeout-minutes: 30 + env: + CARGO_BUILD_JOBS: "4" + CARGO_INCREMENTAL: "0" + CARGO_TARGET_DIR: ${{ github.workspace }}/target + RUSTC_WRAPPER: "" + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: .node-version + package-manager-cache: false + - name: Test macOS native Rust flows + if: needs.changes.outputs.rust == 'true' + run: node scripts/test-macos-native.mjs + - name: Test macOS code layout and release packaging + if: needs.changes.outputs.macos_scripts == 'true' + run: | + node --test scripts/code-layout-darwin.test.mjs + node --test --test-name-pattern='^native package staging' scripts/release.test.mjs acp-registry: needs: changes if: github.event_name != 'pull_request' && (needs.changes.outputs.rust == 'true' || needs.changes.outputs.scripts == 'true') @@ -335,7 +386,7 @@ jobs: retention-days: 1 ci-ok: # The one check to require: it passes when every selected job passed and skipped jobs were not needed. - needs: [changes, dependencies, windows-cli, web, verify, acp-registry] + needs: [changes, dependencies, windows-cli, web, verify, macos-native, acp-registry] if: always() runs-on: self-hosted timeout-minutes: 5 diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 6ac8b48dd0..076e8df19d 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -918,10 +918,6 @@ async fn a_confined_helper_returns_when_its_root_exits_with_a_descendant_on_its_ std::fs::remove_dir_all(&base).unwrap(); } -/// A descendant that left the process group keeps the pipes open past the -/// drain bound. The call still returns with the root's status and the bytes -/// read so far, and the escaped process is the caller's to kill: that is the -/// limit the confinement documents for macOS and unconfined Linux. #[tokio::test] async fn a_confined_helper_returns_when_an_escaped_descendant_holds_its_pipes() { let Some(perl) = perl() else { @@ -933,7 +929,8 @@ async fn a_confined_helper_returns_when_an_escaped_descendant_holds_its_pipes() std::fs::create_dir_all(&write).unwrap(); let pid_file = write.join("escapee.pid"); let escape = format!( - "setpgrp(0, 0); open my $f, q(>), q({}) or die; print $f $$; close $f; sleep 100;", + "use Fcntl qw(:flock); setpgrp(0, 0); open my $f, q(>), q({}) or die; \ + flock($f, LOCK_EX) or die; syswrite($f, $$) or die; sleep 100;", pid_file.display() ); let script = format!( @@ -959,6 +956,15 @@ async fn a_confined_helper_returns_when_an_escaped_descendant_holds_its_pipes() elapsed < Duration::from_secs(5), "the call took {elapsed:?} with the drain bound at one second" ); + #[cfg(target_os = "linux")] + if output.confined { + std::fs::File::open(&pid_file) + .unwrap() + .try_lock() + .expect("the descendant must release its file lock when the PID namespace ends"); + std::fs::remove_dir_all(&base).unwrap(); + return; + } let pid: i32 = std::fs::read_to_string(&pid_file) .expect("the escapee records its pid") .trim() diff --git a/crates/dim-agent-capabilities/tests/permission_flow.rs b/crates/dim-agent-capabilities/tests/permission_flow.rs index b5b847c884..735f102822 100644 --- a/crates/dim-agent-capabilities/tests/permission_flow.rs +++ b/crates/dim-agent-capabilities/tests/permission_flow.rs @@ -1211,6 +1211,12 @@ async fn full_access_releases_all_waiting_calls_without_user_responses() { .await .unwrap(); let child_approval = session.service::(&child).unwrap(); + let child_request = loop { + if let Some(request) = child_approval.pending().pop() { + break request.approval_id; + } + tokio::task::yield_now().await; + }; submit_exec(&session, "echo model call").await; let model_request = approval_request(&session, "echo model call").await; let approval = session.service::("main").unwrap(); @@ -1288,14 +1294,6 @@ async fn full_access_releases_all_waiting_calls_without_user_responses() { ); } approval.replay(|request| panic!("stale approval: {request:?}")); - let child_request = loop { - let mut requests = Vec::new(); - child_approval.replay(|request| requests.push(request.approval_id.clone())); - if let Some(request) = requests.pop() { - break request; - } - tokio::task::yield_now().await; - }; child_approval .respond(&child_request, ApprovalDecision::Deny) .await diff --git a/crates/dim-app-server/tests/transport_flow/default_effort.rs b/crates/dim-app-server/tests/transport_flow/default_effort.rs index 49223e0e47..de1391dd8d 100644 --- a/crates/dim-app-server/tests/transport_flow/default_effort.rs +++ b/crates/dim-app-server/tests/transport_flow/default_effort.rs @@ -1257,6 +1257,28 @@ fn summarising(model_id: &str, default: Option<&str>, options: &[&str]) -> Value value } +async fn baseline_turn(client: &mut Client, session_id: &Value) { + let at = json!({"sessionId":session_id,"branchId":"main"}); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let pending = client.rpc("session.input.pending", at.clone()).await; + assert_ok(&pending); + let inputs = pending["result"]["inputs"].as_array().unwrap(); + if inputs + .iter() + .filter(|input| input["applied"] == true) + .count() + == 4 + { + break; + } + } + }) + .await + .expect("four startup inputs reach the branch before the baseline request"); + turn(client, session_id, "hello").await; +} + /// The request body with the prompt replaced by its message roles. Every /// fixture sends the same session prompt and none of these tests is about it, /// but every other field is compared exactly as sent. @@ -1500,7 +1522,7 @@ async fn a_summary_declaration_with_no_effort_sends_nothing() { .await; assert_ok(&created); let session_id = created["result"]["sessionId"].clone(); - turn(&mut client, &session_id, "hello").await; + baseline_turn(&mut client, &session_id).await; let wire = last_body(&capture); assert!(wire.get("reasoning").is_none(), "{wire}"); // The baseline body captured at 1efbd75df for this fixture. @@ -1619,7 +1641,7 @@ async fn a_model_that_declares_no_summary_sends_the_baseline_body() { .await; assert_ok(&created); let session_id = created["result"]["sessionId"].clone(); - turn(&mut client, &session_id, "hello").await; + baseline_turn(&mut client, &session_id).await; let wire = last_body(&capture); // Baseline at 1efbd75df: the adapter's own default already sends // `detailed` beside a concrete effort, so the body is unchanged. diff --git a/crates/dim-app-server/tests/transport_flow/sessions.rs b/crates/dim-app-server/tests/transport_flow/sessions.rs index d25da90f8e..2d6122afca 100644 --- a/crates/dim-app-server/tests/transport_flow/sessions.rs +++ b/crates/dim-app-server/tests/transport_flow/sessions.rs @@ -1708,6 +1708,17 @@ async fn node_session_permissions_reads_live_policy_and_survives_index_reload() ); let starter = client_session(&mut client, &agent, json!({"preset":"full-access"})).await; let at = json!({"sessionId":starter.id(),"branchId":"main"}); + let mut inputs = starter + .on::("main") + .unwrap() + .unwrap(); + tokio::time::timeout( + Duration::from_secs(10), + inputs.wait_for(|state| state.queued == 2), + ) + .await + .expect("client presence and execution settings inputs are published") + .unwrap(); let before = starter.sequence("main").unwrap(); let initial = client.rpc("permissions.branch", at.clone()).await; assert_ok(&initial); diff --git a/crates/dim-app-server/tests/transport_flow/shell_input.rs b/crates/dim-app-server/tests/transport_flow/shell_input.rs index 056feb69aa..3c4f9d6f02 100644 --- a/crates/dim-app-server/tests/transport_flow/shell_input.rs +++ b/crates/dim-app-server/tests/transport_flow/shell_input.rs @@ -974,6 +974,13 @@ async fn reloading_workspace_tools_answers_the_page_method_with_service_reloadin .expect("the page method answers service_reloading while WorkspaceTools reloads"); drop(hold); restart.await.unwrap().unwrap(); + loop { + let notice = shell.client.notice("session.event").await; + let event = ¬ice["params"]["event"]; + if event["type"] == "exec" && event["name"] == "ended" { + break; + } + } assert_ok( &shell .client diff --git a/crates/dim-modality/tests/modality_flow.rs b/crates/dim-modality/tests/modality_flow.rs index 7dc6b57c7a..a1c4d0e763 100644 --- a/crates/dim-modality/tests/modality_flow.rs +++ b/crates/dim-modality/tests/modality_flow.rs @@ -1606,13 +1606,18 @@ async fn the_product_build_reports_image_operations_without_an_adapter() { .filter(|category| category["category"] != "image") { assert_eq!(category["available"], false, "{category}"); - assert_eq!(category["reasons"][0]["dimension"], "build", "{category}"); + let dimension = if category["category"] == "ocr" && !dim_ocr::apple_vision_available() { + "platform" + } else { + "build" + }; + assert_eq!(category["reasons"][0]["dimension"], dimension, "{category}"); assert!( category["operations"] .as_array() .unwrap() .iter() - .all(|operation| operation["reasons"][0]["dimension"] == "build"), + .all(|operation| operation["reasons"][0]["dimension"] == dimension), "{category}" ); } @@ -4789,6 +4794,7 @@ async fn result_bytes(client: &mut Client, task_id: &str, name: &str, length: us } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn ocr_offers_the_local_target_and_configure_sets_the_default() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -4867,6 +4873,7 @@ async fn ocr_offers_the_local_target_and_configure_sets_the_default() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn an_ocr_task_publishes_the_helper_artifacts() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -4910,6 +4917,7 @@ async fn an_ocr_task_publishes_the_helper_artifacts() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn data_carries_at_most_one_mebibyte_of_page_text() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -4945,6 +4953,7 @@ async fn data_carries_at_most_one_mebibyte_of_page_text() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn a_layout_task_publishes_the_page_image() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -4968,6 +4977,7 @@ async fn a_layout_task_publishes_the_page_image() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn helper_artifacts_that_are_not_regular_files_are_refused_without_blocking() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -5016,6 +5026,7 @@ async fn helper_artifacts_that_are_not_regular_files_are_refused_without_blockin } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn an_oversized_helper_result_is_refused_before_it_is_read() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -5049,6 +5060,7 @@ async fn an_oversized_helper_result_is_refused_before_it_is_read() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn a_failed_host_task_removes_its_work_directory() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -5109,6 +5121,7 @@ impl ArtifactHook for ReplaceAfterCount { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn the_host_path_publishes_the_bytes_the_cap_counted() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -5153,6 +5166,7 @@ async fn the_host_path_publishes_the_bytes_the_cap_counted() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn typed_and_broken_helpers_fail_with_the_mapped_code() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -5171,6 +5185,7 @@ async fn typed_and_broken_helpers_fail_with_the_mapped_code() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn a_helper_over_its_output_limit_fails_executor_error() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -5191,6 +5206,7 @@ async fn a_helper_over_its_output_limit_fails_executor_error() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn cancel_stops_a_running_helper() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -5244,6 +5260,7 @@ async fn cancel_stops_a_running_helper() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn a_named_node_is_unavailable() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -5259,6 +5276,7 @@ async fn a_named_node_is_unavailable() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn a_foreign_explicit_model_is_refused() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -5271,6 +5289,7 @@ async fn a_foreign_explicit_model_is_refused() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn ocr_takes_one_input_file() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -5283,6 +5302,7 @@ async fn ocr_takes_one_input_file() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(target_os = "macos"), ignore = "expects a host with Apple Vision")] async fn queued_ocr_keeps_its_input_after_the_source_is_removed() { let home = home("dm-ocr"); let helper = fake_helper(&home); @@ -5332,7 +5352,12 @@ async fn ocr_is_absent_when_the_build_starts_no_helper() { let recognize = operation_in(&snapshot, "ocr", "recognize"); assert_eq!(recognize["available"], false); assert_eq!(recognize["options"], json!([])); - assert_eq!(recognize["reasons"][0]["dimension"], "build"); + let dimension = if dim_ocr::apple_vision_available() { + "build" + } else { + "platform" + }; + assert_eq!(recognize["reasons"][0]["dimension"], dimension); let refused = client .rpc( "modality.configure", @@ -5358,8 +5383,12 @@ async fn ocr_is_absent_when_the_build_starts_no_helper() { .await; assert_eq!( app_error(&submit), - "modality_unavailable", - "a build reason names the code: {submit}" + if dimension == "build" { + "modality_unavailable" + } else { + "unavailable" + }, + "{submit}" ); let message = submit["error"]["message"].as_str().unwrap(); assert_eq!( @@ -5660,6 +5689,21 @@ fn plugin_ocr_submit(name: &str, mode: &str) -> Value { submit } +fn assert_plugin_ocr_refused(reply: &Value, recognize: &Value, detail: &str) { + assert_eq!(app_error(reply), "unavailable"); + let message = reply["error"]["message"].as_str().unwrap(); + if recognize["available"] == true { + assert_eq!(message, detail); + } else { + let reason = format!("runtime: {detail}"); + assert!( + message.starts_with("ocr.recognize is unavailable.\n"), + "{reply}" + ); + assert!(message.lines().any(|line| line == reason), "{reply}"); + } +} + async fn wait_for_path(path: &std::path::Path) { let deadline = std::time::Instant::now() + Duration::from_secs(20); while !path.exists() { @@ -5780,11 +5824,7 @@ async fn ocr_plugin_target_is_absent_without_the_service() { plugin_ocr_submit("scan.png", "text"), ) .await; - assert_eq!(app_error(&refused), "unavailable"); - assert_eq!( - refused["error"]["message"], "The PP-OCR plugin is not running", - "{refused}" - ); + assert_plugin_ocr_refused(&refused, recognize, "The PP-OCR plugin is not running"); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -5827,11 +5867,7 @@ async fn ocr_plugin_target_with_an_older_contract_is_unavailable() { plugin_ocr_submit("scan.png", "text"), ) .await; - assert_eq!(app_error(&refused), "unavailable"); - assert_eq!( - refused["error"]["message"], "The PP-OCR plugin needs an update", - "{refused}" - ); + assert_plugin_ocr_refused(&refused, recognize, "The PP-OCR plugin needs an update"); let configured = client .rpc( "modality.configure", @@ -5875,11 +5911,7 @@ async fn ocr_plugin_target_with_an_older_contract_is_unavailable() { plugin_ocr_submit("scan.png", "text"), ) .await; - assert_eq!(app_error(&refused), "unavailable"); - assert_eq!( - refused["error"]["message"], "The PP-OCR plugin is not running", - "{refused}" - ); + assert_plugin_ocr_refused(&refused, recognize, "The PP-OCR plugin is not running"); } /// A service that declares `describe` sync is never called: it reads as @@ -5923,11 +5955,7 @@ async fn ocr_plugin_target_declaring_describe_sync_needs_an_update() { plugin_ocr_submit("scan.png", "text"), ) .await; - assert_eq!(app_error(&refused), "unavailable", "{refused}"); - assert_eq!( - refused["error"]["message"], "The PP-OCR plugin needs an update", - "{refused}" - ); + assert_plugin_ocr_refused(&refused, recognize, "The PP-OCR plugin needs an update"); assert_eq!( fixture.describes(), 0, @@ -5980,11 +6008,7 @@ async fn ocr_plugin_removal_after_describe_keeps_the_admitted_task() { plugin_ocr_submit("scan.png", "text"), ) .await; - assert_eq!(app_error(&refused), "unavailable"); - assert_eq!( - refused["error"]["message"], "The PP-OCR plugin is not running", - "{refused}" - ); + assert_plugin_ocr_refused(&refused, recognize, "The PP-OCR plugin is not running"); std::fs::write(work.join("go"), b"go").unwrap(); let done = wait_terminal(&mut client, &task_id).await; assert_eq!(state_of(&done), "succeeded", "{done}"); diff --git a/crates/dim-modality/tests/ocr_descriptors.rs b/crates/dim-modality/tests/ocr_descriptors.rs index f1c9e3d18e..3f3d2c923d 100644 --- a/crates/dim-modality/tests/ocr_descriptors.rs +++ b/crates/dim-modality/tests/ocr_descriptors.rs @@ -1,7 +1,7 @@ //! One layout OCR task under a lowered descriptor limit: the host path opens //! and copies one artifact at a time, so a task publishes every page while the //! process holds far fewer descriptors than the page count. -#![cfg(unix)] +#![cfg(target_os = "macos")] use base64::Engine; use dim_agent_capabilities::{adapters::MockTools, defaults}; use dim_agent_runtime::{AgentBuilder, AgentConfig}; diff --git a/crates/dim-session-title/tests/initial_title_flow.rs b/crates/dim-session-title/tests/initial_title_flow.rs index 45a2a1d4c8..0416f9742c 100644 --- a/crates/dim-session-title/tests/initial_title_flow.rs +++ b/crates/dim-session-title/tests/initial_title_flow.rs @@ -161,39 +161,47 @@ async fn entry_of(client: &mut Client, id: &str) -> Value { .clone() } -/// The title entry of `id`, once its notice has arrived. The caller attaches -/// first: a notice reaches only a client the Session is attached to. -async fn titled(client: &mut Client, id: &str, text: &str, source: &str) -> Value { - tokio::time::timeout(Duration::from_secs(10), async { +async fn initial_title(client: &mut Client, id: &str, text: &str) { + let entry = tokio::time::timeout(Duration::from_secs(10), async { loop { - let listed = client.rpc("session.summaries", json!({})).await.unwrap(); - let Some(entry) = listed - .as_array() - .unwrap() - .iter() - .find(|entry| entry["sessionId"] == id) - .cloned() - else { - tokio::time::sleep(Duration::from_millis(5)).await; - continue; - }; - if entry["title"] == text - && entry["titleSource"] == source - && client.notices.iter().any(|notice| { - matches!(notice, - Message::Notice { method, params } - if method == "session.notice" && params["sessionId"] == id - && params["kind"] == "title" - && params["data"]["titleRevision"] == entry["titleRevision"]) - }) - { + let entry = entry_of(client, id).await; + if entry["titleRevision"] != 0 { return entry; } tokio::time::sleep(Duration::from_millis(5)).await; } }) .await - .expect("the committed title and its notice arrive") + .expect("the launch title is committed"); + assert_eq!(entry["title"], text, "{entry}"); + assert_eq!(entry["titleSource"], "manual", "{entry}"); + assert_eq!(entry["titleRevision"], 1, "{entry}"); +} + +async fn rename_and_observe(client: &mut Client, id: &str) { + let renamed = when_served( + client, + "session.rename", + json!({"sessionId":id,"title":" Renamed by hand "}), + ) + .await; + assert_eq!(renamed["title"], "Renamed by hand", "{renamed}"); + let entry = entry_of(client, id).await; + assert_eq!(entry["title"], renamed["title"], "{entry}"); + assert_eq!(entry["titleSource"], "manual", "{entry}"); + assert_eq!(entry["titleRevision"], renamed["revision"], "{entry}"); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if matches!(client.next().await.unwrap(), Message::Notice { method, params } + if method == "session.notice" && params["sessionId"] == id + && params["kind"] == "title" && params["data"]["titleRevision"] == renamed["revision"]) + { + return; + } + } + }) + .await + .expect("the attached client receives the rename notice"); } /// A Session whose creation requests a title gets it once, as the first manual @@ -211,17 +219,8 @@ async fn a_requested_title_is_written_once_and_a_later_rename_wins() { .rpc("session.attach", json!({"sessionId":id})) .await .unwrap(); - let entry = titled(&mut client, &id, "Nightly build", "manual").await; - assert_eq!(entry["titleRevision"], 1, "{entry}"); - - let renamed = when_served( - &mut client, - "session.rename", - json!({"sessionId":id,"title":" Renamed by hand "}), - ) - .await; - assert_eq!(renamed["title"], "Renamed by hand"); - titled(&mut client, &id, "Renamed by hand", "manual").await; + initial_title(&mut client, &id, "Nightly build").await; + rename_and_observe(&mut client, &id).await; drop(client); server.shutdown(); server.join().await.unwrap(); @@ -280,7 +279,7 @@ async fn a_requested_title_is_bounded_by_max_length() { .rpc("session.attach", json!({"sessionId":id})) .await .unwrap(); - titled(&mut client, &id, "A name much", "manual").await; + initial_title(&mut client, &id, "A name much").await; drop(client); server.shutdown(); server.join().await.unwrap(); @@ -350,18 +349,12 @@ async fn a_fork_of_a_renamed_launch_stays_untitled_across_a_restart() { .await; assert_eq!(launched["ok"], true, "{launched}"); let source = launched["value"]["sessionId"].as_str().unwrap().to_owned(); + initial_title(&mut client, &source, "Nightly build").await; client .rpc("session.attach", json!({"sessionId":source})) .await .unwrap(); - titled(&mut client, &source, "Nightly build", "manual").await; - when_served( - &mut client, - "session.rename", - json!({"sessionId":source,"title":" Renamed by hand "}), - ) - .await; - titled(&mut client, &source, "Renamed by hand", "manual").await; + rename_and_observe(&mut client, &source).await; let forked = client .rpc("session.fork", json!({"sessionId":source,"at":0})) @@ -417,7 +410,7 @@ async fn a_fork_of_an_untouched_launch_stays_untitled_across_a_restart() { .rpc("session.attach", json!({"sessionId":source})) .await .unwrap(); - titled(&mut client, &source, "Nightly build", "manual").await; + initial_title(&mut client, &source, "Nightly build").await; let forked = client .rpc("session.fork", json!({"sessionId":source,"at":0})) diff --git a/crates/dimcode/tests/cli_flow.rs b/crates/dimcode/tests/cli_flow.rs index a23d2d31e9..fe5ba96236 100644 --- a/crates/dimcode/tests/cli_flow.rs +++ b/crates/dimcode/tests/cli_flow.rs @@ -8717,6 +8717,7 @@ fn approval_interrupt_stops_the_turn_instead_of_a_deferred_completed_shell() { assert!(!terminal.transcript.contains("deferred output")); terminal.signal(libc::SIGINT); terminal.until("[stopping] Waiting for resource settlement"); + terminal.until("deferred output"); terminal.signal(libc::SIGINT); terminal.until("[stopping] Still waiting for resource settlement"); release.send(()).unwrap(); diff --git a/crates/dimcode/tests/cli_flow/staged_update.rs b/crates/dimcode/tests/cli_flow/staged_update.rs index f16005bcd6..942e66845c 100644 --- a/crates/dimcode/tests/cli_flow/staged_update.rs +++ b/crates/dimcode/tests/cli_flow/staged_update.rs @@ -79,6 +79,18 @@ struct Installed { home: Home, } +fn install_updater(destination: &Path) { + let status = Command::new("install") + .args(["-m", "700", env!("CARGO_BIN_EXE_dimcode")]) + .arg(destination) + .status() + .unwrap(); + assert!( + status.success(), + "install updater at {destination:?}: {status}" + ); +} + impl Installed { fn new(version: &str, commands: &[&str]) -> Self { let home = Home::new(); @@ -91,8 +103,7 @@ impl Installed { // The update runs from inside the package, as the installed command // does, so the copy it runs from is how it finds the installation. let updater = package.join("bin/dimcode"); - fs::copy(env!("CARGO_BIN_EXE_dimcode"), &updater).unwrap(); - fs::set_permissions(&updater, fs::Permissions::from_mode(0o700)).unwrap(); + install_updater(&updater); let launcher = package.join("bin/dimcode.mjs"); fs::write(&launcher, REPORTS_VERSION).unwrap(); fs::set_permissions(&launcher, fs::Permissions::from_mode(0o700)).unwrap(); @@ -596,8 +607,7 @@ fn one_packages_staging_survives_the_others_update() { // is missing, as it is after the interrupted fallback. let stable_updater = installed.prefix.join("lib/node_modules/dimcode-alpha/bin"); let updater = stable_updater.join("dim-stable"); - fs::copy(env!("CARGO_BIN_EXE_dimcode"), &updater).unwrap(); - fs::set_permissions(&updater, fs::Permissions::from_mode(0o700)).unwrap(); + install_updater(&updater); let mut command = Command::new(fs::canonicalize(updater).unwrap()); command .args(["--home", installed.home.0.to_str().unwrap(), "update"]) diff --git a/docs/architecture/build.md b/docs/architecture/build.md index cb139e3bdd..54530aa497 100644 --- a/docs/architecture/build.md +++ b/docs/architecture/build.md @@ -319,7 +319,7 @@ build host, plus the archived copy's `sha256`. CI and `./dev check` run the format check as `cargo fmt --all -- --check --config error_on_line_overflow=true`: when one line in a block cannot fit `max_width`, rustfmt abandons the block without a diagnostic, so the option turns that otherwise-skipped line into a failure ([#1769](https://github.com/arcships/dim/issues/1769)). -The macOS `verify` job has a seventy-five-minute overall deadline and allows four concurrent Cargo build jobs. It builds all workspace targets once, checks the architecture, then runs up to three recorded test executables at a time with up to three test threads per executable. The workspace run starts `transport_flow` and `cli_flow` first. The separate CLI profile and Node- and Python-backed Rust suites use two test threads each. The `dependencies` job allows two Cargo build jobs when installing `cargo-deny`. +The PR `macos-native` job has a thirty-minute deadline. The full `verify` job has a seventy-five-minute deadline on either platform. It builds all workspace targets once, checks the architecture, then runs up to three recorded test executables at a time with up to three test threads per executable. The workspace run starts `transport_flow` and `cli_flow` first. The separate CLI profile and Node- and Python-backed Rust suites use two test threads each. The `dependencies` job allows two Cargo build jobs when installing `cargo-deny`. CI sets `CARGO_TARGET_DIR` to the checkout's `target` directory so a compiler cache's managed-target collection cannot remove binaries between the build and their later execution. Each executable keeps its Cargo package working directory and streams output immediately, with target start/end markers and exit status. A target has a ten-minute default deadline (`DIM_TEST_TIMEOUT_MS` overrides it); the full workspace step sets fifteen minutes per executable for the large flow suites at three test threads. Timeout and cancellation terminate its process tree. Failures still allow the other targets to finish and fail the step. Cargo runs documentation tests separately with the same feature selection. Local `cargo test --workspace --locked` remains available without Node. @@ -331,7 +331,7 @@ The root `./dev` entry performs incremental CLI/App Server builds without disabl The [Web workspace](../design/web-workspace.md) frontend in `web/` is a separate artifact (`scripts/stage-web.mjs` builds it; the CLI finds the installed `dimcode-web` package or a `web/` directory beside the executable or in the product home, or `DIMCODE_WEB_ASSETS` names one), so building `dim-app-server` and `dimcode` needs neither Node nor npm. Only `cargo build --features embedded-web` compiles the frontend in; then `build.rs` runs `npm ci` and `npm run build` when that frontend changed, and a host without npm fails the build. Otherwise Node is only needed for packaging, packaging checks and TypeScript plugin execution/development. `.node-version` pins the Node version bundled into account-enabled releases. The `runtime/package-lock.json` fixes the rutis Node runtime and its transitive dependencies; `npm ci --ignore-scripts --prefix runtime` installs them for local bridge testing. -Full-workspace CI uses self-hosted macOS ARM64 runners; pull requests run only the check groups their paths need (see [GitHub workflows](../release/README.md#github-workflows)). The separate `windows-cli` job runs native boundary flows on a self-hosted Windows x64 runner, where its fixture writes to the clipboard. The layout workflow uses hosted `windows-2022` and `windows-11-arm` runners, with Python 3.13 and the pinned native MSVC Rust host toolchain provisioned explicitly. Release builds use GitHub-hosted VMs matching each target OS and CPU. See the [runner setup and release matrix](../release/README.md#runner-setup). +Pull requests run workspace verification on self-hosted Linux x64 runners labelled `dim-verify`, with eight Cargo build jobs. The job checks that bubblewrap can create a sandbox before running the confined process tests. The macOS ARM64 runners use four Cargo jobs for the native Rust checks on pull requests and for full workspace verification on `main`. Use `node scripts/test-macos-native.mjs --list` to inspect the Rust selection from the current Cargo targets, Rust platform guards and host-specific test fixtures. On an Apple Silicon Mac, run `node scripts/test-macos-native.mjs` to build those targets and check each selected name against its compiled test binary before execution. Tests marked for manual execution keep their normal ignore status. The [workflow guide](../release/README.md#github-workflows) describes path selection, native packaging checks and manual dispatch. The separate `windows-cli` job runs native boundary flows on a self-hosted Windows x64 runner, where its fixture writes to the clipboard. The layout workflow uses hosted `windows-2022` and `windows-11-arm` runners, with Python 3.13 and the pinned native MSVC Rust host toolchain provisioned explicitly. Release builds use GitHub-hosted VMs matching each target OS and CPU. See the [runner setup and release matrix](../release/README.md#runner-setup). The macOS clipboard flows use private pasteboards and serialize access to the shared pasteboard server; other tests remain parallel. diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index dafe01dea6..e2dadab46a 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -327,12 +327,13 @@ helper's tree; `a_confined_helper_leaves_no_process_after_it_exits` that a helper which exits on its own leaves nothing either; `a_confined_helper_returns_when_its_root_exits_with_a_descendant_on_its_pipes` that a descendant holding both pipes cannot turn a completed helper into a timeout, and -`a_confined_helper_returns_when_an_escaped_descendant_holds_its_pipes` that a descendant which -left the process group is returned past and is then the caller's to kill (skipped when perl is -absent); -`a_confined_helper_gets_the_allowlist_plus_its_own_environment` that only the -allowlist and the helper's own entries reach it, with its `TMPDIR` honored; and -`a_confined_helper_refuses_relative_and_missing_paths` the path refusals. +`a_confined_helper_returns_when_an_escaped_descendant_holds_its_pipes` checks the lifetime of a +descendant that left the group. On Linux with bubblewrap, the descendant's file lock must be +released when the call returns. On macOS and unconfined Linux, the caller cleans up the surviving +descendant. This probe requires Perl. +`a_confined_helper_gets_the_allowlist_plus_its_own_environment` checks that only the allowlist +and the helper's own entries reach it, with its `TMPDIR` honored. +`a_confined_helper_refuses_relative_and_missing_paths` covers the path refusals. `a_host_without_bubblewrap_runs_the_confined_helper_unconfined` covers the Linux fallback. [host_platform_windows_flow.rs](../../../../crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs): diff --git a/docs/release/README.md b/docs/release/README.md index 61772dbda9..6413c43644 100644 --- a/docs/release/README.md +++ b/docs/release/README.md @@ -141,7 +141,7 @@ peak memory requirements. The Ubuntu preflight generates the Rust distribution notices once with cargo-about 0.9.3 using the versioned checkout. All six targets download that artifact. Linux builds on each native host with GNU tools in a digest-pinned manylinux_2_28 container. The executable also runs in that glibc 2.28 environment. Windows uses native MSVC, clang-cl on ARM64, NASM on x64, and the Windows system tar to create ZIP archives. Actions installs Node from `.node-version` and Rust uses `rust-toolchain.toml`. Web and Release assembly run on hosted Ubuntu. -The separate PR workflow uses self-hosted macOS ARM64, Windows x64, and Linux x64 runners. Register self-hosted runners with the [OS and architecture labels](https://docs.github.com/en/actions/how-tos/manage-runners/self-hosted-runners/use-in-a-workflow). Keep PR runner credentials and private networks isolated as required by the [CI trust model](#ci-trust-model). +The separate PR workflow uses self-hosted macOS ARM64, Windows x64, and Linux x64 runners. Register self-hosted runners with the [OS and architecture labels](https://docs.github.com/en/actions/how-tos/manage-runners/self-hosted-runners/use-in-a-workflow). A Linux x64 runner that carries workspace verification also has the `dim-verify` label and bubblewrap installed. Keep PR runner credentials and private networks isolated as required by the [CI trust model](#ci-trust-model). The platform-independent `changes` and `ci-ok` jobs can run on any eligible self-hosted runner. @@ -180,7 +180,7 @@ release packages use the ordinary Cargo executable. `ci.yml` runs on pull requests, pushes to `main`, and manual dispatch. A pull request runs the groups its changed paths need, as decided by `scripts/ci-changes.mjs`. A push to `main` runs only `changes` and `ci-ok` when its entire push range changes only documentation paths that select no check group. Architecture pages checked by `xtask` and the native storage format document retain the full main run, as do mixed pushes and pushes whose base cannot be compared. Manual dispatch selects every group. Every push to `main` runs its selected jobs to completion: a later push does not cancel them, so each merge has its own result and the `main CI` badge in the [README](../../README.md) reports the latest finished one. -CI builds the workspace, checks formatting and Clippy, runs workspace tests and boundary checks, runs the packaging/development script tests, and exercises the ignored actual CLI profile and public Node-backed flows. `ci-ok` passes when every selected job passed, so it is the check to require. CI builds without debug info (`CARGO_PROFILE_DEV_DEBUG=0`). The [build environment](../architecture/build.md) describes test artifact reuse, concurrency limits, and target deadlines. Cargo runs documentation tests with the same features, and ignored CLI and Node flows reuse the recorded binaries without package-scoped recompilation. Web source changes also run the `xtask` check, which reads them for branch id literals. Node-backed checks run for runtime, binding and service-contract paths, and CLI-only changes retain their ordinary and actual-profile flows. Evaluation tests use `xtask/eval-tests` for `xtask/` changes, and the wall-clock handoff runs for execution-related changes. The `web` job runs on self-hosted Windows x64 alongside macOS `verify` when both are selected. It stages the frontend package, verifies generated declarations and bundled dependency notices, and runs the Web tests. +CI builds the workspace, checks formatting and Clippy, runs workspace tests and boundary checks, runs the packaging/development script tests, and exercises the ignored actual CLI profile and public Node-backed flows. `ci-ok` passes when every selected gating job passes, so it is the check to require. CI builds without debug info (`CARGO_PROFILE_DEV_DEBUG=0`). The [build environment](../architecture/build.md) describes test artifact reuse, concurrency limits, and target deadlines. Cargo runs documentation tests with the same features, and ignored CLI and Node flows reuse the recorded binaries without package-scoped recompilation. Web source changes also run the `xtask` check, which reads them for branch id literals. Node-backed checks run for runtime, binding and service-contract paths, and CLI-only changes retain their ordinary and actual-profile flows. Evaluation tests use `xtask/eval-tests` for `xtask/` changes, and the wall-clock handoff runs for execution-related changes. PRs run `verify (linux)` for the selected groups. Rust changes also run `macos-native` on Apple Silicon, and changes affecting native packaging or code layout select its macOS script checks. Both jobs feed `ci-ok`. Full `main` pushes run `verify (macos)`, and manual dispatch runs full verification on both Linux and macOS. The `web` job runs on self-hosted Windows x64. It stages the frontend package, verifies generated declarations and bundled dependency notices, and runs the Web tests. The `Verify Python plugins` step is off by default. When a Python plugin ships, set the repository Actions variable `DIM_CI_PYTHON_PLUGINS` to `true` to run it whenever the Node check group is selected. It prepares CPython for the `python_plugin_` flows and reuses the App Server test binary from the workspace build. See the [App Server verification commands](../../crates/dim-app-server/README.md#verification) to run the suites locally. diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index 05a3f3483d..fc6a4b54f0 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -1,7 +1,7 @@ import {execFileSync,spawnSync} from 'node:child_process'; import {appendFileSync} from 'node:fs'; -export const groups=['rust','windows','xtask','node','eval','execution','web','scripts','dependencies']; +export const groups=['rust','windows','xtask','node','eval','execution','web','scripts','macos_scripts','dependencies']; const everything=Object.fromEntries(groups.map(group=>[group,true])); const documentation=/^docs\/|^[^/]+\.md$/; @@ -16,6 +16,9 @@ const rules=[ [/^web\/src\/.*\.(ts|vue|mjs|js)$/,['web','xtask']], [/^web\//,['web']], [/^scripts\/run-rust-test\.mjs$/,groups], + [/^scripts\/test-macos-native(?:\.test)?\.mjs$/,['rust','scripts','web']], + [/^scripts\/(code-layout\/|code-layout-darwin\.test\.mjs$)/,['scripts','web','macos_scripts']], + [/^scripts\/(stage-release|pack-release|native-binary|store-formats|release\.test)\.mjs$/,['scripts','web','macos_scripts']], [/^scripts\//,['scripts','web']], [/^docker\//,['scripts']], [/^crates\/dim-cli\//,['rust','windows']], diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index eea78e70c0..9bdbecadc9 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -55,6 +55,14 @@ test('source areas select their groups',()=>{ assert.deepEqual(classify(['docs/notes.md','crates/dim-cli/src/notes.rs']),only('rust','windows')); }); +test('native macOS CI follows its runner, packaging and Mach-O layout sources',()=>{ + assert.deepEqual(classify(['scripts/test-macos-native.mjs']),only('rust','scripts','web')); + for (const name of ['release.test.mjs','stage-release.mjs','pack-release.mjs','native-binary.mjs','store-formats.mjs', + 'code-layout-darwin.test.mjs','code-layout/macho.py','code-layout/link_capture.rs']) { + assert.deepEqual(classify([`scripts/${name}`]),only('scripts','web','macos_scripts'),name); + } +}); + test('bridge, evaluation and wall-clock flows follow their owning paths',()=>{ assert.deepEqual(classify(['crates/dim-cli/src/ui/tui.rs']),only('rust','windows')); assert.deepEqual(classify(['crates/dimcode/tests/cli_flow/models.rs']),only('rust')); diff --git a/scripts/release.test.mjs b/scripts/release.test.mjs index b65c87671d..371b0251c0 100644 --- a/scripts/release.test.mjs +++ b/scripts/release.test.mjs @@ -4,7 +4,7 @@ import {spawn,spawnSync} from 'node:child_process'; import {cpSync,existsSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,renameSync,rmSync,writeFileSync} from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import {test} from 'node:test'; +import {describe,test} from 'node:test'; import {pathToFileURL} from 'node:url'; import {gunzipSync} from 'node:zlib'; @@ -972,68 +972,70 @@ test('stages the Web workspace as one native archive and npm package with its pr assert.equal(existsSync(path.join(temporary,'again')),false); }); -/** An extended attribute is what makes macOS tar add the AppleDouble entry the account package must exclude. */ -test('an account build records the account and stages only its executable', {skip:process.platform==='win32'}, (t)=>{ - const temporary=fixture(t); - const bin=path.join(temporary,'bin'); - mkdirSync(bin); - writeFileSync(path.join(bin,'dimcode'),`#!/bin/sh\nprintf "dimcode ${version}\\n"\n`,{mode:0o755}); - const stage=path.join(temporary,'stage'); - const staged=run('stage-release.mjs',[bin,stage,version,commit,'--account','--plugins',stubPlugins(temporary),'--rust-notices',stubRustNotices(temporary)]); - assert.equal(staged.status,0,staged.stderr); - if(process.platform==='darwin') assert.equal(spawnSync('xattr',['-w','com.apple.provenance','x',path.join(stage,'bin/dimcode')]).status,0, - 'setting the extended attribute must succeed before packing'); - const manifest=JSON.parse(readFileSync(path.join(stage,'release-manifest.json'))); - assert.equal(manifest.account,true); - assert.deepEqual(Object.keys(manifest.files).sort(),['default-plugins.json','LICENSE','NOTICE','bin/dimcode','licenses/aimux/LICENSE','licenses/RUST-THIRD-PARTY-NOTICES.txt',...['LICENSE','NOTICE','xai-ratatui-inline/NOTICE','xai-ratatui-textarea/NOTICE'].map((file)=>`licenses/grok-build/${file}`)].sort()); - const packed=run('pack-release.mjs',[stage,path.join(temporary,'packed')]); - assert.equal(packed.status,0,packed.stderr); - const npmFile=JSON.parse(readFileSync(path.join(temporary,'packed/release-manifest.json'))).npmPackages[0].file; - assert.deepEqual(entries(path.join(temporary,'packed',npmFile)).filter((name)=>!name.endsWith('/')).sort(), - ['package/default-plugins.json','package/LICENSE','package/NOTICE','package/bin/dimcode','package/package.json','package/release-manifest.json','package/licenses/aimux/LICENSE','package/licenses/RUST-THIRD-PARTY-NOTICES.txt',...['LICENSE','NOTICE','xai-ratatui-inline/NOTICE','xai-ratatui-textarea/NOTICE'].map((file)=>`package/licenses/grok-build/${file}`)].sort()); -}); +describe('native package staging',()=>{ + /** An extended attribute is what makes macOS tar add the AppleDouble entry the account package must exclude. */ + test('an account build records the account and stages only its executable', {skip:process.platform==='win32'}, (t)=>{ + const temporary=fixture(t); + const bin=path.join(temporary,'bin'); + mkdirSync(bin); + writeFileSync(path.join(bin,'dimcode'),`#!/bin/sh\nprintf "dimcode ${version}\\n"\n`,{mode:0o755}); + const stage=path.join(temporary,'stage'); + const staged=run('stage-release.mjs',[bin,stage,version,commit,'--account','--plugins',stubPlugins(temporary),'--rust-notices',stubRustNotices(temporary)]); + assert.equal(staged.status,0,staged.stderr); + if(process.platform==='darwin') assert.equal(spawnSync('xattr',['-w','com.apple.provenance','x',path.join(stage,'bin/dimcode')]).status,0, + 'setting the extended attribute must succeed before packing'); + const manifest=JSON.parse(readFileSync(path.join(stage,'release-manifest.json'))); + assert.equal(manifest.account,true); + assert.deepEqual(Object.keys(manifest.files).sort(),['default-plugins.json','LICENSE','NOTICE','bin/dimcode','licenses/aimux/LICENSE','licenses/RUST-THIRD-PARTY-NOTICES.txt',...['LICENSE','NOTICE','xai-ratatui-inline/NOTICE','xai-ratatui-textarea/NOTICE'].map((file)=>`licenses/grok-build/${file}`)].sort()); + const packed=run('pack-release.mjs',[stage,path.join(temporary,'packed')]); + assert.equal(packed.status,0,packed.stderr); + const npmFile=JSON.parse(readFileSync(path.join(temporary,'packed/release-manifest.json'))).npmPackages[0].file; + assert.deepEqual(entries(path.join(temporary,'packed',npmFile)).filter((name)=>!name.endsWith('/')).sort(), + ['package/default-plugins.json','package/LICENSE','package/NOTICE','package/bin/dimcode','package/package.json','package/release-manifest.json','package/licenses/aimux/LICENSE','package/licenses/RUST-THIRD-PARTY-NOTICES.txt',...['LICENSE','NOTICE','xai-ratatui-inline/NOTICE','xai-ratatui-textarea/NOTICE'].map((file)=>`package/licenses/grok-build/${file}`)].sort()); + }); -test('stages cross-built executables without running them and rejects the wrong architecture', (t)=>{ - const temporary=fixture(t); - const osName=process.platform==='win32'?'windows':process.platform; - const cpu=process.arch==='arm64'?'x64':'arm64'; - const platform=`${osName}-${cpu}`; - const bin=path.join(temporary,'bin'); - mkdirSync(bin); - const header=Buffer.alloc(128); - if(osName==='windows') { - header.writeUInt16LE(0x5a4d,0); - header.writeUInt32LE(64,0x3c); - header.writeUInt32LE(0x00004550,64); - header.writeUInt16LE(cpu==='arm64'?0xaa64:0x8664,68); - } else if(osName==='darwin') { - header.writeUInt32LE(0xfeedfacf,0); - header.writeUInt32LE(cpu==='arm64'?0x0100000c:0x01000007,4); - } else { - Buffer.from('7f454c460201','hex').copy(header); - header.writeUInt16LE(cpu==='arm64'?183:62,18); - } - const suffix=osName==='windows'?'.exe':''; - const cli=path.join(bin,`dimcode${suffix}`); - writeFileSync(cli,header,{mode:0o755}); - const stage=path.join(temporary,'stage'); - const plugins=stubPlugins(temporary); - const rustNotices=stubRustNotices(temporary); - const result=run('stage-release.mjs',[bin,stage,version,commit,'--plugins',plugins,'--rust-notices',rustNotices],{DIM_BUILD_PLATFORM:platform}); - assert.equal(result.status,0,result.stderr); - assert.equal(JSON.parse(readFileSync(path.join(stage,'release-manifest.json'))).platform,platform); - const packed=run('pack-release.mjs',[stage,path.join(temporary,'packed')]); - assert.equal(packed.status,0,packed.stderr); - assert.equal(JSON.parse(readFileSync(path.join(temporary,'packed/release-manifest.json'))).nativeArchives[0].platform,platform); - const rejected=path.join(temporary,'rejected'); - if(osName==='windows') header.writeUInt16LE(cpu==='arm64'?0x8664:0xaa64,68); - else if(osName==='darwin') header.writeUInt32LE(cpu==='arm64'?0x01000007:0x0100000c,4); - else header.writeUInt16LE(cpu==='arm64'?62:183,18); - writeFileSync(cli,header); - const mismatch=run('stage-release.mjs',[bin,rejected,version,commit,'--plugins',plugins,'--rust-notices',rustNotices],{DIM_BUILD_PLATFORM:platform}); - assert.notEqual(mismatch.status,0); - assert.match(mismatch.stderr,/architecture mismatch/); - assert.equal(existsSync(rejected),false); + test('stages cross-built executables without running them and rejects the wrong architecture', (t)=>{ + const temporary=fixture(t); + const osName=process.platform==='win32'?'windows':process.platform; + const cpu=process.arch==='arm64'?'x64':'arm64'; + const platform=`${osName}-${cpu}`; + const bin=path.join(temporary,'bin'); + mkdirSync(bin); + const header=Buffer.alloc(128); + if(osName==='windows') { + header.writeUInt16LE(0x5a4d,0); + header.writeUInt32LE(64,0x3c); + header.writeUInt32LE(0x00004550,64); + header.writeUInt16LE(cpu==='arm64'?0xaa64:0x8664,68); + } else if(osName==='darwin') { + header.writeUInt32LE(0xfeedfacf,0); + header.writeUInt32LE(cpu==='arm64'?0x0100000c:0x01000007,4); + } else { + Buffer.from('7f454c460201','hex').copy(header); + header.writeUInt16LE(cpu==='arm64'?183:62,18); + } + const suffix=osName==='windows'?'.exe':''; + const cli=path.join(bin,`dimcode${suffix}`); + writeFileSync(cli,header,{mode:0o755}); + const stage=path.join(temporary,'stage'); + const plugins=stubPlugins(temporary); + const rustNotices=stubRustNotices(temporary); + const result=run('stage-release.mjs',[bin,stage,version,commit,'--plugins',plugins,'--rust-notices',rustNotices],{DIM_BUILD_PLATFORM:platform}); + assert.equal(result.status,0,result.stderr); + assert.equal(JSON.parse(readFileSync(path.join(stage,'release-manifest.json'))).platform,platform); + const packed=run('pack-release.mjs',[stage,path.join(temporary,'packed')]); + assert.equal(packed.status,0,packed.stderr); + assert.equal(JSON.parse(readFileSync(path.join(temporary,'packed/release-manifest.json'))).nativeArchives[0].platform,platform); + const rejected=path.join(temporary,'rejected'); + if(osName==='windows') header.writeUInt16LE(cpu==='arm64'?0x8664:0xaa64,68); + else if(osName==='darwin') header.writeUInt32LE(cpu==='arm64'?0x01000007:0x0100000c,4); + else header.writeUInt16LE(cpu==='arm64'?62:183,18); + writeFileSync(cli,header); + const mismatch=run('stage-release.mjs',[bin,rejected,version,commit,'--plugins',plugins,'--rust-notices',rustNotices],{DIM_BUILD_PLATFORM:platform}); + assert.notEqual(mismatch.status,0); + assert.match(mismatch.stderr,/architecture mismatch/); + assert.equal(existsSync(rejected),false); + }); }); test('collects exact platform packages, installs wrapper offline and rejects inconsistent account provenance', (t)=>{ diff --git a/scripts/test-macos-native.mjs b/scripts/test-macos-native.mjs new file mode 100644 index 0000000000..e8d2c37186 --- /dev/null +++ b/scripts/test-macos-native.mjs @@ -0,0 +1,108 @@ +import assert from 'node:assert/strict'; +import {execFileSync} from 'node:child_process'; +import {closeSync, mkdtempSync, openSync, readFileSync, realpathSync, rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join, posix, relative, resolve, sep} from 'node:path'; +import {fileURLToPath} from 'node:url'; + +const root = realpathSync(fileURLToPath(new URL('../', import.meta.url))); +process.chdir(root); +const macOS = /target_os\s*=\s*"macos"|target_vendor\s*=\s*"apple"/; +const testAttribute = /#\[(?:\w+::)*test\b/; + +function macOSGuard(attributes) { + return [...attributes.matchAll(/#!?\[cfg(_attr)?\(([\s\S]*?)\)\]/g)].some(([, conditionalAttribute, condition]) => { + if (!macOS.test(condition)) return false; + if (conditionalAttribute) return /^\s*not\s*\(\s*target_(?:os|vendor)\s*=\s*"(?:macos|apple)"\s*\)\s*,\s*ignore\b/.test(condition); + return !/\bnot\s*\(|target_os\s*=\s*"linux"|\bany\s*\(\s*test\b/.test(condition); + }); +} + +function nativeTests(file, source, gatedModules) { + const fileGated = macOSGuard(source.match(/^#!\[cfg\([^\]]+\]/gm)?.join('\n') ?? '') || + gatedModules.some(directory => file === `${directory}.rs` || file.startsWith(`${directory}/`)); + const modules = []; + const names = []; + for (const match of source.matchAll(/^([ \t]*)((?:#\[[^\]]+\]\s*)*)(?:(?:pub(?:\([^)]*\))?|async|unsafe)\s+)*(mod|fn)\s+(\w+)\b/gm)) { + const [, indent, attributes, kind, name] = match; + while (modules.length && match.index >= modules.at(-1)) modules.pop(); + if (kind === 'mod' && (!macOSGuard(attributes) || !/^\s*\{/.test(source.slice(match.index + match[0].length)))) continue; + if (kind === 'fn' && !testAttribute.test(attributes)) continue; + const endPattern = new RegExp(`^${indent}\\}`, 'gm'); + endPattern.lastIndex = match.index + match[0].length; + const lineEnd = source.indexOf('\n', endPattern.lastIndex); + const end = source.slice(endPattern.lastIndex, lineEnd).trimEnd().endsWith('}') + ? lineEnd + : endPattern.exec(source)?.index ?? source.length; + if (kind === 'mod') { + modules.push(end); + continue; + } + const body = source.slice(match.index + match[0].length, end); + if (fileGated || modules.length || macOSGuard(attributes) || macOSGuard(body) || + /cfg!\(target_os\s*=\s*"macos"\)|\bapple_vision_available\s*\(/.test(body) || + (posix.basename(file) === 'modality_flow.rs' && /\bassert_plugin_ocr_refused\(/.test(body)) || + (posix.basename(file) === 'host_platform_flow.rs' && /\bconfined_platform\(/.test(body) && !macOS.test(attributes))) { + names.push(name); + } + } + return names; +} + +const metadata = JSON.parse(execFileSync('cargo', ['metadata', '--locked', '--no-deps', '--format-version=1'], {encoding: 'utf8'})); +const targets = metadata.packages.flatMap(pkg => pkg.targets.filter(t => t.test && ['lib', 'test', 'bin'].includes(t.kind[0])).map(t => ({ + pkg: pkg.name, name: t.name, kind: t.kind[0], src: relative(root, t.src_path).split(sep).join('/'), tests: new Set(), +}))); +const files = execFileSync('git', ['ls-files', '-z', '--', '*.rs'], {encoding: 'utf8'}).split('\0').filter(Boolean); +const sources = new Map(files.map(file => [file, readFileSync(file, 'utf8')])); +const gatedModules = []; +for (const [file, source] of sources) { + for (const [, attributes, name] of source.matchAll(/^\s*((?:#\[[^\]]+\]\s*)+)(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*;/gm)) { + if (!macOSGuard(attributes)) continue; + const directory = /\/(lib|main|mod)\.rs$/.test(file) ? posix.dirname(file) : file.slice(0, -3); + gatedModules.push(posix.join(directory, name)); + } +} +for (const [file, source] of sources) { + const names = nativeTests(file, source, gatedModules); + if (!names.length) continue; + const target = targets.find(t => t.src === file) ?? targets.find(t => file.startsWith(`${t.src.slice(0, -3)}/`)) ?? + targets.find(t => /\/(lib|main)\.rs$/.test(t.src) && file.startsWith(`${posix.dirname(t.src)}/`)); + assert(target, `No Cargo test target owns ${file}`); + for (const name of names) target.tests.add(name); +} +const selected = targets.filter(t => t.tests.size); +assert(selected.length, 'No native macOS test targets found'); +for (const t of selected) console.log(`${t.pkg} ${t.name}: ${[...t.tests].join(', ')}`); +if (process.argv.includes('--list')) process.exit(0); +assert.equal(process.platform, 'darwin', 'Native tests require macOS'); +assert.equal(process.arch, 'arm64', 'Apple Vision tests require an ARM64 runner'); +const temporary = mkdtempSync(join(tmpdir(), 'dim-macos-ci-')); +try { + const env = {...process.env, DIMCODE_HOME: join(temporary, 'home')}; + const artifacts = join(temporary, 'artifacts.jsonl'); + const output = openSync(artifacts, 'w'); + const packages = [...new Set(selected.map(t => t.pkg))]; + const targetArgs = [...new Set(selected.map(t => t.kind === 'lib' ? '--lib' : `--${t.kind}=${t.name}`))]; + try { + execFileSync('cargo', ['test', '--locked', '--no-run', '--message-format=json-render-diagnostics', + ...packages.flatMap(pkg => ['-p', pkg]), ...targetArgs], {env, stdio: ['ignore', output, 'inherit']}); + } finally { + closeSync(output); + } + const records = readFileSync(artifacts, 'utf8').trimEnd().split('\n').map(line => JSON.parse(line)); + for (const t of selected) { + const record = records.find(r => r.reason === 'compiler-artifact' && r.profile.test && r.executable && relative(root, r.target.src_path) === t.src); + assert(record, `Missing compiled test target ${t.src}`); + const listing = execFileSync(record.executable, ['--list', '--format=terse'], {encoding: 'utf8', env}); + const available = listing.split('\n').filter(line => line.endsWith(': test')).map(line => line.slice(0, -6)); + const exact = [...t.tests].map(name => { + const matches = available.filter(test => test.split('::').at(-1) === name); + assert.equal(matches.length, 1, `Expected one ${name} in ${t.src}, found ${matches.length}`); + return matches[0]; + }); + execFileSync(process.execPath, [resolve('scripts/run-rust-test.mjs'), artifacts, t.name, '--test-threads=2', '--exact', ...exact], {env, stdio: 'inherit'}); + } +} finally { + rmSync(temporary, {recursive: true, force: true}); +} diff --git a/scripts/test-macos-native.test.mjs b/scripts/test-macos-native.test.mjs new file mode 100644 index 0000000000..36e249149a --- /dev/null +++ b/scripts/test-macos-native.test.mjs @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict'; +import {execFileSync} from 'node:child_process'; +import {cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import test from 'node:test'; + +const script = 'test-macos-native.mjs'; + +test('macOS discovery selects gated modules, individual tests and native assertions in Cargo targets', t => { + const cwd = mkdtempSync(join(tmpdir(), 'dim-native-selection-')); + t.after(() => rmSync(cwd, {recursive: true, force: true})); + for (const dir of ['src', 'scripts', 'tests']) mkdirSync(join(cwd, dir)); + cpSync(new URL(script, import.meta.url), join(cwd, 'scripts', script)); + writeFileSync(join(cwd, 'Cargo.toml'), '[package]\nname="native-selection"\nversion="0.1.0"\nedition="2024"\n'); + writeFileSync(join(cwd, 'src/lib.rs'), ` +#[cfg(all(test, target_os = "macos"))] +mod native; +#[test] +fn ordinary() {} +#[test] +fn native_assertion() { + #[cfg(target_os = "macos")] + assert!(true); +} +#[cfg(any(target_os = "macos", target_os = "linux"))] +#[test] +fn both_platforms() {} +#[cfg(not(target_os = "macos"))] +#[test] +fn other_platform() {} +#[cfg_attr(not(target_os = "macos"), ignore = "requires Apple Vision")] +#[test] +fn vision() {} +`); + writeFileSync(join(cwd, 'src/native.rs'), '#[test]\nfn nested_case() {}\n'); + writeFileSync(join(cwd, 'tests/engine.rs'), ` +#![cfg(target_os = "macos")] +#[test] +fn engine_case() {} +`); + execFileSync('git', ['init', '--quiet'], {cwd}); + execFileSync('git', ['add', '--', 'Cargo.toml', 'src', 'tests'], {cwd}); + const output = execFileSync(process.execPath, [join(cwd, 'scripts', script), '--list'], {cwd, encoding: 'utf8'}); + const tests = output.trim().split('\n').flatMap(row => row.split(': ')[1].split(', ')); + assert.deepEqual(tests.sort(), ['engine_case', 'native_assertion', 'nested_case', 'vision']); +}); diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index df72587dac..ee6aaf7649 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -3286,10 +3286,10 @@ fn preflight_checks( } if let Some(result) = exec(results, 0) { let text = text_of(result); - let printed = text.lines().next().unwrap_or_default().trim(); + let home = params.env_home.to_string_lossy(); check( "home", - !is_error(result) && printed == params.env_home.to_string_lossy(), + !is_error(result) && text.lines().any(|line| line.trim() == home), if is_error(result) { "echo $HOME was refused".into() } else { @@ -13125,14 +13125,6 @@ mod run_tools_tests { path } - /// A socket path short enough to bind: a profile's endpoint is a unix - /// socket path, and the platform bounds its length (`SUN_LEN`), which the - /// scratch directory's own path overruns. The test never connects to it; - /// `serve_home` only binds it. - fn socket_path(label: &str) -> PathBuf { - std::env::temp_dir().join(format!("dim-run-tools-{label}-{}.sock", std::process::id())) - } - fn difference_message( profile: &str, declared: &BTreeSet, @@ -13152,13 +13144,19 @@ mod run_tools_tests { let workspace = directory.join("workspace"); private_directory(&workspace).unwrap(); let models = fixture_models(&directory); + let sockets = Sockets::new().unwrap(); let probe = RegistryProbe::default(); let serving = probe.clone(); let server = app_server::serve_home( &directory.join("probe-home"), &workspace, directory.join("probe-output"), - native_probe_settings(models, socket_path("probe"), None, Overrides::default()), + native_probe_settings( + models, + sockets.0.join("probe.sock"), + None, + Overrides::default(), + ), move |builder| { builder.require_feature( Feature::new("RunToolsProbe").session("RunToolsProbe", move |names| {