diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..642fd9d --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,201 @@ +name: Release + +# Tag vX.Y.Z -> checks, build, DRAFT GitHub Release with the Windows installer attached. +# Pull request touching this file and manual runs -> same checks and build, installer kept as a +# workflow artifact only (no release). +on: + push: + tags: ["v*"] + pull_request: + paths: [".github/workflows/release.yml"] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: release-${{ github.ref }} + # A tag build is never cancelled half way. + cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }} + +env: + # Same toolchains as the development PC. + # Bumping RUST_VERSION can change the test-binary folder layout; crates/core/tests/pairing_flow.rs + # fake_phone_exe() depends on target/debug/deps (cargo 1.99 layout). + RUST_VERSION: "1.99.1" + BUN_VERSION: "1.3.14" + +jobs: + build: + runs-on: windows-latest + # Tag builds are always cold (no cache from a tag ref), so allow for a long first build. + timeout-minutes: 120 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install Rust + run: | + rustup toolchain install "$RUST_VERSION" --profile minimal --component clippy + rustup default "$RUST_VERSION" + rustc --version + + # Fails loudly if Cargo.lock is stale (version bump without committing the lock). + - name: Cargo.lock is current + run: cargo fetch --locked + + - name: Check versions + env: + EVENT_NAME: ${{ github.event_name }} + REF_NAME: ${{ github.ref_name }} + run: | + set -eu + # Native jq.exe on Windows writes CRLF: strip the CR from every value. + v_conf=$(jq -r .version apps/desktop/src-tauri/tauri.conf.json | tr -d '\r') + v_pkg=$(jq -r .version apps/desktop/package.json | tr -d '\r') + v_cargo=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "tugboat-desktop") | .version' | tr -d '\r') + echo "tauri.conf.json $v_conf | package.json $v_pkg | Cargo.toml (workspace) $v_cargo" + for v in "$v_conf" "$v_pkg" "$v_cargo"; do + [[ "$v" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || { echo "::error::BAD VERSION '$v' (empty, null or stray characters)"; exit 1; } + done + if [ "$v_conf" != "$v_pkg" ] || [ "$v_conf" != "$v_cargo" ]; then + echo "::error::VERSION MISMATCH - tauri.conf.json=$v_conf, package.json=$v_pkg, Cargo.toml=$v_cargo. Set the same version in all three." + exit 1 + fi + if [ "$EVENT_NAME" = "push" ]; then + if [ "$REF_NAME" != "v$v_conf" ]; then + echo "::error::TAG MISMATCH - tag is $REF_NAME but the three files say v$v_conf. Delete the tag, fix the versions, tag again." + exit 1 + fi + fi + + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: ${{ env.BUN_VERSION }} + + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + cache-on-failure: true + + - name: Install frontend packages + working-directory: apps/desktop + run: bun install --frozen-lockfile + + # The Rust side embeds ../dist at compile time (tauri::generate_context), so the + # frontend is built before clippy and the tests. + - name: Build frontend + working-directory: apps/desktop + run: bun run build + + # Same commands as `bun run check` (check:ts, test, check:rust), spelled out so each is its own log step. + - name: Check TypeScript and Svelte + working-directory: apps/desktop + run: bun run check:ts + + - name: Frontend tests + working-directory: apps/desktop + run: bun run test + + - name: Clippy and desktop Rust tests + working-directory: apps/desktop + run: bun run check:rust + + # The desktop crate was just tested by check:rust; every other crate is tested here. + - name: Rust workspace tests + run: cargo test --workspace --exclude tugboat-desktop + + - name: Build installer + working-directory: apps/desktop + run: bun run tauri build + + - name: Locate installer + id: installer + run: | + set -eu + shopt -s nullglob + files=(target/release/bundle/nsis/*-setup.exe) + if [ "${#files[@]}" -ne 1 ]; then + echo "::error::Expected exactly one NSIS installer in target/release/bundle/nsis, found ${#files[@]}" + ls -la target/release/bundle/nsis || true + exit 1 + fi + ver=$(jq -r .version apps/desktop/src-tauri/tauri.conf.json | tr -d '\r') + expected="target/release/bundle/nsis/Local Tugboat_${ver}_x64-setup.exe" + if [ "${files[0]}" != "$expected" ]; then + echo "::error::Installer name '${files[0]}' is not the expected '$expected'" + exit 1 + fi + mkdir out + cp "${files[0]}" "out/LocalTugboat_${ver}_x64-setup.exe" + (cd out && sha256sum "LocalTugboat_${ver}_x64-setup.exe" > "LocalTugboat_${ver}_x64-setup.exe.sha256") + ls -la out + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: windows-installer + path: out/* + if-no-files-found: error + retention-days: 14 + overwrite: true + + release: + # Tags only. Never on pull requests or manual runs. + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') + needs: build + runs-on: windows-latest + timeout-minutes: 15 + permissions: + contents: write + defaults: + run: + shell: bash + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: windows-installer + path: installer + + - name: Create draft release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TAG: ${{ github.ref_name }} + BUILT_SHA: ${{ github.sha }} + run: | + set -eu + shopt -s nullglob + files=(installer/*-setup.exe) + sums=(installer/*.sha256) + if [ "${#files[@]}" -ne 1 ] || [ "${#sums[@]}" -ne 1 ]; then + echo "::error::Expected exactly one installer and one .sha256, found ${#files[@]} and ${#sums[@]}" + exit 1 + fi + st=$(gh api "repos/$GH_REPO/compare/main...$TAG" --jq .status) + case "$st" in + identical|behind) ;; + *) echo "::error::TAG $TAG IS NOT ON main (compare status: $st)"; exit 1 ;; + esac + # The tag must still point at the commit this run built (an annotated tag resolves to its commit). + tag_sha=$(gh api "repos/$GH_REPO/commits/$TAG" --jq .sha) + if [ "$tag_sha" != "$BUILT_SHA" ]; then + echo "::error::TAG $TAG MOVED - it points at $tag_sha, this run built $BUILT_SHA" + exit 1 + fi + if gh release view "$TAG" >/dev/null 2>&1; then + echo "::error::RELEASE $TAG ALREADY EXISTS - delete that draft on GitHub, then re-run" + exit 1 + fi + cat > notes.md <<'EOF' + Windows installer for Local Tugboat (per-machine install, needs administrator approval). + + The installer is not code-signed yet. Windows may warn: More info > Run anyway. + + SHA-256: see the .sha256 file. + + Android: Google Play (link added when published). + EOF + gh release create "$TAG" "${files[0]}" "${sums[0]}" --draft --verify-tag --title "$TAG" --notes-file notes.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..5d579b2 --- /dev/null +++ b/README.md @@ -0,0 +1,31 @@ +# Local Tugboat + +Local Tugboat ("Tugboat") syncs photos and files between your Android phone and Windows PC over your own Wi-Fi only. Files are temporary by default. + +## Download + +- Windows: installer from https://github.com/Page011/LocalTugboat/releases/latest + (the installer is not code-signed yet; Windows may warn: More info > Run anyway) +- Android: Google Play (coming soon; link added when published) + +## Make a release + +1. Set the same version in `apps/desktop/src-tauri/tauri.conf.json`, `apps/desktop/package.json` and `[workspace.package]` in the root `Cargo.toml` (the desktop crate inherits it). Run `cargo check -p tugboat-desktop` so `Cargo.lock` updates, and commit all four files. +2. Commit to `main` and push `main` first. Then tag `vX.Y.Z` on that commit and push the tag (a tag pushed before its commit is on `main` on GitHub fails the run after the full build; push `main`, then re-run the workflow). +3. GitHub Actions (`.github/workflows/release.yml`) runs the checks, builds the installer and creates a draft release with the installer and its `.sha256` file. The run fails if the tag and the three versions differ, if the tag is not on `main`, if the tag was moved during the run, or if `Cargo.lock` is out of date. +4. Check the draft release and its installer, then publish it. + +The Android version (`versionName` and `versionCode` in `apps/android/app/build.gradle.kts`) is set separately; the workflow does not check it. + +To test the build on GitHub without a tag, run the workflow manually (Actions, Release, Run workflow); the installer is kept as a workflow artifact. + +## Build from source + +Needs Bun and Rust (see `RUST_VERSION` and `BUN_VERSION` in the release workflow for the pinned versions). + +- Windows: also needs the Visual Studio C++ Build Tools (MSVC Rust target). In `apps/desktop` run `bun install`, then `bun run tauri build`. The installer lands in `target/release/bundle/nsis`. +- Android: needs the Android SDK with platform 37 (Gradle finds it through `ANDROID_HOME` or `sdk.dir` in `apps/android/local.properties`; Android Studio's SDK Manager installs it), the Rust targets `aarch64-linux-android` and `x86_64-linux-android`, `cargo-ndk`, NDK 30.0.16248370 (`ANDROID_NDK_HOME`, the default used by `build-rust.cmd`) and JDK 17. Run `apps/android/build-rust.cmd`, then `gradlew.bat bundleRelease` in `apps/android`. The bundle is unsigned: sign it before uploading to Google Play. + +## Licence + +Apache-2.0, see `LICENSE`. diff --git a/crates/core/src/facade.rs b/crates/core/src/facade.rs index 7628fda..5b76eb7 100644 --- a/crates/core/src/facade.rs +++ b/crates/core/src/facade.rs @@ -92,6 +92,8 @@ pub(crate) struct Inner { pub pairing: Mutex>, pub proto: AtomicU32, pub retry_base_ms: AtomicU64, + /// Test hook: extra delay before the PC saves a confirmed pairing (0 in the apps). + pub pair_save_delay_ms: AtomicU64, pub generation: AtomicU64, /// Bytes of downloads that continued from an existing part file (tests assert on it). pub resumed_bytes: AtomicU64, @@ -142,6 +144,7 @@ impl Core { pairing: Mutex::new(None), proto: AtomicU32::new(wire::PROTO), retry_base_ms: AtomicU64::new(2000), + pair_save_delay_ms: AtomicU64::new(0), generation: AtomicU64::new(0), resumed_bytes: AtomicU64::new(0), notice_running: std::sync::atomic::AtomicBool::new(false), @@ -222,6 +225,12 @@ impl Core { self.inner.retry_base_ms.store(ms.max(1), Ordering::SeqCst); } + /// Test hook: make the PC slow to save a confirmed pairing (a busy disk or CPU). + #[doc(hidden)] + pub fn debug_set_pairing_save_delay_ms(&self, ms: u64) { + self.inner.pair_save_delay_ms.store(ms, Ordering::SeqCst); + } + /// Test hook: total bytes that downloads resumed from an existing part file. #[doc(hidden)] pub fn debug_resumed_bytes(&self) -> u64 { diff --git a/crates/core/src/sync/pair.rs b/crates/core/src/sync/pair.rs index 21d084d..5827bd1 100644 --- a/crates/core/src/sync/pair.rs +++ b/crates/core/src/sync/pair.rs @@ -19,7 +19,7 @@ use tugboat_net::{ close, pairing::{ format_code, pc_read_hello, pc_send_decision, phone_start, HelloOutcome, PairDecision, PairError, PairPayload, PairingWindow, - CONFIRM_TIMEOUT_MS, + CONFIRM_TIMEOUT_MS, PC_SAVE_WAIT, }, NetError, }; @@ -38,7 +38,9 @@ const HELLO_TIMEOUT: Duration = Duration::from_secs(10); /// Dialing the PC from the QR addresses. const DIAL_TIMEOUT: Duration = Duration::from_secs(8); -type Decision = (PairDecision, oneshot::Sender>); +/// The decision for the phone, the channel that reports its delivery and, for Accepted, the +/// signal that the PC has finished saving the pairing (sent or dropped once saving ended). +type Decision = (PairDecision, oneshot::Sender>, Option>); pub(crate) struct PendingConn { phone_key: [u8; 32], @@ -104,7 +106,7 @@ pub(crate) fn begin(core: &Core, replace_existing: bool) -> Result { if let Some(PairState { pending: Some(p), .. }) = old { // A window that was still waiting for a click is replaced: tell that phone. let (rtx, _) = oneshot::channel(); - let _ = p.decide.send((PairDecision::Refused { reason: PairError::Cancelled }, rtx)); + let _ = p.decide.send((PairDecision::Refused { reason: PairError::Cancelled }, rtx, None)); } node.set_pairing_open(true); core.emit(Event::Pairing(PairingEvent::WindowOpen { payload: payload.clone(), expires_at })); @@ -120,7 +122,7 @@ fn finish_window(core: &Core, reason: PairError) { } if let Some(p) = st.pending { let (rtx, _) = oneshot::channel(); - let _ = p.decide.send((PairDecision::Refused { reason: reason.clone() }, rtx)); + let _ = p.decide.send((PairDecision::Refused { reason: reason.clone() }, rtx, None)); } core.emit(Event::Pairing(PairingEvent::Cancelled { code: pair_code(&reason), message: pair_text(&reason) })); } @@ -193,10 +195,16 @@ pub(crate) async fn handle_conn(core: Core, peer: tugboat_net::node::PeerConn) { } tokio::select! { d = decision => match d { - Ok((decision, reply)) => { + Ok((decision, reply, stored)) => { let accepted = matches!(decision, PairDecision::Accepted { .. }); let r = pc_send_decision(&mut tx, &decision).await; let _ = reply.send(r); + // The phone dials to sync as soon as this connection closes. Close only once + // the pairing is saved here (or saving failed): a sync dial that arrives first + // is refused as "not paired", and the phone then unpairs itself. + if let Some(stored) = stored { + let _ = tokio::time::timeout(PC_SAVE_WAIT, stored).await; + } peer.close(if accepted { close::NORMAL } else { close::PAIRING_CLOSED }, "pairing finished"); } Err(_) => peer.close(close::PAIRING_CLOSED, "pairing superseded"), @@ -248,8 +256,10 @@ pub(crate) async fn confirm(core: &Core, accept: bool) -> Result<()> { Ok(Some(p)) => p, }; let (rtx, rrx) = oneshot::channel(); + // Held until the pairing is saved; dropping it on any early return also lets the connection close. + let (stored_tx, stored_rx) = oneshot::channel(); let accepted = PairDecision::Accepted { pc_name: core.inner.cfg.device_name.clone() }; - let delivered = match pending.decide.send((accepted, rtx)) { + let delivered = match pending.decide.send((accepted, rtx, Some(stored_rx))) { Ok(()) => tokio::time::timeout(Duration::from_secs(15), rrx).await.ok().and_then(|r| r.ok()), Err(_) => None, }; @@ -272,8 +282,14 @@ pub(crate) async fn confirm(core: &Core, accept: bool) -> Result<()> { last_seen_at: None, addresses: Vec::new(), }; + let delay = core.inner.pair_save_delay_ms.load(std::sync::atomic::Ordering::SeqCst); + if delay > 0 { + tokio::time::sleep(Duration::from_millis(delay)).await; + } core.with_ctx(|c, ctx| ops::pairing_completed(c, ctx, &row))?; drop_other_sessions(core, row.id); + // Saved: the pairing connection may close now, and the phone's first sync dial is accepted. + let _ = stored_tx.send(()); core.emit(Event::Pairing(PairingEvent::Completed { peer: row.id, peer_name: row.name.clone() })); core.emit(Event::ActivityAdded); core.emit_status(); diff --git a/crates/core/tests/pairing_flow.rs b/crates/core/tests/pairing_flow.rs index 891f879..b69e0b9 100644 --- a/crates/core/tests/pairing_flow.rs +++ b/crates/core/tests/pairing_flow.rs @@ -452,3 +452,24 @@ async fn s21_fake_phone_pairs_sends_and_lists() { assert!(text.contains("3 items"), "{text}"); pc.stop().await; } + +// A PC that is slow to save the pairing (2 s, a busy disk or CPU): the phone must not make its +// first sync dial before the save, or the PC refuses it as "not paired" and the phone unpairs +// itself a moment after pairing (seen on a loaded CI runner). +#[tokio::test(flavor = "multi_thread")] +async fn a_slow_pairing_save_on_the_pc_still_ends_paired_on_both() { + let r = Rig::unconnected(); + r.pc.start().await; + r.phone.start().await; + r.pc.core.debug_set_pairing_save_delay_ms(2000); + let payload = r.pc.core.begin_pairing(false).unwrap(); + let phone = r.phone.core.clone(); + let task = tokio::spawn(async move { phone.pair_with(&payload).await }); + until("codes", 10, || r.pc.code().is_some() && r.phone.code().is_some()).await; + r.pc.core.confirm_pairing(true).await.unwrap(); + task.await.unwrap().unwrap(); + r.settle().await; + assert!(r.phone.core.paired_device().unwrap().is_some(), "the phone is still paired"); + assert!(r.pc.core.paired_device().unwrap().is_some(), "the PC is still paired"); + r.shutdown().await; +} diff --git a/crates/net/src/pairing.rs b/crates/net/src/pairing.rs index 370938f..c1bd4ba 100644 --- a/crates/net/src/pairing.rs +++ b/crates/net/src/pairing.rs @@ -51,6 +51,13 @@ pub const CODE_CONTEXT: &str = "localtugboat 2026-11-17 pairing code v1"; const MAX_PAIR_FRAME: u32 = 4096; /// Waiting for the decision to reach the phone before the PC closes the connection. const DELIVERY_TIMEOUT: Duration = Duration::from_secs(5); +/// PC, after Accepted was delivered: how long it keeps the pairing connection open while it saves +/// the pairing (normally milliseconds). It closes the connection once saved. +pub const PC_SAVE_WAIT: Duration = Duration::from_secs(10); +/// Phone, after Accepted: waiting for the PC to close the pairing connection. Covers the PC's +/// whole path (its delivery wait, then its save wait) plus a margin, so the phone never dials +/// to sync before the PC has saved the pairing. +const CLOSE_WAIT: Duration = Duration::from_secs(DELIVERY_TIMEOUT.as_secs() + PC_SAVE_WAIT.as_secs() + 2); const PAYLOAD_PREFIX: &str = "localtugboat://pair?"; @@ -594,15 +601,16 @@ impl PhonePairing { /// Step 2b, after `read_decision`: let the PC see the decision arrived, then leave. Accepted /// -> Ok(pc_name, cleaned). Refused -> Err(NetError::Pairing(reason)). Once the decision is /// read the PC may already have completed its side, so a caller must not abandon this step - /// (it takes up to DELIVERY_TIMEOUT + 2 s) before it stores the pairing. + /// (it takes up to DELIVERY_TIMEOUT + CLOSE_WAIT) before it stores the pairing. pub async fn finish(self, decision: PairDecision) -> Result { let mut this = self; // Read the stream to its end before leaving: that is what tells the PC the decision // arrived. Closing first would make a delivered decision look undelivered on the PC. let mut one = [0u8; 1]; let _ = tokio::time::timeout(DELIVERY_TIMEOUT, this.rx.read(&mut one)).await; - // The PC closes after it sees the delivery; give it a moment, then leave ourselves. - let _ = tokio::time::timeout(Duration::from_secs(2), this.conn.conn.closed()).await; + // The PC closes once it has saved the pairing. Wait for that: a sync dial made earlier is + // refused as "not paired". If the PC never closes, leave after CLOSE_WAIT. + let _ = tokio::time::timeout(CLOSE_WAIT, this.conn.conn.closed()).await; this.conn.close(close::NORMAL, "pairing finished"); match decision { PairDecision::Accepted { pc_name } => Ok(clean_name(&pc_name, "PC")),