Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(desktop): connect community daemon and harden native lifecycle (#469)
Genere91ba3f4f425
diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex c1e121fb2..eb55e9172 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -69,7 +69,7 @@ jobs:releaseBody: ""releaseDraft: falseprerelease: false- includeUpdaterJson: true+ uploadUpdaterJson: trueargs: --target ${{ matrix.target }}update-release-notes:@@ -103,9 +103,13 @@ jobs:### macOS[Apple Silicon](${BASE}/Alook_${VERSION}_aarch64.dmg) | [Intel](${BASE}/Alook_${VERSION}_x64.dmg)+ These macOS builds are ad-hoc signed and are not notarized. On first launch, macOS may block the app; open System Settings → Privacy & Security and choose **Open Anyway**.+### Windows[.exe Installer](${BASE}/Alook_${VERSION}_x64-setup.exe) | [.msi](${BASE}/Alook_${VERSION}_x64_en-US.msi)+ These Windows builds are not Authenticode code-signed. On first launch, Microsoft Defender SmartScreen may block the app; choose **More info** → **Run anyway** to continue.+### Linux[.deb](${BASE}/Alook_${VERSION}_amd64.deb) | [.rpm](${BASE}/Alook-${VERSION}-1.x86_64.rpm) | [.AppImage](${BASE}/Alook_${VERSION}_amd64.AppImage)"diff --git a/.github/workflows/mobile-release.yml b/.github/workflows/mobile-release.ymldeleted file mode 100644index a9c2d84bb..000000000--- a/.github/workflows/mobile-release.yml+++ /dev/null@@ -1,113 +0,0 @@-name: Mobile Release--on:- push:- branches: [main]- paths:- - "src/desktop/.deploy-version-mobile"--permissions:- contents: read--jobs:- ios:- runs-on: macos-latest- timeout-minutes: 45- steps:- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7-- - name: Setup Node.js- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7- with:- node-version: 22-- - name: Install pnpm- uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6-- - name: Install Rust stable- uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stable- with:- targets: aarch64-apple-ios-- - name: Install frontend dependencies- run: pnpm install --frozen-lockfile- working-directory: src/desktop-- - name: Build iOS- working-directory: src/desktop- run: pnpm tauri ios build- env:- APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}- APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}- APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}- APPLE_PROVISIONING_PROFILE: ${{ secrets.APPLE_PROVISIONING_PROFILE }}-- - name: Upload to App Store Connect- run: |- xcrun altool --upload-app \- --type ios \- --file src/desktop/src-tauri/gen/apple/build/arm64/alook.ipa \- --apiKey ${{ secrets.APP_STORE_API_KEY }} \- --apiIssuer ${{ secrets.APP_STORE_API_ISSUER }}-- android:- runs-on: ubuntu-22.04- timeout-minutes: 45- steps:- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7-- - name: Setup Node.js- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7- with:- node-version: 22-- - name: Install pnpm- uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6-- - name: Install Rust stable- uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stable- with:- targets: aarch64-linux-android,armv7-linux-androideabi-- - name: Setup Java- uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5- with:- distribution: temurin- java-version: 17-- - name: Setup Android SDK- uses: android-actions/setup-android@40fd30fb8d7440372e1316f5d1809ec01dcd3699 # v4-- - name: Install Android NDK- run: sdkmanager "ndk;27.0.12077973"-- - name: Install frontend dependencies- run: pnpm install --frozen-lockfile- working-directory: src/desktop-- - name: Decode Android keystore- run: echo "${{ secrets.ANDROID_KEYSTORE_BASE64 }}" | base64 -d > ${{ github.workspace }}/release.keystore-- - name: Write keystore.properties- run: |- mkdir -p src/desktop/src-tauri/gen/android/app- cat > src/desktop/src-tauri/gen/android/app/keystore.properties <<EOF- storeFile=${{ github.workspace }}/release.keystore- storePassword=${{ secrets.ANDROID_STORE_PASSWORD }}- keyAlias=${{ secrets.ANDROID_KEY_ALIAS }}- keyPassword=${{ secrets.ANDROID_KEY_PASSWORD }}- EOF-- - name: Build Android- working-directory: src/desktop- run: pnpm tauri android build- env:- NDK_HOME: /usr/local/lib/android/sdk/ndk/27.0.12077973-- - name: Upload to Google Play- uses: r0adkll/upload-google-play@e738b9dd8f2476ea806d921b64aacd24f34515a5 # v1- with:- serviceAccountJsonPlainText: ${{ secrets.GOOGLE_PLAY_SERVICE_ACCOUNT }}- packageName: ai.alook.desktop- releaseFiles: src/desktop/src-tauri/gen/android/app/build/outputs/bundle/release/*.aab- track: internaldiff --git a/AGENTS.md b/AGENTS.mdindex b96d9306a..02596be8e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -24,12 +24,11 @@ pnpm bump 0.0.11 # explicit version (v prefix optional)pnpm bump patch # auto-increment patch/minor/majorpnpm bump patch --min-cli # also update MIN_CLI_VERSION in src/web/wrangler.tomlpnpm bump patch --desktop # trigger desktop build-pnpm bump patch --mobile # trigger mobile build```This updates every `src/*/package.json` and commits `release: vX.Y.Z`.Add `--min-cli` when the release contains breaking changes that require users to update their CLI.Add `--desktop` when the release includes desktop app changes that need a new build.-Add `--mobile` when the release includes mobile app changes.+Mobile store releases are not configured; add current signing accounts and rebuild the release workflow before exposing a mobile release flag.After reviewing the commit:```bashdiff --git a/assets/alook-tray-offline.svg b/assets/alook-tray-offline.svgnew file mode 100644index 000000000..1245e70ad--- /dev/null+++ b/assets/alook-tray-offline.svg@@ -0,0 +1,9 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 1200">+ <mask id="face" maskUnits="userSpaceOnUse" x="0" y="0" width="1200" height="1200">+ <rect width="1200" height="1200" fill="black"/>+ <path d="M73.3744 799.986L80.287 602.034C88.6974 361.193 232.448 217.568 434.621 198.202C507.549 190.84 540.698 92.9006 702.358 98.5459C972.892 107.993 1146.28 345.273 1136.03 638.902L1129.12 836.853C1122.78 1018.31 954.364 1111.52 591.453 1098.85C228.541 1086.18 67.0378 981.442 73.3744 799.986Z" fill="white"/>+ <path d="M442 470H556M704 470H818" stroke="black" stroke-width="48" stroke-linecap="round"/>+ <path d="M520 640C577 584 665 584 738 640" fill="none" stroke="black" stroke-width="46" stroke-linecap="round"/>+ </mask>+ <rect width="1200" height="1200" fill="black" mask="url(#face)"/>+</svg>diff --git a/assets/alook-tray.svg b/assets/alook-tray.svgnew file mode 100644index 000000000..f2d306610--- /dev/null+++ b/assets/alook-tray.svg@@ -0,0 +1,12 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 1200">+ <mask id="face" maskUnits="userSpaceOnUse" x="0" y="0" width="1200" height="1200">+ <rect width="1200" height="1200" fill="black"/>+ <path d="M73.3744 799.986L80.287 602.034C88.6974 361.193 232.448 217.568 434.621 198.202C507.549 190.84 540.698 92.9006 702.358 98.5459C972.892 107.993 1146.28 345.273 1136.03 638.902L1129.12 836.853C1122.78 1018.31 954.364 1111.52 591.453 1098.85C228.541 1086.18 67.0378 981.442 73.3744 799.986Z" fill="white"/>+ <path d="M499.787 535.435C538.186 535.435 569.315 505.031 569.315 467.525C569.315 430.019 538.186 399.614 499.787 399.614C461.388 399.614 430.26 430.019 430.26 467.525C430.26 505.031 461.388 535.435 499.787 535.435Z" fill="black"/>+ <path d="M522.424 513.445C540.641 513.445 555.409 498.677 555.409 480.46C555.409 462.243 540.641 447.475 522.424 447.475C504.207 447.475 489.439 462.243 489.439 480.46C489.439 498.677 504.207 513.445 522.424 513.445Z" fill="white"/>+ <path d="M758.494 535.435C796.893 535.435 828.021 505.031 828.021 467.525C828.021 430.019 796.893 399.614 758.494 399.614C720.095 399.614 688.966 430.019 688.966 467.525C688.966 505.031 720.095 535.435 758.494 535.435Z" fill="black"/>+ <path d="M781.131 513.445C799.348 513.445 814.116 498.677 814.116 480.46C814.116 462.243 799.348 447.475 781.131 447.475C762.914 447.475 748.146 462.243 748.146 480.46C748.146 498.677 762.914 513.445 781.131 513.445Z" fill="white"/>+ <path d="M711.48 571.1C722.145 562.995 737.361 565.07 745.466 575.735C753.571 586.399 751.496 601.615 740.832 609.72C680.61 655.489 608.609 669.247 527.369 652.999C514.235 650.372 505.716 637.594 508.343 624.459C510.971 611.325 523.748 602.806 536.883 605.433C606.555 619.368 663.908 607.255 711.48 571.1Z" fill="black"/>+ </mask>+ <rect width="1200" height="1200" fill="black" mask="url(#face)"/>+</svg>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5b9c35daa..3b54b312b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -147,28 +147,6 @@ importers:version: 4.1.10(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))src/desktop:- dependencies:- '@tauri-apps/api':- specifier: ^2.11.1- version: 2.11.1- '@tauri-apps/plugin-autostart':- specifier: ^2.2.0- version: 2.5.1- '@tauri-apps/plugin-deep-link':- specifier: ^2.2.0- version: 2.4.9- '@tauri-apps/plugin-dialog':- specifier: ^2.7.2- version: 2.7.2- '@tauri-apps/plugin-global-shortcut':- specifier: ^2.2.0- version: 2.3.2- '@tauri-apps/plugin-notification':- specifier: ^2.2.0- version: 2.3.3- '@tauri-apps/plugin-shell':- specifier: ^2.2.0- version: 2.3.5devDependencies:'@tauri-apps/cli':specifier: ^2.11.4@@ -3572,9 +3550,6 @@ packages:'@tanstack/[email protected]':resolution: {integrity: sha512-bp+v10y65sp2H7WpWfIMyxTNfl8ZVfxFTLRjPIFRryi6FV/J33z4IS53WO4pTk36KlvJ4iLiQz+oaydDC1xbcA==}- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA==}-'@tauri-apps/[email protected]':resolution: {integrity: sha512-1ryOF3ZhpZ/nemHV5zVwBQBz9jDGKmKPvWPADOhc83ig0P4bMc2iER4NbC6r9sjeIZ6RVQ4g3RZIYvezhcl4TQ==}engines: {node: '>= 10'}@@ -3651,24 +3626,6 @@ packages:engines: {node: '>= 10'}hasBin: true- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-zS/xx7yzveCcotkA+8TqkI2lysmG2wvQXv2HGAVExITmnFfHAdj1arGsbbfs3o6EktRHf6l34pJxc3YGG2mg7w==}-- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-u0SKOUHnJ1wqeqXsDFq2+kASCBj9xxbG0g9XZWPy9SOmU4wXtp6b/wiYpm6oH6/5fBTQsLqnLhIvqLBRpgHJlA==}-- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-pX0IGm1I3I6wc+zeKYcq1GSqogK6okCNX5fOdaNU5ab1AjGS6l1E5wFNjEb7meg7ZFSp0JUs+0jQGQNyOvLrsg==}-- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-UReHNXrLvpEjylE4jb4oCYiy96uRykPUthoCQCmRXYrd5hs5X9DrW+qOn7GLW57EJN4tdK8bgK5twBTz2NOxzA==}-- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-Zw+ZH18RJb41G4NrfHgIuofJiymusqN+q8fGUIIV7vyCH+5sSn5coqRv/MWB9qETsUs97vmU045q7OyseCV3Qg==}-- '@tauri-apps/[email protected]':- resolution: {integrity: sha512-jewtULhiQ7lI7+owCKAjc8tYLJr92U16bPOeAa472LHJdgaibLP83NcfAF2e+wkEcA53FxKQAZ7byDzs2eeizg==}-'@tiptap/[email protected]':resolution: {integrity: sha512-oKUkiPUB7noilVYxI9lNzUD4rX17sHub+PYjMfHMWHG9A3nvIy+FdePIVIIhThKWF7ijhr3eIqHY51Bn+GAFtw==}peerDependencies:@@ -12262,8 +12219,6 @@ snapshots:'@tanstack/[email protected]': {}- '@tauri-apps/[email protected]': {}-'@tauri-apps/[email protected]':optional: true@@ -12311,30 +12266,6 @@ snapshots:'@tauri-apps/cli-win32-ia32-msvc': 2.11.4'@tauri-apps/cli-win32-x64-msvc': 2.11.4- '@tauri-apps/[email protected]':- dependencies:- '@tauri-apps/api': 2.11.1-- '@tauri-apps/[email protected]':- dependencies:- '@tauri-apps/api': 2.11.1-- '@tauri-apps/[email protected]':- dependencies:- '@tauri-apps/api': 2.11.1-- '@tauri-apps/[email protected]':- dependencies:- '@tauri-apps/api': 2.11.1-- '@tauri-apps/[email protected]':- dependencies:- '@tauri-apps/api': 2.11.1-- '@tauri-apps/[email protected]':- dependencies:- '@tauri-apps/api': 2.11.1-'@tiptap/[email protected](@tiptap/[email protected])':dependencies:'@tiptap/pm': 3.29.2diff --git a/scripts/bump-version.mjs b/scripts/bump-version.mjsindex 80af89bb4..5417dafbb 100644--- a/scripts/bump-version.mjs+++ b/scripts/bump-version.mjs@@ -27,7 +27,14 @@ function bumpSemver(current, type) {const args = process.argv.slice(2);const updateMinCli = args.includes("--min-cli");const includeDesktop = args.includes("--desktop");-const includeMobile = args.includes("--mobile");+const unsupportedFlag = args.find(+ (arg) => arg.startsWith("--") && !["--min-cli", "--desktop"].includes(arg),+);+if (unsupportedFlag) {+ console.error(`Unsupported flag: ${unsupportedFlag}`);+ console.error("Mobile releases are not configured; store signing accounts are required first.");+ process.exit(1);+}const filtered = args.filter((a) => !a.startsWith("--"));const arg = filtered[0];@@ -35,8 +42,6 @@ if (!arg) {console.error("Usage: pnpm bump <version|patch|minor|major> [flags]");console.error(" pnpm bump patch");console.error(" pnpm bump patch --desktop # trigger desktop build");- console.error(" pnpm bump patch --mobile # trigger mobile build");- console.error(" pnpm bump patch --desktop --mobile # trigger both");console.error(" pnpm bump patch --min-cli # also update MIN_CLI_VERSION");process.exit(1);}@@ -114,14 +119,6 @@ if (includeDesktop) {console.log(` Desktop deploy trigger written`);}-// Mobile deploy trigger (only with --mobile)-if (includeMobile) {- const triggerPath = join(ROOT, "src/desktop/.deploy-version-mobile");- writeFileSync(triggerPath, version + "\n");- files.push(triggerPath);- console.log(` Mobile deploy trigger written`);-}-if (updateMinCli) {const tomlPath = join(ROOT, "src/web/wrangler.toml");let toml = readFileSync(tomlPath, "utf8");@@ -143,6 +140,5 @@ console.log(` git push origin main`);console.log(` # CI will auto-tag and trigger:`);console.log(` # - CF Workers deploy (always)`);if (includeDesktop) console.log(` # - Desktop build (macOS/Linux/Windows)`);-if (includeMobile) console.log(` # - Mobile build (iOS/Android)`);-if (!includeDesktop && !includeMobile) console.log(` # - No desktop/mobile builds (add --desktop or --mobile to include)`);+if (!includeDesktop) console.log(` # - No desktop build (add --desktop to include)`);console.log();diff --git a/scripts/ci/logo-assets.test.ts b/scripts/ci/logo-assets.test.tsindex bf0d762ca..2c2a74eda 100644--- a/scripts/ci/logo-assets.test.ts+++ b/scripts/ci/logo-assets.test.ts@@ -9,6 +9,7 @@ import {fullBleedSvg,iosRasterAssets,preservedAssets,+ trayRasterAssets,} from "../generate-logo-assets.mjs"const repoRoot = resolve(import.meta.dirname, "../..")@@ -52,11 +53,13 @@ describe("logo asset generator", () => {expect(iosRasterAssets).toHaveLength(18)expect(preservedAssets).toEqual(["src/web/src/app/favicon.ico",- "src/desktop/src-tauri/icons/tray-default.png",- "src/desktop/src-tauri/icons/tray-online.png",- "src/desktop/src-tauri/icons/tray-offline.png","assets/readme-banner.png",])+ expect(trayRasterAssets).toEqual([+ ["assets/alook-tray.svg", "src/desktop/src-tauri/icons/tray-default.png"],+ ["assets/alook-tray.svg", "src/desktop/src-tauri/icons/tray-online.png"],+ ["assets/alook-tray-offline.svg", "src/desktop/src-tauri/icons/tray-offline.png"],+ ])})it("canonicalizes nondeterministic ICNS chunk order", () => {@@ -78,6 +81,20 @@ describe("logo asset generator", () => {expect(canonicalizeIcns(canonical)).toEqual(canonical)})+ it("keeps Retina Tray templates generated from their SVG sources", async () => {+ for (const [source, destination] of trayRasterAssets) {+ const svg = await readFile(resolve(repoRoot, source))+ const expected = await sharp(svg).resize(36, 36).png().toBuffer()+ expect(await readFile(resolve(repoRoot, destination))).toEqual(expected)+ expect(await alphaBounds(resolve(repoRoot, destination))).toEqual({+ width: 36,+ height: 36,+ bounds: [2, 2, 35, 33],+ opaque: false,+ })+ }+ })+it("preserves web, platform, and splash canvas contracts", async () => {expect(await alphaBounds(resolve(repoRoot, "src/web/public/icon-192.png"))).toEqual({width: 192,diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.tsindex 8ded7ef89..f20632a2b 100644--- a/scripts/ci/workflow-contract.test.ts+++ b/scripts/ci/workflow-contract.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs"+import { existsSync, readFileSync } from "node:fs"import { resolve } from "node:path"import { describe, expect, it } from "vitest"@@ -9,6 +9,30 @@ function normalizeWorkflow(text: string): string {const workflow = normalizeWorkflow(readFileSync(resolve(workflowRoot, "e2e-ui.yml"), "utf8"))const ciWorkflow = normalizeWorkflow(readFileSync(resolve(workflowRoot, "ci.yml"), "utf8"))+const desktopReleaseWorkflow = normalizeWorkflow(readFileSync(resolve(workflowRoot, "desktop-release.yml"), "utf8"))+const desktopConfig = JSON.parse(+ readFileSync(resolve(import.meta.dirname, "../../src/desktop/src-tauri/tauri.conf.json"), "utf8"),+) as {+ bundle?: { createUpdaterArtifacts?: boolean | string }+ plugins?: { updater?: { endpoints?: string[] } }+}+const desktopMacConfig = JSON.parse(+ readFileSync(resolve(import.meta.dirname, "../../src/desktop/src-tauri/tauri.macos.conf.json"), "utf8"),+) as { bundle?: { macOS?: { entitlements?: string; signingIdentity?: string } } }+const desktopEntitlementsPath = resolve(+ import.meta.dirname,+ "../../src/desktop/src-tauri/entitlements.plist",+)+const desktopBuildScript = readFileSync(+ resolve(import.meta.dirname, "../../src/desktop/scripts/build.sh"),+ "utf8",+)+const bumpScript = readFileSync(resolve(import.meta.dirname, "../bump-version.mjs"), "utf8")+const mobileReleaseWorkflow = resolve(workflowRoot, "mobile-release.yml")+const desktopUpdateRoute = readFileSync(+ resolve(import.meta.dirname, "../../src/web/src/app/api/desktop/update/[target]/[arch]/[current_version]/route.ts"),+ "utf8",+)const publishWorkflows = ["publish-app.yml", "publish-cli.yml", "publish-daemon.yml"].map((name) => normalizeWorkflow(readFileSync(resolve(workflowRoot, name), "utf8")))@@ -53,3 +77,50 @@ describe("Bun workflow setup", () => {}})})++describe("Desktop updater release", () => {+ it("builds signed updater artifacts and publishes updater metadata", () => {+ expect(desktopConfig.bundle?.createUpdaterArtifacts).toBe(true)+ expect(desktopConfig.plugins?.updater?.endpoints).toEqual([+ "https://alook.ai/api/desktop/update/{{target}}/{{arch}}/{{current_version}}?bundle_type={{bundle_type}}",+ ])+ expect(desktopReleaseWorkflow).toContain("uploadUpdaterJson: true")+ expect(desktopReleaseWorkflow).not.toContain("includeUpdaterJson")+ expect(desktopReleaseWorkflow).toContain("TAURI_SIGNING_PRIVATE_KEY:")+ expect(desktopUpdateRoute).toContain('"darwin-aarch64-app"')+ expect(desktopUpdateRoute).toContain('"linux-x86_64-appimage"')+ expect(desktopUpdateRoute).toContain('"linux-x86_64-deb"')+ expect(desktopUpdateRoute).toContain('"linux-x86_64-rpm"')+ expect(desktopUpdateRoute).toContain('"windows-x86_64-msi"')+ expect(desktopUpdateRoute).toContain('"windows-x86_64-nsis"')+ })++ it("uses an inline unsigned-build overlay without mutating tracked configuration", () => {+ expect(desktopBuildScript).toContain(+ `--config '{"bundle":{"createUpdaterArtifacts":false}}'`,+ )+ expect(desktopBuildScript).not.toContain("tauri.conf.json")+ expect(desktopBuildScript).not.toMatch(/\b(?:cp|mv|sed)\b/)+ expect(desktopBuildScript).not.toContain(".bak")+ })++ it("ad-hoc signs unnotarized macOS builds and discloses manual approval", () => {+ expect(desktopMacConfig.bundle?.macOS?.signingIdentity).toBe("-")+ expect(desktopMacConfig.bundle?.macOS?.entitlements).toBeUndefined()+ expect(existsSync(desktopEntitlementsPath)).toBe(false)+ expect(desktopReleaseWorkflow).toContain("ad-hoc signed and are not notarized")+ expect(desktopReleaseWorkflow).toContain("Privacy & Security")+ expect(desktopReleaseWorkflow).toContain("not Authenticode code-signed")+ expect(desktopReleaseWorkflow).toContain("More info")+ expect(desktopReleaseWorkflow).toContain("Run anyway")+ expect(desktopReleaseWorkflow).not.toContain("APPLE_CERTIFICATE:")+ })+})++describe("Mobile release availability", () => {+ it("fails closed until store signing accounts and a current workflow exist", () => {+ expect(existsSync(mobileReleaseWorkflow)).toBe(false)+ expect(bumpScript).not.toContain("deploy-version-mobile")+ expect(bumpScript).toContain("Mobile releases are not configured")+ })+})diff --git a/scripts/generate-logo-assets.mjs b/scripts/generate-logo-assets.mjsindex 027e08249..a8db06530 100644--- a/scripts/generate-logo-assets.mjs+++ b/scripts/generate-logo-assets.mjs@@ -18,12 +18,15 @@ const sharp = requireFromCli("sharp")export const preservedAssets = ["src/web/src/app/favicon.ico",- "src/desktop/src-tauri/icons/tray-default.png",- "src/desktop/src-tauri/icons/tray-online.png",- "src/desktop/src-tauri/icons/tray-offline.png","assets/readme-banner.png",]+export const trayRasterAssets = [+ ["assets/alook-tray.svg", "src/desktop/src-tauri/icons/tray-default.png"],+ ["assets/alook-tray.svg", "src/desktop/src-tauri/icons/tray-online.png"],+ ["assets/alook-tray-offline.svg", "src/desktop/src-tauri/icons/tray-offline.png"],+]+export const desktopRasterAssets = ["32x32.png","64x64.png",@@ -124,6 +127,13 @@ async function renderContained(svg, canvasSize, artworkSize) {}).composite([{ input: artwork, left: offset, top: offset }]).png().toBuffer()}+export async function generateTrayAssets() {+ for (const [source, destination] of trayRasterAssets) {+ const svg = await readFile(resolve(repoRoot, source), "utf8")+ await writeFile(resolve(repoRoot, destination), await render(svg, 36))+ }+}+async function assertDimensions(path, width, height = width) {const metadata = await sharp(path).metadata()if (metadata.width !== width || metadata.height !== height) {@@ -156,6 +166,7 @@ export async function generateLogoAssets() {await writeFile(resolve(repoRoot, "src/web/public/icon-512.png"), await render(canonical, 512))const fullBleed = fullBleedSvg(canonical)await writeFile(resolve(repoRoot, "src/web/public/apple-touch-icon.png"), await renderOpaque(fullBleed, 180))+ await generateTrayAssets()for (const file of desktopRasterAssets) {const source = join(roundedOutput, file)diff --git a/src/desktop/package.json b/src/desktop/package.jsonindex 330b617c9..fe0023b60 100644--- a/src/desktop/package.json+++ b/src/desktop/package.json@@ -3,21 +3,12 @@"version": "0.1.7","private": true,"scripts": {- "dev": "tauri dev",+ "dev": "tauri dev --config src-tauri/tauri.dev.conf.json","build": "sh scripts/build.sh","tauri": "tauri","ios": "tauri ios dev","android": "tauri android dev"},- "dependencies": {- "@tauri-apps/api": "^2.11.1",- "@tauri-apps/plugin-autostart": "^2.2.0",- "@tauri-apps/plugin-deep-link": "^2.2.0",- "@tauri-apps/plugin-dialog": "^2.7.2",- "@tauri-apps/plugin-global-shortcut": "^2.2.0",- "@tauri-apps/plugin-notification": "^2.2.0",- "@tauri-apps/plugin-shell": "^2.2.0"- },"devDependencies": {"@tauri-apps/cli": "^2.11.4"}diff --git a/src/desktop/scripts/build.sh b/src/desktop/scripts/build.shindex e46368386..48f0d127b 100755--- a/src/desktop/scripts/build.sh+++ b/src/desktop/scripts/build.sh@@ -1,20 +1,8 @@#!/bin/shset -e-CONF="src-tauri/tauri.conf.json"-NEEDS_RESTORE=false--# If no signing key is set, temporarily disable updater artifact signingif [ -z "$TAURI_SIGNING_PRIVATE_KEY" ]; then- sed -i.bak 's/"createUpdaterArtifacts": true/"createUpdaterArtifacts": false/' "$CONF"- NEEDS_RESTORE=true-fi--tauri build "$@"-EXIT_CODE=$?--if [ "$NEEDS_RESTORE" = true ]; then- mv "$CONF.bak" "$CONF"+ exec tauri build --config '{"bundle":{"createUpdaterArtifacts":false}}' "$@"fi-exit $EXIT_CODE+exec tauri build "$@"diff --git a/src/desktop/src-tauri/Cargo.lock b/src/desktop/src-tauri/Cargo.lockindex 92a8fa9c6..342ee3c4f 100644--- a/src/desktop/src-tauri/Cargo.lock+++ b/src/desktop/src-tauri/Cargo.lock@@ -37,6 +37,7 @@ name = "alook-desktop"version = "0.1.7"dependencies = ["base64 0.22.1",+ "command-group","objc2","objc2-app-kit","objc2-foundation",@@ -44,15 +45,11 @@ dependencies = ["serde_json","tauri","tauri-build",- "tauri-plugin-autostart",- "tauri-plugin-biometric",- "tauri-plugin-deep-link","tauri-plugin-dialog",- "tauri-plugin-global-shortcut","tauri-plugin-notification",- "tauri-plugin-push",- "tauri-plugin-shell",+ "tauri-plugin-single-instance","tauri-plugin-updater",+ "tokio",][[package]]@@ -239,17 +236,6 @@ version = "1.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"-[[package]]-name = "auto-launch"-version = "0.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1f012b8cc0c850f34117ec8252a44418f2e34a2cf501de89e29b241ae5f79471"-dependencies = [- "dirs 4.0.0",- "thiserror 1.0.69",- "winreg 0.10.1",-]-[[package]]name = "autocfg"version = "1.5.1"@@ -525,32 +511,22 @@ dependencies = [][[package]]-name = "concurrent-queue"-version = "2.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"-dependencies = [- "crossbeam-utils",-]--[[package]]-name = "const-random"-version = "0.1.18"+name = "command-group"+version = "5.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"+checksum = "a68fa787550392a9d58f44c21a3022cfb3ea3e2458b7f85d3b399d0ceeccf409"dependencies = [- "const-random-macro",+ "nix",+ "winapi",][[package]]-name = "const-random-macro"-version = "0.1.16"+name = "concurrent-queue"+version = "2.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"dependencies = [- "getrandom 0.2.17",- "once_cell",- "tiny-keccak",+ "crossbeam-utils",][[package]]@@ -636,12 +612,6 @@ version = "0.8.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"-[[package]]-name = "crunchy"-version = "0.2.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"-[[package]]name = "crypto-common"version = "0.1.7"@@ -788,33 +758,13 @@ dependencies = ["crypto-common",]-[[package]]-name = "dirs"-version = "4.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059"-dependencies = [- "dirs-sys 0.3.7",-]-[[package]]name = "dirs"version = "6.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"dependencies = [- "dirs-sys 0.5.0",-]--[[package]]-name = "dirs-sys"-version = "0.3.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6"-dependencies = [- "libc",- "redox_users 0.4.6",- "winapi",+ "dirs-sys",][[package]]@@ -825,7 +775,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"dependencies = ["libc","option-ext",- "redox_users 0.5.2",+ "redox_users","windows-sys 0.61.2",]@@ -875,15 +825,6 @@ dependencies = ["syn 2.0.117",]-[[package]]-name = "dlv-list"-version = "0.5.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f"-dependencies = [- "const-random",-]-[[package]]name = "dom_query"version = "0.27.0"@@ -961,7 +902,7 @@ dependencies = ["rustc_version","toml 1.1.2+spec-1.1.0","vswhom",- "winreg 0.55.0",+ "winreg",][[package]]@@ -970,15 +911,6 @@ version = "1.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"-[[package]]-name = "encoding_rs"-version = "0.8.35"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"-dependencies = [- "cfg-if",-]-[[package]]name = "endi"version = "1.1.1"@@ -1352,16 +1284,6 @@ dependencies = ["version_check",]-[[package]]-name = "gethostname"-version = "1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"-dependencies = [- "rustix",- "windows-link 0.2.1",-]-[[package]]name = "getrandom"version = "0.2.17"@@ -1483,24 +1405,6 @@ version = "0.3.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"-[[package]]-name = "global-hotkey"-version = "0.8.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8c386b0a4a70cb2d39fffd74480f985b6f0bfbcb934b6a6b6b7e630e448f242e"-dependencies = [- "crossbeam-channel",- "keyboard-types",- "objc2",- "objc2-app-kit",- "once_cell",- "serde",- "thiserror 2.0.18",- "windows-sys 0.59.0",- "x11rb",- "xkeysym",-]-[[package]]name = "gobject-sys"version = "0.18.0"@@ -1570,12 +1474,6 @@ version = "0.12.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"-[[package]]-name = "hashbrown"-version = "0.14.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"-[[package]]name = "hashbrown"version = "0.15.5"@@ -1922,25 +1820,6 @@ version = "2.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"-[[package]]-name = "is-docker"-version = "0.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"-dependencies = [- "once_cell",-]--[[package]]-name = "is-wsl"-version = "0.4.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"-dependencies = [- "is-docker",- "once_cell",-]-[[package]]name = "itoa"version = "1.0.18"@@ -2312,6 +2191,17 @@ version = "1.0.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"+[[package]]+name = "nix"+version = "0.27.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053"+dependencies = [+ "bitflags 2.12.1",+ "cfg-if",+ "libc",+]+[[package]]name = "notify-rust"version = "4.17.0"@@ -2599,18 +2489,6 @@ version = "1.21.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"-[[package]]-name = "open"-version = "5.3.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2fbaa89d2ddc8473c78a3adf69eea8cffa28c483b8e02a971ef31527cd0fc92c"-dependencies = [- "dunce",- "is-wsl",- "libc",- "pathdiff",-]-[[package]]name = "openssl-probe"version = "0.2.1"@@ -2623,16 +2501,6 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"-[[package]]-name = "ordered-multimap"-version = "0.7.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79"-dependencies = [- "dlv-list",- "hashbrown 0.14.5",-]-[[package]]name = "ordered-stream"version = "0.2.0"@@ -2643,16 +2511,6 @@ dependencies = ["pin-project-lite",]-[[package]]-name = "os_pipe"-version = "1.2.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"-dependencies = [- "libc",- "windows-sys 0.61.2",-]-[[package]]name = "osakit"version = "0.3.1"@@ -2721,12 +2579,6 @@ dependencies = ["windows-link 0.2.1",]-[[package]]-name = "pathdiff"-version = "0.2.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"-[[package]]name = "percent-encoding"version = "2.3.2"@@ -3053,17 +2905,6 @@ dependencies = ["bitflags 2.12.1",]-[[package]]-name = "redox_users"-version = "0.4.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"-dependencies = [- "getrandom 0.2.17",- "libredox",- "thiserror 1.0.69",-]-[[package]]name = "redox_users"version = "0.5.2"@@ -3201,16 +3042,6 @@ dependencies = ["windows-sys 0.52.0",]-[[package]]-name = "rust-ini"-version = "0.21.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7"-dependencies = [- "cfg-if",- "ordered-multimap",-]-[[package]]name = "rustc-hash"version = "2.1.2"@@ -3614,44 +3445,12 @@ dependencies = ["digest",]-[[package]]-name = "shared_child"-version = "1.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1e362d9935bc50f019969e2f9ecd66786612daae13e8f277be7bfb66e8bed3f7"-dependencies = [- "libc",- "sigchld",- "windows-sys 0.60.2",-]-[[package]]name = "shlex"version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"-[[package]]-name = "sigchld"-version = "0.2.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1"-dependencies = [- "libc",- "os_pipe",- "signal-hook",-]--[[package]]-name = "signal-hook"-version = "0.3.18"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"-dependencies = [- "libc",- "signal-hook-registry",-]-[[package]]name = "signal-hook-registry"version = "1.4.8"@@ -3944,7 +3743,7 @@ dependencies = ["anyhow","bytes","cookie",- "dirs 6.0.0",+ "dirs","dunce","embed_plist","getrandom 0.3.4",@@ -3995,7 +3794,7 @@ checksum = "4aa1f9055fc23919a54e4e125052bed16ed04aef0487086e758fe01a67b451c7"dependencies = ["anyhow","cargo_toml",- "dirs 6.0.0",+ "dirs","glob","heck 0.5.0","json-patch",@@ -4065,56 +3864,6 @@ dependencies = ["walkdir",]-[[package]]-name = "tauri-plugin-autostart"-version = "2.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "459383cebc193cdd03d1ba4acc40f2c408a7abce419d64bdcd2d745bc2886f70"-dependencies = [- "auto-launch",- "serde",- "serde_json",- "tauri",- "tauri-plugin",- "thiserror 2.0.18",-]--[[package]]-name = "tauri-plugin-biometric"-version = "2.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "306175b744890b5e4aeb8add6aae7debec1b1504c5087bd0310ed7c9c6feae38"-dependencies = [- "log",- "serde",- "serde_json",- "serde_repr",- "tauri",- "tauri-plugin",- "thiserror 2.0.18",-]--[[package]]-name = "tauri-plugin-deep-link"-version = "2.4.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "70ee75bc5627f77bfdf40c913255ebc258117b10ebe2b2239a1a1cf40b0b58aa"-dependencies = [- "dunce",- "plist",- "rust-ini",- "serde",- "serde_json",- "tauri",- "tauri-plugin",- "tauri-utils",- "thiserror 2.0.18",- "tracing",- "url",- "windows-registry",- "windows-result 0.3.4",-]-[[package]]name = "tauri-plugin-dialog"version = "2.7.1"@@ -4157,21 +3906,6 @@ dependencies = ["url",]-[[package]]-name = "tauri-plugin-global-shortcut"-version = "2.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b4dd9f4c5136c09cd962da0c86dc4accd4666db2ea591cf16e6597435843bd2b"-dependencies = [- "global-hotkey",- "log",- "serde",- "serde_json",- "tauri",- "tauri-plugin",- "thiserror 2.0.18",-]-[[package]]name = "tauri-plugin-notification"version = "2.3.3"@@ -4192,33 +3926,19 @@ dependencies = [][[package]]-name = "tauri-plugin-push"-version = "0.1.0"-dependencies = [- "serde",- "tauri",- "tauri-plugin",-]--[[package]]-name = "tauri-plugin-shell"-version = "2.3.5"+name = "tauri-plugin-single-instance"+version = "2.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8457dbf9e2bab1edd8df22bb2c20857a59a9868e79cb3eac5ed639eec4d0c73b"+checksum = "b3214becf9ef5783c0ae99a3bb25adf5353a7a16ebf53e74b909e29205735c6c"dependencies = [- "encoding_rs",- "log",- "open",- "os_pipe",- "regex",- "schemars 0.8.22","serde","serde_json",- "shared_child","tauri",- "tauri-plugin","thiserror 2.0.18","tokio",+ "tracing",+ "windows-sys 0.60.2",+ "zbus",][[package]]@@ -4228,7 +3948,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "806d9dac662c2e4594ff03c647a552f2c9bd544e7d0f683ec58f872f952ce4af"dependencies = ["base64 0.22.1",- "dirs 6.0.0",+ "dirs","flate2","futures-util","http",@@ -4460,15 +4180,6 @@ dependencies = ["time-core",]-[[package]]-name = "tiny-keccak"-version = "2.0.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"-dependencies = [- "crunchy",-]-[[package]]name = "tinystr"version = "0.8.3"@@ -4505,9 +4216,21 @@ dependencies = ["mio","pin-project-lite","socket2",+ "tokio-macros","windows-sys 0.61.2",]+[[package]]+name = "tokio-macros"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6328af13490e73a9b4694030fafd93f8c8c6a9dede33e821c3fc63eddf8042ba"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "tokio-rustls"version = "0.26.4"@@ -4734,7 +4457,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "15edbb0d80583e85ee8df283410038e17314df5cba30da2087a54a85216c0773"dependencies = ["crossbeam-channel",- "dirs 6.0.0",+ "dirs","libappindicator","muda","objc2",@@ -5329,17 +5052,6 @@ dependencies = ["windows-link 0.1.3",]-[[package]]-name = "windows-registry"-version = "0.5.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e"-dependencies = [- "windows-link 0.1.3",- "windows-result 0.3.4",- "windows-strings 0.4.2",-]-[[package]]name = "windows-result"version = "0.3.4"@@ -5649,15 +5361,6 @@ dependencies = ["memchr",]-[[package]]-name = "winreg"-version = "0.10.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"-dependencies = [- "winapi",-]-[[package]]name = "winreg"version = "0.55.0"@@ -5778,7 +5481,7 @@ dependencies = ["block2","cookie","crossbeam-channel",- "dirs 6.0.0",+ "dirs","dom_query","dpi","dunce",@@ -5833,23 +5536,6 @@ dependencies = ["pkg-config",]-[[package]]-name = "x11rb"-version = "0.13.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"-dependencies = [- "gethostname",- "rustix",- "x11rb-protocol",-]--[[package]]-name = "x11rb-protocol"-version = "0.13.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"-[[package]]name = "xattr"version = "1.6.1"@@ -5860,12 +5546,6 @@ dependencies = ["rustix",]-[[package]]-name = "xkeysym"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"-[[package]]name = "yoke"version = "0.8.2"diff --git a/src/desktop/src-tauri/Cargo.toml b/src/desktop/src-tauri/Cargo.tomlindex 3b82035af..bc65b3c5c 100644--- a/src/desktop/src-tauri/Cargo.toml+++ b/src/desktop/src-tauri/Cargo.toml@@ -1,6 +1,3 @@-[workspace]-members = ["plugins/tauri-plugin-push"]-[package]name = "alook-desktop"version = "0.1.7"@@ -16,28 +13,26 @@ tauri-build = { version = "2", features = [] }[dependencies]tauri = { version = "2", features = ["tray-icon", "image-png", "macos-private-api"] }-tauri-plugin-deep-link = "2"-tauri-plugin-notification = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"+[package.metadata.cargo-machete]+ignored = ["serde_json"]+[target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies]-tauri-plugin-shell = "2"-tauri-plugin-autostart = "2"-tauri-plugin-global-shortcut = "2"+tauri-plugin-notification = "2"tauri-plugin-updater = "2"tauri-plugin-dialog = "2"base64 = "0.22"+tokio = { version = "1", features = ["macros"] }+command-group = "5.0.1"+tauri-plugin-single-instance = "2"[target."cfg(target_os = \"macos\")".dependencies]objc2 = "0.6"objc2-foundation = { version = "0.3", features = ["NSGeometry"] }objc2-app-kit = { version = "0.3", features = ["NSView", "NSWindow", "NSColor"] }-[target."cfg(any(target_os = \"android\", target_os = \"ios\"))".dependencies]-tauri-plugin-biometric = "2"-tauri-plugin-push = { path = "plugins/tauri-plugin-push" }-[features]default = ["custom-protocol"]custom-protocol = ["tauri/custom-protocol"]diff --git a/src/desktop/src-tauri/capabilities/default.json b/src/desktop/src-tauri/capabilities/default.jsondeleted file mode 100644index d788e3a73..000000000--- a/src/desktop/src-tauri/capabilities/default.json+++ /dev/null@@ -1,17 +0,0 @@-{- "$schema": "../gen/schemas/desktop-schema.json",- "identifier": "default",- "description": "Default capability for all platforms",- "windows": ["main"],- "remote": {- "urls": ["https://alook.ai", "http://localhost:3000"]- },- "permissions": [- "core:default",- "core:event:default",- "core:window:default",- "core:app:default",- "notification:default",- "deep-link:default"- ]-}diff --git a/src/desktop/src-tauri/capabilities/desktop.json b/src/desktop/src-tauri/capabilities/desktop.jsonindex 75b268e3f..474a9f24e 100644--- a/src/desktop/src-tauri/capabilities/desktop.json+++ b/src/desktop/src-tauri/capabilities/desktop.json@@ -1,22 +1,12 @@{"$schema": "../gen/schemas/desktop-schema.json","identifier": "desktop-capability",- "description": "Desktop-only capabilities",+ "description": "Production custom-command access for the Desktop webview","windows": ["main"],"platforms": ["linux", "macOS", "windows"],+ "local": false,"remote": {- "urls": ["https://alook.ai", "http://localhost:3000"]+ "urls": ["https://alook.ai"]},- "permissions": [- "shell:allow-open",- "global-shortcut:allow-register",- "global-shortcut:allow-unregister",- "autostart:allow-enable",- "autostart:allow-disable",- "autostart:allow-is-enabled",- "core:tray:default",- "core:window:allow-start-dragging",- "updater:default",- "dialog:default"- ]+ "permissions": []}diff --git a/src/desktop/src-tauri/capabilities/mobile.json b/src/desktop/src-tauri/capabilities/mobile.jsondeleted file mode 100644index 54c8a6574..000000000--- a/src/desktop/src-tauri/capabilities/mobile.json+++ /dev/null@@ -1,13 +0,0 @@-{- "$schema": "../gen/schemas/mobile-schema.json",- "identifier": "mobile-capability",- "description": "Mobile-only capabilities",- "windows": ["main"],- "platforms": ["iOS", "android"],- "remote": {- "urls": ["https://app.alook.ai"]- },- "permissions": [- "biometric:default"- ]-}diff --git a/src/desktop/src-tauri/entitlements.plist b/src/desktop/src-tauri/entitlements.plistdeleted file mode 100644index 0bd73fe94..000000000--- a/src/desktop/src-tauri/entitlements.plist+++ /dev/null@@ -1,14 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>com.apple.security.app-sandbox</key>- <false/>- <key>com.apple.security.application-groups</key>- <array>- <string>ai.alook.desktop</string>- </array>- <key>com.apple.security.inherit</key>- <true/>-</dict>-</plist>diff --git a/src/desktop/src-tauri/icons/tray-default.png b/src/desktop/src-tauri/icons/tray-default.pngindex c29886093..061e6e319 100644Binary files a/src/desktop/src-tauri/icons/tray-default.png and b/src/desktop/src-tauri/icons/tray-default.png differdiff --git a/src/desktop/src-tauri/icons/tray-offline.png b/src/desktop/src-tauri/icons/tray-offline.pngindex d29508071..6b75e9bbb 100644Binary files a/src/desktop/src-tauri/icons/tray-offline.png and b/src/desktop/src-tauri/icons/tray-offline.png differdiff --git a/src/desktop/src-tauri/icons/tray-online.png b/src/desktop/src-tauri/icons/tray-online.pngindex c29886093..061e6e319 100644Binary files a/src/desktop/src-tauri/icons/tray-online.png and b/src/desktop/src-tauri/icons/tray-online.png differdiff --git a/src/desktop/src-tauri/plugins/tauri-plugin-push/Cargo.toml b/src/desktop/src-tauri/plugins/tauri-plugin-push/Cargo.tomldeleted file mode 100644index 436aa95fb..000000000--- a/src/desktop/src-tauri/plugins/tauri-plugin-push/Cargo.toml+++ /dev/null@@ -1,13 +0,0 @@-[package]-name = "tauri-plugin-push"-version = "0.1.0"-edition = "2021"-description = "Tauri plugin for push notifications via FCM (Android) and APNs (iOS)"-links = "tauri-plugin-push"--[dependencies]-tauri = "2"-serde = { version = "1", features = ["derive"] }--[build-dependencies]-tauri-plugin = { version = "2", features = ["build"] }diff --git a/src/desktop/src-tauri/plugins/tauri-plugin-push/android/src/main/kotlin/com/alook/push/PushMessagingService.kt b/src/desktop/src-tauri/plugins/tauri-plugin-push/android/src/main/kotlin/com/alook/push/PushMessagingService.ktdeleted file mode 100644index 482108002..000000000--- a/src/desktop/src-tauri/plugins/tauri-plugin-push/android/src/main/kotlin/com/alook/push/PushMessagingService.kt+++ /dev/null@@ -1,20 +0,0 @@-package com.alook.push--import com.google.firebase.messaging.FirebaseMessagingService-import com.google.firebase.messaging.RemoteMessage-import android.util.Log--class PushMessagingService : FirebaseMessagingService() {-- override fun onMessageReceived(remoteMessage: RemoteMessage) {- super.onMessageReceived(remoteMessage)- Log.d("AlookPush", "Message received: ${remoteMessage.data}")- PushPlugin.instance?.onMessageReceived(remoteMessage)- }-- override fun onNewToken(token: String) {- super.onNewToken(token)- Log.d("AlookPush", "New FCM token: $token")- PushPlugin.instance?.onTokenRefresh(token)- }-}diff --git a/src/desktop/src-tauri/plugins/tauri-plugin-push/android/src/main/kotlin/com/alook/push/PushPlugin.kt b/src/desktop/src-tauri/plugins/tauri-plugin-push/android/src/main/kotlin/com/alook/push/PushPlugin.ktdeleted file mode 100644index be6ea6622..000000000--- a/src/desktop/src-tauri/plugins/tauri-plugin-push/android/src/main/kotlin/com/alook/push/PushPlugin.kt+++ /dev/null@@ -1,70 +0,0 @@-package com.alook.push--import android.app.Activity-import app.tauri.annotation.Command-import app.tauri.annotation.TauriPlugin-import app.tauri.plugin.JSObject-import app.tauri.plugin.Plugin-import app.tauri.plugin.Invoke-import com.google.firebase.messaging.FirebaseMessaging-import com.google.firebase.messaging.RemoteMessage--@TauriPlugin-class PushPlugin(private val activity: Activity) : Plugin(activity) {-- private var pushToken: String? = null-- companion object {- var instance: PushPlugin? = null- private set- }-- override fun load(webView: app.tauri.plugin.WebView) {- super.load(webView)- instance = this- FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->- if (task.isSuccessful) {- pushToken = task.result- val event = JSObject()- event.put("token", pushToken)- event.put("platform", "android")- trigger("token", event)- }- }- }-- fun onTokenRefresh(token: String) {- pushToken = token- val event = JSObject()- event.put("token", token)- event.put("platform", "android")- trigger("token", event)- }-- fun onMessageReceived(remoteMessage: RemoteMessage) {- val event = JSObject()- event.put("title", remoteMessage.notification?.title ?: "")- event.put("body", remoteMessage.notification?.body ?: "")- val data = JSObject()- remoteMessage.data.forEach { (key, value) -> data.put(key, value) }- event.put("data", data)- trigger("notification", event)- }-- @Command- fun getToken(invoke: Invoke) {- val result = JSObject()- if (pushToken != null) {- result.put("token", pushToken)- result.put("platform", "android")- invoke.resolve(result)- } else {- invoke.reject("Push token not yet available")- }- }-- @Command- fun onNotification(invoke: Invoke) {- invoke.resolve()- }-}diff --git a/src/desktop/src-tauri/plugins/tauri-plugin-push/build.rs b/src/desktop/src-tauri/plugins/tauri-plugin-push/build.rsdeleted file mode 100644index ccb3ea0e9..000000000--- a/src/desktop/src-tauri/plugins/tauri-plugin-push/build.rs+++ /dev/null@@ -1,5 +0,0 @@-const COMMANDS: &[&str] = &["get_token", "on_notification"];--fn main() {- tauri_plugin::Builder::new(COMMANDS).build();-}diff --git a/src/desktop/src-tauri/plugins/tauri-plugin-push/ios/Sources/PushPlugin.swift b/src/desktop/src-tauri/plugins/tauri-plugin-push/ios/Sources/PushPlugin.swiftdeleted file mode 100644index 47bb45da5..000000000--- a/src/desktop/src-tauri/plugins/tauri-plugin-push/ios/Sources/PushPlugin.swift+++ /dev/null@@ -1,63 +0,0 @@-import UIKit-import UserNotifications-import Tauri-import WebKit--class PushPlugin: Plugin {- private var pushToken: String?-- static var shared: PushPlugin?-- override init() {- super.init()- PushPlugin.shared = self- }-- @objc override func load(webview: WKWebView) {- super.load(webview: webview)- requestPushPermission()- }-- private func requestPushPermission() {- UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in- if granted {- DispatchQueue.main.async {- UIApplication.shared.registerForRemoteNotifications()- }- }- }- }-- func didRegisterForRemoteNotifications(deviceToken: Data) {- let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()- self.pushToken = token- let event: [String: Any] = ["token": token, "platform": "ios"]- self.trigger("token", data: event)- }-- func didReceiveRemoteNotification(userInfo: [AnyHashable: Any]) {- var event: [String: Any] = [:]- if let aps = userInfo["aps"] as? [String: Any],- let alert = aps["alert"] as? [String: Any] {- event["title"] = alert["title"] ?? ""- event["body"] = alert["body"] ?? ""- }- event["data"] = userInfo- self.trigger("notification", data: event)- }-- @objc func getToken(_ invoke: Invoke) {- if let token = pushToken {- invoke.resolve([- "token": token,- "platform": "ios"- ])- } else {- invoke.reject("Push token not yet available")- }- }-- @objc func onNotification(_ invoke: Invoke) {- invoke.resolve()- }-}diff --git a/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/autogenerated/commands/get_token.toml b/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/autogenerated/commands/get_token.tomldeleted file mode 100644index a8ca0a440..000000000--- a/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/autogenerated/commands/get_token.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-get-token"-description = "Enables the get_token command without any pre-configured scope."-commands.allow = ["get_token"]--[[permission]]-identifier = "deny-get-token"-description = "Denies the get_token command without any pre-configured scope."-commands.deny = ["get_token"]diff --git a/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/autogenerated/commands/on_notification.toml b/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/autogenerated/commands/on_notification.tomldeleted file mode 100644index 793fbb51d..000000000--- a/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/autogenerated/commands/on_notification.toml+++ /dev/null@@ -1,13 +0,0 @@-# Automatically generated - DO NOT EDIT!--"$schema" = "../../schemas/schema.json"--[[permission]]-identifier = "allow-on-notification"-description = "Enables the on_notification command without any pre-configured scope."-commands.allow = ["on_notification"]--[[permission]]-identifier = "deny-on-notification"-description = "Denies the on_notification command without any pre-configured scope."-commands.deny = ["on_notification"]diff --git a/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/autogenerated/reference.md b/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/autogenerated/reference.mddeleted file mode 100644index c6200ca7b..000000000--- a/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/autogenerated/reference.md+++ /dev/null@@ -1,61 +0,0 @@-## Permission Table--<table>-<tr>-<th>Identifier</th>-<th>Description</th>-</tr>---<tr>-<td>--`push:allow-get-token`--</td>-<td>--Enables the get_token command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`push:deny-get-token`--</td>-<td>--Denies the get_token command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`push:allow-on-notification`--</td>-<td>--Enables the on_notification command without any pre-configured scope.--</td>-</tr>--<tr>-<td>--`push:deny-on-notification`--</td>-<td>--Denies the on_notification command without any pre-configured scope.--</td>-</tr>-</table>diff --git a/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/schemas/schema.json b/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/schemas/schema.jsondeleted file mode 100644index cc0eb57c2..000000000--- a/src/desktop/src-tauri/plugins/tauri-plugin-push/permissions/schemas/schema.json+++ /dev/null@@ -1,324 +0,0 @@-{- "$schema": "http://json-schema.org/draft-07/schema#",- "title": "PermissionFile",- "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",- "type": "object",- "properties": {- "default": {- "description": "The default permission set for the plugin",- "anyOf": [- {- "$ref": "#/definitions/DefaultPermission"- },- {- "type": "null"- }- ]- },- "set": {- "description": "A list of permissions sets defined",- "type": "array",- "items": {- "$ref": "#/definitions/PermissionSet"- }- },- "permission": {- "description": "A list of inlined permissions",- "default": [],- "type": "array",- "items": {- "$ref": "#/definitions/Permission"- }- }- },- "definitions": {- "DefaultPermission": {- "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",- "type": "object",- "required": [- "permissions"- ],- "properties": {- "version": {- "description": "The version of the permission.",- "type": [- "integer",- "null"- ],- "format": "uint64",- "minimum": 1.0- },- "description": {- "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",- "type": [- "string",- "null"- ]- },- "permissions": {- "description": "All permissions this set contains.",- "type": "array",- "items": {- "type": "string"- }- }- }- },- "PermissionSet": {- "description": "A set of direct permissions grouped together under a new name.",- "type": "object",- "required": [- "description",- "identifier",- "permissions"- ],- "properties": {- "identifier": {- "description": "A unique identifier for the permission.",- "type": "string"- },- "description": {- "description": "Human-readable description of what the permission does.",- "type": "string"- },- "permissions": {- "description": "All permissions this set contains.",- "type": "array",- "items": {- "$ref": "#/definitions/PermissionKind"- }- }- }- },- "Permission": {- "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",- "type": "object",- "required": [- "identifier"- ],- "properties": {- "version": {- "description": "The version of the permission.",- "type": [- "integer",- "null"- ],- "format": "uint64",- "minimum": 1.0- },- "identifier": {- "description": "A unique identifier for the permission.",- "type": "string"- },- "description": {- "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",- "type": [- "string",- "null"- ]- },- "commands": {- "description": "Allowed or denied commands when using this permission.",- "default": {- "allow": [],- "deny": []- },- "allOf": [- {- "$ref": "#/definitions/Commands"- }- ]- },- "scope": {- "description": "Allowed or denied scoped when using this permission.",- "allOf": [- {- "$ref": "#/definitions/Scopes"- }- ]- },- "platforms": {- "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",- "type": [- "array",- "null"- ],- "items": {- "$ref": "#/definitions/Target"- }- }- }- },- "Commands": {- "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",- "type": "object",- "properties": {- "allow": {- "description": "Allowed command.",- "default": [],- "type": "array",- "items": {- "type": "string"- }- },- "deny": {- "description": "Denied command, which takes priority.",- "default": [],- "type": "array",- "items": {- "type": "string"- }- }- }- },- "Scopes": {- "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",- "type": "object",- "properties": {- "allow": {- "description": "Data that defines what is allowed by the scope.",- "type": [- "array",- "null"- ],- "items": {- "$ref": "#/definitions/Value"- }- },- "deny": {- "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",- "type": [- "array",- "null"- ],- "items": {- "$ref": "#/definitions/Value"- }- }- }- },- "Value": {- "description": "All supported ACL values.",- "anyOf": [- {- "description": "Represents a null JSON value.",- "type": "null"- },- {- "description": "Represents a [`bool`].",- "type": "boolean"- },- {- "description": "Represents a valid ACL [`Number`].",- "allOf": [- {- "$ref": "#/definitions/Number"- }- ]- },- {- "description": "Represents a [`String`].",- "type": "string"- },- {- "description": "Represents a list of other [`Value`]s.",- "type": "array",- "items": {- "$ref": "#/definitions/Value"- }- },- {- "description": "Represents a map of [`String`] keys to [`Value`]s.",- "type": "object",- "additionalProperties": {- "$ref": "#/definitions/Value"- }- }- ]- },- "Number": {- "description": "A valid ACL number.",- "anyOf": [- {- "description": "Represents an [`i64`].",- "type": "integer",- "format": "int64"- },- {- "description": "Represents a [`f64`].",- "type": "number",- "format": "double"- }- ]- },- "Target": {- "description": "Platform target.",- "oneOf": [- {- "description": "MacOS.",- "type": "string",- "enum": [- "macOS"- ]- },- {- "description": "Windows.",- "type": "string",- "enum": [- "windows"- ]- },- {- "description": "Linux.",- "type": "string",- "enum": [- "linux"- ]- },- {- "description": "Android.",- "type": "string",- "enum": [- "android"- ]- },- {- "description": "iOS.",- "type": "string",- "enum": [- "iOS"- ]- }- ]- },- "PermissionKind": {- "type": "string",- "oneOf": [- {- "description": "Enables the get_token command without any pre-configured scope.",- "type": "string",- "const": "allow-get-token",- "markdownDescription": "Enables the get_token command without any pre-configured scope."- },- {- "description": "Denies the get_token command without any pre-configured scope.",- "type": "string",- "const": "deny-get-token",- "markdownDescription": "Denies the get_token command without any pre-configured scope."- },- {- "description": "Enables the on_notification command without any pre-configured scope.",- "type": "string",- "const": "allow-on-notification",- "markdownDescription": "Enables the on_notification command without any pre-configured scope."- },- {- "description": "Denies the on_notification command without any pre-configured scope.",- "type": "string",- "const": "deny-on-notification",- "markdownDescription": "Denies the on_notification command without any pre-configured scope."- }- ]- }- }-}\ No newline at end of filediff --git a/src/desktop/src-tauri/plugins/tauri-plugin-push/src/commands.rs b/src/desktop/src-tauri/plugins/tauri-plugin-push/src/commands.rsdeleted file mode 100644index b4f3fde40..000000000--- a/src/desktop/src-tauri/plugins/tauri-plugin-push/src/commands.rs+++ /dev/null@@ -1,23 +0,0 @@-use serde::Serialize;-use tauri::command;--#[derive(Serialize)]-pub struct PushToken {- pub token: String,- pub platform: String,-}--#[command]-pub async fn get_token() -> Result<PushToken, String> {- // On mobile, the native layer (Kotlin/Swift) registers for push and- // provides the token via the plugin bridge. This is a placeholder that- // returns the cached token from the native side.- Err("Push token not available on this platform".to_string())-}--#[command]-pub async fn on_notification() -> Result<(), String> {- // Notification handling is done via event listeners on the native side.- // This command exists as a placeholder for the JS API surface.- Ok(())-}diff --git a/src/desktop/src-tauri/plugins/tauri-plugin-push/src/lib.rs b/src/desktop/src-tauri/plugins/tauri-plugin-push/src/lib.rsdeleted file mode 100644index 49f41cf77..000000000--- a/src/desktop/src-tauri/plugins/tauri-plugin-push/src/lib.rs+++ /dev/null@@ -1,15 +0,0 @@-use tauri::{- plugin::{Builder, TauriPlugin},- Runtime,-};--mod commands;--pub fn init<R: Runtime>() -> TauriPlugin<R> {- Builder::new("push")- .invoke_handler(tauri::generate_handler![- commands::get_token,- commands::on_notification,- ])- .build()-}diff --git a/src/desktop/src-tauri/src/commands.rs b/src/desktop/src-tauri/src/commands.rsindex ce6306eae..14837c9dd 100644--- a/src/desktop/src-tauri/src/commands.rs+++ b/src/desktop/src-tauri/src/commands.rs@@ -1,8 +1,7 @@+#[cfg(desktop)]use serde::Serialize;-use tauri::{AppHandle, Manager};-#[cfg(desktop)]-use tauri_plugin_shell::ShellExt;+use tauri::{AppHandle, Manager};#[cfg(desktop)]use tauri_plugin_notification::NotificationExt;@@ -10,123 +9,338 @@ use tauri_plugin_notification::NotificationExt;#[cfg(desktop)]use std::path::PathBuf;+#[cfg(desktop)]+use std::{+ io::Read,+ process::{Command, Stdio},+ time::{Duration, Instant},+};++#[cfg(desktop)]+use command_group::CommandGroup;+#[cfg(desktop)]use std::sync::atomic::{AtomicBool, Ordering};+#[cfg(desktop)]+const PATH_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(2);-#[derive(Serialize)]-pub struct DaemonStatusResult {- pub running: bool,- pub pid: Option<u32>,- pub version: Option<String>,-}+#[cfg(desktop)]+const RUNTIME_PROBE_TIMEOUT: Duration = Duration::from_secs(5);++#[cfg(desktop)]+const DAEMON_PAIR_TIMEOUT: Duration = Duration::from_secs(60);++#[cfg(desktop)]+const UPDATE_CHECK_TIMEOUT: Duration = Duration::from_secs(15);++#[cfg(desktop)]+const UPDATE_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(10 * 60);#[derive(Serialize)]+#[cfg(desktop)]pub struct CommandResult {pub success: bool,pub message: String,}-#[derive(Serialize)]-pub struct CliInfo {- pub command: String,- pub is_dev: bool,+#[derive(Clone, Debug, Serialize, PartialEq, Eq)]+#[cfg(desktop)]+#[serde(rename_all = "camelCase")]+pub struct DaemonRuntimeCapability {+ pub available: bool,+ pub reason: Option<String>,+ pub node_version: Option<String>,}+#[derive(Clone, Debug, PartialEq, Eq)]#[cfg(desktop)]-struct CliConfig {+struct DaemonConfig {command: &'static str,base_args: &'static [&'static str],- env: Vec<(&'static str, &'static str)>,cwd: Option<PathBuf>,}#[cfg(desktop)]-fn resolve_path() -> String {- use std::sync::OnceLock;- static CACHED: OnceLock<String> = OnceLock::new();- CACHED.get_or_init(|| {- let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());- if let Ok(output) = std::process::Command::new(&shell)- .args(["-ilc", "echo $PATH"])- .output()- {- let shell_path = String::from_utf8_lossy(&output.stdout).trim().to_string();- if !shell_path.is_empty() {- return shell_path;- }- }- std::env::var("PATH").unwrap_or_default()- }).clone()+fn daemon_config() -> DaemonConfig {+ daemon_config_for(cfg!(debug_assertions))}#[cfg(desktop)]-fn cli_config() -> CliConfig {- if cfg!(debug_assertions) {+fn daemon_config_for(is_debug: bool) -> DaemonConfig {+ if is_debug {let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));let monorepo_root = manifest_dir.parent().and_then(|p| p.parent()).and_then(|p| p.parent()).map(|p| p.to_path_buf());- CliConfig {+ DaemonConfig {command: "pnpm",- base_args: &["dev:cli"],- env: vec![],+ base_args: &[],cwd: monorepo_root,}} else {- CliConfig {+ DaemonConfig {command: "npx",- base_args: &["@alook/cli"],- env: vec![],+ base_args: &["--yes", "@alook/daemon"],cwd: None,}}}#[cfg(desktop)]-struct CliOutput {+fn executable_for_platform(command: &str, is_windows: bool) -> String {+ if is_windows && matches!(command, "npm" | "npx" | "pnpm") {+ format!("{command}.cmd")+ } else {+ command.to_string()+ }+}++#[cfg(desktop)]+fn executable(command: &str) -> String {+ executable_for_platform(command, cfg!(windows))+}++#[cfg(desktop)]+fn daemon_endpoints_for(is_debug: bool) -> (&'static str, &'static str) {+ if is_debug {+ ("http://localhost:3000", "ws://localhost:8789")+ } else {+ ("https://alook.ai", "wss://alook.ai/api/ws/community-daemon")+ }+}++#[cfg(desktop)]+#[derive(Debug)]+struct DaemonOutput {success: bool,stdout: String,stderr: String,}#[cfg(desktop)]-async fn run_cli(app: &AppHandle, extra_args: &[&str]) -> Result<CliOutput, String> {- let cfg = cli_config();- let mut args: Vec<&str> = cfg.base_args.to_vec();- args.extend_from_slice(extra_args);+fn read_process_pipe<R: Read + Send + 'static>(mut pipe: R) -> std::thread::JoinHandle<Vec<u8>> {+ std::thread::spawn(move || {+ let mut bytes = Vec::new();+ let _ = pipe.read_to_end(&mut bytes);+ bytes+ })+}++#[cfg(desktop)]+fn run_process_with_timeout(+ mut command: Command,+ timeout: Duration,+ timeout_message: String,+) -> Result<DaemonOutput, String> {+ command.stdout(Stdio::piped()).stderr(Stdio::piped());+ let mut child = command.group_spawn().map_err(|error| error.to_string())?;+ let stdout = child+ .inner()+ .stdout+ .take()+ .map(read_process_pipe)+ .ok_or("failed to capture process stdout")?;+ let stderr = child+ .inner()+ .stderr+ .take()+ .map(read_process_pipe)+ .ok_or("failed to capture process stderr")?;+ let deadline = Instant::now() + timeout;++ let mut status = None;+ loop {+ if status.is_none() {+ status = child.try_wait().map_err(|error| error.to_string())?;+ }+ if status.is_some() && stdout.is_finished() && stderr.is_finished() {+ break;+ }+ if Instant::now() >= deadline {+ let _ = child.kill();+ let _ = child.wait();+ let _ = stdout.join();+ let _ = stderr.join();+ return Err(timeout_message);+ }+ std::thread::sleep(Duration::from_millis(20));+ }++ let stdout = stdout.join().map_err(|_| "stdout reader failed")?;+ let stderr = stderr.join().map_err(|_| "stderr reader failed")?;+ Ok(DaemonOutput {+ success: status.is_some_and(|status| status.success()),+ stdout: String::from_utf8_lossy(&stdout).trim().to_string(),+ stderr: String::from_utf8_lossy(&stderr).trim().to_string(),+ })+}++#[cfg(desktop)]+async fn run_process(+ command: Command,+ timeout: Duration,+ timeout_message: String,+) -> Result<DaemonOutput, String> {+ tauri::async_runtime::spawn_blocking(move || {+ run_process_with_timeout(command, timeout, timeout_message)+ })+ .await+ .map_err(|error| error.to_string())?+}- let mut cmd = app.shell().command(cfg.command);- cmd = cmd.env("PATH", resolve_path());- for (key, val) in &cfg.env {- cmd = cmd.env(key, val);+#[cfg(desktop)]+fn parse_shell_path(stdout: &str) -> Option<String> {+ let value = stdout.trim();+ if value.is_empty() || value.lines().count() != 1 {+ return None;+ }+ let paths: Vec<PathBuf> = std::env::split_paths(value).collect();+ if paths.is_empty() || paths.iter().any(|path| !path.is_absolute()) {+ return None;}+ Some(value.to_string())+}++#[cfg(desktop)]+async fn resolve_path() -> String {+ let fallback = std::env::var("PATH").unwrap_or_default();+ let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());+ let mut command = Command::new(shell);+ command.args(["-ilc", "printf '%s\\n' \"$PATH\""]);+ match run_process(+ command,+ PATH_DISCOVERY_TIMEOUT,+ "login shell PATH lookup timed out".to_string(),+ )+ .await+ {+ Ok(output) if output.success => parse_shell_path(&output.stdout).unwrap_or(fallback),+ _ => fallback,+ }+}++#[cfg(desktop)]+async fn run_daemon(extra_args: &[String]) -> Result<DaemonOutput, String> {+ let cfg = daemon_config();+ let mut args: Vec<String> = cfg.base_args.iter().map(|arg| (*arg).to_string()).collect();+ args.extend_from_slice(extra_args);++ let mut command = Command::new(executable(cfg.command));+ command.env("PATH", resolve_path().await);if let Some(cwd) = &cfg.cwd {- cmd = cmd.current_dir(cwd.clone());+ command.current_dir(cwd);}- let output = cmd.args(&args).output().await.map_err(|e| e.to_string())?;+ command.args(&args);+ run_process(+ command,+ DAEMON_PAIR_TIMEOUT,+ "The daemon didn't start within 60 seconds. Check your network and try again.".to_string(),+ )+ .await+}- Ok(CliOutput {- success: output.status.success(),- stdout: String::from_utf8_lossy(&output.stdout).to_string(),- stderr: String::from_utf8_lossy(&output.stderr).to_string(),- })+#[cfg(desktop)]+fn valid_machine_key(machine_key: &str) -> bool {+ let value = machine_key+ .strip_prefix("cmt_")+ .or_else(|| machine_key.strip_prefix("cmk_"));+ let Some(value) = value else {+ return false;+ };+ value.len() == 32+ && value+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')+}++#[cfg(desktop)]+fn daemon_pair_args(machine_key: &str, is_debug: bool) -> Result<Vec<String>, String> {+ if !valid_machine_key(machine_key) {+ return Err("invalid Community machine key".to_string());+ }+ let (server_url, ws_url) = daemon_endpoints_for(is_debug);+ Ok(vec![+ "daemon".to_string(),+ "start".to_string(),+ "--machine-key".to_string(),+ machine_key.to_string(),+ "--server-url".to_string(),+ server_url.to_string(),+ "--ws-url".to_string(),+ ws_url.to_string(),+ ])+}++#[cfg(desktop)]+fn evaluate_runtime_capability(+ node: Result<String, String>,+ npm: Result<String, String>,+ npx: Result<String, String>,+) -> DaemonRuntimeCapability {+ let node_output = match node {+ Ok(output) => output,+ Err(reason) => {+ return DaemonRuntimeCapability {+ available: false,+ reason: Some(format!("Node.js is required: {reason}.")),+ node_version: None,+ };+ }+ };+ for result in [npm, npx] {+ if let Err(reason) = result {+ return DaemonRuntimeCapability {+ available: false,+ reason: Some(format!(+ "Node.js is available, but {reason}. Install npm with Node.js and try again."+ )),+ node_version: (!node_output.is_empty()).then_some(node_output),+ };+ }+ }+ DaemonRuntimeCapability {+ available: true,+ reason: None,+ node_version: (!node_output.is_empty()).then_some(node_output),+ }}#[cfg(desktop)]-fn to_command_result(output: CliOutput) -> CommandResult {- CommandResult {- success: output.success,- message: if output.success {- output.stdout- } else if output.stderr.trim().is_empty() {- output.stdout+fn daemon_failure_message(stdout: &str, stderr: &str) -> String {+ let detail = if !stderr.trim().is_empty() {+ stderr.trim()+ } else if !stdout.trim().is_empty() {+ stdout.trim()+ } else {+ "The daemon process exited before it reported a reason."+ };+ format!("The daemon couldn't start: {detail}")+}++#[cfg(desktop)]+async fn probe_runtime_command(command: &'static str, path: String) -> Result<String, String> {+ let mut process = Command::new(executable(command));+ process.env("PATH", path).arg("--version");+ let output = run_process(+ process,+ RUNTIME_PROBE_TIMEOUT,+ format!("{command} did not respond within 5 seconds"),+ )+ .await+ .map_err(|error| {+ if error.contains("did not respond") {+ error} else {- output.stderr- },+ format!("{command} was not found")+ }+ })?;+ if !output.success {+ return Err(format!("{command} could not run"));}+ Ok(output.stdout)}// --- Splashscreen ---@@ -134,15 +348,25 @@ fn to_command_result(output: CliOutput) -> CommandResult {#[cfg(desktop)]static SPLASH_CLOSED: AtomicBool = AtomicBool::new(false);-#[cfg(desktop)]-static SPLASH_DAEMON_READY: AtomicBool = AtomicBool::new(false);-#[cfg(desktop)]static SPLASH_FRONTEND_READY: AtomicBool = AtomicBool::new(false);#[cfg(desktop)]static SPLASH_MIN_ELAPSED: AtomicBool = AtomicBool::new(false);+#[cfg(desktop)]+static SPLASH_MAX_WAIT_ELAPSED: AtomicBool = AtomicBool::new(false);++#[cfg(desktop)]+pub fn should_hide_on_close(window_label: &str) -> bool {+ window_label == "main"+}++#[cfg(desktop)]+fn should_close_splash(frontend_ready: bool, min_elapsed: bool, max_wait_elapsed: bool) -> bool {+ max_wait_elapsed || (frontend_ready && min_elapsed)+}+#[cfg(desktop)]pub fn splash_html() -> String {use base64::Engine;@@ -171,17 +395,21 @@ pub fn splash_html() -> String {pub fn create_splash_window(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {use tauri::{WebviewUrl, WebviewWindowBuilder};- WebviewWindowBuilder::new(app, "splash", WebviewUrl::CustomProtocol("splash://index".parse()?))- .title("Alook")- .inner_size(200.0, 200.0)- .center()- .decorations(false)- .resizable(false)- .transparent(true)- .shadow(false)- .always_on_top(true)- .skip_taskbar(true)- .build()?;+ WebviewWindowBuilder::new(+ app,+ "splash",+ WebviewUrl::CustomProtocol("splash://index".parse()?),+ )+ .title("Alook")+ .inner_size(200.0, 200.0)+ .center()+ .decorations(false)+ .resizable(false)+ .transparent(true)+ .shadow(false)+ .always_on_top(true)+ .skip_taskbar(true)+ .build()?;Ok(())}@@ -191,48 +419,24 @@ fn do_close_splashscreen(handle: &AppHandle) {if SPLASH_CLOSED.swap(true, Ordering::SeqCst) {return;}- if let Some(main) = handle.get_webview_window("main") {- let _ = main.show();- let _ = main.set_focus();- }- let h = handle.clone();- std::thread::spawn(move || {- fade_out_and_close_splash(&h);- });-}--#[cfg(desktop)]-fn fade_out_and_close_splash(handle: &AppHandle) {- let Some(splash) = handle.get_webview_window("splash") else { return };-- #[cfg(target_os = "macos")]- {- use objc2::runtime::AnyObject;- use objc2::msg_send;- unsafe {- let ns_window = splash.ns_window().unwrap() as *mut AnyObject;- for i in (0..=5).rev() {- let alpha = i as f64 / 5.0;- let _: () = msg_send![ns_window, setAlphaValue: alpha];- std::thread::sleep(std::time::Duration::from_millis(40));- }+ let app = handle.clone();+ let _ = handle.run_on_main_thread(move || {+ if let Some(main) = app.get_webview_window("main") {+ let _ = main.show();+ let _ = main.set_focus();}- }-- #[cfg(not(target_os = "macos"))]- {- std::thread::sleep(std::time::Duration::from_millis(200));- }-- let _ = splash.close();+ if let Some(splash) = app.get_webview_window("splash") {+ let _ = splash.close();+ }+ });}#[cfg(desktop)]fn try_close_splashscreen(handle: &AppHandle) {- let daemon = SPLASH_DAEMON_READY.load(Ordering::SeqCst);let frontend = SPLASH_FRONTEND_READY.load(Ordering::SeqCst);let min = SPLASH_MIN_ELAPSED.load(Ordering::SeqCst);- if daemon && frontend && min {+ let max = SPLASH_MAX_WAIT_ELAPSED.load(Ordering::SeqCst);+ if should_close_splash(frontend, min, max) {do_close_splashscreen(handle);}}@@ -244,28 +448,11 @@ pub fn mark_splash_min_elapsed(handle: &AppHandle) {}#[cfg(desktop)]-pub fn mark_daemon_ready(handle: &AppHandle) {- SPLASH_DAEMON_READY.store(true, Ordering::SeqCst);+pub fn mark_splash_max_wait_elapsed(handle: &AppHandle) {+ SPLASH_MAX_WAIT_ELAPSED.store(true, Ordering::SeqCst);try_close_splashscreen(handle);}-#[cfg(desktop)]-pub fn fatal_exit(handle: &AppHandle, msg: &str) {- use tauri_plugin_dialog::{DialogExt, MessageDialogButtons};- // Close splash if still showing- if let Some(splash) = handle.get_webview_window("splash") {- let _ = splash.close();- }- let h = handle.clone();- handle.dialog()- .message(msg)- .title("Alook — Fatal Error")- .buttons(MessageDialogButtons::OkCustom("Quit".into()))- .show(move |_| {- h.exit(1);- });-}-#[cfg(desktop)]#[tauri::command]pub fn close_splashscreen(app: AppHandle) {@@ -273,190 +460,60 @@ pub fn close_splashscreen(app: AppHandle) {try_close_splashscreen(&app);}-// --- CLI commands -----#[cfg(desktop)]-#[tauri::command]-pub fn get_cli_info() -> CliInfo {- let cfg = cli_config();- CliInfo {- command: format!("{} {}", cfg.command, cfg.base_args.join(" ")),- is_dev: cfg!(debug_assertions),- }-}--#[cfg(desktop)]-#[tauri::command]-pub async fn register_cli(app: AppHandle, token: String) -> Result<CommandResult, String> {- let cfg = cli_config();- let mut args: Vec<&str> = cfg.base_args.to_vec();- args.extend_from_slice(&["register", "--token"]);- let token_ref: &str = &token;-- let mut cmd = app.shell().command(cfg.command);- cmd = cmd.env("PATH", resolve_path());- for (key, val) in &cfg.env {- cmd = cmd.env(key, val);- }- if let Some(cwd) = &cfg.cwd {- cmd = cmd.current_dir(cwd.clone());- }- let output = cmd- .args(&args)- .arg(token_ref)- .output()- .await- .map_err(|e| e.to_string())?;-- let cli_output = CliOutput {- success: output.status.success(),- stdout: String::from_utf8_lossy(&output.stdout).to_string(),- stderr: String::from_utf8_lossy(&output.stderr).to_string(),- };- Ok(to_command_result(cli_output))-}--#[cfg(desktop)]-#[tauri::command]-pub async fn daemon_start(app: AppHandle) -> Result<CommandResult, String> {- let output = run_cli(&app, &["daemon", "start"]).await?;- Ok(to_command_result(output))-}+// --- Daemon commands ---#[cfg(desktop)]#[tauri::command]-pub async fn daemon_stop(app: AppHandle) -> Result<CommandResult, String> {- let output = run_cli(&app, &["daemon", "stop"]).await?;- Ok(to_command_result(output))+pub async fn daemon_runtime_capability() -> DaemonRuntimeCapability {+ let path = resolve_path().await;+ let (node, npm, npx) = tokio::join!(+ probe_runtime_command("node", path.clone()),+ probe_runtime_command("npm", path.clone()),+ probe_runtime_command("npx", path),+ );+ evaluate_runtime_capability(node, npm, npx)}#[cfg(desktop)]#[tauri::command]-pub async fn daemon_status(app: AppHandle) -> Result<DaemonStatusResult, String> {- let output = run_cli(&app, &["daemon", "status"]).await?;- Ok(parse_daemon_status(&output.stdout))-}--#[cfg(desktop)]-#[tauri::command]-pub async fn cli_update(app: AppHandle) -> Result<CommandResult, String> {- if cfg!(debug_assertions) {- return Ok(CommandResult {+pub async fn daemon_pair(machine_key: String) -> Result<CommandResult, String> {+ let args = daemon_pair_args(&machine_key, cfg!(debug_assertions))?;+ let output = run_daemon(&args).await?;+ if output.success {+ Ok(CommandResult {success: true,- message: "CLI update skipped in dev mode".to_string(),- });+ message: "Daemon paired and started".to_string(),+ })+ } else {+ Ok(CommandResult {+ success: false,+ message: daemon_failure_message(&output.stdout, &output.stderr),+ })}-- let mut stop_cmd = app.shell().command("npx");- stop_cmd = stop_cmd.env("PATH", resolve_path());- let _ = stop_cmd- .args(["--yes", "@alook/cli", "daemon", "stop"])- .output()- .await;-- let mut start_cmd = app.shell().command("npx");- start_cmd = start_cmd.env("PATH", resolve_path());- let start_output = start_cmd- .args(["--yes", "@alook/cli@latest", "daemon", "start"])- .output()- .await- .map_err(|e| e.to_string())?;-- Ok(CommandResult {- success: start_output.status.success(),- message: if start_output.status.success() {- "CLI updated and daemon restarted".to_string()- } else {- String::from_utf8_lossy(&start_output.stderr).to_string()- },- })-}--#[cfg(desktop)]-#[tauri::command]-pub async fn cli_check(app: AppHandle) -> Result<CommandResult, String> {- let output = run_cli(&app, &["--version"]).await?;- Ok(CommandResult {- success: output.success,- message: output.stdout.trim().to_string(),- })}// --- App updater ---#[derive(Serialize, Clone)]-pub struct UpdateInfo {- pub available: bool,- pub version: Option<String>,- pub notes: Option<String>,-}--#[derive(Serialize, Clone)]+#[cfg(desktop)]struct UpdateProgress {percent: f64,downloaded: u64,total: Option<u64>,}-#[cfg(desktop)]-#[tauri::command]-pub async fn check_for_updates(app: AppHandle) -> Result<UpdateInfo, String> {- use tauri_plugin_updater::UpdaterExt;- let updater = app.updater().map_err(|e| e.to_string())?;- match updater.check().await {- Ok(Some(update)) => Ok(UpdateInfo {- available: true,- version: Some(update.version.clone()),- notes: update.body.clone(),- }),- Ok(None) => Ok(UpdateInfo {- available: false,- version: None,- notes: None,- }),- Err(e) => Err(e.to_string()),- }-}--#[cfg(desktop)]-#[tauri::command]-pub async fn install_update(app: AppHandle) -> Result<(), String> {- use tauri_plugin_updater::UpdaterExt;- use tauri::Emitter;-- let updater = app.updater().map_err(|e| e.to_string())?;- let update = updater.check().await.map_err(|e| e.to_string())?- .ok_or("No update available".to_string())?;-- let handle = app.clone();- let mut cumulative: u64 = 0;- update.download_and_install(- move |chunk_size, total| {- cumulative += chunk_size as u64;- let percent = total.map(|t| (cumulative as f64 / t as f64) * 100.0).unwrap_or(0.0);- let _ = handle.emit("update://progress", UpdateProgress {- percent,- downloaded: cumulative,- total,- });- },- || {},- ).await.map_err(|e| e.to_string())?;-- app.restart();-}-#[cfg(desktop)]#[tauri::command]pub fn set_window_theme(window: tauri::WebviewWindow, dark: bool) {let _ = (&window, dark);#[cfg(target_os = "macos")]{- use objc2::runtime::AnyObject;use objc2::msg_send;+ use objc2::runtime::AnyObject;- unsafe {- let ns_window = window.ns_window().unwrap() as *mut AnyObject;+ let target = window.clone();+ let _ = window.run_on_main_thread(move || unsafe {+ let ns_window = target.ns_window().unwrap() as *mut AnyObject;let (r, g, b) = if dark {(0.063f64, 0.051f64, 0.039f64)} else {@@ -470,78 +527,47 @@ pub fn set_window_theme(window: tauri::WebviewWindow, dark: bool) {alpha: 1.0f64];let _: () = msg_send![ns_window, setBackgroundColor: color];- }+ });}}#[cfg(desktop)]-#[tauri::command]-pub fn is_daemon_online() -> bool {- DAEMON_ONLINE.load(Ordering::Relaxed)-}--// --- Daemon state -----#[cfg(desktop)]-pub static DAEMON_ONLINE: AtomicBool = AtomicBool::new(false);-+static UPDATE_AVAILABLE_VERSION: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);#[cfg(desktop)]-static QUIT_BEHAVIOR: std::sync::Mutex<Option<QuitBehavior>> = std::sync::Mutex::new(None);+static UPDATE_IN_PROGRESS: AtomicBool = AtomicBool::new(false);#[cfg(desktop)]-#[derive(Clone, Copy, PartialEq)]-enum QuitBehavior {- KeepRunning,- StopDaemon,+struct UpdateInProgressGuard<'a> {+ flag: &'a AtomicBool,}#[cfg(desktop)]-fn load_quit_behavior(handle: &AppHandle) -> Option<QuitBehavior> {- let path = handle.path().app_config_dir().ok()?.join("quit-behavior.json");- let content = std::fs::read_to_string(path).ok()?;- let val: serde_json::Value = serde_json::from_str(&content).ok()?;- match val["quit_behavior"].as_str()? {- "keep_running" => Some(QuitBehavior::KeepRunning),- "stop_daemon" => Some(QuitBehavior::StopDaemon),- _ => None,+impl<'a> UpdateInProgressGuard<'a> {+ fn acquire(flag: &'a AtomicBool) -> Option<Self> {+ flag.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)+ .ok()+ .map(|_| Self { flag })}}#[cfg(desktop)]-fn save_quit_behavior(handle: &AppHandle, behavior: QuitBehavior) {- if let Ok(dir) = handle.path().app_config_dir() {- let _ = std::fs::create_dir_all(&dir);- let val = match behavior {- QuitBehavior::KeepRunning => "keep_running",- QuitBehavior::StopDaemon => "stop_daemon",- };- let json = format!(r#"{{"quit_behavior":"{}"}}"#, val);- let _ = std::fs::write(dir.join("quit-behavior.json"), json);+impl Drop for UpdateInProgressGuard<'_> {+ fn drop(&mut self) {+ self.flag.store(false, Ordering::SeqCst);}- *QUIT_BEHAVIOR.lock().unwrap_or_else(|e| e.into_inner()) = Some(behavior);}#[cfg(desktop)]-fn get_quit_behavior(handle: &AppHandle) -> Option<QuitBehavior> {- let guard = QUIT_BEHAVIOR.lock().unwrap_or_else(|e| e.into_inner());- if guard.is_some() {- return *guard;+pub fn show_main_window(app: &AppHandle) {+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.show();+ let _ = window.unminimize();+ let _ = window.set_focus();}- drop(guard);- let loaded = load_quit_behavior(handle);- *QUIT_BEHAVIOR.lock().unwrap_or_else(|e| e.into_inner()) = loaded;- loaded}-#[cfg(desktop)]-static UPDATE_AVAILABLE_VERSION: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);--#[cfg(desktop)]-static UPDATE_IN_PROGRESS: AtomicBool = AtomicBool::new(false);-// --- System tray ----#[cfg(desktop)]pub fn setup_tray(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {use tauri::{@@ -550,15 +576,12 @@ pub fn setup_tray(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {tray::TrayIconBuilder,};- use tauri::menu::CheckMenuItemBuilder;-- let show = MenuItemBuilder::with_id("show", "Show").build(app)?;- let version = MenuItemBuilder::with_id("version", format!("Version {}", app.package_info().version)).enabled(false).build(app)?;- let update_item = MenuItemBuilder::with_id("update", "Check for Updates").build(app)?;- let stop_on_quit_checked = get_quit_behavior(app.handle()) == Some(QuitBehavior::StopDaemon);- let stop_on_quit = CheckMenuItemBuilder::with_id("stop_on_quit", "Stop daemon on quit")- .checked(stop_on_quit_checked)- .build(app)?;+ let show = MenuItemBuilder::with_id("show", "Open Alook").build(app)?;+ let version =+ MenuItemBuilder::with_id("version", format!("Version {}", app.package_info().version))+ .enabled(false)+ .build(app)?;+ let update_item = MenuItemBuilder::with_id("update", "Check for Alook Updates…").build(app)?;let quit = MenuItemBuilder::with_id("quit", "Quit").build(app)?;let menu = MenuBuilder::new(app)@@ -566,182 +589,71 @@ pub fn setup_tray(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {.separator().item(&version).item(&update_item)- .item(&stop_on_quit).separator().item(&quit).build()?;- let tray = TrayIconBuilder::new()- .icon(Image::from_bytes(include_bytes!("../icons/tray-default.png"))- .expect("tray icon"))+ let _tray = TrayIconBuilder::new()+ .icon(Image::from_bytes(include_bytes!("../icons/tray-default.png")).expect("tray icon")).icon_as_template(true).menu(&menu).show_menu_on_left_click(false).tooltip("Alook").on_menu_event(move |app, event| match event.id().as_ref() {- "show" => {- if let Some(window) = app.get_webview_window("main") {- let _ = window.show();- let _ = window.unminimize();- let _ = window.set_focus();- }- }+ "show" => show_main_window(app),"update" => {let handle = app.clone();tauri::async_runtime::spawn(async move {do_install_update(&handle).await;});}- "stop_on_quit" => {- let current = get_quit_behavior(app) == Some(QuitBehavior::StopDaemon);- let new_behavior = if current { QuitBehavior::KeepRunning } else { QuitBehavior::StopDaemon };- save_quit_behavior(app, new_behavior);- }"quit" => {- let handle = app.clone();- quit_with_daemon_prompt(&handle);+ app.exit(0);}_ => {}}).on_tray_icon_event(|tray, event| {if let tauri::tray::TrayIconEvent::Click {- button: tauri::tray::MouseButton::Left, ..- } = event {- if let Some(window) = tray.app_handle().get_webview_window("main") {- let _ = window.show();- let _ = window.unminimize();- let _ = window.set_focus();- }+ button: tauri::tray::MouseButton::Left,+ button_state: tauri::tray::MouseButtonState::Up,+ ..+ } = event+ {+ show_main_window(tray.app_handle());}}).build(app)?;- let handle = app.handle().clone();- std::thread::spawn(move || {- let mut restart_attempts: u32 = 0;- loop {- std::thread::sleep(std::time::Duration::from_secs(15));- let h = handle.clone();- let online = tauri::async_runtime::block_on(check_daemon_online(&h));- DAEMON_ONLINE.store(online, Ordering::Relaxed);-- if !online {- // Try to restart daemon- let h2 = handle.clone();- let started = tauri::async_runtime::block_on(async {- match run_cli(&h2, &["daemon", "start"]).await {- Ok(output) if output.success => true,- Ok(output) => {- if restart_attempts == 0 {- let msg = if output.stderr.trim().is_empty() {- "Daemon stopped unexpectedly. Failed to restart.".to_string()- } else {- format!("Daemon stopped unexpectedly: {}", output.stderr.trim())- };- let _ = h2.notification()- .builder()- .title("Alook")- .body(&msg)- .show();- }- false- }- Err(e) => {- if restart_attempts == 0 {- let _ = h2.notification()- .builder()- .title("Alook")- .body(&format!("Could not restart daemon: {}", e))- .show();- }- false- }- }- });- if started {- restart_attempts = 0;- DAEMON_ONLINE.store(true, Ordering::Relaxed);- } else {- restart_attempts += 1;- }- } else {- restart_attempts = 0;- }-- let icon_bytes: &[u8] = if DAEMON_ONLINE.load(Ordering::Relaxed) {- include_bytes!("../icons/tray-online.png")- } else {- include_bytes!("../icons/tray-offline.png")- };- if let Ok(img) = tauri::image::Image::from_bytes(icon_bytes) {- let _ = tray.set_icon(Some(img));- let _ = tray.set_icon_as_template(true);- }- }- });-Ok(())}-// --- Quit with daemon prompt -----#[cfg(desktop)]-pub fn quit_with_daemon_prompt(handle: &AppHandle) {- use tauri_plugin_dialog::{DialogExt, MessageDialogButtons};-- if !DAEMON_ONLINE.load(Ordering::Relaxed) {- handle.exit(0);- return;- }-- let will_stop = get_quit_behavior(handle) == Some(QuitBehavior::StopDaemon);- let msg = if will_stop {- "The daemon will be stopped after quitting.\n\nYou can change this in the tray menu → \"Stop daemon on quit\"."- } else {- "The daemon will keep running in the background.\n\nYou can change this in the tray menu → \"Stop daemon on quit\"."- };-- let h = handle.clone();- handle.dialog()- .message(msg)- .title("Quit Alook")- .buttons(MessageDialogButtons::OkCancelCustom("Quit".into(), "Cancel".into()))- .show(move |confirmed| {- if !confirmed { return; }- if will_stop {- tauri::async_runtime::spawn(async move {- let _ = run_cli(&h, &["daemon", "stop"]).await;- h.exit(0);- });- } else {- h.exit(0);- }- });-}-// --- Update flow ---#[cfg(desktop)]async fn do_install_update(handle: &AppHandle) {- use tauri_plugin_updater::UpdaterExt;use tauri_plugin_dialog::{DialogExt, MessageDialogButtons};- use tauri::Emitter;+ use tauri_plugin_updater::UpdaterExt;- if UPDATE_IN_PROGRESS.swap(true, Ordering::SeqCst) {- handle.dialog()+ let Some(update_guard) = UpdateInProgressGuard::acquire(&UPDATE_IN_PROGRESS) else {+ handle+ .dialog().message("An update is already in progress.").title("Alook").buttons(MessageDialogButtons::OkCustom("OK".into())).show(|_| {});return;- }+ };- let updater = match handle.updater() {+ let updater = match handle+ .updater_builder()+ .timeout(UPDATE_CHECK_TIMEOUT)+ .build()+ {Ok(u) => u,Err(e) => {- UPDATE_IN_PROGRESS.store(false, Ordering::SeqCst);- handle.dialog()- .message(&format!("Could not check for updates: {}", e))+ handle+ .dialog()+ .message(format!("Could not check for updates: {}", e)).title("Update Check Failed").buttons(MessageDialogButtons::OkCustom("OK".into())).show(|_| {});@@ -750,90 +662,49 @@ async fn do_install_update(handle: &AppHandle) {};match updater.check().await {- Ok(Some(update)) => {+ Ok(Some(mut update)) => {+ update.timeout = Some(UPDATE_DOWNLOAD_TIMEOUT);let version = update.version.clone();let notes = update.body.clone().unwrap_or_default();let msg = if notes.is_empty() {format!("Version {} is available. Download and install?", version)} else {- format!("Version {} is available.\n\n{}\n\nDownload and install?", version, notes)+ format!(+ "Version {} is available.\n\n{}\n\nDownload and install?",+ version, notes+ )};- let (tx, rx) = std::sync::mpsc::channel();- handle.dialog()+ let h = handle.clone();+ handle+ .dialog().message(&msg).title("Update Available")- .buttons(MessageDialogButtons::OkCancelCustom("Update".into(), "Later".into()))+ .buttons(MessageDialogButtons::OkCancelCustom(+ "Update".into(),+ "Later".into(),+ )).show(move |confirmed| {- let _ = tx.send(confirmed);- });-- let confirmed = rx.recv().unwrap_or(false);- if !confirmed {- UPDATE_IN_PROGRESS.store(false, Ordering::SeqCst);- return;- }-- let _ = handle.notification()- .builder()- .title("Alook")- .body(&format!("Downloading v{}...", version))- .show();-- let h = handle.clone();- let mut cumulative: u64 = 0;- let result = update.download_and_install(- move |chunk_size, total| {- cumulative += chunk_size as u64;- let percent = total.map(|t| (cumulative as f64 / t as f64) * 100.0).unwrap_or(0.0);- let _ = h.emit("update://progress", UpdateProgress {- percent,- downloaded: cumulative,- total,- });- },- || {},- ).await;-- match result {- Ok(_) => {- let (tx2, rx2) = std::sync::mpsc::channel();- handle.dialog()- .message(&format!("Version {} has been installed. Restart now?", version))- .title("Update Complete")- .buttons(MessageDialogButtons::OkCancelCustom("Restart".into(), "Later".into()))- .show(move |restart| {- let _ = tx2.send(restart);- });-- if rx2.recv().unwrap_or(false) {- handle.restart();- } else {- UPDATE_IN_PROGRESS.store(false, Ordering::SeqCst);+ if !confirmed {+ return;}- }- Err(e) => {- UPDATE_IN_PROGRESS.store(false, Ordering::SeqCst);- handle.dialog()- .message(&format!("Download failed: {}", e))- .title("Update Failed")- .buttons(MessageDialogButtons::OkCustom("OK".into()))- .show(|_| {});- }- }+ tauri::async_runtime::spawn(async move {+ install_checked_update(h, update, update_guard).await;+ });+ });}Ok(None) => {- UPDATE_IN_PROGRESS.store(false, Ordering::SeqCst);- handle.dialog()+ handle+ .dialog().message("You're on the latest version.").title("No Updates Available").buttons(MessageDialogButtons::OkCustom("OK".into())).show(|_| {});}Err(e) => {- UPDATE_IN_PROGRESS.store(false, Ordering::SeqCst);- handle.dialog()- .message(&format!("Could not check for updates: {}", e))+ handle+ .dialog()+ .message(format!("Could not check for updates: {}", e)).title("Update Check Failed").buttons(MessageDialogButtons::OkCustom("OK".into())).show(|_| {});@@ -841,6 +712,76 @@ async fn do_install_update(handle: &AppHandle) {}}+#[cfg(desktop)]+async fn install_checked_update(+ handle: AppHandle,+ update: tauri_plugin_updater::Update,+ update_guard: UpdateInProgressGuard<'static>,+) {+ use tauri::Emitter;+ use tauri_plugin_dialog::{DialogExt, MessageDialogButtons};++ let version = update.version.clone();+ let _ = handle+ .notification()+ .builder()+ .title("Alook")+ .body(format!("Downloading v{version}…"))+ .show();++ let h = handle.clone();+ let mut cumulative: u64 = 0;+ let result = update+ .download_and_install(+ move |chunk_size, total| {+ cumulative += chunk_size as u64;+ let percent = total+ .map(|value| (cumulative as f64 / value as f64) * 100.0)+ .unwrap_or(0.0);+ let _ = h.emit(+ "update://progress",+ UpdateProgress {+ percent,+ downloaded: cumulative,+ total,+ },+ );+ },+ || {},+ )+ .await;++ match result {+ Ok(()) => {+ let h = handle.clone();+ handle+ .dialog()+ .message(format!(+ "Version {version} has been installed. Restart now?"+ ))+ .title("Update Complete")+ .buttons(MessageDialogButtons::OkCancelCustom(+ "Restart".into(),+ "Later".into(),+ ))+ .show(move |restart| {+ if restart {+ h.restart();+ }+ drop(update_guard);+ });+ }+ Err(error) => {+ handle+ .dialog()+ .message(format!("Download failed: {error}"))+ .title("Update Failed")+ .buttons(MessageDialogButtons::OkCustom("Close".into()))+ .show(|_| {});+ }+ }+}+#[cfg(desktop)]pub fn auto_check_updates(handle: AppHandle) {use tauri_plugin_updater::UpdaterExt;@@ -852,21 +793,31 @@ pub fn auto_check_updates(handle: AppHandle) {loop {let h = handle.clone();let found = tauri::async_runtime::block_on(async {- let updater = h.updater().ok()?;+ let updater = h+ .updater_builder()+ .timeout(UPDATE_CHECK_TIMEOUT)+ .build()+ .ok()?;let update = updater.check().await.ok()??;Some(update.version.clone())});if let Some(version) = found {- let mut guard = UPDATE_AVAILABLE_VERSION.lock().unwrap_or_else(|e| e.into_inner());+ let mut guard = UPDATE_AVAILABLE_VERSION+ .lock()+ .unwrap_or_else(|e| e.into_inner());let already_notified = guard.as_deref() == Some(&*version);if !already_notified {*guard = Some(version.clone());drop(guard);- let _ = handle.notification()+ let _ = handle+ .notification().builder().title("Alook Update Available")- .body(&format!("Version {} is ready to install. Use the tray menu to update.", version))+ .body(format!(+ "Version {} is ready to install. Use the tray menu to update.",+ version+ )).show();}}@@ -876,172 +827,292 @@ pub fn auto_check_updates(handle: AppHandle) {});}-// --- Daemon helpers ---+#[cfg(test)]+mod tests {+ use super::*;-#[cfg(desktop)]-async fn check_daemon_online(handle: &AppHandle) -> bool {- match run_cli(handle, &["daemon", "status"]).await {- Ok(output) => parse_daemon_status(&output.stdout).running,- Err(_) => false,+ #[test]+ fn runtime_capability_requires_node_npm_and_npx() {+ let ok = || Ok("10.9.3".to_string());+ let old = evaluate_runtime_capability(Ok("v16.0.0".to_string()), ok(), ok());+ assert!(old.available);+ assert_eq!(old.node_version.as_deref(), Some("v16.0.0"));++ let unrecognized = evaluate_runtime_capability(Ok("not-a-version".to_string()), ok(), ok());+ assert!(unrecognized.available);++ let missing_npm = evaluate_runtime_capability(+ Ok("v22.0.0".to_string()),+ Err("npm was not found".to_string()),+ ok(),+ );+ assert!(!missing_npm.available);+ assert!(missing_npm.reason.unwrap().contains("npm was not found"));++ let missing_npx = evaluate_runtime_capability(+ Ok("v22.0.0".to_string()),+ ok(),+ Err("npx was not found".to_string()),+ );+ assert!(!missing_npx.available);+ assert!(missing_npx.reason.unwrap().contains("npx was not found"));}-}-#[cfg(desktop)]-pub fn auto_start_daemon(handle: AppHandle) {- tauri::async_runtime::spawn(async move {- if check_daemon_online(&handle).await {- DAEMON_ONLINE.store(true, Ordering::Relaxed);- mark_daemon_ready(&handle);- return;- }+ #[test]+ fn daemon_failure_prefers_stderr_and_falls_back_to_stdout() {+ assert_eq!(+ daemon_failure_message("less useful stdout", "Node.js 20.9 or newer is required"),+ "The daemon couldn't start: Node.js 20.9 or newer is required"+ );+ assert_eq!(+ daemon_failure_message("npm failed", ""),+ "The daemon couldn't start: npm failed"+ );+ assert_eq!(+ daemon_failure_message("", ""),+ "The daemon couldn't start: The daemon process exited before it reported a reason."+ );+ }- match run_cli(&handle, &["daemon", "start"]).await {- Ok(output) if output.success => {- DAEMON_ONLINE.store(true, Ordering::Relaxed);- mark_daemon_ready(&handle);- }- Ok(output) => {- let msg = if output.stderr.trim().is_empty() {- "Failed to start daemon.".to_string()- } else {- format!("Failed to start daemon: {}", output.stderr.trim())- };- fatal_exit(&handle, &msg);- }- Err(e) => {- fatal_exit(&handle, &format!("Could not find CLI: {}", e));- }- }- });-}+ #[test]+ fn daemon_config_selects_repository_and_published_commands() {+ let debug = daemon_config_for(true);+ assert_eq!(debug.command, "pnpm");+ assert!(debug.base_args.is_empty());+ assert!(debug.cwd.is_some());++ let release = daemon_config_for(false);+ assert_eq!(release.command, "npx");+ assert_eq!(release.base_args, &["--yes", "@alook/daemon"]);+ assert!(release.cwd.is_none());+ }+ #[test]+ fn windows_uses_command_shims_for_node_package_tools() {+ assert_eq!(executable_for_platform("node", true), "node");+ assert_eq!(executable_for_platform("npm", true), "npm.cmd");+ assert_eq!(executable_for_platform("npx", true), "npx.cmd");+ assert_eq!(executable_for_platform("pnpm", true), "pnpm.cmd");+ assert_eq!(executable_for_platform("npx", false), "npx");+ }-pub fn parse_daemon_status(stdout: &str) -> DaemonStatusResult {- if let Ok(json) = serde_json::from_str::<serde_json::Value>(stdout) {- return DaemonStatusResult {- running: json["running"].as_bool().unwrap_or(false),- pid: json["pid"].as_u64().map(|p| p as u32),- version: json["version"].as_str().map(|s| s.to_string()),- };+ #[test]+ fn daemon_endpoints_are_fixed_at_the_native_boundary() {+ assert_eq!(+ daemon_endpoints_for(true),+ ("http://localhost:3000", "ws://localhost:8789")+ );+ assert_eq!(+ daemon_endpoints_for(false),+ ("https://alook.ai", "wss://alook.ai/api/ws/community-daemon")+ );}- let running = stdout.contains("running (pid=");- let pid = if running {- stdout- .split("pid=")- .nth(1)- .and_then(|s| s.trim_end_matches(')').trim().parse::<u32>().ok())- } else {- None- };+ #[test]+ fn pairing_accepts_only_machine_keys_and_builds_fixed_arguments() {+ for key in [+ "cmt_abcdefghijklmnopqrstuvwxyz012345",+ "cmk_abcDEF0123456789_-abcdefghijklmn",+ ] {+ let args = daemon_pair_args(key, false).unwrap();+ assert_eq!(+ args,+ vec![+ "daemon",+ "start",+ "--machine-key",+ key,+ "--server-url",+ "https://alook.ai",+ "--ws-url",+ "wss://alook.ai/api/ws/community-daemon",+ ]+ );+ assert!(!args.iter().any(|arg| arg == "--base-dir"));+ }- DaemonStatusResult {- running,- pid,- version: None,+ for invalid in [+ "cmt_too_short",+ "cmk_has spaces",+ "cm_machine_1234",+ "--server-url=https://example.com",+ ] {+ assert!(daemon_pair_args(invalid, false).is_err());+ }}-}-#[cfg(test)]-mod tests {- use super::*;+ #[test]+ fn development_pairing_uses_only_fixed_local_endpoints() {+ let args = daemon_pair_args("cmt_abcdefghijklmnopqrstuvwxyz012345", true).unwrap();+ assert_eq!(args[5], "http://localhost:3000");+ assert_eq!(args[7], "ws://localhost:8789");+ assert_eq!(args.len(), 8);+ }#[test]- fn parse_status_json_running() {- let input = r#"{"running":true,"pid":12345,"version":"0.1.0"}"#;- let result = parse_daemon_status(input);- assert!(result.running);- assert_eq!(result.pid, Some(12345));- assert_eq!(result.version.as_deref(), Some("0.1.0"));+ fn desktop_registers_no_daemon_lifecycle_commands() {+ let app_source = include_str!("lib.rs");+ for rejected in [+ "commands::daemon_start",+ "commands::daemon_stop",+ "commands::daemon_status",+ "commands::register_cli",+ "commands::cli_update",+ "commands::cli_check",+ "commands::check_for_updates",+ "commands::install_update",+ "auto_start_daemon",+ "prevent_exit",+ ] {+ assert!(+ !app_source.contains(rejected),+ "found rejected lifecycle hook: {rejected}"+ );+ }}#[test]- fn parse_status_json_not_running() {- let input = r#"{"running":false,"pid":null,"version":null}"#;- let result = parse_daemon_status(input);- assert!(!result.running);- assert_eq!(result.pid, None);- assert_eq!(result.version, None);+ fn desktop_restores_the_main_window_on_macos_reopen() {+ let app_source = include_str!("lib.rs");+ assert!(app_source.contains("tauri::RunEvent::Reopen"));+ assert!(app_source.contains("commands::show_main_window(app)"));}#[test]- fn parse_status_text_running() {- let input = "Daemon running (pid=54321)";- let result = parse_daemon_status(input);- assert!(result.running);- assert_eq!(result.pid, Some(54321));- assert_eq!(result.version, None);+ fn desktop_restores_the_main_window_for_a_second_instance() {+ let app_source = include_str!("lib.rs");+ let single_instance = app_source+ .find("tauri_plugin_single_instance::init")+ .unwrap();+ let updater = app_source.find("tauri_plugin_updater::Builder").unwrap();+ assert!(single_instance < updater);+ assert!(app_source[single_instance..updater].contains("show_main_window(app)"));}#[test]- fn parse_status_text_not_running() {- let input = "Daemon not running.";- let result = parse_daemon_status(input);- assert!(!result.running);- assert_eq!(result.pid, None);+ fn update_lock_releases_on_every_scope_exit() {+ let flag = AtomicBool::new(false);+ let guard = UpdateInProgressGuard::acquire(&flag).unwrap();+ assert!(flag.load(Ordering::SeqCst));+ assert!(UpdateInProgressGuard::acquire(&flag).is_none());+ drop(guard);+ assert!(!flag.load(Ordering::SeqCst));+ assert!(UpdateInProgressGuard::acquire(&flag).is_some());}#[test]- fn parse_status_empty_string() {- let result = parse_daemon_status("");- assert!(!result.running);- assert_eq!(result.pid, None);- assert_eq!(result.version, None);+ fn updater_network_operations_have_explicit_deadlines() {+ let source = include_str!("commands.rs");+ assert_eq!(UPDATE_CHECK_TIMEOUT, Duration::from_secs(15));+ assert_eq!(UPDATE_DOWNLOAD_TIMEOUT, Duration::from_secs(10 * 60));+ assert!(source.matches(".timeout(UPDATE_CHECK_TIMEOUT)").count() >= 2);+ assert!(source.contains("update.timeout = Some(UPDATE_DOWNLOAD_TIMEOUT)"));}#[test]- fn cli_config_args_construction() {- let cfg = cli_config();- let mut args: Vec<&str> = cfg.base_args.to_vec();- args.extend_from_slice(&["register", "--token"]);-- if cfg!(debug_assertions) {- assert_eq!(cfg.command, "pnpm");- assert_eq!(args, vec!["dev:cli", "register", "--token"]);- assert!(cfg.cwd.is_some());- } else {- assert_eq!(cfg.command, "npx");- assert_eq!(args, vec!["@alook/cli", "register", "--token"]);- assert!(cfg.cwd.is_none());- }+ fn close_to_hide_applies_only_to_the_main_window() {+ assert!(should_hide_on_close("main"));+ assert!(!should_hide_on_close("splash"));+ assert!(!should_hide_on_close("settings"));++ let app_source = include_str!("lib.rs");+ assert!(app_source.contains("should_hide_on_close(window.label())"));}#[test]- fn cli_config_daemon_start_args() {- let cfg = cli_config();- let mut args: Vec<&str> = cfg.base_args.to_vec();- args.extend_from_slice(&["daemon", "start"]);+ fn splash_closes_when_ready_or_when_the_native_deadline_expires() {+ assert!(!should_close_splash(false, false, false));+ assert!(!should_close_splash(true, false, false));+ assert!(!should_close_splash(false, true, false));+ assert!(should_close_splash(true, true, false));+ assert!(should_close_splash(false, false, true));++ let app_source = include_str!("lib.rs");+ assert!(app_source.contains("Duration::from_secs(10)"));+ assert!(app_source.contains("mark_splash_max_wait_elapsed"));+ }- if cfg!(debug_assertions) {- assert_eq!(args, vec!["dev:cli", "daemon", "start"]);- } else {- assert_eq!(args, vec!["@alook/cli", "daemon", "start"]);- }+ #[test]+ fn login_shell_path_accepts_only_one_line_of_absolute_entries() {+ let root = std::env::current_dir().unwrap();+ let first = root.join("runtime-path-one");+ let second = root.join("runtime-path-two");+ let valid = std::env::join_paths([first, second])+ .unwrap()+ .to_string_lossy()+ .to_string();+ assert_eq!(parse_shell_path(&valid).as_deref(), Some(valid.as_str()));+ assert!(parse_shell_path("").is_none());+ assert!(parse_shell_path("banner\n/usr/bin").is_none());+ assert!(parse_shell_path("relative/bin").is_none());}+ #[cfg(unix)]#[test]- fn cli_config_daemon_status_args() {- let cfg = cli_config();- let mut args: Vec<&str> = cfg.base_args.to_vec();- args.extend_from_slice(&["daemon", "status"]);+ fn bounded_process_kills_a_stalled_process_group_holding_output_pipes() {+ let mut command = Command::new("sh");+ command.args(["-c", "(sh -c 'sleep 5') &"]);+ let started = Instant::now();+ let error = run_process_with_timeout(+ command,+ Duration::from_millis(50),+ "process timed out".to_string(),+ )+ .unwrap_err();++ assert_eq!(error, "process timed out");+ assert!(started.elapsed() < Duration::from_secs(1));+ }- if cfg!(debug_assertions) {- assert_eq!(args, vec!["dev:cli", "daemon", "status"]);- } else {- assert_eq!(args, vec!["@alook/cli", "daemon", "status"]);+ #[test]+ fn desktop_remote_capability_has_no_plugin_permissions_or_localhost() {+ let capability = include_str!("../capabilities/desktop.json");+ assert!(capability.contains("https://alook.ai"));+ assert!(!capability.contains("localhost"));+ for rejected in [+ "shell:",+ "autostart:",+ "global-shortcut:",+ "updater:",+ "dialog:",+ "notification:",+ "deep-link:",+ ] {+ assert!(!capability.contains(rejected));+ }++ let app_source = include_str!("lib.rs");+ let cargo_manifest = include_str!("../Cargo.toml");+ for removed in ["autostart", "global_shortcut", "deep_link"] {+ assert!(!app_source.contains(removed));+ assert!(!cargo_manifest.contains(&removed.replace('_', "-")));}}#[test]- fn cli_config_version_args() {- let cfg = cli_config();- let mut args: Vec<&str> = cfg.base_args.to_vec();- args.push("--version");+ fn cocoa_mutations_are_dispatched_to_the_main_thread() {+ let command_source = include_str!("commands.rs");+ let window_source = include_str!("macos_window.rs");+ let removed_fade = ["fade", "out", "and", "close", "splash"].join("_");+ assert!(!command_source.contains(&removed_fade));+ assert!(command_source.contains("handle.run_on_main_thread"));+ assert!(command_source.contains("window.run_on_main_thread"));+ assert!(window_source.contains("window.run_on_main_thread"));+ }- if cfg!(debug_assertions) {- assert_eq!(args, vec!["dev:cli", "--version"]);- } else {- assert_eq!(args, vec!["@alook/cli", "--version"]);+ #[test]+ fn mobile_placeholder_plugins_are_not_linked_or_registered() {+ let app_source = include_str!("lib.rs");+ let cargo_manifest = include_str!("../Cargo.toml");+ for removed in ["tauri_plugin_biometric", "tauri_plugin_push"] {+ assert!(!app_source.contains(removed));+ assert!(!cargo_manifest.contains(&removed.replace('_', "-")));}+ let common_dependencies = cargo_manifest+ .split("[target.\"cfg(not(any(target_os = \\\"android\\\", target_os = \\\"ios\\\")))\".dependencies]")+ .next()+ .unwrap();+ assert!(!common_dependencies.contains("tauri-plugin-notification"));+ assert!(app_source.contains(".plugin(tauri_plugin_notification::init())"));}}diff --git a/src/desktop/src-tauri/src/lib.rs b/src/desktop/src-tauri/src/lib.rsindex d3d8d3537..a6fa60f11 100644--- a/src/desktop/src-tauri/src/lib.rs+++ b/src/desktop/src-tauri/src/lib.rs@@ -5,120 +5,111 @@ mod macos_window;#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {- let mut builder = tauri::Builder::default();+ let builder = tauri::Builder::default();// Desktop-only plugins#[cfg(desktop)]{- builder = builder- .plugin(tauri_plugin_shell::init())- .plugin(tauri_plugin_autostart::init(- tauri_plugin_autostart::MacosLauncher::LaunchAgent,- None,- ))- .plugin(tauri_plugin_global_shortcut::Builder::new().build())+ let builder = builder+ .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {+ commands::show_main_window(app);+ }))+ .plugin(tauri_plugin_notification::init()).plugin(tauri_plugin_updater::Builder::new().build()).plugin(tauri_plugin_dialog::init());+ run_desktop(builder);}- // Mobile-only plugins- #[cfg(mobile)]- {- builder = builder.plugin(tauri_plugin_biometric::init());- }-- // Cross-platform plugins- builder = builder- .plugin(tauri_plugin_deep_link::init())- .plugin(tauri_plugin_notification::init());+ #[cfg(not(desktop))]+ run_app(builder);+}+#[cfg(desktop)]+fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {// Register splash:// protocol to serve inline HTML for the splash window- #[cfg(desktop)]- {- builder = builder.register_uri_scheme_protocol("splash", |_ctx, _req| {- let html = commands::splash_html();- tauri::http::Response::builder()- .header("content-type", "text/html; charset=utf-8")- .body(html.into_bytes())- .unwrap()- });- }+ builder = builder.register_uri_scheme_protocol("splash", |_ctx, _req| {+ let html = commands::splash_html();+ tauri::http::Response::builder()+ .header("content-type", "text/html; charset=utf-8")+ .body(html.into_bytes())+ .unwrap()+ });// Register IPC commands (desktop only)- #[cfg(desktop)]- {- builder = builder.invoke_handler(tauri::generate_handler![- commands::get_cli_info,- commands::register_cli,- commands::daemon_start,- commands::daemon_stop,- commands::daemon_status,- commands::cli_update,- commands::cli_check,- commands::check_for_updates,- commands::install_update,- commands::set_window_theme,- commands::is_daemon_online,- commands::close_splashscreen,- ]);- }+ builder = builder.invoke_handler(tauri::generate_handler![+ commands::daemon_runtime_capability,+ commands::daemon_pair,+ commands::set_window_theme,+ commands::close_splashscreen,+ ]);// System tray + window setup (desktop only)- #[cfg(desktop)]- {- builder = builder.setup(|app| {- commands::setup_tray(app)?;- commands::auto_start_daemon(app.handle().clone());- commands::auto_check_updates(app.handle().clone());-- // Create splash window with inline HTML (frontendDist is remote, so url won't work)- commands::create_splash_window(app)?;-- // Minimum splash display time (1s) to prevent flash- let h1 = app.handle().clone();- std::thread::spawn(move || {- std::thread::sleep(std::time::Duration::from_millis(1000));- commands::mark_splash_min_elapsed(&h1);- });-- // macOS: inset the webview with rounded corners, window bg as frame- #[cfg(target_os = "macos")]- {- use tauri::Manager;- if let Some(window) = app.get_webview_window("main") {- commands::set_window_theme(window.clone(), false);- macos_window::setup_inset_webview(&window);- }- }+ builder = builder.setup(|app| {+ commands::setup_tray(app)?;+ commands::auto_check_updates(app.handle().clone());++ // Create splash window with inline HTML (frontendDist is remote, so url won't work)+ commands::create_splash_window(app)?;++ // Minimum splash display time (1s) to prevent flash+ let h1 = app.handle().clone();+ std::thread::spawn(move || {+ std::thread::sleep(std::time::Duration::from_millis(1000));+ commands::mark_splash_min_elapsed(&h1);+ });- Ok(())+ let h2 = app.handle().clone();+ std::thread::spawn(move || {+ std::thread::sleep(std::time::Duration::from_secs(10));+ commands::mark_splash_max_wait_elapsed(&h2);});- builder = builder.on_window_event(|window, event| {+ // macOS: inset the webview with rounded corners, window bg as frame+ #[cfg(target_os = "macos")]+ {+ use tauri::Manager;+ if let Some(window) = app.get_webview_window("main") {+ commands::set_window_theme(window.clone(), false);+ macos_window::setup_inset_webview(&window);+ }+ }++ Ok(())+ });++ builder = builder.on_window_event(|window, event| {+ #[cfg(target_os = "macos")]+ if window.label() == "main"+ && matches!(+ event,+ tauri::WindowEvent::Resized(_) | tauri::WindowEvent::ScaleFactorChanged { .. }+ )+ {+ use tauri::Manager;+ if let Some(webview) = window.app_handle().get_webview_window("main") {+ macos_window::update_inset_webview(&webview);+ }+ }+ if commands::should_hide_on_close(window.label()) {if let tauri::WindowEvent::CloseRequested { api, .. } = event {api.prevent_close();let _ = window.hide();}- });- }+ }+ });+ run_app(builder);+}++fn run_app(builder: tauri::Builder<tauri::Wry>) {let app = builder.build(tauri::generate_context!()).expect("error while building tauri application");- #[cfg(desktop)]- {- app.run(|app_handle, event| {- // code == None means user-initiated (Cmd+Q), Some(_) means programmatic exit(0)- if let tauri::RunEvent::ExitRequested { code: None, api, .. } = event {- api.prevent_exit();- commands::quit_with_daemon_prompt(app_handle);- }- });- }-- #[cfg(not(desktop))]- {- app.run(|_, _| {});- }+ app.run(|_app, _event| {+ #[cfg(target_os = "macos")]+ if let tauri::RunEvent::Reopen { .. } = _event {+ commands::show_main_window(_app);+ }+ });}diff --git a/src/desktop/src-tauri/src/macos_window.rs b/src/desktop/src-tauri/src/macos_window.rsindex 83dbdcc28..65c45112c 100644--- a/src/desktop/src-tauri/src/macos_window.rs+++ b/src/desktop/src-tauri/src/macos_window.rs@@ -1,13 +1,27 @@use tauri::WebviewWindow;const INSET_TOP: f64 = 38.0;-const INSET_SIDE: f64 = 8.0;-const INSET_BOTTOM: f64 = 8.0;+const INSET_SIDE: f64 = 0.0;+const INSET_BOTTOM: f64 = 0.0;const CORNER_RADIUS: f64 = 10.0;+const NS_LAYOUT_ATTRIBUTE_TOP: isize = 3;++fn top_inset(fullscreen: bool) -> f64 {+ if fullscreen {+ 0.0+ } else {+ INSET_TOP+ }+}pub fn setup_inset_webview(window: &WebviewWindow) {- use objc2::runtime::AnyObject;+ let target = window.clone();+ let _ = window.run_on_main_thread(move || setup_inset_webview_on_main(&target));+}++fn setup_inset_webview_on_main(window: &WebviewWindow) {use objc2::msg_send;+ use objc2::runtime::AnyObject;unsafe {let ns_view = window.ns_view().unwrap() as *mut AnyObject;@@ -56,26 +70,92 @@ pub fn setup_inset_webview(window: &WebviewWindow) {// leading: webview.leading = superview.leading + INSET_SIDElet leading: *mut AnyObject = msg_send![ns_view, leadingAnchor];let sv_leading: *mut AnyObject = msg_send![superview, leadingAnchor];- let c: *mut AnyObject = msg_send![leading, constraintEqualToAnchor: sv_leading, constant: INSET_SIDE];+ let c: *mut AnyObject =+ msg_send![leading, constraintEqualToAnchor: sv_leading, constant: INSET_SIDE];let _: () = msg_send![c, setActive: true];// trailing: superview.trailing = webview.trailing + INSET_SIDElet trailing: *mut AnyObject = msg_send![ns_view, trailingAnchor];let sv_trailing: *mut AnyObject = msg_send![superview, trailingAnchor];- let c: *mut AnyObject = msg_send![sv_trailing, constraintEqualToAnchor: trailing, constant: INSET_SIDE];+ let c: *mut AnyObject =+ msg_send![sv_trailing, constraintEqualToAnchor: trailing, constant: INSET_SIDE];let _: () = msg_send![c, setActive: true];// top: webview.top = superview.top + INSET_TOPlet top: *mut AnyObject = msg_send![ns_view, topAnchor];let sv_top: *mut AnyObject = msg_send![superview, topAnchor];- let c: *mut AnyObject = msg_send![top, constraintEqualToAnchor: sv_top, constant: INSET_TOP];+ let c: *mut AnyObject =+ msg_send![top, constraintEqualToAnchor: sv_top, constant: INSET_TOP];let _: () = msg_send![c, setActive: true];// bottom: superview.bottom = webview.bottom + INSET_BOTTOMlet bottom: *mut AnyObject = msg_send![ns_view, bottomAnchor];let sv_bottom: *mut AnyObject = msg_send![superview, bottomAnchor];- let c: *mut AnyObject = msg_send![sv_bottom, constraintEqualToAnchor: bottom, constant: INSET_BOTTOM];+ let c: *mut AnyObject =+ msg_send![sv_bottom, constraintEqualToAnchor: bottom, constant: INSET_BOTTOM];let _: () = msg_send![c, setActive: true];}}+pub fn update_inset_webview(window: &WebviewWindow) {+ let fullscreen = window.is_fullscreen().unwrap_or(false);+ let target = window.clone();+ let _ = window.run_on_main_thread(move || update_inset_webview_on_main(&target, fullscreen));+}++fn update_inset_webview_on_main(window: &WebviewWindow, fullscreen: bool) {+ use objc2::msg_send;+ use objc2::runtime::AnyObject;++ unsafe {+ let ns_view = window.ns_view().unwrap() as *mut AnyObject;+ let layer: *mut AnyObject = msg_send![ns_view, layer];+ if !layer.is_null() {+ let radius = if fullscreen { 0.0 } else { CORNER_RADIUS };+ let _: () = msg_send![layer, setCornerRadius: radius];+ }++ let superview: *mut AnyObject = msg_send![ns_view, superview];+ if superview.is_null() {+ return;+ }+ let constraints: *mut AnyObject = msg_send![superview, constraints];+ let count: usize = msg_send![constraints, count];+ for index in 0..count {+ let constraint: *mut AnyObject = msg_send![constraints, objectAtIndex: index];+ let first_item: *mut AnyObject = msg_send![constraint, firstItem];+ let second_item: *mut AnyObject = msg_send![constraint, secondItem];+ let first_attribute: isize = msg_send![constraint, firstAttribute];+ let second_attribute: isize = msg_send![constraint, secondAttribute];+ if first_item == ns_view+ && second_item == superview+ && first_attribute == NS_LAYOUT_ATTRIBUTE_TOP+ && second_attribute == NS_LAYOUT_ATTRIBUTE_TOP+ {+ let inset = top_inset(fullscreen);+ let _: () = msg_send![constraint, setConstant: inset];+ let _: () = msg_send![superview, layoutSubtreeIfNeeded];+ break;+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn keeps_only_the_top_inset() {+ assert_eq!(INSET_TOP, 38.0);+ assert_eq!(INSET_SIDE, 0.0);+ assert_eq!(INSET_BOTTOM, 0.0);+ }++ #[test]+ fn fullscreen_uses_the_top_constraint_attribute() {+ assert_eq!(NS_LAYOUT_ATTRIBUTE_TOP, 3);+ assert_eq!(top_inset(true), 0.0);+ assert_eq!(top_inset(false), 38.0);+ }+}diff --git a/src/desktop/src-tauri/tauri.conf.json b/src/desktop/src-tauri/tauri.conf.jsonindex 8f5d1fa25..f918f34c0 100644--- a/src/desktop/src-tauri/tauri.conf.json+++ b/src/desktop/src-tauri/tauri.conf.json@@ -3,13 +3,13 @@"version": "0.1.7","identifier": "ai.alook.desktop","build": {- "devUrl": "http://localhost:3000/workspaces?auto",- "frontendDist": "https://alook.ai/workspaces?auto"+ "devUrl": "http://localhost:3000/c",+ "frontendDist": "https://alook.ai/c"},"bundle": {"active": true,"targets": "all",- "createUpdaterArtifacts": false,+ "createUpdaterArtifacts": true,"icon": ["icons/32x32.png","icons/128x128.png",@@ -43,30 +43,15 @@}],"security": {- "capabilities": []+ "capabilities": ["desktop-capability"]}},"plugins": {"updater": {"endpoints": [- "https://alook.ai/api/desktop/update/{{target}}/{{arch}}/{{current_version}}"+ "https://alook.ai/api/desktop/update/{{target}}/{{arch}}/{{current_version}}?bundle_type={{bundle_type}}"],"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDg4QUQ2RTkxNENEOTZGRDEKUldUUmI5bE1rVzZ0aUY5SGgxVmRjZkUxeTNUKzlpZC8rQXQ3R0xDTFBsUFV4Kzc0U3pXc3hRV1MK"- },- "deep-link": {- "desktop": {- "schemes": [- "alook"- ]- },- "mobile": [- {- "scheme": [- "alook"- ],- "host": "alook.ai"- }- ]}}}diff --git a/src/desktop/src-tauri/tauri.dev.conf.json b/src/desktop/src-tauri/tauri.dev.conf.jsonnew file mode 100644index 000000000..5304c5b55--- /dev/null+++ b/src/desktop/src-tauri/tauri.dev.conf.json@@ -0,0 +1,21 @@+{+ "$schema": "./gen/schemas/desktop-schema.json",+ "app": {+ "security": {+ "capabilities": [+ "desktop-capability",+ {+ "identifier": "desktop-development",+ "description": "Development custom-command access for the local webview",+ "windows": ["main"],+ "platforms": ["linux", "macOS", "windows"],+ "local": false,+ "remote": {+ "urls": ["http://localhost:3000"]+ },+ "permissions": []+ }+ ]+ }+ }+}diff --git a/src/desktop/src-tauri/tauri.macos.conf.json b/src/desktop/src-tauri/tauri.macos.conf.jsonindex c41ae1cbd..9635c7ab8 100644--- a/src/desktop/src-tauri/tauri.macos.conf.json+++ b/src/desktop/src-tauri/tauri.macos.conf.json@@ -5,7 +5,7 @@"targets": ["app", "dmg"],"macOS": {"minimumSystemVersion": "11.0",- "entitlements": "entitlements.plist"+ "signingIdentity": "-"}}}diff --git a/src/web/src/app/(app)/studio/new/client.tsx b/src/web/src/app/(app)/studio/new/client.tsxindex a3c9c0d5c..309580dbd 100644--- a/src/web/src/app/(app)/studio/new/client.tsx+++ b/src/web/src/app/(app)/studio/new/client.tsx@@ -20,7 +20,6 @@ import {import type { AgentRuntime as Runtime } from "@alook/shared";import type { WsMessage } from "@alook/shared";-import { isTauri, isDesktop, tauriInvoke } from "@alook/shared";import { listRuntimes, createMachineToken } from "@/lib/api";import { useUserWs } from "@/lib/use-user-ws";import { ConnectMachineSteps } from "@/components/connect-machine-steps";@@ -50,11 +49,9 @@ export function StudioOnboardingClient({const [machineRegistered, setMachineRegistered] = useState(false);const [daemonOnline, setDaemonOnline] = useState(false);- const isTauriDesktop = isTauri() && isDesktop();const onlineRuntimes = runtimes.filter((r) => r.status === "online");const hasOnlineRuntime = onlineRuntimes.length > 0;- const computerConnected =- hasOnlineRuntime || (machineRegistered && daemonOnline) || isTauriDesktop;+ const computerConnected = hasOnlineRuntime || (machineRegistered && daemonOnline);useEffect(() => {listRuntimes(workspaceId)@@ -88,30 +85,12 @@ export function StudioOnboardingClient({try {const res = await createMachineToken("cli", workspaceId);setGeneratedToken(res.token);- if (isTauriDesktop) {- const result = await tauriInvoke<{ success: boolean; message: string }>("register_cli", { token: res.token });- if (result.success) {- setMachineRegistered(true);- setDaemonOnline(true);- const rts = await listRuntimes(workspaceId).catch(() => [] as Runtime[]);- setRuntimes(rts);- } else {- toast.error(result.message || "Auto-registration failed");- }- }} catch {toast.error("Failed to generate token");} finally {setGeneratingToken(false);}- }, [workspaceId, isTauriDesktop]);-- // In Tauri desktop mode, auto-register the CLI when no runtime is online- useEffect(() => {- if (!isTauriDesktop || loadingRuntimes || hasOnlineRuntime || machineRegistered) return;- handleGenerateToken();- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [isTauriDesktop, loadingRuntimes]);+ }, [workspaceId]);useEffect(() => {const firstOnline = onlineRuntimes[0]?.id;@@ -427,31 +406,28 @@ export function StudioOnboardingClient({onAssignRuntime={handleAssignRuntime}/>- {/* Connect Machine — hidden in Tauri desktop (the app IS the computer) */}- {!isTauriDesktop && (- <div className="space-y-3">- {computerConnected ? (- <p className="text-xs text-emerald-600 flex items-center gap-1">- <CheckCircle2 className="size-3" /> Computer connected+ <div className="space-y-3">+ {computerConnected ? (+ <p className="text-xs text-emerald-600 flex items-center gap-1">+ <CheckCircle2 className="size-3" /> Computer connected+ </p>+ ) : (+ <>+ <p className="text-xs text-muted-foreground">+ Your company needs a connected computer to run tasks.</p>- ) : (- <>- <p className="text-xs text-muted-foreground">- Your company needs a connected computer to run tasks.- </p>- <div className="rounded-xl bg-muted/40 p-4">- <ConnectMachineSteps- generatedToken={generatedToken}- generatingToken={generatingToken}- onGenerateToken={handleGenerateToken}- registered={machineRegistered}- daemonOnline={daemonOnline}- />- </div>- </>- )}- </div>- )}+ <div className="rounded-xl bg-muted/40 p-4">+ <ConnectMachineSteps+ generatedToken={generatedToken}+ generatingToken={generatingToken}+ onGenerateToken={handleGenerateToken}+ registered={machineRegistered}+ daemonOnline={daemonOnline}+ />+ </div>+ </>+ )}+ </div>{/* Create */}<Buttondiff --git a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsxindex 5491147b6..fa87739f4 100644--- a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx@@ -26,7 +26,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { Monitor, Plus } from "lucide-react";import type { AgentRuntime as Runtime } from "@alook/shared";-import { semverGte, isTauri, isDesktop, tauriInvoke } from "@alook/shared";+import { semverGte } from "@alook/shared";import { cliCmd, getAppMode } from "@/lib/utils";import { ProviderLogo } from "@/components/provider-logo";import { triggerRuntimeUpdate, triggerRuntimeRescan, fetchLatestCliVersion } from "@/lib/api";@@ -43,8 +43,7 @@ export default function RuntimesPage() {const pathname = usePathname();const mode = getAppMode();const isMobileApp = mode === "mobile";- const isTauriDesktop = isTauri() && isDesktop();- const hideNewMachine = isMobileApp || isTauriDesktop;+ const hideNewMachine = isMobileApp;const [sheetOpen, setSheetOpen] = useState(() => searchParams.has("connect"));const [generatedToken, setGeneratedToken] = useState("");@@ -453,41 +452,23 @@ export default function RuntimesPage() {<p className="text-[11px] text-muted-foreground mb-2">Bring this machine online:</p>- {mode === "desktop" && isTauri() ? (- <Button- size="sm"- variant="outline"- className="w-full h-7 text-[11px]"- onClick={async () => {- try {- await tauriInvoke("daemon_start");- toast.success("Daemon started");- } catch {- toast.error("Failed to start daemon");- }- }}+ <Tooltip>+ <TooltipTrigger+ render={+ <div+ className="relative overflow-hidden rounded-md bg-muted px-2 py-2 font-mono text-[11px] text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"+ onClick={() => {+ navigator.clipboard.writeText(`${cliCmd()} daemon start`);+ toast.success("Copied to clipboard");+ }}+ />+ }>- Start Daemon- </Button>- ) : (- <Tooltip>- <TooltipTrigger- render={- <div- className="relative overflow-hidden rounded-md bg-muted px-2 py-2 font-mono text-[11px] text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"- onClick={() => {- navigator.clipboard.writeText(`${cliCmd()} daemon start`);- toast.success("Copied to clipboard");- }}- />- }- >- <span className="absolute inset-0 -translate-x-full animate-[shimmer_2.5s_infinite] bg-linear-to-r from-transparent via-(--shimmer-peak) to-transparent" />- <span className="relative">{cliCmd()} daemon start</span>- </TooltipTrigger>- <TooltipContent>Click to copy</TooltipContent>- </Tooltip>- )}+ <span className="absolute inset-0 -translate-x-full animate-[shimmer_2.5s_infinite] bg-linear-to-r from-transparent via-(--shimmer-peak) to-transparent" />+ <span className="relative">{cliCmd()} daemon start</span>+ </TooltipTrigger>+ <TooltipContent>Click to copy</TooltipContent>+ </Tooltip></div>)}</div>diff --git a/src/web/src/app/api/daemon/latest-version/route.test.ts b/src/web/src/app/api/daemon/latest-version/route.test.tsnew file mode 100644index 000000000..261f530c0--- /dev/null+++ b/src/web/src/app/api/daemon/latest-version/route.test.ts@@ -0,0 +1,46 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const mockFetch = vi.fn()+vi.stubGlobal("fetch", mockFetch)++import { GET } from "./route"++describe("GET /api/daemon/latest-version", () => {+ beforeEach(() => vi.clearAllMocks())++ it("returns the latest daemon package metadata", async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ json: async () => ({ version: "0.1.8" }),+ })++ const response = await GET()++ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({ version: "0.1.8", package: "@alook/daemon" })+ expect(mockFetch).toHaveBeenCalledWith("https://registry.npmjs.org/@alook/daemon/latest")+ })++ it.each([+ { ok: false, json: async () => ({}) },+ { ok: true, json: async () => ({}) },+ ])("returns 502 for an unusable registry response", async (registryResponse) => {+ mockFetch.mockResolvedValue(registryResponse)++ const response = await GET()++ expect(response.status).toBe(502)+ expect(await response.json()).toEqual({ error: "failed to fetch latest daemon version from npm" })+ })++ it("returns 502 when the registry request fails", async () => {+ mockFetch.mockRejectedValue(new Error("registry unavailable"))++ const response = await GET()++ expect(response.status).toBe(502)+ expect(await response.json()).toEqual({+ error: "failed to fetch latest daemon version from npm",+ })+ })+})diff --git a/src/web/src/app/api/daemon/latest-version/route.ts b/src/web/src/app/api/daemon/latest-version/route.tsnew file mode 100644index 000000000..f0ecdc85d--- /dev/null+++ b/src/web/src/app/api/daemon/latest-version/route.ts@@ -0,0 +1,10 @@+import { writeError, writeJSON } from "@/lib/middleware/helpers"+import { fetchLatestDaemonVersion } from "@/lib/npm"++export async function GET() {+ const result = await fetchLatestDaemonVersion()+ if (!result) {+ return writeError("failed to fetch latest daemon version from npm", 502)+ }+ return writeJSON(result)+}diff --git a/src/web/src/app/api/desktop/update/[target]/[arch]/[current_version]/route.test.ts b/src/web/src/app/api/desktop/update/[target]/[arch]/[current_version]/route.test.tsindex 0b1d6271b..97c5680f2 100644--- a/src/web/src/app/api/desktop/update/[target]/[arch]/[current_version]/route.test.ts+++ b/src/web/src/app/api/desktop/update/[target]/[arch]/[current_version]/route.test.ts@@ -1,20 +1,37 @@-import { describe, it, expect, vi, beforeEach } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";const mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);import { GET } from "./route";-function makeRequest(target: string, arch: string, current_version: string) {- const url = `http://localhost/api/desktop/update/${target}/${arch}/${current_version}`;+interface Asset {+ name: string;+ browser_download_url: string;+}++function makeRequest(+ target: string,+ arch: string,+ currentVersion: string,+ bundleType = "app",+) {+ const url = new URL(+ `http://localhost/api/desktop/update/${target}/${arch}/${currentVersion}`,+ );+ url.searchParams.set("bundle_type", bundleType);return new Request(url);}-function makeParams(target: string, arch: string, current_version: string) {- return { params: Promise.resolve({ target, arch, current_version }) };+function makeParams(target: string, arch: string, currentVersion: string) {+ return { params: Promise.resolve({ target, arch, current_version: currentVersion }) };+}++function makeAsset(name: string): Asset {+ return { name, browser_download_url: `https://example.com/${name}` };}-function makeRelease(version: string, assets: { name: string; browser_download_url: string }[] = []) {+function makeRelease(version: string, assets: Asset[] = []) {return {draft: false,prerelease: false,@@ -25,187 +42,271 @@ function makeRelease(version: string, assets: { name: string; browser_download_u};}+function updaterAssets(...names: string[]) {+ return names.flatMap((name) => [makeAsset(name), makeAsset(`${name}.sig`)]);+}++async function requestUpdate(+ target: string,+ arch: string,+ currentVersion: string,+ bundleType = "app",+) {+ return GET(+ makeRequest(target, arch, currentVersion, bundleType),+ makeParams(target, arch, currentVersion),+ );+}+describe("GET /api/desktop/update/[target]/[arch]/[current_version]", () => {beforeEach(() => {- vi.clearAllMocks();+ mockFetch.mockReset();});it("returns 502 when GitHub API fails", async () => {mockFetch.mockResolvedValueOnce({ ok: false, status: 500 });- const res = await GET(- makeRequest("darwin", "aarch64", "1.0.0"),- makeParams("darwin", "aarch64", "1.0.0"),- );+ const res = await requestUpdate("darwin", "aarch64", "1.0.0");expect(res.status).toBe(502);- const body = await res.json();- expect(body.error).toBe("Failed to fetch releases");+ expect(await res.json()).toEqual({ error: "Failed to fetch releases" });});it("returns 204 when no desktop release exists", async () => {mockFetch.mockResolvedValueOnce({ok: true,- json: async () => [{ draft: false, prerelease: false, tag_name: "web-v1.0.0", assets: [] }],+ json: async () => [+ { draft: false, prerelease: false, tag_name: "web-v1.0.0", assets: [] },+ ],});- const res = await GET(- makeRequest("darwin", "aarch64", "1.0.0"),- makeParams("darwin", "aarch64", "1.0.0"),- );-- expect(res.status).toBe(204);+ expect((await requestUpdate("darwin", "aarch64", "1.0.0")).status).toBe(204);});it("returns 204 when current_version is already latest", async () => {mockFetch.mockResolvedValueOnce({ok: true,- json: async () => [makeRelease("1.0.0")],+ json: async () => [+ makeRelease("1.0.0", updaterAssets("Alook_1.0.0_aarch64.app.tar.gz")),+ ],});- const res = await GET(- makeRequest("darwin", "aarch64", "1.0.0"),- makeParams("darwin", "aarch64", "1.0.0"),- );-- expect(res.status).toBe(204);+ expect((await requestUpdate("darwin", "aarch64", "1.0.0")).status).toBe(204);});- it("returns 204 when platform/arch combo has no matching asset", async () => {+ it.each([["freebsd", "x86_64", "app"]])(+ "returns 204 for unsupported %s-%s-%s updater targets",+ async (target, arch, bundleType) => {mockFetch.mockResolvedValueOnce({ok: true,- json: async () => [makeRelease("2.0.0", [- { name: "app-windows.msi.zip", browser_download_url: "https://example.com/app.msi.zip" },- ])],+ json: async () => [+ makeRelease("2.0.0", updaterAssets("Alook_2.0.0_amd64.AppImage")),+ ],});- const res = await GET(- makeRequest("freebsd", "arm", "1.0.0"),- makeParams("freebsd", "arm", "1.0.0"),- );-- expect(res.status).toBe(204);- });+ expect((await requestUpdate(target, arch, "1.0.0", bundleType)).status).toBe(204);+ expect(mockFetch).not.toHaveBeenCalled();+ },+ );- it("returns 204 when binary or sig asset is missing", async () => {+ it("returns 204 when the matching binary has no signature asset", async () => {mockFetch.mockResolvedValueOnce({ok: true,- json: async () => [makeRelease("2.0.0", [- { name: "app.app.tar.gz", browser_download_url: "https://example.com/app.tar.gz" },- // no .sig file- ])],+ json: async () => [makeRelease("2.0.0", [makeAsset("Alook_2.0.0_aarch64.app.tar.gz")])],});- const res = await GET(- makeRequest("darwin", "aarch64", "1.0.0"),- makeParams("darwin", "aarch64", "1.0.0"),+ expect((await requestUpdate("darwin", "aarch64", "1.0.0")).status).toBe(204);+ });++ it.each([+ ["darwin", "aarch64", "app", "Alook_2.0.0_aarch64.app.tar.gz"],+ ["darwin", "x86_64", "app", "Alook_2.0.0_x64.app.tar.gz"],+ ["linux", "x86_64", "appimage", "Alook_2.0.0_amd64.AppImage"],+ ["linux", "x86_64", "deb", "Alook_2.0.0_amd64.deb"],+ ["linux", "x86_64", "rpm", "Alook-2.0.0-1.x86_64.rpm"],+ ["windows", "x86_64", "msi", "Alook_2.0.0_x64_en-US.msi"],+ ["windows", "x86_64", "nsis", "Alook_2.0.0_x64-setup.exe"],+ ])(+ "returns the exact Tauri v2 %s-%s-%s artifact and signature",+ async (target, arch, bundleType, assetName) => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => [makeRelease("2.0.0", updaterAssets(assetName))],+ });+ mockFetch.mockResolvedValueOnce({ ok: true, text: async () => "sig-content-here" });++ const res = await requestUpdate(target, arch, "1.0.0", bundleType);++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ version: "2.0.0",+ notes: "Release notes",+ pub_date: "2026-06-01T00:00:00Z",+ platforms: {+ [`${target}-${arch}-${bundleType}`]: {+ url: `https://example.com/${assetName}`,+ signature: "sig-content-here",+ },+ },+ });+ },+ );++ it("keeps Windows MSI and NSIS assets distinct", async () => {+ const assets = updaterAssets(+ "Alook_2.0.0_x64_en-US.msi",+ "Alook_2.0.0_x64-setup.exe",+ );+ mockFetch.mockResolvedValueOnce({ ok: true, json: async () => [makeRelease("2.0.0", assets)] });+ mockFetch.mockResolvedValueOnce({ ok: true, text: async () => "msi-signature" });+ mockFetch.mockResolvedValueOnce({ ok: true, json: async () => [makeRelease("2.0.0", assets)] });+ mockFetch.mockResolvedValueOnce({ ok: true, text: async () => "nsis-signature" });++ const msi = await requestUpdate("windows", "x86_64", "1.0.0", "msi");+ const nsis = await requestUpdate("windows", "x86_64", "1.0.0", "nsis");++ expect((await msi.json()).platforms["windows-x86_64-msi"].url).toContain(".msi");+ expect((await nsis.json()).platforms["windows-x86_64-nsis"].url).toContain("-setup.exe");+ });++ it("keeps Linux package formats distinct from AppImage", async () => {+ const assets = updaterAssets(+ "Alook_2.0.0_amd64.AppImage",+ "Alook_2.0.0_amd64.deb",+ "Alook-2.0.0-1.x86_64.rpm",);+ for (const [bundleType, suffix] of [+ ["appimage", ".AppImage"],+ ["deb", ".deb"],+ ["rpm", ".rpm"],+ ] as const) {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => [makeRelease("2.0.0", assets)],+ });+ mockFetch.mockResolvedValueOnce({ ok: true, text: async () => `${bundleType}-signature` });++ const response = await requestUpdate("linux", "x86_64", "1.0.0", bundleType);+ expect((await response.json()).platforms[`linux-x86_64-${bundleType}`].url).toContain(+ suffix,+ );+ }+ });++ it("selects each macOS architecture even when assets are reversed", async () => {+ const assets = updaterAssets(+ "Alook_2.0.0_x64.app.tar.gz",+ "Alook_2.0.0_aarch64.app.tar.gz",+ );+ mockFetch.mockResolvedValueOnce({ ok: true, json: async () => [makeRelease("2.0.0", assets)] });+ mockFetch.mockResolvedValueOnce({ ok: true, text: async () => "arm-signature" });+ mockFetch.mockResolvedValueOnce({ ok: true, json: async () => [makeRelease("2.0.0", assets)] });+ mockFetch.mockResolvedValueOnce({ ok: true, text: async () => "intel-signature" });- expect(res.status).toBe(204);+ const arm = await requestUpdate("darwin", "aarch64", "1.0.0");+ const intel = await requestUpdate("darwin", "x86_64", "1.0.0");++ expect((await arm.json()).platforms["darwin-aarch64-app"].url).toContain("aarch64");+ expect((await intel.json()).platforms["darwin-x86_64-app"].url).toContain("x64");});- it("returns JSON with version, notes, pub_date, platforms when update is available", async () => {+ it("ignores invalid non-SemVer tags and selects the next valid release", async () => {mockFetch.mockResolvedValueOnce({ok: true,- json: async () => [makeRelease("2.0.0", [- { name: "app.app.tar.gz", browser_download_url: "https://example.com/app.tar.gz" },- { name: "app.app.tar.gz.sig", browser_download_url: "https://example.com/app.tar.gz.sig" },- ])],+ json: async () => [+ makeRelease("1.0.0.1", updaterAssets("Alook_1.0.0.1_aarch64.app.tar.gz")),+ makeRelease("1.1.0", updaterAssets("Alook_1.1.0_aarch64.app.tar.gz")),+ ],});- // Signature fetch- mockFetch.mockResolvedValueOnce({ ok: true, text: async () => "sig-content-here" });+ mockFetch.mockResolvedValueOnce({ ok: true, text: async () => "signature" });- const res = await GET(- makeRequest("darwin", "aarch64", "1.0.0"),- makeParams("darwin", "aarch64", "1.0.0"),- );+ const res = await requestUpdate("darwin", "aarch64", "1.0.0");expect(res.status).toBe(200);- const body = await res.json();- expect(body.version).toBe("2.0.0");- expect(body.notes).toBe("Release notes");- expect(body.pub_date).toBe("2026-06-01T00:00:00Z");- expect(body.platforms["darwin-aarch64"]).toEqual({- url: "https://example.com/app.tar.gz",- signature: "sig-content-here",- });+ expect((await res.json()).version).toBe("1.1.0");+ });++ it("returns 204 for an invalid current version", async () => {+ expect((await requestUpdate("darwin", "aarch64", "1.0.0.1")).status).toBe(204);+ expect(mockFetch).not.toHaveBeenCalled();});- it("returns empty signature when sig fetch fails", async () => {+ it("searches up to 100 releases and skips interleaved non-desktop releases", async () => {+ const unrelated = Array.from({ length: 12 }, (_, index) => ({+ ...makeRelease(`9.0.${index}`),+ tag_name: `cli-v9.0.${index}`,+ }));mockFetch.mockResolvedValueOnce({ok: true,- json: async () => [makeRelease("2.0.0", [- { name: "app.app.tar.gz", browser_download_url: "https://example.com/app.tar.gz" },- { name: "app.app.tar.gz.sig", browser_download_url: "https://example.com/app.tar.gz.sig" },- ])],+ json: async () => [+ ...unrelated,+ makeRelease("2.0.0", updaterAssets("Alook_2.0.0_aarch64.app.tar.gz")),+ ],});- mockFetch.mockResolvedValueOnce({ ok: false });+ mockFetch.mockResolvedValueOnce({ ok: true, text: async () => "signature" });- const res = await GET(- makeRequest("darwin", "aarch64", "1.0.0"),- makeParams("darwin", "aarch64", "1.0.0"),- );+ const res = await requestUpdate("darwin", "aarch64", "1.0.0");expect(res.status).toBe(200);- const body = await res.json();- expect(body.platforms["darwin-aarch64"].signature).toBe("");+ expect((await res.json()).version).toBe("2.0.0");+ expect(mockFetch.mock.calls[0][0]).toContain("per_page=100");});- describe("compareVersions", () => {- it("current version newer than release returns 204", async () => {- mockFetch.mockResolvedValueOnce({- ok: true,- json: async () => [makeRelease("1.0.0")],- });+ it("selects the highest compatible signed SemVer regardless of API order", async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => [+ makeRelease("1.1.0", updaterAssets("Alook_1.1.0_aarch64.app.tar.gz")),+ makeRelease("3.0.0", [makeAsset("Alook_3.0.0_aarch64.app.tar.gz")]),+ makeRelease("2.0.0", updaterAssets("Alook_2.0.0_aarch64.app.tar.gz")),+ ],+ });+ mockFetch.mockResolvedValueOnce({ ok: true, text: async () => "signature" });- const res = await GET(- makeRequest("darwin", "aarch64", "2.0.0"),- makeParams("darwin", "aarch64", "2.0.0"),- );+ const res = await requestUpdate("darwin", "aarch64", "1.0.0");- expect(res.status).toBe(204);- });+ expect(res.status).toBe(200);+ expect((await res.json()).version).toBe("2.0.0");+ });- it("handles versions with different segment lengths", async () => {- mockFetch.mockResolvedValueOnce({- ok: true,- json: async () => [makeRelease("1.0.0.1")],- });- mockFetch.mockResolvedValueOnce({ ok: true, text: async () => "sig" });+ it("returns 502 when signature fetch fails", async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => [+ makeRelease("2.0.0", updaterAssets("Alook_2.0.0_aarch64.app.tar.gz")),+ ],+ });+ mockFetch.mockResolvedValueOnce({ ok: false });- const assets = [- { name: "app.app.tar.gz", browser_download_url: "https://example.com/app.tar.gz" },- { name: "app.app.tar.gz.sig", browser_download_url: "https://example.com/app.tar.gz.sig" },- ];- mockFetch.mockReset();- mockFetch.mockResolvedValueOnce({- ok: true,- json: async () => [makeRelease("1.0.0.1", assets)],- });- mockFetch.mockResolvedValueOnce({ ok: true, text: async () => "sig" });+ const res = await requestUpdate("darwin", "aarch64", "1.0.0");- const res = await GET(- makeRequest("darwin", "aarch64", "1.0.0"),- makeParams("darwin", "aarch64", "1.0.0"),- );+ expect(res.status).toBe(502);+ expect(await res.json()).toEqual({ error: "Failed to fetch update signature" });+ });- expect(res.status).toBe(200);- const body = await res.json();- expect(body.version).toBe("1.0.0.1");+ it("returns 502 when the signature body is empty", async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => [+ makeRelease("2.0.0", updaterAssets("Alook_2.0.0_amd64.AppImage")),+ ],});+ mockFetch.mockResolvedValueOnce({ ok: true, text: async () => " \n" });- it("equal versions return 204", async () => {- mockFetch.mockResolvedValueOnce({- ok: true,- json: async () => [makeRelease("1.2.3")],- });+ const res = await requestUpdate("linux", "x86_64", "1.0.0", "appimage");- const res = await GET(- makeRequest("darwin", "aarch64", "1.2.3"),- makeParams("darwin", "aarch64", "1.2.3"),- );+ expect(res.status).toBe(502);+ expect(await res.json()).toEqual({ error: "Update signature is empty" });+ });- expect(res.status).toBe(204);+ it("returns 204 when the current version is newer", async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => [+ makeRelease("1.0.0", updaterAssets("Alook_1.0.0_aarch64.app.tar.gz")),+ ],});++ expect((await requestUpdate("darwin", "aarch64", "2.0.0")).status).toBe(204);});});diff --git a/src/web/src/app/api/desktop/update/[target]/[arch]/[current_version]/route.ts b/src/web/src/app/api/desktop/update/[target]/[arch]/[current_version]/route.tsindex 78c64de52..93e053050 100644--- a/src/web/src/app/api/desktop/update/[target]/[arch]/[current_version]/route.ts+++ b/src/web/src/app/api/desktop/update/[target]/[arch]/[current_version]/route.ts@@ -4,33 +4,95 @@ const GITHUB_REPO = "alookai/alook";const TAG_PREFIX = "v";const CACHE_TTL = 300;-const PLATFORM_MAP: Record<string, string> = {- "darwin-aarch64": ".app.tar.gz",- "darwin-x86_64": ".app.tar.gz",- "linux-x86_64": ".AppImage.tar.gz",- "windows-x86_64": ".msi.zip",+interface PlatformSpec {+ suffix: string;+ architecture: RegExp;+}++const PLATFORM_MAP: Record<string, PlatformSpec> = {+ "darwin-aarch64-app": {+ suffix: ".app.tar.gz",+ architecture: /(?:^|[._-])aarch64(?:[._-]|$)/i,+ },+ "darwin-x86_64-app": {+ suffix: ".app.tar.gz",+ architecture: /(?:^|[._-])(?:x64|x86_64)(?:[._-]|$)/i,+ },+ "linux-x86_64-appimage": {+ suffix: ".AppImage",+ architecture: /(?:^|[._-])(?:amd64|x64|x86_64)(?:[._-]|$)/i,+ },+ "linux-x86_64-deb": {+ suffix: ".deb",+ architecture: /(?:^|[._-])(?:amd64|x64|x86_64)(?:[._-]|$)/i,+ },+ "linux-x86_64-rpm": {+ suffix: ".rpm",+ architecture: /(?:^|[._-])(?:amd64|x64|x86_64)(?:[._-]|$)/i,+ },+ "windows-x86_64-msi": {+ suffix: ".msi",+ architecture: /(?:^|[._-])(?:x64|x86_64)(?:[._-]|$)/i,+ },+ "windows-x86_64-nsis": {+ suffix: "-setup.exe",+ architecture: /(?:^|[._-])(?:x64|x86_64)(?:[._-]|$)/i,+ },};-function compareVersions(a: string, b: string): number {- const pa = a.split(".").map(Number);- const pb = b.split(".").map(Number);- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {- const na = pa[i] ?? 0;- const nb = pb[i] ?? 0;+interface GitHubAsset {+ name: string;+ browser_download_url: string;+}++function findPlatformBinary(assets: GitHubAsset[], spec: PlatformSpec) {+ return assets.find(+ (asset) =>+ !asset.name.endsWith(".sig") &&+ asset.name.endsWith(spec.suffix) &&+ spec.architecture.test(asset.name),+ );+}++function findPlatformAssets(assets: GitHubAsset[], spec: PlatformSpec) {+ const binary = findPlatformBinary(assets, spec);+ const signature = binary+ ? assets.find((asset) => asset.name === `${binary.name}.sig`)+ : undefined;+ return binary && signature ? { binary, signature } : null;+}++function parseStableSemver(version: string): [number, number, number] | null {+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(+ version,+ );+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;+}++function compareVersions(a: [number, number, number], b: [number, number, number]): number {+ for (let i = 0; i < 3; i++) {+ const na = a[i];+ const nb = b[i];if (na !== nb) return na - nb;}return 0;}export async function GET(- _req: Request,+ req: Request,{ params }: { params: Promise<{ target: string; arch: string; current_version: string }> },) {const { target, arch, current_version } = await params;- const platformKey = `${target}-${arch}`;+ const bundleType = new URL(req.url).searchParams.get("bundle_type");+ const platformKey = `${target}-${arch}-${bundleType}`;+ const platform = PLATFORM_MAP[platformKey];+ const currentVersion = parseStableSemver(current_version);+ if (!platform || !currentVersion) {+ return new NextResponse(null, { status: 204 });+ }const res = await fetch(- `https://api.github.com/repos/${GITHUB_REPO}/releases?per_page=10`,+ `https://api.github.com/repos/${GITHUB_REPO}/releases?per_page=100`,{headers: {Accept: "application/vnd.github.v3+json",@@ -48,56 +110,60 @@ export async function GET(tag_name: string;draft: boolean;prerelease: boolean;- assets: { name: string; browser_download_url: string }[];+ assets: GitHubAsset[];body: string | null;published_at: string | null;}const releases = (await res.json()) as GitHubRelease[];- const suffix = PLATFORM_MAP[platformKey];- if (!suffix) {- return new NextResponse(null, { status: 204 });- }-- const desktopRelease = releases.find(- (r) =>- !r.draft &&- !r.prerelease &&- r.tag_name?.startsWith(TAG_PREFIX) &&- r.assets.some((a) => a.name.endsWith(suffix) && !a.name.endsWith(".sig")),+ const candidates = releases.flatMap((release) => {+ if (release.draft || release.prerelease || !release.tag_name?.startsWith(TAG_PREFIX)) {+ return [];+ }+ const versionText = release.tag_name.slice(TAG_PREFIX.length);+ const version = parseStableSemver(versionText);+ const assets = findPlatformAssets(release.assets, platform);+ return version && assets ? [{ release, version, versionText, ...assets }] : [];+ });+ const desktopRelease = candidates.reduce<(typeof candidates)[number] | null>(+ (latest, candidate) =>+ !latest || compareVersions(candidate.version, latest.version) > 0 ? candidate : latest,+ null,);if (!desktopRelease) {return new NextResponse(null, { status: 204 });}- const latestVersion = desktopRelease.tag_name.replace(TAG_PREFIX, "");- if (compareVersions(latestVersion, current_version) <= 0) {+ if (compareVersions(desktopRelease.version, currentVersion) <= 0) {return new NextResponse(null, { status: 204 });}- const assets = desktopRelease.assets;- const binary = assets.find((a) => a.name.endsWith(suffix) && !a.name.endsWith(".sig"));- const sig = assets.find((a) => a.name.endsWith(`${suffix}.sig`));-- if (!binary || !sig) {- return new NextResponse(null, { status: 204 });+ let signature: string;+ try {+ const sigRes = await fetch(desktopRelease.signature.browser_download_url);+ if (!sigRes.ok) {+ return NextResponse.json({ error: "Failed to fetch update signature" }, { status: 502 });+ }+ signature = (await sigRes.text()).trim();+ } catch {+ return NextResponse.json({ error: "Failed to fetch update signature" }, { status: 502 });+ }+ if (!signature) {+ return NextResponse.json({ error: "Update signature is empty" }, { status: 502 });}-- const sigRes = await fetch(sig.browser_download_url);- const signature = sigRes.ok ? await sigRes.text() : "";const platforms: Record<string, { url: string; signature: string }> = {};platforms[platformKey] = {- url: binary.browser_download_url,+ url: desktopRelease.binary.browser_download_url,signature,};return NextResponse.json({- version: latestVersion,- notes: desktopRelease.body || "",- pub_date: desktopRelease.published_at,+ version: desktopRelease.versionText,+ notes: desktopRelease.release.body || "",+ pub_date: desktopRelease.release.published_at,platforms,},{diff --git a/src/web/src/components/community/machines/machine-list.test.ts b/src/web/src/components/community/machines/machine-list.test.tsindex 9eff4c8e8..5f3d10c69 100644--- a/src/web/src/components/community/machines/machine-list.test.ts+++ b/src/web/src/components/community/machines/machine-list.test.ts@@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({apiFetch: vi.fn(),toastSuccess: vi.fn(),toastError: vi.fn(),+ fetchLatestDaemonVersion: vi.fn(),}))vi.mock("sonner", () => ({@@ -69,12 +70,15 @@ vi.mock("@/lib/community-onboarding", () => ({updateCommunityOnboardingResources: vi.fn(),useCommunityOnboarding: () => "done",}))-vi.mock("@/lib/api/config", () => ({ fetchLatestCliVersion: vi.fn() }))+vi.mock("@/lib/api/config", () => ({+ fetchLatestDaemonVersion: mocks.fetchLatestDaemonVersion,+}))vi.mock("@/lib/utils", () => ({ getAppMode: () => "production" }))import type { CommunityMachineSummary } from "@alook/shared"import {canUpdateMachine,+ MachineList,MachineUpdateDialog,requestMachineUpdate,} from "./machine-list"@@ -95,6 +99,21 @@ describe("machine daemon update UI", () => {mocks.apiFetch.mockReset()mocks.toastSuccess.mockReset()mocks.toastError.mockReset()+ mocks.fetchLatestDaemonVersion.mockReset()+ mocks.fetchLatestDaemonVersion.mockResolvedValue({+ version: "0.1.8",+ package: "@alook/daemon",+ })+ })++ it("loads Community update eligibility from the daemon package endpoint", async () => {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(MachineList))+ })++ expect(mocks.fetchLatestDaemonVersion).toHaveBeenCalledOnce()+ act(() => renderer.unmount())})it("allows every remote controller mode and hides Update only in dev", () => {diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsxindex 0102ae1ba..41c840fa1 100644--- a/src/web/src/components/community/machines/machine-list.tsx+++ b/src/web/src/components/community/machines/machine-list.tsx@@ -26,7 +26,7 @@ import {AlertDialogCancel,} from "@/components/ui/alert-dialog"import { apiFetch, getErrorMessage } from "@/lib/api/client"-import { fetchLatestCliVersion } from "@/lib/api/config"+import { fetchLatestDaemonVersion } from "@/lib/api/config"import { getAppMode } from "@/lib/utils"import { machineName } from "@/lib/community/machine-name"import { MachineCard } from "./machine-card"@@ -155,7 +155,7 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {useEffect(() => {if (controllerMode === "dev") returnlet active = true- void fetchLatestCliVersion()+ void fetchLatestDaemonVersion().then(({ version }) => {if (active) setLatestVersion(version)})diff --git a/src/web/src/components/community/machines/pair-machine-sheet.test.ts b/src/web/src/components/community/machines/pair-machine-sheet.test.tsnew file mode 100644index 000000000..be741cc00--- /dev/null+++ b/src/web/src/components/community/machines/pair-machine-sheet.test.ts@@ -0,0 +1,208 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ apiFetch: vi.fn(),+ invoke: vi.fn(),+ isTauri: vi.fn(() => true),+ toastSuccess: vi.fn(),+ toastError: vi.fn(),+}))++vi.mock("@alook/shared", () => ({+ isDesktop: () => true,+ isTauri: mocks.isTauri,+ tauriInvoke: mocks.invoke,+}))++vi.mock("sonner", () => ({+ toast: { success: mocks.toastSuccess, error: mocks.toastError },+}))++vi.mock("@/lib/api/client", () => ({+ apiFetch: mocks.apiFetch,+ toastApiError: vi.fn(),+}))++vi.mock("@/lib/utils", () => ({+ isLocalMode: () => false,+ WS_DO_PORT_DEFAULT: 8788,+}))++vi.mock("@/components/ui/button", () => ({+ Button: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>+ React.createElement("button", props, children),+}))++vi.mock("@/components/ui/sheet", () => ({+ Sheet: ({ children }: React.PropsWithChildren) => React.createElement("div", {}, children),+ SheetContent: ({ children }: React.PropsWithChildren) => React.createElement("div", {}, children),+ SheetHeader: ({ children }: React.PropsWithChildren) => React.createElement("header", {}, children),+ SheetTitle: ({ children }: React.PropsWithChildren) => React.createElement("h2", {}, children),+ SheetDescription: ({ children }: React.PropsWithChildren) => React.createElement("p", {}, children),+ SheetBody: ({ children }: React.PropsWithChildren) => React.createElement("main", {}, children),+ SheetFooter: ({ children }: React.PropsWithChildren) => React.createElement("footer", {}, children),+ SheetClose: () => null,+}))++import { PairMachineSheet, PairMachineSteps } from "./pair-machine-sheet"+import { tid } from "@/lib/community/testids"++describe("PairMachineSheet desktop daemon integration", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal("location", { origin: "https://alook.ai" })+ mocks.isTauri.mockReturnValue(true)+ mocks.apiFetch.mockResolvedValue({ tokenId: "cmt_generated", expiresAt: "soon" })+ mocks.invoke.mockImplementation((command: string) => {+ if (command === "daemon_runtime_capability") {+ return Promise.resolve({ available: true, reason: null, nodeVersion: "v22.12.0" })+ }+ return Promise.resolve({ success: true, message: "Daemon paired and started" })+ })+ })++ it("probes and pairs once through Tauri while retaining the command fallback", async () => {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PairMachineSheet, {+ open: true,+ onOpenChange: vi.fn(),+ pendingTokenId: "cmt_desktop_token",+ setPendingTokenId: vi.fn(),+ connectedHostname: null,+ }))+ })++ const connect = renderer.root.findByProps({ "data-testid": tid.machinePairDesktopConnect })+ await act(async () => {+ await connect.props.onClick()+ })++ expect(mocks.invoke).toHaveBeenCalledWith("daemon_runtime_capability")+ expect(mocks.invoke).toHaveBeenCalledWith("daemon_pair", {+ machineKey: "cmt_desktop_token",+ })+ expect(mocks.invoke.mock.calls.filter(([command]) => command === "daemon_pair")).toHaveLength(1)+ expect(mocks.toastSuccess).toHaveBeenCalledWith("This computer is connecting")+ expect(renderer.root.findByProps({ "data-testid": tid.machinePairDesktopConnect }).props.disabled).toBe(true)+ expect(renderer.root.findByProps({ "data-testid": tid.machinePairCommand }).children.join(""))+ .toContain("@alook/daemon")+ })++ it("surfaces a daemon launch error without removing command and copy fallback", async () => {+ mocks.invoke.mockImplementation((command: string) => {+ if (command === "daemon_runtime_capability") {+ return Promise.resolve({ available: true, reason: null, nodeVersion: "v22.12.0" })+ }+ return Promise.resolve({ success: false, message: "The daemon couldn't start" })+ })+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PairMachineSheet, {+ open: true,+ onOpenChange: vi.fn(),+ pendingTokenId: "cmt_desktop_token",+ setPendingTokenId: vi.fn(),+ connectedHostname: null,+ }))+ })++ await act(async () => {+ await renderer.root.findByProps({ "data-testid": tid.machinePairDesktopConnect }).props.onClick()+ })++ expect(mocks.toastError).toHaveBeenCalledWith("The daemon couldn't start")+ expect(renderer.root.findByProps({ "data-testid": tid.machinePairRuntimeHint }).children.join(""))+ .toContain("terminal command remains available")+ expect(renderer.root.findByProps({ "data-testid": tid.machinePairCopy })).toBeTruthy()+ })++ it("surfaces a native string rejection without removing the fallback", async () => {+ mocks.invoke.mockImplementation((command: string) => {+ if (command === "daemon_runtime_capability") {+ return Promise.resolve({ available: true, reason: null, nodeVersion: "v16.0.0" })+ }+ return Promise.reject("Node.js 20.9 or newer is required by @alook/daemon")+ })+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PairMachineSheet, {+ open: true,+ onOpenChange: vi.fn(),+ pendingTokenId: "cmt_desktop_token",+ setPendingTokenId: vi.fn(),+ connectedHostname: null,+ }))+ })++ await act(async () => {+ await renderer.root.findByProps({ "data-testid": tid.machinePairDesktopConnect }).props.onClick()+ })++ expect(mocks.toastError).toHaveBeenCalledWith("Node.js 20.9 or newer is required by @alook/daemon")+ expect(renderer.root.findByProps({ "data-testid": tid.machinePairRuntimeHint }).children.join(""))+ .toContain("Node.js 20.9 or newer is required by @alook/daemon")+ expect(renderer.root.findByProps({ "data-testid": tid.machinePairCopy })).toBeTruthy()+ })++ it("keeps the command fallback and explains an unavailable Desktop runtime", async () => {+ mocks.invoke.mockResolvedValue({+ available: false,+ reason: "npx was not found. Install npm with Node.js and try again.",+ nodeVersion: "v16.0.0",+ })+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PairMachineSheet, {+ open: true,+ onOpenChange: vi.fn(),+ pendingTokenId: "cmt_desktop_token",+ setPendingTokenId: vi.fn(),+ connectedHostname: null,+ }))+ })++ expect(renderer.root.findAllByProps({ "data-testid": tid.machinePairDesktopConnect })).toHaveLength(0)+ expect(renderer.root.findByProps({ "data-testid": tid.machinePairRuntimeHint }).children.join(""))+ .toContain("npx was not found")+ expect(renderer.root.findByProps({ "data-testid": tid.machinePairCommand })).toBeTruthy()+ expect(renderer.root.findByProps({ "data-testid": tid.machinePairCopy })).toBeTruthy()+ })++ it("never invokes native commands in a normal browser", async () => {+ mocks.isTauri.mockReturnValue(false)+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PairMachineSheet, {+ open: true,+ onOpenChange: vi.fn(),+ pendingTokenId: "cmt_browser_token",+ setPendingTokenId: vi.fn(),+ connectedHostname: null,+ }))+ })++ expect(mocks.invoke).not.toHaveBeenCalled()+ expect(renderer.root.findByProps({ "data-testid": tid.machinePairCommand })).toBeTruthy()+ expect(renderer.root.findByProps({ "data-testid": tid.machinePairCopy })).toBeTruthy()+ expect(renderer.root.findAllByProps({ "data-testid": tid.machinePairDesktopConnect })).toHaveLength(0)+ })++ it("keeps the command copy surface in the reusable browser steps", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(PairMachineSteps, {+ command: "npx @alook/daemon daemon start",+ generating: false,+ onCopy: vi.fn(),+ connectedHostname: null,+ }))+ })++ expect(renderer.root.findByProps({ "data-testid": tid.machinePairCommand }).children.join(""))+ .toContain("@alook/daemon")+ expect(renderer.root.findAllByProps({ "data-testid": tid.machinePairDesktopConnect })).toHaveLength(0)+ })+})diff --git a/src/web/src/components/community/machines/pair-machine-sheet.tsx b/src/web/src/components/community/machines/pair-machine-sheet.tsxindex 2b704d131..d2058dfda 100644--- a/src/web/src/components/community/machines/pair-machine-sheet.tsx+++ b/src/web/src/components/community/machines/pair-machine-sheet.tsx@@ -3,6 +3,7 @@import { useCallback, useEffect, useRef, useState } from "react"import { toast } from "sonner"import { Copy, Loader2 } from "lucide-react"+import { isDesktop, isTauri, tauriInvoke } from "@alook/shared"import {Sheet,SheetContent,@@ -29,17 +30,34 @@ const isLocal = isLocalMode()// Only ever called once `pendingTokenId` is set, which happens from a// client-only effect — safe to touch `location` here (never runs during SSR).function buildPairCommand(machineKey: string): string {+ const { serverUrl, wsUrl } = pairEndpoints()+ const bin = isLocal ? "pnpm daemon" : "npx @alook/daemon daemon"+ return `${bin} start --machine-key ${machineKey} --server-url ${serverUrl} --ws-url ${wsUrl}`+}++function pairEndpoints(): { serverUrl: string; wsUrl: string } {const wsUrl = isLocal? `ws://localhost:${WS_DO_PORT_DEFAULT}`: `${location.origin.replace("http", "ws")}/api/ws/community-daemon`- const bin = isLocal ? "pnpm daemon" : "npx @alook/daemon daemon"- return `${bin} start --machine-key ${machineKey} --server-url ${location.origin} --ws-url ${wsUrl}`+ return { serverUrl: location.origin, wsUrl }}export type PairMachineSheetMode =| { kind: "pair" }| { kind: "reconnect"; machineId: string; hostname: string }+type DaemonRuntimeCapability = {+ available: boolean+ reason: string | null+ nodeVersion: string | null+}++function nativeErrorMessage(error: unknown, fallback: string): string {+ if (typeof error === "string" && error.trim()) return error.trim()+ if (error instanceof Error && error.message) return error.message+ return fallback+}+export function PairMachineSheet({open,onOpenChange,@@ -57,7 +75,14 @@ export function PairMachineSheet({}) {const isReconnect = mode.kind === "reconnect"const [generating, setGenerating] = useState(false)+ const [connecting, setConnecting] = useState(false)+ const [started, setStarted] = useState(false)+ const [checkingRuntime, setCheckingRuntime] = useState(false)+ const [runtimeCapability, setRuntimeCapability] = useState<DaemonRuntimeCapability | null>(null)+ const [launchError, setLaunchError] = useState<string | null>(null)const generatedForKey = useRef<string | null>(null)+ const connectingRef = useRef(false)+ const desktopNative = isTauri() && isDesktop()const generate = useCallback(async () => {setGenerating(true)@@ -93,10 +118,44 @@ export function PairMachineSheet({}if (generatedForKey.current === openKey) returngeneratedForKey.current = openKey+ setStarted(false)setPendingTokenId(null)void generate()}, [openKey, generate, setPendingTokenId])+ useEffect(() => {+ if (!open || !desktopNative) {+ setCheckingRuntime(false)+ setRuntimeCapability(null)+ return+ }+ let active = true+ setCheckingRuntime(true)+ setRuntimeCapability(null)+ setLaunchError(null)+ void tauriInvoke<DaemonRuntimeCapability>("daemon_runtime_capability")+ .then((capability) => {+ if (active) setRuntimeCapability(capability)+ })+ .catch((error) => {+ if (!active) return+ setRuntimeCapability({+ available: false,+ reason: nativeErrorMessage(+ error,+ "Alook couldn't check Node.js, npm, and npx on this computer.",+ ),+ nodeVersion: null,+ })+ })+ .finally(() => {+ if (active) setCheckingRuntime(false)+ })+ return () => {+ active = false+ }+ }, [open, desktopNative])+const command = pendingTokenId ? buildPairCommand(pendingTokenId) : ""const copyCommand = useCallback(async () => {@@ -109,6 +168,31 @@ export function PairMachineSheet({}}, [command])+ const connectDesktop = useCallback(async () => {+ if (!pendingTokenId || connectingRef.current || !runtimeCapability?.available) return+ connectingRef.current = true+ setConnecting(true)+ setLaunchError(null)+ try {+ const result = await tauriInvoke<{ success: boolean; message: string }>("daemon_pair", {+ machineKey: pendingTokenId,+ })+ if (!result.success) throw new Error(result.message || "The daemon did not start")+ setStarted(true)+ toast.success(isReconnect ? "Machine reconnected" : "This computer is connecting")+ } catch (error) {+ const message = nativeErrorMessage(+ error,+ "Couldn't start the daemon. Run the command below in a terminal instead.",+ )+ setLaunchError(message)+ toast.error(message)+ } finally {+ connectingRef.current = false+ setConnecting(false)+ }+ }, [pendingTokenId, runtimeCapability?.available, isReconnect])+return (<Sheet open={open} onOpenChange={onOpenChange}><SheetContent@@ -121,7 +205,7 @@ export function PairMachineSheet({</SheetTitle><SheetDescription>{isReconnect- ? "We rotated the key. Run the new command on your machine — the old one is no longer accepted."+ ? "We rotated the key. Run the new command before it expires — the old one is no longer accepted.": "Run this on the computer you want to connect. The key is good for 15 minutes."}</SheetDescription></SheetHeader>@@ -130,6 +214,13 @@ export function PairMachineSheet({command={command}generating={generating || !command}onCopy={copyCommand}+ desktopNative={desktopNative}+ checkingRuntime={checkingRuntime}+ runtimeCapability={runtimeCapability}+ launchError={launchError}+ connecting={connecting}+ started={started}+ onConnectDesktop={connectDesktop}connectedHostname={connectedHostname}/></SheetBody>@@ -151,6 +242,13 @@ export function PairMachineSteps({step1ClassName,step2ClassName,headingAs = "h3",+ desktopNative = false,+ checkingRuntime = false,+ runtimeCapability = null,+ launchError = null,+ connecting = false,+ started = false,+ onConnectDesktop,}: {command: stringgenerating: boolean@@ -161,14 +259,37 @@ export function PairMachineSteps({step1ClassName?: stringstep2ClassName?: stringheadingAs?: "h3" | "div"+ desktopNative?: boolean+ checkingRuntime?: boolean+ runtimeCapability?: DaemonRuntimeCapability | null+ launchError?: string | null+ connecting?: boolean+ started?: boolean+ onConnectDesktop?: () => void}) {return (<><div data-motion-target={step1MotionTarget} className={step1ClassName}>- <Step1 command={command} generating={generating} onCopy={onCopy} headingAs={headingAs} />+ <Step1+ command={command}+ generating={generating}+ onCopy={onCopy}+ headingAs={headingAs}+ desktopNative={desktopNative}+ checkingRuntime={checkingRuntime}+ runtimeCapability={runtimeCapability}+ launchError={launchError}+ connecting={connecting}+ started={started}+ onConnectDesktop={onConnectDesktop}+ /></div><div data-motion-target={step2MotionTarget} className={step2ClassName}>- <Step2 ready={Boolean(command)} connectedHostname={connectedHostname} headingAs={headingAs} />+ <Step2+ ready={desktopNative && runtimeCapability?.available ? started : Boolean(command)}+ connectedHostname={connectedHostname}+ headingAs={headingAs}+ /></div></>)@@ -179,11 +300,25 @@ function Step1({generating,onCopy,headingAs: Heading,+ desktopNative,+ checkingRuntime,+ runtimeCapability,+ launchError,+ connecting,+ started,+ onConnectDesktop,}: {command: stringgenerating: booleanonCopy: () => voidheadingAs: "h3" | "div"+ desktopNative: boolean+ checkingRuntime: boolean+ runtimeCapability: DaemonRuntimeCapability | null+ launchError: string | null+ connecting: boolean+ started: boolean+ onConnectDesktop?: () => void}) {return (<section className="flex flex-col gap-3">@@ -195,7 +330,7 @@ function Step1({</header><p className="text-sm text-muted-foreground">Open a terminal on the computer you want to connect, paste the command,- and hit enter. Node 20+ is the only prerequisite.+ and hit enter. Node.js with npm and npx is required.</p>{generating ? (<div className="flex items-center gap-2 rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">@@ -203,19 +338,49 @@ function Step1({Preparing your command…</div>) : (- <div className="flex items-start gap-2 rounded-lg border bg-muted/30 p-3 font-mono text-xs">- <code data-testid={tid.machinePairCommand} className="flex-1 break-all">- {command}- </code>- <button- data-testid={tid.machinePairCopy}- onClick={onCopy}- className="grid size-6 shrink-0 place-items-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"- aria-label="Copy command"- >- <Copy className="size-3.5" />- </button>- </div>+ <>+ {desktopNative && (+ <div className="flex flex-col gap-2">+ {runtimeCapability?.available && (+ <Button+ data-testid={tid.machinePairDesktopConnect}+ onClick={onConnectDesktop}+ disabled={connecting || started}+ className="w-full"+ >+ {connecting && <Loader2 className="size-4 animate-spin" />}+ {connecting ? "Connecting…" : started ? "Daemon started" : "Connect this computer"}+ </Button>+ )}+ {(checkingRuntime || !runtimeCapability?.available || launchError) && (+ <p+ data-testid={tid.machinePairRuntimeHint}+ role={launchError || runtimeCapability?.reason ? "status" : undefined}+ className="text-sm text-muted-foreground"+ >+ {launchError+ ? `${launchError} The terminal command remains available below.`+ : checkingRuntime+ ? "Checking this computer for Node.js, npm, and npx…"+ : runtimeCapability?.reason ?? "Node.js, npm, and npx are required for one-click connection."}+ </p>+ )}+ </div>+ )}+ <div className="flex items-start gap-2 rounded-lg border bg-muted/30 p-3 font-mono text-xs">+ <code data-testid={tid.machinePairCommand} className="flex-1 break-all">+ {command}+ </code>+ <button+ data-testid={tid.machinePairCopy}+ onClick={onCopy}+ className="grid size-6 shrink-0 place-items-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"+ aria-label="Copy command"+ >+ <Copy className="size-3.5" />+ </button>+ </div>+ </>)}</section>)@@ -232,7 +397,7 @@ function Step2({}) {if (connectedHostname) {return (- <section className="flex flex-col gap-3">+ <section data-testid={tid.machinePairStatus} className="flex flex-col gap-3"><header className="flex items-center gap-2"><Marker n={2} done /><Heading className="font-heading text-sm font-medium leading-tight tracking-[-0.015em] text-foreground">@@ -252,7 +417,7 @@ function Step2({)}return (- <section className="flex flex-col gap-3">+ <section data-testid={tid.machinePairStatus} className="flex flex-col gap-3"><header className="flex items-center gap-2"><Marker n={2} muted={!ready} spinning={ready} /><Headingdiff --git a/src/web/src/components/connect-machine-steps.test.ts b/src/web/src/components/connect-machine-steps.test.tsnew file mode 100644index 000000000..e702f41ca--- /dev/null+++ b/src/web/src/components/connect-machine-steps.test.ts@@ -0,0 +1,59 @@+import React from "react";+import TestRenderer, { act } from "react-test-renderer";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ clipboardWrite: vi.fn(),+ toastSuccess: vi.fn(),+}));++vi.mock("@/lib/utils", () => ({+ cliCmd: () => "npx @alook/cli",+}));++vi.mock("sonner", () => ({+ toast: { success: mocks.toastSuccess },+}));++vi.mock("@/components/ui/button", () => ({+ Button: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>+ React.createElement("button", props, children),+}));++vi.mock("@/components/ui/tooltip", () => ({+ Tooltip: ({ children }: React.PropsWithChildren) => React.createElement("div", {}, children),+ TooltipTrigger: ({ children, render }: React.PropsWithChildren<{ render?: React.ReactElement }>) =>+ React.cloneElement(render ?? React.createElement("div"), {}, children),+ TooltipContent: ({ children }: React.PropsWithChildren) => React.createElement("span", {}, children),+}));++import { ConnectMachineSteps } from "./connect-machine-steps";++describe("ConnectMachineSteps", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal("navigator", { clipboard: { writeText: mocks.clipboardWrite } });+ });++ it("keeps the supported terminal registration path available", () => {+ let renderer!: TestRenderer.ReactTestRenderer;+ act(() => {+ renderer = TestRenderer.create(React.createElement(ConnectMachineSteps, {+ generatedToken: "machine_token",+ generatingToken: false,+ onGenerateToken: vi.fn(),+ registered: false,+ daemonOnline: false,+ }));+ });++ expect(renderer.root.findAllByType("button")).toHaveLength(1);+ expect(JSON.stringify(renderer.toJSON())).toContain("npx @alook/cli register --token machine_token");++ act(() => {+ renderer.root.findByType("button").props.onClick();+ });+ expect(mocks.clipboardWrite).toHaveBeenCalledWith("npx @alook/cli register --token machine_token");+ expect(mocks.toastSuccess).toHaveBeenCalledWith("Copied to clipboard");+ });+});diff --git a/src/web/src/components/connect-machine-steps.tsx b/src/web/src/components/connect-machine-steps.tsxindex 4ea7f6c56..9c0e0f6dc 100644--- a/src/web/src/components/connect-machine-steps.tsx+++ b/src/web/src/components/connect-machine-steps.tsx@@ -1,12 +1,11 @@"use client";-import { useRef, useEffect, useState } from "react";+import { useRef, useEffect } from "react";import { Button } from "@/components/ui/button";import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";-import { Check, Play, Loader2 } from "lucide-react";+import { Check } from "lucide-react";import { toast } from "sonner";-import { cliCmd, getAppMode } from "@/lib/utils";-import { isTauri, tauriInvoke } from "@alook/shared";+import { cliCmd } from "@/lib/utils";export function ConnectMachineSteps({generatedToken,@@ -22,21 +21,9 @@ export function ConnectMachineSteps({daemonOnline: boolean;}) {const hasTriggered = useRef(false);- const mode = getAppMode();- const isDesktopApp = mode === "desktop";- const [executing, setExecuting] = useState(false);- const [cliPrefix, setCliPrefix] = useState<string | null>(null);const connected = registered && daemonOnline;- useEffect(() => {- if (isDesktopApp && isTauri()) {- tauriInvoke<{ command: string; is_dev: boolean }>("get_cli_info")- .then((info) => setCliPrefix(info.command))- .catch(() => {});- }- }, [isDesktopApp]);-useEffect(() => {if (!generatedToken && !generatingToken && !hasTriggered.current) {hasTriggered.current = true;@@ -51,23 +38,6 @@ export function ConnectMachineSteps({toast.success("Copied to clipboard");};- const executeRegister = async () => {- if (!isTauri()) return;- setExecuting(true);- try {- const result = await tauriInvoke<{ success: boolean; message: string }>("register_cli", { token: generatedToken });- if (result.success) {- toast.success("Registered successfully");- } else {- toast.error(result.message || "Registration failed");- }- } catch {- toast.error("Failed to execute registration");- } finally {- setExecuting(false);- }- };-if (connected) {return (<div className="flex items-center gap-2 text-sm text-emerald-600">@@ -81,9 +51,7 @@ export function ConnectMachineSteps({<div className="space-y-3"><p className="text-sm font-medium">Connect a computer</p><p className="text-xs text-muted-foreground">- {isDesktopApp- ? "Click to register your machine with Alook."- : "Run this in your terminal to link your machine."}+ Run this in your terminal to link your machine.</p>{generatingToken ? (<div className="rounded-md bg-muted p-2 font-mono text-xs text-muted-foreground animate-pulse">@@ -91,40 +59,22 @@ export function ConnectMachineSteps({</div>) : generatedToken ? (<div className="space-y-2">- {isDesktopApp ? (- <Button- size="sm"- onClick={executeRegister}- disabled={executing}- className="w-full"- title={cliPrefix ? `${cliPrefix} register --token <token>` : undefined}+ <Tooltip>+ <TooltipTrigger+ render={+ <div+ className="rounded-md bg-muted p-2 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors break-all"+ onClick={copyRegister}+ />+ }>- {executing ? (- <><Loader2 className="size-3 animate-spin mr-1" /> Registering...</>- ) : (- <><Play className="size-3 mr-1" /> Register</>- )}- </Button>- ) : (- <>- <Tooltip>- <TooltipTrigger- render={- <div- className="rounded-md bg-muted p-2 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors break-all"- onClick={copyRegister}- />- }- >- {command}- </TooltipTrigger>- <TooltipContent>Click to copy</TooltipContent>- </Tooltip>- <Button size="sm" onClick={copyRegister} className="w-full">- Copy Command- </Button>- </>- )}+ {command}+ </TooltipTrigger>+ <TooltipContent>Click to copy</TooltipContent>+ </Tooltip>+ <Button size="sm" onClick={copyRegister} className="w-full">+ Copy Command+ </Button></div>) : null}</div>diff --git a/src/web/src/components/legacy-desktop-command-contract.test.ts b/src/web/src/components/legacy-desktop-command-contract.test.tsnew file mode 100644index 000000000..ba333f2f7--- /dev/null+++ b/src/web/src/components/legacy-desktop-command-contract.test.ts@@ -0,0 +1,29 @@+import { readdirSync, readFileSync } from "node:fs";+import { extname, join, relative } from "node:path";+import { describe, expect, it } from "vitest";++const sourceRoot = new URL("../", import.meta.url);+const removedCommands = ["get_cli_info", "register_cli", "daemon_start", "cli_update"];++function sourceFiles(directory: URL): URL[] {+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const child = new URL(`${entry.name}${entry.isDirectory() ? "/" : ""}`, directory);+ if (entry.isDirectory()) return sourceFiles(child);+ if (![".ts", ".tsx"].includes(extname(entry.name))) return [];+ if (entry.name.includes(".test.") || entry.name.includes(".spec.")) return [];+ return [child];+ });+}++describe("legacy desktop command contract", () => {+ it("does not invoke removed Tauri lifecycle commands from reachable web code", () => {+ const violations = sourceFiles(sourceRoot).flatMap((file) => {+ const source = readFileSync(file, "utf8");+ return removedCommands+ .filter((command) => source.includes(`tauriInvoke(\"${command}\"`) || source.includes(`tauriInvoke<`) && source.includes(`>(\"${command}\"`))+ .map((command) => `${relative(sourceRoot.pathname, file.pathname)}: ${command}`);+ });++ expect(violations).toEqual([]);+ });+});diff --git a/src/web/src/components/runtime-version-gate.tsx b/src/web/src/components/runtime-version-gate.tsxindex 5d2b143f9..d5a7a8d93 100644--- a/src/web/src/components/runtime-version-gate.tsx+++ b/src/web/src/components/runtime-version-gate.tsx@@ -3,7 +3,7 @@import { useEffect, useRef, useState } from "react";import { useAgentContext } from "@/contexts/agent-context";import { getMinCliVersion, triggerRuntimeUpdate } from "@/lib/api";-import { semverGte, isTauri, tauriInvoke } from "@alook/shared";+import { semverGte } from "@alook/shared";import { getAppMode, updateCmd } from "@/lib/utils";import {Dialog,@@ -59,22 +59,6 @@ export function RuntimeVersionGate() {if (outdatedMachines.size === 0) return null;const handleUpdate = async (rt: AgentRuntime) => {- if (mode === "desktop" && isTauri()) {- setUpdating((prev) => new Set(prev).add(rt.id));- try {- await tauriInvoke("cli_update");- toast.success("CLI updated");- } catch {- toast.error("Failed to update CLI");- } finally {- setUpdating((prev) => {- const next = new Set(prev);- next.delete(rt.id);- return next;- });- }- return;- }if (mode === "app") {setShowManualHint(true);return;diff --git a/src/web/src/components/tauri-theme-sync.test.ts b/src/web/src/components/tauri-theme-sync.test.tsnew file mode 100644index 000000000..d004aad6e--- /dev/null+++ b/src/web/src/components/tauri-theme-sync.test.ts@@ -0,0 +1,46 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ invoke: vi.fn(),+}));++vi.mock("@alook/shared", () => ({+ isDesktop: () => true,+ isTauri: () => true,+ tauriInvoke: mocks.invoke,+}));++vi.mock("next-themes", () => ({+ useTheme: () => ({ resolvedTheme: "dark" }),+}));++import { syncTauriWindowTheme } from "./tauri-theme-sync";++describe("syncTauriWindowTheme", () => {+ beforeEach(() => {+ mocks.invoke.mockReset();+ });++ it("closes the splash after applying the native theme", async () => {+ mocks.invoke.mockResolvedValue(undefined);++ await syncTauriWindowTheme(true);++ expect(mocks.invoke.mock.calls).toEqual([+ ["set_window_theme", { dark: true }],+ ["close_splashscreen"],+ ]);+ });++ it("still closes the splash when native theme application rejects", async () => {+ mocks.invoke+ .mockRejectedValueOnce(new Error("theme unavailable"))+ .mockResolvedValueOnce(undefined);++ await expect(syncTauriWindowTheme(false)).rejects.toThrow("theme unavailable");+ expect(mocks.invoke.mock.calls).toEqual([+ ["set_window_theme", { dark: false }],+ ["close_splashscreen"],+ ]);+ });+});diff --git a/src/web/src/components/tauri-theme-sync.tsx b/src/web/src/components/tauri-theme-sync.tsxindex 528771d0c..ab90c48a6 100644--- a/src/web/src/components/tauri-theme-sync.tsx+++ b/src/web/src/components/tauri-theme-sync.tsx@@ -4,6 +4,14 @@ import { useEffect } from "react";import { useTheme } from "next-themes";import { isTauri, isDesktop, tauriInvoke } from "@alook/shared";+export async function syncTauriWindowTheme(dark: boolean) {+ try {+ await tauriInvoke("set_window_theme", { dark });+ } finally {+ await tauriInvoke("close_splashscreen").catch(() => {});+ }+}+export function TauriThemeSync() {const { resolvedTheme } = useTheme();@@ -11,9 +19,7 @@ export function TauriThemeSync() {if (!isTauri() || !isDesktop()) return;if (!resolvedTheme) return;- tauriInvoke("set_window_theme", { dark: resolvedTheme === "dark" })- .then(() => tauriInvoke("close_splashscreen"))- .catch(() => {});+ void syncTauriWindowTheme(resolvedTheme === "dark").catch(() => {});}, [resolvedTheme]);return null;diff --git a/src/web/src/lib/api/config.ts b/src/web/src/lib/api/config.tsindex 70d419983..50b9fd0b4 100644--- a/src/web/src/lib/api/config.ts+++ b/src/web/src/lib/api/config.ts@@ -8,3 +8,6 @@ export const getMinCliVersion = () =>export const fetchLatestCliVersion = () =>apiFetch<{ version: string; package: string }>("/api/cli/latest-version");++export const fetchLatestDaemonVersion = () =>+ apiFetch<{ version: string; package: string }>("/api/daemon/latest-version");diff --git a/src/web/src/lib/api/index.ts b/src/web/src/lib/api/index.tsindex 3301bb199..83f0a5e36 100644--- a/src/web/src/lib/api/index.ts+++ b/src/web/src/lib/api/index.ts@@ -1,6 +1,6 @@export { apiFetch, wsQuery } from "./client";export { getMe } from "./me";-export { fetchModelOptions, getMinCliVersion, fetchLatestCliVersion } from "./config";+export { fetchModelOptions, getMinCliVersion, fetchLatestCliVersion, fetchLatestDaemonVersion } from "./config";export {listAgents,createAgent,diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 6502abf97..8a7c98115 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -21,6 +21,9 @@ export const tid = {machinePairOpen: "community-machine-pair-open",machinePairCommand: "community-machine-pair-command",machinePairCopy: "community-machine-pair-copy",+ machinePairDesktopConnect: "community-machine-pair-desktop-connect",+ machinePairRuntimeHint: "community-machine-pair-runtime-hint",+ machinePairStatus: "community-machine-pair-status",machineActions: (id: string) => `machine-actions-${id}`,machineUpdate: (id: string) => `machine-update-${id}`,machineUpdateConfirm: "machine-update-confirm",diff --git a/src/web/src/lib/npm.ts b/src/web/src/lib/npm.tsindex f3ccb899c..2e0677e3c 100644--- a/src/web/src/lib/npm.ts+++ b/src/web/src/lib/npm.ts@@ -10,8 +10,7 @@ function getPackageName(): string {return "@alook/cli"}-export async function fetchLatestCliVersion(): Promise<{ version: string; package: string } | null> {- const pkg = getPackageName()+async function fetchLatestPackageVersion(pkg: string): Promise<{ version: string; package: string } | null> {try {const res = await fetch(`https://registry.npmjs.org/${pkg}/latest`);if (!res.ok) return null;@@ -22,3 +21,11 @@ export async function fetchLatestCliVersion(): Promise<{ version: string; packagreturn null;}}++export function fetchLatestCliVersion(): Promise<{ version: string; package: string } | null> {+ return fetchLatestPackageVersion(getPackageName())+}++export function fetchLatestDaemonVersion(): Promise<{ version: string; package: string } | null> {+ return fetchLatestPackageVersion("@alook/daemon")+}