commit 4b2edf73188e5dc63cc6a1deb71c4c5eb0f87de2 Author: Bohdan Triapitsyn Date: Sun Dec 7 19:32:53 2025 +0200 Initial public release diff --git a/.env b/.env new file mode 100644 index 00000000..c0d66521 --- /dev/null +++ b/.env @@ -0,0 +1 @@ +NODE_ENV=development diff --git a/.github/workflows/opencode.yml b/.github/workflows/opencode.yml new file mode 100644 index 00000000..1f4ca012 --- /dev/null +++ b/.github/workflows/opencode.yml @@ -0,0 +1,29 @@ +name: opencode + +on: + issue_comment: + types: [created] + +jobs: + opencode: + if: | + contains(github.event.comment.body, ' /oc') || + startsWith(github.event.comment.body, '/oc') || + contains(github.event.comment.body, ' /opencode') || + startsWith(github.event.comment.body, '/opencode') + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + pull-requests: write + issues: write + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Run opencode + uses: sst/opencode/github@latest + env: + ZHIPU_API_KEY: ${{ secrets.ZHIPU_API_KEY }} + with: + model: zai-coding-plan/glm-4.6 \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..c6158055 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,269 @@ +name: Release + +on: + push: + tags: + - 'v*' + workflow_dispatch: + inputs: + version: + description: 'Version to release (e.g., 0.1.0)' + required: true + type: string + dry_run: + description: 'Dry run (skip publishing)' + required: false + default: false + type: boolean + +env: + CARGO_INCREMENTAL: 0 + RUST_BACKTRACE: short + +permissions: + contents: write + +jobs: + create-release: + runs-on: ubuntu-latest + outputs: + release_id: ${{ steps.create_release.outputs.id }} + release_upload_url: ${{ steps.create_release.outputs.upload_url }} + version: ${{ steps.get_version.outputs.version }} + steps: + - uses: actions/checkout@v4 + + - name: Get version + id: get_version + run: | + if [[ -n "${{ github.event.inputs.version }}" ]]; then + echo "version=${{ github.event.inputs.version }}" >> $GITHUB_OUTPUT + elif [[ "${{ github.ref }}" == refs/tags/* ]]; then + echo "version=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT + else + echo "version=0.0.0-dev" >> $GITHUB_OUTPUT + fi + + - name: Extract changelog for release + env: + VERSION: ${{ steps.get_version.outputs.version }} + run: | + node - <<'NODE' + const fs = require('fs'); + const version = process.env.VERSION; + const changelogPath = 'CHANGELOG.md'; + if (!fs.existsSync(changelogPath)) { + throw new Error('CHANGELOG.md not found; add it before releasing.'); + } + const changelog = fs.readFileSync(changelogPath, 'utf8'); + const sections = changelog.split(/^## /m); + const section = sections.find(s => s.startsWith('[' + version + ']')); + if (!section) { + throw new Error('Changelog section [' + version + '] not found. Add a section like "## [' + version + '] - YYYY-MM-DD".'); + } + const content = ('## ' + section).trim(); + fs.mkdirSync('artifacts', { recursive: true }); + fs.writeFileSync('artifacts/release-notes.md', content + '\n'); + NODE + + - name: Create GitHub Release + id: create_release + uses: softprops/action-gh-release@v2 + with: + tag_name: v${{ steps.get_version.outputs.version }} + draft: true + generate_release_notes: false + body_path: artifacts/release-notes.md + name: OpenChamber v${{ steps.get_version.outputs.version }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + build-desktop-macos: + needs: create-release + runs-on: macos-14 + steps: + - uses: actions/checkout@v4 + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'pnpm' + + - name: Install Rust stable + uses: dtolnay/rust-toolchain@stable + + - name: Rust cache + uses: swatinem/rust-cache@v2 + with: + workspaces: packages/desktop/src-tauri + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Install Apple Certificate + env: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + run: | + # Create temporary keychain + KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db + KEYCHAIN_PASSWORD=$(openssl rand -base64 32) + + security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH" + security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH" + security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH" + + # Import certificate + echo "$APPLE_CERTIFICATE" | base64 --decode > $RUNNER_TEMP/certificate.p12 + security import $RUNNER_TEMP/certificate.p12 \ + -P "$APPLE_CERTIFICATE_PASSWORD" \ + -A -t cert -f pkcs12 \ + -k "$KEYCHAIN_PATH" + + security list-keychain -d user -s "$KEYCHAIN_PATH" + security set-key-partition-list -S apple-tool:,apple:,codesign: \ + -s -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH" + + - name: Set up notarization credentials + env: + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + run: | + # Validate secrets are set + if [ -z "$APPLE_ID" ] || [ -z "$APPLE_TEAM_ID" ] || [ -z "$APPLE_PASSWORD" ]; then + echo "Error: Missing Apple notarization credentials" + exit 1 + fi + + xcrun notarytool store-credentials "openchamber-notarize" \ + --apple-id "$APPLE_ID" \ + --team-id "$APPLE_TEAM_ID" \ + --password "$APPLE_PASSWORD" + + - name: Build UI package + run: pnpm -C packages/ui run build + + - name: Build Desktop app + run: pnpm desktop:build + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + + - name: Prepare release artifacts + run: | + mkdir -p artifacts + VERSION="${{ needs.create-release.outputs.version }}" + + # Copy DMG + cp packages/desktop/src-tauri/target/release/bundle/dmg/*.dmg artifacts/ 2>/dev/null || true + + # Copy tar.gz and signature for updater + cp packages/desktop/src-tauri/target/release/bundle/macos/*.tar.gz artifacts/ 2>/dev/null || true + cp packages/desktop/src-tauri/target/release/bundle/macos/*.tar.gz.sig artifacts/ 2>/dev/null || true + + - name: Generate update manifest + run: | + VERSION="${{ needs.create-release.outputs.version }}" + + # Find the signature file + SIG_FILE=$(find artifacts -name "*.tar.gz.sig" | head -1) + if [ -f "$SIG_FILE" ]; then + SIGNATURE=$(cat "$SIG_FILE") + else + SIGNATURE="" + fi + + # Find the tar.gz file name + TAR_FILE=$(find artifacts -name "*.tar.gz" ! -name "*.sig" | head -1) + TAR_NAME=$(basename "$TAR_FILE" 2>/dev/null || echo "OpenChamber.app.tar.gz") + + cat > artifacts/latest.json << EOF + { + "version": "${VERSION}", + "notes": "See release notes at https://github.com/${{ github.repository }}/releases/tag/v${VERSION}", + "pub_date": "$(date -u +%Y-%m-%dT%H:%M:%SZ)", + "platforms": { + "darwin-aarch64": { + "signature": "${SIGNATURE}", + "url": "https://github.com/${{ github.repository }}/releases/download/v${VERSION}/${TAR_NAME}" + } + } + } + EOF + + echo "Generated latest.json:" + cat artifacts/latest.json + + - name: Upload release assets + uses: softprops/action-gh-release@v2 + with: + tag_name: v${{ needs.create-release.outputs.version }} + files: | + artifacts/*.dmg + artifacts/*.tar.gz + artifacts/*.tar.gz.sig + artifacts/latest.json + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + publish-npm: + needs: create-release + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'pnpm' + registry-url: 'https://registry.npmjs.org' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Build packages + run: pnpm run build + + - name: Create npm tarball + working-directory: packages/web + run: npm pack + + - name: Upload npm tarball to release + uses: softprops/action-gh-release@v2 + with: + tag_name: v${{ needs.create-release.outputs.version }} + files: packages/web/*.tgz + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish to npm + if: ${{ github.event.inputs.dry_run != 'true' }} + working-directory: packages/web + run: npm publish --access public + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + finalize-release: + needs: [create-release, build-desktop-macos, publish-npm] + runs-on: ubuntu-latest + steps: + - name: Publish release + uses: softprops/action-gh-release@v2 + with: + tag_name: v${{ needs.create-release.outputs.version }} + draft: false + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..4ac51bd5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# Logs +logs +*.log +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* + +node_modules +dist +dist-ssr +release +*.local +*.tgz +/npm +/tsc +/openchamber@* +local-dev* +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 00000000..a24992d1 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +lts diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..7d5d0c2f --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,138 @@ +# OpenChamber - AI Agent & Contributor Reference + +Technical reference for AI coding agents and human contributors working on this project. + +## Core Purpose + +Web and desktop interface for OpenCode AI coding agent. Provides cross-device continuity, remote accessibility, and a unified chat interface using the OpenCode API backend. + +## Tech Stack + +- **React 19.1.1**: Modern React with concurrent features +- **TypeScript 5.8.3**: Full type safety +- **Vite 7.1.2**: Build tool with HMR and proxy +- **Tailwind CSS v4.0.0**: Latest `@import` syntax +- **Zustand 5.0.8**: State management with persistence +- **@opencode-ai/sdk**: Official OpenCode SDK with typed endpoints and SSE +- **@remixicon/react**: Icon system +- **@radix-ui primitives**: Accessible component foundations + +## Architecture Overview (Monorepo) + +Workspaces: +- `packages/ui` - Shared UI components and stores +- `packages/web` - Web runtime, Express server, CLI +- `packages/desktop` - Tauri desktop app with native APIs + +### Core Components (UI) +In `packages/ui/src/components/`: ChatContainer, MessageList, ChatMessage, StreamingAnimatedText, ChatInput, FileAttachment, ModelControls, PermissionCard, SessionList, SessionSwitcherDialog, DirectoryTree, DirectoryExplorerDialog, MainLayout, Header, Sidebar, SettingsDialog, AgentsPage, CommandsPage, GitIdentitiesPage, ProvidersPage, SessionsPage, SettingsPage, CommandPalette, HelpDialog, ConfigUpdateOverlay, ContextUsageDisplay, ErrorBoundary, MemoryDebugPanel, MobileOverlayPanel, ThemeDemo, ThemeSwitcher. + +In `packages/ui/src/components/views/`: ChatView, GitView, DiffView, TerminalView. + +In `packages/ui/src/components/terminal/`: TerminalViewport + +### State Management (UI) +In `packages/ui/src/stores/`: ConfigStore, SessionStore, DirectoryStore, UIStore, FileStore, MessageStore, ContextStore, PermissionStore, AgentsStore, CommandsStore, GitIdentitiesStore, TerminalStore + +### OpenCode SDK Integration (UI) +In `packages/ui/src/lib/opencode/`: client.ts wrapper around `@opencode-ai/sdk` with directory-aware API calls, SDK methods (session.*, message.*, agent.*, provider.*, config.*, project.*, path.*), AsyncGenerator SSE streaming (2 retry attempts, 500ms->8s backoff), automatic directory parameter injection. + +In `packages/ui/src/hooks/`: useEventStream.ts for real-time SSE connection management. + +### Web Runtime (server/CLI) +Express server and CLI in `packages/web`: API adapters in `packages/web/src/api`, server in `packages/web/server/index.js` (git/terminal/config), UI bundle imported from `@openchamber/ui`. + +### Desktop Runtime (Tauri) +Native desktop app in `packages/desktop`: Tauri backend in `src-tauri/` (Rust), frontend API adapters in `src/api/` (settings, permissions, diagnostics, files, git, terminal, notifications, tools), bridge layer in `src/lib/` for Tauri IPC communication. + +## Development Commands + +### Code Validation +Always validate changes before committing: + +```bash +pnpm -r type-check # TypeScript validation +pnpm -r lint # ESLint checks +pnpm -r build # Production build +``` + +### Building +```bash +pnpm run build # Build all packages +pnpm run desktop:build # Build desktop app +``` + +## Key Patterns + +### Section-Based Navigation +Modular section architecture with dedicated pages and sidebars. Sections: Agents, Commands, Git Identities, Providers, Sessions, Settings. Independent state management and routing. + +### File Attachments +Drag-and-drop upload with 10MB limit (`FileAttachment.tsx`), Data URL encoding, type validation with fallbacks, integrated via `useFileStore.addAttachedFile()`. + +### Theme System +In `packages/ui/src/lib/theme/`: TypeScript-based themes (Flexoki Light and Dark), CSS variable generation, component-specific theming, Tailwind CSS v4 integration. + +### Typography System +In `packages/ui/src/lib/`: Semantic typography with 6 CSS variables, theme-independent scales. **CRITICAL**: Always use semantic typography classes, never hardcoded font sizes. + +### Streaming Architecture +SDK-managed SSE with AsyncGenerator, temp->real ID swap, pending-user guards, empty-response detection via `window.__opencodeDebug`. + +## Development Guidelines + +### Lint & Type Safety + +- Never land code that introduces new ESLint or TypeScript errors +- Run `pnpm run lint` and `pnpm run type-check` before finalizing changes +- Adding `eslint-disable` requires justification in a comment explaining why typing is impossible +- Do **not** use `any` or `unknown` casts as escape hatches; build narrow adapter interfaces instead +- Refactors or new features must keep existing lint/type baselines green + +### Theme Integration + +- Check theme definitions before adding colors or font sizes to new components +- Always use theme-defined typography classes, never hardcoded font sizes +- Reference existing theme colors instead of adding new ones +- Ensure new components support both light and dark themes +- Use theme-generated CSS variables for dynamic styling + +### Code Standards + +- **Functional components**: Exclusive use of function components with hooks +- **Custom hooks**: Extract logic for reusability +- **Type-first development**: Comprehensive TypeScript usage +- **Component composition**: Prefer composition over inheritance + +## Feature Implementation Map + +### Directory & File System +`packages/ui/src/components/session/`: DirectoryTree, DirectoryExplorerDialog +`packages/ui/src/stores/`: DirectoryStore +Backend: `packages/web/server/index.js` with `listLocalDirectory()`, `getFilesystemHome()` + +### Session Switcher +`SessionSwitcherDialog.tsx`: Collapsible date groups, mobile parity with MobileOverlayPanel, Git worktree and shared session chips, streaming indicators. + +### Settings & Configuration +`packages/ui/src/components/sections/`: AgentsPage, CommandsPage, GitIdentitiesPage, ProvidersPage, SessionsPage, SettingsPage +Related stores: useAgentsStore, useCommandsStore, useConfigStore, useGitIdentitiesStore + +### Git Operations +`packages/ui/src/components/views/`: GitView, DiffView +`packages/ui/src/stores/`: useGitIdentitiesStore +Backend: `packages/ui/src/lib/gitApi.ts` + `packages/web/server/index.js` (simple-git wrapper) + +### Terminal +`packages/ui/src/components/views/`: TerminalView +`packages/ui/src/components/terminal/`: TerminalViewport (Xterm.js with FitAddon) +`packages/ui/src/stores/`: useTerminalStore +Backend: `packages/web/server/index.js` (node-pty wrapper with SSE) + +### Theme System +`packages/ui/src/lib/theme/`: themes (2 definitions), cssGenerator, syntaxThemeGenerator +`packages/ui/src/components/providers/`: ThemeProvider + +### Mobile & UX +`packages/ui/src/components/ui/`: MobileOverlayPanel +`packages/ui/src/hooks/`: useEdgeSwipe, useChatScrollManager diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..6aec091b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +## [Unreleased] + +- Pending + +## [1.0.0] - 2025-12-07 + +- Initial public release of OpenChamber web and desktop packages in a unified monorepo. +- Added GitHub Actions release pipeline with macOS signing/notarization, npm publish, and release asset uploads. +- Introduced OpenCode agent chat experience with section-based navigation, theming, and session persistence. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..e14fcde9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,41 @@ +# Contributing to OpenChamber + +## Quick Start + +```bash +git clone https://github.com/btriapitsyn/openchamber.git +cd openchamber +pnpm install +pnpm run dev:web:full # Web development +pnpm run desktop:dev # Desktop development (Tauri) +``` + +## Before Submitting + +```bash +pnpm -r type-check # Must pass +pnpm -r lint # Must pass +pnpm -r build # Must succeed +``` + +## Code Style + +- Functional React components only +- TypeScript strict mode - no `any` without justification +- Use existing theme colors/typography - don't add new ones +- Components must support light and dark themes + +## Pull Requests + +1. Fork and create a branch +2. Make changes +3. Run validation commands above +4. Submit PR with clear description of what and why + +## Project Structure + +See [AGENTS.md](./AGENTS.md) for detailed architecture reference. + +## Questions? + +Open an issue. diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..6a962170 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Bohdan Triapitsyn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 00000000..213accfe --- /dev/null +++ b/README.md @@ -0,0 +1,86 @@ +# OpenChamber + +Web and desktop interface for the [OpenCode](https://opencode.ai) AI coding agent. Works alongside the OpenCode TUI. + +The OpenCode team is actively working on their own desktop app. I still decided to release this project as a fan-made alternative. + +It was entirely built with OpenCode tool - first with the TUI version, then with the first usable version of OpenChamber, which I then used to build the rest. + +The whole project was built entirely with AI coding agents under my supervision. It started as a hobby project and proof of concept that AI agents can create genuinely usable software. + +## Why use OpenChamber? + +- **Cross-device continuity**: Start in TUI, continue on tablet/phone, return to terminal - same session +- **Remote access**: Use OpenCode from anywhere via browser +- **Familiarity**: A visual alternative for developers who prefer GUI workflows + +## Features + +- Integrated terminal +- Git operations with identity management and AI commit message generation +- Beautiful themes (Flexoki Light/Dark) with dynamic CSS variable system +- Mobile-optimized with edge-swipe gestures, terminal control and optimizations all around +- Git worktrees operations with isolating sessions within them +- Memory optimizations with LRU eviction +- Rich permission cards with syntax-highlighted operation previews +- Smart tool visualization (inline diffs, file trees, results highlighting) +- Per-agent permission mode control (ask, allow, full) adjustable per-session +- Familiar diff viewer like you're used to in VSCode +- Built-in OpenCode agent/command management + +## Installation + +### CLI (Web Server) + +```bash +pnpm add -g openchamber + +openchamber # Start on port 3000 +openchamber --port 8080 # Custom port +openchamber --daemon # Background mode +openchamber --ui-password secret # Password-protect UI +openchamber stop # Stop server +``` + +### Desktop App (macOS) + +Download from [Releases](https://github.com/btriapitsyn/openchamber/releases). + +## Prerequisites + +- [OpenCode CLI](https://opencode.ai) installed and running (`opencode serve`) +- Node.js 20+ + +## Development + +```bash +git clone https://github.com/btriapitsyn/openchamber.git +cd openchamber +pnpm install + +pnpm run dev:web:full # Web development +pnpm run desktop:dev # Desktop development (Tauri) +pnpm run build # Production build +``` + +See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines. + +## Tech Stack + +React 19, TypeScript, Vite 7, Tailwind CSS v4, Zustand, Radix UI, @opencode-ai/sdk, Express, Tauri (desktop) + +## Acknowledgments + +Independent project, not affiliated with OpenCode team. + +**Special thanks to:** + +- [OpenCode](https://opencode.ai) - For the excellent API and extensible architecture +- [Flexoki](https://github.com/kepano/flexoki) - Beautiful color scheme by [Steph Ango](https://stephango.com/flexoki) +- [Tauri](https://github.com/tauri-apps/tauri) - Desktop application framework +- [David Hill](https://x.com/iamdavidhill) - who inspired me to release this without [overthinking](https://x.com/iamdavidhill/status/1993648326450020746?s=20) +- My wife, who created a beautiful firework animation for the app while testing it for the first time + +## License + +MIT diff --git a/components.json b/components.json new file mode 100644 index 00000000..73afbdbc --- /dev/null +++ b/components.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/index.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "iconLibrary": "lucide" +} \ No newline at end of file diff --git a/docs/.gitkeep b/docs/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 00000000..552d2124 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,23 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { globalIgnores } from 'eslint/config' + +export default tseslint.config([ + globalIgnores(['dist', '.openchamber']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs['recommended-latest'], + reactRefresh.configs.vite, + ], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + }, +]) diff --git a/fix-deprecation.js b/fix-deprecation.js new file mode 100644 index 00000000..059058e5 --- /dev/null +++ b/fix-deprecation.js @@ -0,0 +1,81 @@ +#!/usr/bin/env node + +/** + * Fix for http-proxy package util._extend deprecation warning + * This script patches the http-proxy package to use Object.assign instead of util._extend + */ + +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +function fixHttpProxyDeprecation() { + try { + // Find the http-proxy package in node_modules + const httpProxyDir = path.join(__dirname, 'node_modules', 'http-proxy', 'lib', 'http-proxy'); + const indexPath = path.join(httpProxyDir, 'index.js'); + const commonPath = path.join(httpProxyDir, 'common.js'); + + if (!fs.existsSync(indexPath) || !fs.existsSync(commonPath)) { + return; + } + + // Patch index.js + let needsPatch = false; + + if (fs.existsSync(indexPath)) { + let content = fs.readFileSync(indexPath, 'utf8'); + + let indexPatched = false; + + if (content.includes("require('util')._extend")) { + content = content.replace( + /extend\s*=\s*require\('util'\)\._extend,/, + "extend = Object.assign," + ); + indexPatched = true; + } + + if (content.includes("require('util').inherits")) { + content = content.replace( + /require\('util'\)\.inherits\((\w+),\s*(\w+)\);/, + "Object.setPrototypeOf($1.prototype, $2.prototype);" + ); + indexPatched = true; + } + + if (indexPatched) { + fs.writeFileSync(indexPath, content, 'utf8'); + needsPatch = true; + } + } + + // Patch common.js + if (fs.existsSync(commonPath)) { + let content = fs.readFileSync(commonPath, 'utf8'); + + let commonPatched = false; + + if (content.includes("require('util')._extend")) { + content = content.replace( + /extend\s*=\s*require\('util'\)\._extend,/, + "extend = Object.assign," + ); + commonPatched = true; + } + + if (commonPatched) { + fs.writeFileSync(commonPath, content, 'utf8'); + needsPatch = true; + } + } + } catch (error) { + // Silently handle errors - functionality is not affected + } +} + +// Run the fix +fixHttpProxyDeprecation(); \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 00000000..7b0b1675 --- /dev/null +++ b/package.json @@ -0,0 +1,118 @@ +{ + "name": "openchamber-monorepo", + "version": "1.0.0", + "description": "OpenChamber monorepo workspace for web, ui, and desktop runtimes", + "private": true, + "type": "module", + "packageManager": "pnpm@10.22.0", + "workspaces": [ + "packages/*" + ], + "engines": { + "node": ">=20.0.0" + }, + "keywords": [ + "opencode", + "ai", + "coding", + "openchamber", + "cli" + ], + "author": "Bohdan Triapitsyn", + "license": "MIT", + "scripts": { + "build": "pnpm --if-present run --recursive --filter \"./packages/*\" build", + "build:web": "pnpm -C packages/web run build", + "build:ui": "pnpm -C packages/ui run build", + "build:desktop": "pnpm -C packages/desktop run build", + "type-check": "pnpm --if-present run --recursive --filter \"./packages/*\" type-check", + "type-check:web": "pnpm -C packages/web run type-check", + "type-check:ui": "pnpm -C packages/ui run type-check", + "type-check:desktop": "pnpm -C packages/desktop run type-check", + "lint": "pnpm --if-present run --recursive --filter \"./packages/*\" lint", + "lint:web": "pnpm -C packages/web run lint", + "lint:ui": "pnpm -C packages/ui run lint", + "lint:desktop": "pnpm -C packages/desktop run lint", + "clean": "pnpm --if-present run --recursive --filter \"./packages/*\" clean", + "dev:web": "pnpm -C packages/web run build:watch", + "dev:web:server": "pnpm -C packages/web run dev:server:watch", + "dev:web:full": "concurrently -n \"api,build\" -c \"cyan,magenta\" \"pnpm -C packages/web run dev:server:watch\" \"pnpm -C packages/web run build:watch\"", + "start:web": "pnpm -C packages/web run start", + "pack:web": "pnpm -C packages/web pack --pack-destination .", + "desktop:start-cli": "node ./packages/desktop/scripts/opencode-cli.mjs start", + "desktop:stop-cli": "node ./packages/desktop/scripts/opencode-cli.mjs stop", + "desktop:dev": "node ./packages/desktop/scripts/desktop-dev.mjs", + "desktop:build": "pnpm -C packages/desktop build && pnpm -C packages/desktop tauri build", + "desktop:lint": "pnpm -C packages/desktop run lint && cargo fmt --manifest-path packages/desktop/src-tauri/Cargo.toml -- --check && cargo clippy --manifest-path packages/desktop/src-tauri/Cargo.toml -- -D warnings", + "desktop:type-check": "pnpm -C packages/desktop run type-check && cargo fmt --manifest-path packages/desktop/src-tauri/Cargo.toml -- --check && cargo clippy --manifest-path packages/desktop/src-tauri/Cargo.toml -- -D warnings", + "version:bump": "node scripts/bump-version.mjs", + "release:prepare": "pnpm run build && pnpm run type-check && pnpm run lint" + }, + "dependencies": { + "@fontsource/ibm-plex-mono": "^5.2.7", + "@fontsource/ibm-plex-sans": "^5.1.1", + "@heroui/scroll-shadow": "^2.3.18", + "@heroui/system": "^2.4.23", + "@heroui/theme": "^2.4.23", + "@ibm/plex": "^6.4.1", + "@opencode-ai/sdk": "^1.0.133", + "@radix-ui/react-collapsible": "^1.1.12", + "@radix-ui/react-dialog": "^1.1.15", + "@radix-ui/react-dropdown-menu": "^2.1.16", + "@radix-ui/react-scroll-area": "^1.2.10", + "@radix-ui/react-select": "^2.2.6", + "@radix-ui/react-separator": "^1.1.7", + "@radix-ui/react-slot": "^1.2.3", + "@radix-ui/react-toggle": "^1.1.10", + "@radix-ui/react-tooltip": "^1.2.8", + "@remixicon/react": "^4.7.0", + "@types/react-syntax-highlighter": "^15.5.13", + "@xterm/addon-fit": "^0.10.0", + "@xterm/xterm": "^5.3.0", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "cmdk": "^1.1.1", + "electron-context-menu": "^4.1.1", + "electron-store": "^11.0.2", + "express": "^5.1.0", + "http-proxy-middleware": "^3.0.5", + "next-themes": "^0.4.6", + "node-pty": "^1.0.0", + "react": "^19.1.1", + "react-dom": "^19.1.1", + "react-markdown": "^10.1.0", + "react-syntax-highlighter": "^15.6.6", + "remark-gfm": "^4.0.1", + "simple-git": "^3.28.0", + "sonner": "^2.0.7", + "strip-json-comments": "^5.0.3", + "tailwind-merge": "^3.3.1", + "yaml": "^2.8.1", + "zustand": "^5.0.8" + }, + "devDependencies": { + "@eslint/js": "^9.33.0", + "@tailwindcss/postcss": "^4.0.0", + "@types/node": "^24.3.1", + "@types/react": "^19.1.10", + "@types/react-dom": "^19.1.7", + "@vitejs/plugin-react": "^5.0.0", + "autoprefixer": "^10.4.21", + "concurrently": "^9.2.1", + "cors": "^2.8.5", + "cross-env": "^7.0.3", + "electron": "^38.2.0", + "electron-builder": "^24.13.3", + "eslint": "^9.33.0", + "eslint-plugin-react-hooks": "^5.2.0", + "eslint-plugin-react-refresh": "^0.4.20", + "globals": "^16.3.0", + "nodemon": "^3.1.7", + "tailwindcss": "^4.0.0", + "tsx": "^4.20.6", + "tw-animate-css": "^1.3.8", + "typescript": "~5.8.3", + "typescript-eslint": "^8.39.1", + "vite": "^7.1.2" + } +} diff --git a/packages/desktop/.gitignore b/packages/desktop/.gitignore new file mode 100644 index 00000000..1d5fa289 --- /dev/null +++ b/packages/desktop/.gitignore @@ -0,0 +1,14 @@ +# Vite build output +dist/ + +# Tauri build artifacts +src-tauri/target/ + +# Tauri generated code +src-tauri/gen/ + +# OpenCode CLI state tracking +.opencode-cli-state.json + +# OS-specific +.DS_Store diff --git a/packages/desktop/README.md b/packages/desktop/README.md new file mode 100644 index 00000000..a6b3a533 --- /dev/null +++ b/packages/desktop/README.md @@ -0,0 +1,36 @@ +# @openchamber/desktop + +Desktop application for the [OpenCode](https://opencode.ai) AI coding agent. Built with Tauri. + +## Installation + +Download from [Releases](https://github.com/btriapitsyn/openchamber/releases). + +Currently available for macOS (Apple Silicon). + +## Prerequisites + +- [OpenCode CLI](https://opencode.ai) installed + +## Features + +- Native macOS app with auto-updates +- Integrated terminal +- Git operations with identity management and AI commit message generation +- Beautiful themes (Flexoki Light/Dark) +- Rich permission cards with syntax-highlighted operation previews +- Smart tool visualization (inline diffs, file trees, results highlighting) +- Per-agent permission mode control + +## Development + +```bash +git clone https://github.com/btriapitsyn/openchamber.git +cd openchamber +pnpm install +pnpm run desktop:dev +``` + +## License + +MIT diff --git a/packages/desktop/index.html b/packages/desktop/index.html new file mode 100644 index 00000000..769ba619 --- /dev/null +++ b/packages/desktop/index.html @@ -0,0 +1,64 @@ + + + + + + + + OpenChamber Desktop + + + +
+
OpenChamber
+
+ + + diff --git a/packages/desktop/package.json b/packages/desktop/package.json new file mode 100644 index 00000000..7d646389 --- /dev/null +++ b/packages/desktop/package.json @@ -0,0 +1,38 @@ +{ + "name": "@openchamber/desktop", + "version": "1.0.0", + "private": true, + "type": "module", + "desktopPrerequisites": [ + "Rust stable toolchain (via rustup)", + "Xcode Command Line Tools installed", + "Tauri CLI installed (cargo install tauri-cli@^2)" + ], + "scripts": { + "tauri": "tauri", + "dev": "vite dev --host 127.0.0.1 --port 1421", + "build": "vite build", + "preview": "vite preview --host 127.0.0.1 --port 5051", + "type-check": "tsc --noEmit", + "lint": "eslint \"./src/**/*.{ts,tsx}\" --config ../../eslint.config.js" + }, + "dependencies": { + "@tauri-apps/plugin-notification": "^2.3.3", + "@tauri-apps/plugin-process": "^2", + "@tauri-apps/plugin-updater": "^2", + "@openchamber/ui": "workspace:*", + "react": "^19.1.1", + "react-dom": "^19.1.1" + }, + "devDependencies": { + "@tauri-apps/cli": "^2", + "@tauri-apps/api": "^2.9.1", + "@tauri-apps/plugin-dialog": "^2.4.2", + "@types/node": "^24.3.1", + "@types/react": "^19.1.10", + "@types/react-dom": "^19.1.7", + "@vitejs/plugin-react": "^5.0.0", + "typescript": "~5.8.3", + "vite": "^7.1.2" + } +} diff --git a/packages/desktop/public/ibm-plex-mono-latin-600-normal.woff2 b/packages/desktop/public/ibm-plex-mono-latin-600-normal.woff2 new file mode 100644 index 00000000..67aeeb01 Binary files /dev/null and b/packages/desktop/public/ibm-plex-mono-latin-600-normal.woff2 differ diff --git a/packages/desktop/public/ibm-plex-mono-latin-700-normal.woff2 b/packages/desktop/public/ibm-plex-mono-latin-700-normal.woff2 new file mode 100644 index 00000000..5d7ff0c5 Binary files /dev/null and b/packages/desktop/public/ibm-plex-mono-latin-700-normal.woff2 differ diff --git a/packages/desktop/scripts/desktop-dev.mjs b/packages/desktop/scripts/desktop-dev.mjs new file mode 100644 index 00000000..b5848cf7 --- /dev/null +++ b/packages/desktop/scripts/desktop-dev.mjs @@ -0,0 +1,88 @@ +#!/usr/bin/env node +import { spawn } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { startCli, stopCli } from './opencode-cli.mjs'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const repoRoot = path.resolve(__dirname, '../../..'); +const desktopDir = path.join(repoRoot, 'packages/desktop'); + +function spawnProcess(command, args, opts = {}) { + return spawn(command, args, { + cwd: repoRoot, + env: { ...process.env }, + stdio: 'inherit', + ...opts, + }); +} + +async function main() { + await startCli(); + + const tauriProcess = spawnProcess('pnpm', ['-C', desktopDir, 'tauri', 'dev']); + + let cleaning = false; + + const teardown = async (code) => { + if (cleaning) { + return; + } + cleaning = true; + + const stopChild = (child, label) => { + if (!child || child.killed) { + return; + } + try { + child.kill('SIGINT'); + } catch (error) { + console.warn(`[desktop:dev] Failed to stop ${label}:`, error); + } + }; + + stopChild(tauriProcess, 'Tauri dev process'); + + await stopCli({ silent: true }).catch((error) => { + console.warn('[desktop:dev] Failed to stop OpenCode CLI:', error); + }); + + process.exit(typeof code === 'number' ? code : 0); + }; + + const handleChildExit = (childName) => (code, signal) => { + if (code !== 0 || signal) { + console.warn(`[desktop:dev] ${childName} exited with code ${code ?? 'null'} signal ${signal ?? 'none'}.`); + } + teardown(code).catch((error) => { + console.error('[desktop:dev] Cleanup error:', error); + process.exit(code ?? 1); + }); + }; + + tauriProcess.on('exit', handleChildExit('Tauri dev process')); + const errorHandler = (label) => (error) => { + console.error(`[desktop:dev] Failed to start ${label}:`, error); + teardown(1).catch(() => process.exit(1)); + }; + + tauriProcess.on('error', errorHandler('Tauri dev process')); + + const signalExitCodes = { + SIGINT: 130, + SIGTERM: 143, + SIGQUIT: 131, + }; + + Object.entries(signalExitCodes).forEach(([signal, exitCode]) => { + process.on(signal, () => { + teardown(exitCode).catch(() => process.exit(exitCode)); + }); + }); +} + +main().catch((error) => { + console.error('[desktop:dev] Unexpected error:', error); + process.exit(1); +}); diff --git a/packages/desktop/scripts/opencode-cli.mjs b/packages/desktop/scripts/opencode-cli.mjs new file mode 100644 index 00000000..199fc967 --- /dev/null +++ b/packages/desktop/scripts/opencode-cli.mjs @@ -0,0 +1,237 @@ +#!/usr/bin/env node +import { spawn } from 'node:child_process'; +import { access, readFile, unlink, writeFile } from 'node:fs/promises'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const desktopDir = path.resolve(__dirname, '..'); +const stateFile = path.join(desktopDir, '.opencode-cli-state.json'); +const DEFAULT_BIN_CANDIDATES = [ + process.env.OPENCHAMBER_OPENCODE_PATH, + process.env.OPENCHAMBER_OPENCODE_BIN, + process.env.OPENCODE_PATH, + process.env.OPENCODE_BINARY, + '/opt/homebrew/bin/opencode', + '/usr/local/bin/opencode', + '/usr/bin/opencode', + path.join(os.homedir(), '.local/bin/opencode'), +].filter(Boolean); +const CLI_ARGS_ENV = process.env.OPENCHAMBER_OPENCODE_ARGS; +const DEFAULT_ARGS = CLI_ARGS_ENV + ? parseArgs(CLI_ARGS_ENV) + : ['api']; + +function parseArgs(raw) { + if (!raw || typeof raw !== 'string') { + return []; + } + const trimmed = raw.trim(); + if (!trimmed) { + return []; + } + if (trimmed.startsWith('[')) { + try { + const parsed = JSON.parse(trimmed); + if (Array.isArray(parsed) && parsed.every((item) => typeof item === 'string')) { + return parsed; + } + } catch { + // fall through to whitespace split + } + } + return trimmed.split(/\s+/g); +} + +async function fileExists(targetPath) { + try { + await access(targetPath, fs.constants.X_OK); + return true; + } catch { + return false; + } +} + +async function resolveCliPath() { + for (const candidate of DEFAULT_BIN_CANDIDATES) { + if (candidate && await fileExists(candidate)) { + return candidate; + } + } + + const envPath = process.env.PATH || ''; + for (const segment of envPath.split(path.delimiter)) { + const candidate = path.join(segment, 'opencode'); + if (await fileExists(candidate)) { + return candidate; + } + } + + throw new Error('Unable to locate the OpenCode CLI. Set OPENCHAMBER_OPENCODE_PATH to the executable.'); +} + +async function readState() { + try { + const raw = await readFile(stateFile, 'utf8'); + const data = JSON.parse(raw); + if (typeof data?.pid === 'number') { + return data; + } + } catch { + // ignore + } + return null; +} + +function isProcessAlive(pid) { + if (!pid || typeof pid !== 'number') { + return false; + } + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function writeState(pid) { + await writeFile(stateFile, JSON.stringify({ pid }), 'utf8'); +} + +async function removeStateFile() { + try { + await unlink(stateFile); + } catch { + // already removed + } +} + +function spawnCli(cliPath, args) { + const env = { + ...process.env, + OPENCHAMBER_OPENCODE_PORT: process.env.OPENCHAMBER_OPENCODE_PORT || process.env.OPENCODE_PORT || process.env.OPENCHAMBER_INTERNAL_PORT || '0', + }; + const cwd = process.env.OPENCHAMBER_OPENCODE_CWD || process.cwd(); + + const child = spawn(cliPath, args.length > 0 ? args : DEFAULT_ARGS, { + cwd, + env, + detached: true, + stdio: 'ignore', + }); + + child.unref(); + return child; +} + +export async function startCli({ silent = false } = {}) { + const existing = await readState(); + if (existing?.pid && isProcessAlive(existing.pid)) { + if (!silent) { + console.log(`[desktop:start-cli] OpenCode CLI already running (pid ${existing.pid}).`); + } + return existing.pid; + } + + const cliPath = await resolveCliPath(); + const child = spawnCli(cliPath, DEFAULT_ARGS); + await writeState(child.pid); + if (!silent) { + console.log(`[desktop:start-cli] OpenCode CLI started (${cliPath}) pid ${child.pid}.`); + } + return child.pid; +} + +export async function stopCli({ silent = false } = {}) { + const state = await readState(); + if (!state?.pid) { + if (!silent) { + console.log('[desktop:stop-cli] No OpenCode CLI PID recorded.'); + } + return; + } + + const { pid } = state; + if (!isProcessAlive(pid)) { + await removeStateFile(); + if (!silent) { + console.log('[desktop:stop-cli] CLI already stopped.'); + } + return; + } + + try { + process.kill(pid, 'SIGTERM'); + } catch (error) { + if (!silent) { + console.error(`[desktop:stop-cli] Failed to send SIGTERM to pid ${pid}:`, error); + } + } + + const timeoutMs = 5000; + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + if (!isProcessAlive(pid)) { + await removeStateFile(); + if (!silent) { + console.log('[desktop:stop-cli] OpenCode CLI stopped.'); + } + return; + } + await new Promise((resolve) => setTimeout(resolve, 250)); + } + + try { + process.kill(pid, 'SIGKILL'); + if (!silent) { + console.warn(`[desktop:stop-cli] Forced termination sent to pid ${pid}.`); + } + } catch (error) { + if (!silent) { + console.error(`[desktop:stop-cli] Unable to terminate pid ${pid}:`, error); + } + } finally { + await removeStateFile(); + } +} + +async function main() { + const [, , command] = process.argv; + if (!command || command === '--help' || command === '-h') { + console.log('Usage: node opencode-cli.mjs '); + process.exit(0); + } + + if (command === 'start') { + await startCli(); + return; + } + if (command === 'stop') { + await stopCli(); + return; + } + if (command === 'status') { + const state = await readState(); + if (state?.pid && isProcessAlive(state.pid)) { + console.log(`OpenCode CLI running (pid ${state.pid}).`); + } else { + console.log('OpenCode CLI not running.'); + } + process.exit(0); + return; + } + + console.error(`Unknown command: ${command}`); + process.exit(1); +} + +if (import.meta.url === pathToFileURL(process.argv[1] || '').href) { + main().catch((error) => { + console.error('[desktop:opencode-cli] Unexpected error:', error); + process.exit(1); + }); +} diff --git a/packages/desktop/src-tauri/Cargo.lock b/packages/desktop/src-tauri/Cargo.lock new file mode 100644 index 00000000..74269d1e --- /dev/null +++ b/packages/desktop/src-tauri/Cargo.lock @@ -0,0 +1,6606 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" +dependencies = [ + "getrandom 0.2.16", + "once_cell", + "version_check", +] + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "android_log-sys" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84521a3cf562bc62942e294181d9eef17eb38ceb8c68677bc49f144e4c3d4f8d" + +[[package]] +name = "android_logger" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbb4e440d04be07da1f1bf44fb4495ebd58669372fe0cffa6e48595ac5bd88a3" +dependencies = [ + "android_log-sys", + "env_filter", + "log", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" + +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "ashpd" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cbdf310d77fd3aaee6ea2093db7011dc2d35d2eb3481e5607f1f8d942ed99df" +dependencies = [ + "enumflags2", + "futures-channel", + "futures-util", + "rand 0.9.2", + "raw-window-handle", + "serde", + "serde_repr", + "tokio", + "url", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "zbus", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-compression" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e86f6d3dc9dc4352edeea6b8e499e13e3f5dc3b964d7ca5fd411415a3498473" +dependencies = [ + "compression-codecs", + "compression-core", + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "async-executor" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "497c00e0fd83a72a79a39fcbd8e3e2f055d6f6c7e025f3b3d91f4f8e76527fb8" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd03604047cee9b6ce9de9f70c6cd540a0520c813cbd49bae61f33ab80ed1dc" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-recursion" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "async-signal" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43c070bbf59cd3570b6b2dd54cd772527c7c3620fce8be898406dd3ed6adc64c" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "atk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" +dependencies = [ + "atk-sys", + "glib", + "libc", +] + +[[package]] +name = "atk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "axum" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b098575ebe77cb6d14fc7f32749631a6e44edbef6b796f89b020e99ba20d425" +dependencies = [ + "axum-core", + "axum-macros", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59446ce19cd142f8833f856eb31f3eb097812d1479ab224f54d72428ca21ea22" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-macros" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +dependencies = [ + "serde_core", +] + +[[package]] +name = "bitvec" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.2", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.3", +] + +[[package]] +name = "blocking" +version = "1.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "borsh" +version = "1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8646f98db542e39fc66e68a20b2144f6a732636df7c2354e74645faaa433ce" +dependencies = [ + "borsh-derive", + "cfg_aliases 0.2.1", +] + +[[package]] +name = "borsh-derive" +version = "1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdd1d3c0c2f5833f22386f252fe8ed005c7f59fdcddeef025c01b4c3b9fd9ac3" +dependencies = [ + "once_cell", + "proc-macro-crate 3.4.0", + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "brotli" +version = "8.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + +[[package]] +name = "byte-unit" +version = "5.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cd29c3c585209b0cbc7309bfe3ed7efd8c84c21b7af29c8bfae908f8777174" +dependencies = [ + "rust_decimal", + "serde", + "utf8-width", +] + +[[package]] +name = "bytecheck" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2" +dependencies = [ + "bytecheck_derive", + "ptr_meta", + "simdutf8", +] + +[[package]] +name = "bytecheck_derive" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "bytemuck" +version = "1.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3" +dependencies = [ + "serde", +] + +[[package]] +name = "cairo-rs" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" +dependencies = [ + "bitflags 2.10.0", + "cairo-sys-rs", + "glib", + "libc", + "once_cell", + "thiserror 1.0.69", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "camino" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "276a59bf2b2c967788139340c9f0c5b12d7fd6630315c15c217e559de85d2609" +dependencies = [ + "serde_core", +] + +[[package]] +name = "cargo-platform" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" +dependencies = [ + "serde", +] + +[[package]] +name = "cargo_metadata" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" +dependencies = [ + "camino", + "cargo-platform", + "semver", + "serde", + "serde_json", + "thiserror 2.0.17", +] + +[[package]] +name = "cargo_toml" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77" +dependencies = [ + "serde", + "toml 0.9.8", +] + +[[package]] +name = "cc" +version = "1.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97463e1064cb1b1c1384ad0a0b9c8abd0988e2a91f52606c80ef14aadb63e36" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfb" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f" +dependencies = [ + "byteorder", + "fnv", + "uuid", +] + +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chrono" +version = "0.4.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link 0.2.1", +] + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "compression-codecs" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "302266479cb963552d11bd042013a58ef1adc56768016c8b82b4199488f2d4ad" +dependencies = [ + "brotli", + "compression-core", + "flate2", + "memchr", +] + +[[package]] +name = "compression-core" +version = "0.4.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75984efb6ed102a0d42db99afb6c1948f0380d1d91808d5529916e6c08b49d8d" + +[[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 = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "cookie" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +dependencies = [ + "time", + "version_check", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1" +dependencies = [ + "bitflags 2.10.0", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.10.0", + "core-foundation", + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cssparser" +version = "0.29.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f93d03419cb5950ccfd3daf3ff1c7a36ace64609a1a8746d493df1ca0afde0fa" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "matches", + "phf 0.10.1", + "proc-macro2", + "quote", + "smallvec", + "syn 1.0.109", +] + +[[package]] +name = "cssparser-macros" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" +dependencies = [ + "quote", + "syn 2.0.110", +] + +[[package]] +name = "ctor" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501" +dependencies = [ + "quote", + "syn 2.0.110", +] + +[[package]] +name = "darling" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.110", +] + +[[package]] +name = "darling_macro" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "deranged" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587" +dependencies = [ + "powerfmt", + "serde_core", +] + +[[package]] +name = "derive_arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "derive_more" +version = "0.99.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.110", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys 0.4.1", +] + +[[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.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.4.6", + "windows-sys 0.48.0", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.5.2", + "windows-sys 0.61.2", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89a09f22a6c6069a18470eb92d2298acf25463f14256d24778e1230d789a2aec" +dependencies = [ + "bitflags 2.10.0", + "block2 0.6.2", + "libc", + "objc2 0.6.3", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "dlib" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412" +dependencies = [ + "libloading 0.8.9", +] + +[[package]] +name = "dlopen2" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b54f373ccf864bf587a89e880fb7610f8d73f3045f13580948ccbcaff26febff" +dependencies = [ + "dlopen2_derive", + "libc", + "once_cell", + "winapi", +] + +[[package]] +name = "dlopen2_derive" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "788160fb30de9cdd857af31c6a2675904b16ece8fc2737b2c7127ba368c9d0f4" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +dependencies = [ + "serde", +] + +[[package]] +name = "dtoa" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6add3b8cff394282be81f3fc1a0605db594ed69890078ca6e2cab1c408bcf04" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "embed-resource" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55a075fc573c64510038d7ee9abc7990635863992f83ebc52c8b433b8411a02e" +dependencies = [ + "cc", + "memchr", + "rustc_version", + "toml 0.9.8", + "vswhom", + "winreg 0.55.0", +] + +[[package]] +name = "embed_plist" +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.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d8a32ae18130a3c84dd492d4215c3d913c3b07c6b63c2eb3eb7ff1101ab7bf" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "env_filter" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "erased-serde" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89e8918065695684b2b0702da20382d5ae6065cf3327bc2d6436bd49a71ce9f3" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "fern" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4316185f709b23713e41e3195f90edef7fb00c3ed4adc79769cf09cc762a3b29" +dependencies = [ + "log", +] + +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + +[[package]] +name = "filetime" +version = "0.2.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc0505cd1b6fa6580283f6bdf70a73fcf4aba1184038c90902b92b3dd0df63ed" +dependencies = [ + "cfg-if", + "libc", + "libredox", + "windows-sys 0.60.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844" + +[[package]] +name = "flate2" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfe33edd8e85a12a67454e37f8c75e730830d83e313556ab9ebf9ee7fbeb3bfb" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" +dependencies = [ + "mac", + "new_debug_unreachable", +] + +[[package]] +name = "futures-channel" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-executor" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "futures-sink" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "fxhash" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" +dependencies = [ + "byteorder", +] + +[[package]] +name = "gdk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" +dependencies = [ + "cairo-rs", + "gdk-pixbuf", + "gdk-sys", + "gio", + "glib", + "libc", + "pango", +] + +[[package]] +name = "gdk-pixbuf" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" +dependencies = [ + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", + "once_cell", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gdk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkwayland-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" +dependencies = [ + "gdk-sys", + "glib-sys", + "gobject-sys", + "libc", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkx11" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe" +dependencies = [ + "gdk", + "gdkx11-sys", + "gio", + "glib", + "libc", + "x11", +] + +[[package]] +name = "gdkx11-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" +dependencies = [ + "gdk-sys", + "glib-sys", + "libc", + "system-deps", + "x11", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.9.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "gio" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "gio-sys", + "glib", + "libc", + "once_cell", + "pin-project-lite", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "gio-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "winapi", +] + +[[package]] +name = "glib" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" +dependencies = [ + "bitflags 2.10.0", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "once_cell", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "glib-macros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" +dependencies = [ + "heck 0.4.1", + "proc-macro-crate 2.0.2", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "glib-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" +dependencies = [ + "libc", + "system-deps", +] + +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "gobject-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gtk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" +dependencies = [ + "atk", + "cairo-rs", + "field-offset", + "futures-channel", + "gdk", + "gdk-pixbuf", + "gio", + "glib", + "gtk-sys", + "gtk3-macros", + "libc", + "pango", + "pkg-config", +] + +[[package]] +name = "gtk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" +dependencies = [ + "atk-sys", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "gtk3-macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "html5ever" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b7410cae13cbc75623c98ac4cbfd1f0bedddf3227afc24f370cf0f50a44a11c" +dependencies = [ + "log", + "mac", + "markup5ever", + "match_token", +] + +[[package]] +name = "http" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "pin-utils", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52e9a2a24dc5c6821e71a7030e1e14b7b632acac55c40e9d2e082c621261bb56" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core 0.62.2", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ico" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc50b891e4acf8fe0e71ef88ec43ad82ee07b3810ad09de10f1d01f072ed4b98" +dependencies = [ + "byteorder", + "png", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e93fcd3157766c0c8da2f8cff6ce651a31f0810eaa1c51ec363ef790bbb5fb99" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02845b3647bb045f1100ecd6480ff52f34c35f82d9880e029d329c21d1054899" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6717a8d2a5a929a1a2eb43a12812498ed141a0bcfb7e8f7844fbdbe4303bba9f" +dependencies = [ + "equivalent", + "hashbrown 0.16.0", + "serde", + "serde_core", +] + +[[package]] +name = "infer" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7" +dependencies = [ + "cfb", +] + +[[package]] +name = "ipnet" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" + +[[package]] +name = "iri-string" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f867b9d1d896b67beb18518eda36fdb77a32ea590de864f1325b294a6d14397" +dependencies = [ + "memchr", + "serde", +] + +[[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.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "javascriptcore-rs" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" +dependencies = [ + "bitflags 1.3.2", + "glib", + "javascriptcore-rs-sys", +] + +[[package]] +name = "javascriptcore-rs-sys" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" + +[[package]] +name = "js-sys" +version = "0.3.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b011eec8cc36da2aab2d5cff675ec18454fad408585853910a202391cf9f8e65" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "json-patch" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08" +dependencies = [ + "jsonptr", + "serde", + "serde_json", + "thiserror 1.0.69", +] + +[[package]] +name = "jsonptr" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "keyboard-types" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a" +dependencies = [ + "bitflags 2.10.0", + "serde", + "unicode-segmentation", +] + +[[package]] +name = "kuchikiki" +version = "0.8.8-speedreader" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02cb977175687f33fa4afa0c95c112b987ea1443e5a51c8f8ff27dc618270cc2" +dependencies = [ + "cssparser", + "html5ever", + "indexmap 2.12.0", + "selectors", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libappindicator" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" +dependencies = [ + "glib", + "gtk", + "gtk-sys", + "libappindicator-sys", + "log", +] + +[[package]] +name = "libappindicator-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf" +dependencies = [ + "gtk-sys", + "libloading 0.7.4", + "once_cell", +] + +[[package]] +name = "libc" +version = "0.2.177" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link 0.2.1", +] + +[[package]] +name = "libredox" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" +dependencies = [ + "bitflags 2.10.0", + "libc", + "redox_syscall", +] + +[[package]] +name = "linux-raw-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" + +[[package]] +name = "litemap" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" +dependencies = [ + "value-bag", +] + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "mac" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" + +[[package]] +name = "mac-notification-sys" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65fd3f75411f4725061682ed91f131946e912859d0044d39c4ec0aac818d7621" +dependencies = [ + "cc", + "objc2 0.6.3", + "objc2-foundation 0.3.2", + "time", +] + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +dependencies = [ + "libc", +] + +[[package]] +name = "markup5ever" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a7213d12e1864c0f002f52c2923d4556935a43dec5e71355c2760e0f6e7a18" +dependencies = [ + "log", + "phf 0.11.3", + "phf_codegen 0.11.3", + "string_cache", + "string_cache_codegen", + "tendril", +] + +[[package]] +name = "match_token" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a9689d8d44bf9964484516275f5cd4c9b59457a6940c1d5d0ecbb94510a36b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "matches" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "minisign-verify" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e856fdd13623a2f5f2f54676a4ee49502a96a80ef4a62bcedd23d52427c44d43" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873" +dependencies = [ + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys 0.61.2", +] + +[[package]] +name = "muda" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c1738382f66ed56b3b9c8119e794a2e23148ac8ea214eda86622d4cb9d415a" +dependencies = [ + "crossbeam-channel", + "dpi", + "gtk", + "keyboard-types", + "objc2 0.6.3", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "png", + "serde", + "thiserror 2.0.17", + "windows-sys 0.60.2", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.10.0", + "jni-sys", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nix" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" +dependencies = [ + "bitflags 2.10.0", + "cfg-if", + "cfg_aliases 0.1.1", + "libc", +] + +[[package]] +name = "nix" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6" +dependencies = [ + "bitflags 2.10.0", + "cfg-if", + "cfg_aliases 0.2.1", + "libc", + "memoffset", +] + +[[package]] +name = "nodrop" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" + +[[package]] +name = "notify-rust" +version = "4.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6442248665a5aa2514e794af3b39661a8e73033b1cc5e59899e1276117ee4400" +dependencies = [ + "futures-lite", + "log", + "mac-notification-sys", + "serde", + "tauri-winrt-notification", + "zbus", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_enum" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1207a7e20ad57b847bbddc6776b968420d38292bbfe2089accff5e19e82454c" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff32365de1b6743cb203b710788263c44a03de03802daf96092f2da4fe6ba4d7" +dependencies = [ + "proc-macro-crate 3.4.0", + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "num_threads" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" +dependencies = [ + "libc", +] + +[[package]] +name = "objc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" +dependencies = [ + "malloc_buf", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c2599ce0ec54857b29ce62166b0ed9b4f6f1a70ccc9a71165b6154caca8c05" +dependencies = [ + "objc2-encode", + "objc2-exception-helper", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.10.0", + "block2 0.6.2", + "libc", + "objc2 0.6.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.10.0", + "objc2 0.6.3", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "bitflags 2.10.0", + "objc2 0.6.3", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.10.0", + "dispatch2", + "objc2 0.6.3", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.10.0", + "dispatch2", + "objc2 0.6.3", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2 0.6.3", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.10.0", + "objc2 0.6.3", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.10.0", + "objc2 0.6.3", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-exception-helper" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a" +dependencies = [ + "cc", +] + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.10.0", + "block2 0.5.1", + "libc", + "objc2 0.5.2", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.10.0", + "block2 0.6.2", + "libc", + "objc2 0.6.3", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.10.0", + "objc2 0.6.3", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-javascript-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a1e6550c4caed348956ce3370c9ffeca70bb1dbed4fa96112e7c6170e074586" +dependencies = [ + "objc2 0.6.3", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.10.0", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-osa-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0" +dependencies = [ + "bitflags 2.10.0", + "objc2 0.6.3", + "objc2-app-kit", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.10.0", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-metal", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.10.0", + "objc2 0.6.3", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-security" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a" +dependencies = [ + "bitflags 2.10.0", + "objc2 0.6.3", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.10.0", + "objc2 0.6.3", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-web-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" +dependencies = [ + "bitflags 2.10.0", + "block2 0.6.2", + "objc2 0.6.3", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-javascript-core", + "objc2-security", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "open" +version = "5.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43bb73a7fa3799b198970490a51174027ba0d4ec504b03cd08caf513d40024bc" +dependencies = [ + "dunce", + "is-wsl", + "libc", + "pathdiff", +] + +[[package]] +name = "openchamber-desktop" +version = "0.0.0" +dependencies = [ + "anyhow", + "axum", + "chrono", + "dirs 5.0.1", + "fastrand", + "futures-util", + "log", + "nix 0.28.0", + "objc", + "objc2 0.6.3", + "objc2-foundation 0.3.2", + "once_cell", + "parking_lot", + "portable-pty", + "portpicker", + "regex", + "reqwest", + "serde", + "serde_json", + "serde_yaml", + "tauri", + "tauri-build", + "tauri-plugin-dialog", + "tauri-plugin-fs", + "tauri-plugin-log", + "tauri-plugin-notification", + "tauri-plugin-shell", + "tauri-plugin-updater", + "tokio", + "tokio-util", + "tower-http 0.5.2", + "uuid", + "window-vibrancy 0.7.1", +] + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b" +dependencies = [ + "objc2 0.6.3", + "objc2-foundation 0.3.2", + "objc2-osa-kit", + "serde", + "serde_json", + "thiserror 2.0.17", +] + +[[package]] +name = "pango" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" +dependencies = [ + "gio", + "glib", + "libc", + "once_cell", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dfb61232e34fcb633f43d12c58f83c1df82962dcdfa565a4e866ffc17dafe12" +dependencies = [ + "phf_shared 0.8.0", +] + +[[package]] +name = "phf" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" +dependencies = [ + "phf_macros 0.10.0", + "phf_shared 0.10.0", + "proc-macro-hack", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros 0.11.3", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf_codegen" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbffee61585b0411840d3ece935cce9cb6321f01c45477d30066498cd5e1a815" +dependencies = [ + "phf_generator 0.8.0", + "phf_shared 0.8.0", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf_generator" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17367f0cc86f2d25802b2c26ee58a7b23faeccf78a396094c13dced0d0182526" +dependencies = [ + "phf_shared 0.8.0", + "rand 0.7.3", +] + +[[package]] +name = "phf_generator" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" +dependencies = [ + "phf_shared 0.10.0", + "rand 0.8.5", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand 0.8.5", +] + +[[package]] +name = "phf_macros" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58fdf3184dd560f160dd73922bea2d5cd6e8f064bf4b13110abd81b03697b4e0" +dependencies = [ + "phf_generator 0.10.0", + "phf_shared 0.10.0", + "proc-macro-hack", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "phf_shared" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c00cf8b9eafe68dde5e9eaa2cef8ee84a9336a47d566ec55ca16589633b65af7" +dependencies = [ + "siphasher 0.3.11", +] + +[[package]] +name = "phf_shared" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" +dependencies = [ + "siphasher 0.3.11", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher 1.0.1", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "piper" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "plist" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07" +dependencies = [ + "base64 0.22.1", + "indexmap 2.12.0", + "quick-xml 0.38.4", + "serde", + "time", +] + +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "portable-pty" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e" +dependencies = [ + "anyhow", + "bitflags 1.3.2", + "downcast-rs", + "filedescriptor", + "lazy_static", + "libc", + "log", + "nix 0.28.0", + "serial2", + "shared_library", + "shell-words", + "winapi", + "winreg 0.10.1", +] + +[[package]] +name = "portpicker" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be97d76faf1bfab666e1375477b23fde79eccf0276e9b63b92a39d676a889ba9" +dependencies = [ + "rand 0.8.5", +] + +[[package]] +name = "potential_utf" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + +[[package]] +name = "proc-macro-crate" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24" +dependencies = [ + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "proc-macro-crate" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983" +dependencies = [ + "toml_edit 0.23.7", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro-hack" +version = "0.5.20+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" + +[[package]] +name = "proc-macro2" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "ptr_meta" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1" +dependencies = [ + "ptr_meta_derive", +] + +[[package]] +name = "ptr_meta_derive" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "quick-xml" +version = "0.37.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb" +dependencies = [ + "memchr", +] + +[[package]] +name = "quick-xml" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" +dependencies = [ + "memchr", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases 0.2.1", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.17", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand 0.9.2", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.17", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases 0.2.1", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", +] + +[[package]] +name = "quote" +version = "1.0.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom 0.1.16", + "libc", + "rand_chacha 0.2.2", + "rand_core 0.5.1", + "rand_hc", + "rand_pcg", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.3", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core 0.5.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.3", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom 0.1.16", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.16", +] + +[[package]] +name = "rand_core" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core 0.5.1", +] + +[[package]] +name = "rand_pcg" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16abd0c1b639e9eb4d7c50c0b8100b0d0f849be2349829c740fe8e6eb4816429" +dependencies = [ + "rand_core 0.5.1", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.10.0", +] + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.16", + "libredox", + "thiserror 1.0.69", +] + +[[package]] +name = "redox_users" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +dependencies = [ + "getrandom 0.2.16", + "libredox", + "thiserror 2.0.17", +] + +[[package]] +name = "ref-cast" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "regex" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" + +[[package]] +name = "rend" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71fe3824f5629716b1589be05dacd749f6aa084c87e00e016714a8cdfccc997c" +dependencies = [ + "bytecheck", +] + +[[package]] +name = "reqwest" +version = "0.12.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f" +dependencies = [ + "async-compression", + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http 0.6.6", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "rfd" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2bee61e6cffa4635c72d7d81a84294e28f0930db0ddcb0f66d10244674ebed" +dependencies = [ + "ashpd", + "block2 0.6.2", + "dispatch2", + "glib-sys", + "gobject-sys", + "gtk-sys", + "js-sys", + "log", + "objc2 0.6.3", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.16", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rkyv" +version = "0.7.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9008cd6385b9e161d8229e1f6549dd23c3d022f132a2ea37ac3a10ac4935779b" +dependencies = [ + "bitvec", + "bytecheck", + "bytes", + "hashbrown 0.12.3", + "ptr_meta", + "rend", + "rkyv_derive", + "seahash", + "tinyvec", + "uuid", +] + +[[package]] +name = "rkyv_derive" +version = "0.7.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "503d1d27590a2b0a3a4ca4c94755aa2875657196ecbf401a42eff41d7de532c0" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "rust_decimal" +version = "1.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35affe401787a9bd846712274d97654355d21b2a2c092a3139aabe31e9022282" +dependencies = [ + "arrayvec", + "borsh", + "bytes", + "num-traits", + "rand 0.8.5", + "rkyv", + "serde", + "serde_json", +] + +[[package]] +name = "rustc-hash" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" +dependencies = [ + "bitflags 2.10.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "533f54bc6a7d4f647e46ad909549eda97bf5afc1585190ef692b4286b198bd8f" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94182ad936a0c91c324cd46c6511b9510ed16af436d7b5bab34beab0afd55f7a" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ffdfa2f5286e2247234e03f680868ac2815974dc39e00ea15adc445d0aafe52" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "indexmap 1.9.3", + "schemars_derive", + "serde", + "serde_json", + "url", + "uuid", +] + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9558e172d4e8533736ba97870c4b2cd63f84b382a3d6eb063da41b91cce17289" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.110", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "seahash" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" + +[[package]] +name = "selectors" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c37578180969d00692904465fb7f6b3d50b9a2b952b87c23d0e2e5cb5013416" +dependencies = [ + "bitflags 1.3.2", + "cssparser", + "derive_more", + "fxhash", + "log", + "phf 0.8.0", + "phf_codegen 0.8.0", + "precomputed-hash", + "servo_arc", + "smallvec", +] + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "serde_json" +version = "1.0.145" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", + "serde_core", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_repr" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_spanned" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e24345aa0fe688594e73770a5f6d1b216508b4f93484c0026d521acd30134392" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10574371d41b0d9b2cff89418eda27da52bcaff2cc8741db26382a77c29131f1" +dependencies = [ + "base64 0.22.1", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.12.0", + "schemars 0.9.0", + "schemars 1.1.0", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08a72d8216842fdd57820dc78d840bef99248e35fb2554ff923319e60f2d686b" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.12.0", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + +[[package]] +name = "serial2" +version = "0.2.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cc76fa68e25e771492ca1e3c53d447ef0be3093e05cd3b47f4b712ba10c6f3c" +dependencies = [ + "cfg-if", + "libc", + "winapi", +] + +[[package]] +name = "serialize-to-javascript" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5" +dependencies = [ + "serde", + "serde_json", + "serialize-to-javascript-impl", +] + +[[package]] +name = "serialize-to-javascript-impl" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "servo_arc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d52aa42f8fdf0fed91e5ce7f23d8138441002fa31dca008acf47e6fd4721f741" +dependencies = [ + "nodrop", + "stable_deref_trait", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "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 = "shared_library" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11" +dependencies = [ + "lazy_static", + "libc", +] + +[[package]] +name = "shell-words" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde" + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b" +dependencies = [ + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + +[[package]] +name = "siphasher" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" + +[[package]] +name = "slab" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" +dependencies = [ + "libc", + "windows-sys 0.60.2", +] + +[[package]] +name = "softbuffer" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18051cdd562e792cad055119e0cdb2cfc137e44e3987532e0f9659a77931bb08" +dependencies = [ + "bytemuck", + "cfg_aliases 0.2.1", + "core-graphics", + "foreign-types", + "js-sys", + "log", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", + "raw-window-handle", + "redox_syscall", + "wasm-bindgen", + "web-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "soup3" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" +dependencies = [ + "futures-channel", + "gio", + "glib", + "libc", + "soup3-sys", +] + +[[package]] +name = "soup3-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "string_cache" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.11.3", + "precomputed-hash", + "serde", +] + +[[package]] +name = "string_cache_codegen" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "swift-rs" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4057c98e2e852d51fdcfca832aac7b571f6b351ad159f9eda5db1655f8d0c4d7" +dependencies = [ + "base64 0.21.7", + "serde", + "serde_json", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.110" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a99801b5bd34ede4cf3fc688c5919368fea4e4814a4664359503e6015b280aea" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr", + "heck 0.5.0", + "pkg-config", + "toml 0.8.2", + "version-compare", +] + +[[package]] +name = "tao" +version = "0.34.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a753bdc39c07b192151523a3f77cd0394aa75413802c883a0f6f6a0e5ee2e7" +dependencies = [ + "bitflags 2.10.0", + "block2 0.6.2", + "core-foundation", + "core-graphics", + "crossbeam-channel", + "dispatch", + "dlopen2", + "dpi", + "gdkwayland-sys", + "gdkx11-sys", + "gtk", + "jni", + "lazy_static", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "objc2 0.6.3", + "objc2-app-kit", + "objc2-foundation 0.3.2", + "once_cell", + "parking_lot", + "raw-window-handle", + "scopeguard", + "tao-macros", + "unicode-segmentation", + "url", + "windows", + "windows-core 0.61.2", + "windows-version", + "x11-dl", +] + +[[package]] +name = "tao-macros" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4e16beb8b2ac17db28eab8bca40e62dbfbb34c0fcdc6d9826b11b7b5d047dfd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tar" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "tauri" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15524fc7959bfcaa051ba6d0b3fb1ef18e978de2176c7c6acb977f7fd14d35c7" +dependencies = [ + "anyhow", + "bytes", + "cookie", + "dirs 6.0.0", + "dunce", + "embed_plist", + "getrandom 0.3.4", + "glob", + "gtk", + "heck 0.5.0", + "http", + "jni", + "libc", + "log", + "mime", + "muda", + "objc2 0.6.3", + "objc2-app-kit", + "objc2-foundation 0.3.2", + "objc2-ui-kit", + "objc2-web-kit", + "percent-encoding", + "plist", + "raw-window-handle", + "reqwest", + "serde", + "serde_json", + "serde_repr", + "serialize-to-javascript", + "swift-rs", + "tauri-build", + "tauri-macros", + "tauri-runtime", + "tauri-runtime-wry", + "tauri-utils", + "thiserror 2.0.17", + "tokio", + "tray-icon", + "url", + "webkit2gtk", + "webview2-com", + "window-vibrancy 0.6.0", + "windows", +] + +[[package]] +name = "tauri-build" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17fcb8819fd16463512a12f531d44826ce566f486d7ccd211c9c8cebdaec4e08" +dependencies = [ + "anyhow", + "cargo_toml", + "dirs 6.0.0", + "glob", + "heck 0.5.0", + "json-patch", + "schemars 0.8.22", + "semver", + "serde", + "serde_json", + "tauri-utils", + "tauri-winres", + "toml 0.9.8", + "walkdir", +] + +[[package]] +name = "tauri-codegen" +version = "2.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa9844cefcf99554a16e0a278156ae73b0d8680bbc0e2ad1e4287aadd8489cf" +dependencies = [ + "base64 0.22.1", + "brotli", + "ico", + "json-patch", + "plist", + "png", + "proc-macro2", + "quote", + "semver", + "serde", + "serde_json", + "sha2", + "syn 2.0.110", + "tauri-utils", + "thiserror 2.0.17", + "time", + "url", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-macros" +version = "2.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3764a12f886d8245e66b7ee9b43ccc47883399be2019a61d80cf0f4117446fde" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.110", + "tauri-codegen", + "tauri-utils", +] + +[[package]] +name = "tauri-plugin" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "076c78a474a7247c90cad0b6e87e593c4c620ed4efdb79cbe0214f0021f6c39d" +dependencies = [ + "anyhow", + "glob", + "plist", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri-utils", + "toml 0.9.8", + "walkdir", +] + +[[package]] +name = "tauri-plugin-dialog" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "313f8138692ddc4a2127c4c9607d616a46f5c042e77b3722450866da0aad2f19" +dependencies = [ + "log", + "raw-window-handle", + "rfd", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "tauri-plugin-fs", + "thiserror 2.0.17", + "url", +] + +[[package]] +name = "tauri-plugin-fs" +version = "2.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47df422695255ecbe7bac7012440eddaeefd026656171eac9559f5243d3230d9" +dependencies = [ + "anyhow", + "dunce", + "glob", + "percent-encoding", + "schemars 0.8.22", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "tauri-utils", + "thiserror 2.0.17", + "toml 0.9.8", + "url", +] + +[[package]] +name = "tauri-plugin-log" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5709c792b8630290b5d9811a1f8fe983dd925fc87c7fc7f4923616458cd00b6" +dependencies = [ + "android_logger", + "byte-unit", + "fern", + "log", + "objc2 0.6.3", + "objc2-foundation 0.3.2", + "serde", + "serde_json", + "serde_repr", + "swift-rs", + "tauri", + "tauri-plugin", + "thiserror 2.0.17", + "time", +] + +[[package]] +name = "tauri-plugin-notification" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01fc2c5ff41105bd1f7242d8201fdf3efd70749b82fa013a17f2126357d194cc" +dependencies = [ + "log", + "notify-rust", + "rand 0.9.2", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "thiserror 2.0.17", + "time", + "url", +] + +[[package]] +name = "tauri-plugin-shell" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c374b6db45f2a8a304f0273a15080d98c70cde86178855fc24653ba657a1144c" +dependencies = [ + "encoding_rs", + "log", + "open", + "os_pipe", + "regex", + "schemars 0.8.22", + "serde", + "serde_json", + "shared_child", + "tauri", + "tauri-plugin", + "thiserror 2.0.17", + "tokio", +] + +[[package]] +name = "tauri-plugin-updater" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27cbc31740f4d507712550694749572ec0e43bdd66992db7599b89fbfd6b167b" +dependencies = [ + "base64 0.22.1", + "dirs 6.0.0", + "flate2", + "futures-util", + "http", + "infer", + "log", + "minisign-verify", + "osakit", + "percent-encoding", + "reqwest", + "semver", + "serde", + "serde_json", + "tar", + "tauri", + "tauri-plugin", + "tempfile", + "thiserror 2.0.17", + "time", + "tokio", + "url", + "windows-sys 0.60.2", + "zip", +] + +[[package]] +name = "tauri-runtime" +version = "2.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f766fe9f3d1efc4b59b17e7a891ad5ed195fa8d23582abb02e6c9a01137892" +dependencies = [ + "cookie", + "dpi", + "gtk", + "http", + "jni", + "objc2 0.6.3", + "objc2-ui-kit", + "objc2-web-kit", + "raw-window-handle", + "serde", + "serde_json", + "tauri-utils", + "thiserror 2.0.17", + "url", + "webkit2gtk", + "webview2-com", + "windows", +] + +[[package]] +name = "tauri-runtime-wry" +version = "2.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7950f3bde6bcca6655bc5e76d3d6ec587ceb81032851ab4ddbe1f508bdea2729" +dependencies = [ + "gtk", + "http", + "jni", + "log", + "objc2 0.6.3", + "objc2-app-kit", + "objc2-foundation 0.3.2", + "once_cell", + "percent-encoding", + "raw-window-handle", + "softbuffer", + "tao", + "tauri-runtime", + "tauri-utils", + "url", + "webkit2gtk", + "webview2-com", + "windows", + "wry", +] + +[[package]] +name = "tauri-utils" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a423c51176eb3616ee9b516a9fa67fed5f0e78baaba680e44eb5dd2cc37490" +dependencies = [ + "anyhow", + "brotli", + "cargo_metadata", + "ctor", + "dunce", + "glob", + "html5ever", + "http", + "infer", + "json-patch", + "kuchikiki", + "log", + "memchr", + "phf 0.11.3", + "proc-macro2", + "quote", + "regex", + "schemars 0.8.22", + "semver", + "serde", + "serde-untagged", + "serde_json", + "serde_with", + "swift-rs", + "thiserror 2.0.17", + "toml 0.9.8", + "url", + "urlpattern", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-winres" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1087b111fe2b005e42dbdc1990fc18593234238d47453b0c99b7de1c9ab2c1e0" +dependencies = [ + "dunce", + "embed-resource", + "toml 0.9.8", +] + +[[package]] +name = "tauri-winrt-notification" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b1e66e07de489fe43a46678dd0b8df65e0c973909df1b60ba33874e297ba9b9" +dependencies = [ + "quick-xml 0.37.5", + "thiserror 2.0.17", + "windows", + "windows-version", +] + +[[package]] +name = "tempfile" +version = "3.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16" +dependencies = [ + "fastrand", + "getrandom 0.3.4", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "tendril" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" +dependencies = [ + "futf", + "mac", + "utf-8", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" +dependencies = [ + "thiserror-impl 2.0.17", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "time" +version = "0.3.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d" +dependencies = [ + "deranged", + "itoa", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b" + +[[package]] +name = "time-macros" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "toml" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0dc8b1fb61449e27716ec0e1bdf0f6b8f3e8f6b05391e8497b8b6d7804ea6d8" +dependencies = [ + "indexmap 2.12.0", + "serde_core", + "serde_spanned 1.0.3", + "toml_datetime 0.7.3", + "toml_parser", + "toml_writer", + "winnow 0.7.13", +] + +[[package]] +name = "toml_datetime" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2cdb639ebbc97961c51720f858597f7f24c4fc295327923af55b74c3c724533" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap 2.12.0", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" +dependencies = [ + "indexmap 2.12.0", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.23.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6485ef6d0d9b5d0ec17244ff7eb05310113c3f316f2d14200d4de56b3cb98f8d" +dependencies = [ + "indexmap 2.12.0", + "toml_datetime 0.7.3", + "toml_parser", + "winnow 0.7.13", +] + +[[package]] +name = "toml_parser" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0cbe268d35bdb4bb5a56a2de88d0ad0eb70af5384a99d648cd4b3d04039800e" +dependencies = [ + "winnow 0.7.13", +] + +[[package]] +name = "toml_writer" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8b2b54733674ad286d16267dcfc7a71ed5c776e4ac7aa3c3e2561f7c637bf2" + +[[package]] +name = "tower" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" +dependencies = [ + "bitflags 2.10.0", + "bytes", + "http", + "http-body", + "http-body-util", + "pin-project-lite", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2" +dependencies = [ + "bitflags 2.10.0", + "bytes", + "futures-util", + "http", + "http-body", + "iri-string", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "tracing-core" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tray-icon" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3d5572781bee8e3f994d7467084e1b1fd7a93ce66bd480f8156ba89dee55a2b" +dependencies = [ + "crossbeam-channel", + "dirs 6.0.0", + "libappindicator", + "muda", + "objc2 0.6.3", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "once_cell", + "png", + "serde", + "thiserror 2.0.17", + "windows-sys 0.60.2", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "uds_windows" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89daebc3e6fd160ac4aa9fc8b3bf71e1f74fbf92367ae71fb83a037e8bf164b9" +dependencies = [ + "memoffset", + "tempfile", + "winapi", +] + +[[package]] +name = "unic-char-property" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" +dependencies = [ + "unic-char-range", +] + +[[package]] +name = "unic-char-range" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" + +[[package]] +name = "unic-common" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" + +[[package]] +name = "unic-ucd-ident" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987" +dependencies = [ + "unic-char-property", + "unic-char-range", + "unic-ucd-version", +] + +[[package]] +name = "unic-ucd-version" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" +dependencies = [ + "unic-common", +] + +[[package]] +name = "unicode-ident" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" + +[[package]] +name = "unicode-segmentation" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" + +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "urlpattern" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d" +dependencies = [ + "regex", + "serde", + "unic-ucd-ident", + "url", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8-width" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86bd8d4e895da8537e5315b8254664e6b769c4ff3db18321b297a1e7004392e3" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" +dependencies = [ + "getrandom 0.3.4", + "js-sys", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "value-bag" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "943ce29a8a743eb10d6082545d861b24f9d1b160b7d741e0f2cdf726bec909c5" + +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vswhom" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" +dependencies = [ + "libc", + "vswhom-sys", +] + +[[package]] +name = "vswhom-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da95793dfc411fbbd93f5be7715b0578ec61fe87cb1a42b12eb625caa5c5ea60" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "551f88106c6d5e7ccc7cd9a16f312dd3b5d36ea8b4954304657d5dfba115d4a0" +dependencies = [ + "cfg-if", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04264334509e04a7bf8690f2384ef5265f05143a4bff3889ab7a3269adab59c2" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "420bc339d9f322e562942d52e115d57e950d12d88983a14c79b86859ee6c7ebc" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.110", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76f218a38c84bcb33c25ec7059b07847d465ce0e0a76b995e134a45adcb6af76" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wayland-backend" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673a33c33048a5ade91a6b139580fa174e19fb0d23f396dca9fa15f2e1e49b35" +dependencies = [ + "cc", + "downcast-rs", + "rustix", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66a47e840dc20793f2264eb4b3e4ecb4b75d91c0dd4af04b456128e0bdd449d" +dependencies = [ + "bitflags 2.10.0", + "rustix", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efa790ed75fbfd71283bd2521a1cfdc022aabcc28bdcff00851f9e4ae88d9901" +dependencies = [ + "bitflags 2.10.0", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54cb1e9dc49da91950bdfd8b848c49330536d9d1fb03d4bfec8cae50caa50ae3" +dependencies = [ + "proc-macro2", + "quick-xml 0.37.5", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34949b42822155826b41db8e5d0c1be3a2bd296c747577a43a3e6daefc296142" +dependencies = [ + "dlib", + "log", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a1f95c0d03a47f4ae1f7a64643a6bb97465d9b740f0fa8f90ea33915c99a9a1" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webkit2gtk" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76b1bc1e54c581da1e9f179d0b38512ba358fb1af2d634a1affe42e37172361a" +dependencies = [ + "bitflags 1.3.2", + "cairo-rs", + "gdk", + "gdk-sys", + "gio", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", + "gtk", + "gtk-sys", + "javascriptcore-rs", + "libc", + "once_cell", + "soup3", + "webkit2gtk-sys", +] + +[[package]] +name = "webkit2gtk-sys" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62daa38afc514d1f8f12b8693d30d5993ff77ced33ce30cd04deebc267a6d57c" +dependencies = [ + "bitflags 1.3.2", + "cairo-sys-rs", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "gtk-sys", + "javascriptcore-rs-sys", + "libc", + "pkg-config", + "soup3-sys", + "system-deps", +] + +[[package]] +name = "webpki-roots" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2878ef029c47c6e8cf779119f20fcf52bde7ad42a731b2a304bc221df17571e" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webview2-com" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ba622a989277ef3886dd5afb3e280e3dd6d974b766118950a08f8f678ad6a4" +dependencies = [ + "webview2-com-macros", + "webview2-com-sys", + "windows", + "windows-core 0.61.2", + "windows-implement", + "windows-interface", +] + +[[package]] +name = "webview2-com-macros" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d228f15bba3b9d56dde8bddbee66fa24545bd17b48d5128ccf4a8742b18e431" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "webview2-com-sys" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36695906a1b53a3bf5c4289621efedac12b73eeb0b89e7e1a89b517302d5d75c" +dependencies = [ + "thiserror 2.0.17", + "windows", + "windows-core 0.61.2", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "window-vibrancy" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c" +dependencies = [ + "objc2 0.6.3", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "raw-window-handle", + "windows-sys 0.59.0", + "windows-version", +] + +[[package]] +name = "window-vibrancy" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010797bd7c40396fbc59d3105089fed0885fe267a0ef4a0a4646df54e28647f6" +dependencies = [ + "objc2 0.6.3", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "raw-window-handle", + "windows-sys 0.60.2", + "windows-version", +] + +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections", + "windows-core 0.61.2", + "windows-future", + "windows-link 0.1.3", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link 0.2.1", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-version" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "0.7.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" +dependencies = [ + "cfg-if", + "windows-sys 0.59.0", +] + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "writeable" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" + +[[package]] +name = "wry" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728b7d4c8ec8d81cab295e0b5b8a4c263c0d41a785fb8f8c4df284e5411140a2" +dependencies = [ + "base64 0.22.1", + "block2 0.6.2", + "cookie", + "crossbeam-channel", + "dirs 6.0.0", + "dpi", + "dunce", + "gdkx11", + "gtk", + "html5ever", + "http", + "javascriptcore-rs", + "jni", + "kuchikiki", + "libc", + "ndk", + "objc2 0.6.3", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-ui-kit", + "objc2-web-kit", + "once_cell", + "percent-encoding", + "raw-window-handle", + "sha2", + "soup3", + "tao-macros", + "thiserror 2.0.17", + "url", + "webkit2gtk", + "webkit2gtk-sys", + "webview2-com", + "windows", + "windows-core 0.61.2", + "windows-version", + "x11-dl", +] + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "x11" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix", +] + +[[package]] +name = "yoke" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b622b18155f7a93d1cd2dc8c01d2d6a44e08fb9ebb7b3f9e6ed101488bad6c91" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "nix 0.30.1", + "ordered-stream", + "serde", + "serde_repr", + "tokio", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 0.7.13", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cdb94821ca8a87ca9c298b5d1cbd80e2a8b67115d99f6e4551ac49e42b6a314" +dependencies = [ + "proc-macro-crate 3.4.0", + "proc-macro2", + "quote", + "syn 2.0.110", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7be68e64bf6ce8db94f63e72f0c7eb9a60d733f7e0499e628dfab0f84d6bcb97" +dependencies = [ + "serde", + "static_assertions", + "winnow 0.7.13", + "zvariant", +] + +[[package]] +name = "zerocopy" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "zip" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" +dependencies = [ + "arbitrary", + "crc32fast", + "indexmap 2.12.0", + "memchr", +] + +[[package]] +name = "zvariant" +version = "5.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2be61892e4f2b1772727be11630a62664a1826b62efa43a6fe7449521cb8744c" +dependencies = [ + "endi", + "enumflags2", + "serde", + "url", + "winnow 0.7.13", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da58575a1b2b20766513b1ec59d8e2e68db2745379f961f86650655e862d2006" +dependencies = [ + "proc-macro-crate 3.4.0", + "proc-macro2", + "quote", + "syn 2.0.110", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "3.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6949d142f89f6916deca2232cf26a8afacf2b9fdc35ce766105e104478be599" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 2.0.110", + "winnow 0.7.13", +] diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml new file mode 100644 index 00000000..74456b1f --- /dev/null +++ b/packages/desktop/src-tauri/Cargo.toml @@ -0,0 +1,52 @@ +[package] +name = "openchamber-desktop" +version = "1.0.0" +edition = "2021" +publish = false + +[lib] +name = "openchamber_desktop" +path = "src/lib.rs" + +[[bin]] +name = "openchamber-desktop" +path = "src/main.rs" + +[dependencies] +anyhow = "1.0.86" +axum = { version = "0.8.4", features = ["macros"] } +chrono = { version = "0.4", features = ["serde"] } +dirs = "5.0" +fastrand = "2.0" +futures-util = "0.3" +log = "0.4.28" +nix = { version = "0.28", features = ["signal"] } +objc = "0.2.7" +objc2 = "0.6.3" +objc2-foundation = { version = "0.3.2", features = ["NSProcessInfo", "NSString", "NSObjCRuntime"] } +once_cell = "1.19" +parking_lot = "0.12.3" +portable-pty = "0.9.0" +portpicker = "0.1.1" +regex = "1.10.4" +reqwest = { version = "0.12.4", default-features = false, features = ["json", "stream", "rustls-tls", "gzip", "brotli", "deflate"] } +serde = { version = "1.0.210", features = ["derive"] } +serde_json = "1.0.143" +serde_yaml = "0.9" +tauri = { version = "2.9.4", features = ["macos-private-api", "devtools" ] } +tauri-plugin-dialog = "2.4.2" +tauri-plugin-fs = "2.4.4" +tauri-plugin-log = "2.7.1" +tauri-plugin-shell = "2.3.3" +tokio = { version = "1.38", features = ["macros", "rt-multi-thread", "process", "signal", "sync", "time", "fs"] } +tower-http = { version = "0.5.2", features = ["cors"] } +uuid = { version = "1.18.1", features = ["v4"] } +tokio-util = { version = "0.7", features = ["io"] } +tauri-plugin-notification = "2.3.3" +tauri-plugin-updater = "2" + +[build-dependencies] +tauri-build = { version = "2.5.3", features = [] } + +[target.'cfg(target_os = "macos")'.dependencies] +window-vibrancy = "0.7.1" diff --git a/packages/desktop/src-tauri/Info.plist b/packages/desktop/src-tauri/Info.plist new file mode 100644 index 00000000..09babc54 --- /dev/null +++ b/packages/desktop/src-tauri/Info.plist @@ -0,0 +1,10 @@ + + + + + NSSupportsAutomaticTermination + + NSSupportsSuddenTermination + + + diff --git a/packages/desktop/src-tauri/build.rs b/packages/desktop/src-tauri/build.rs new file mode 100644 index 00000000..261851f6 --- /dev/null +++ b/packages/desktop/src-tauri/build.rs @@ -0,0 +1,3 @@ +fn main() { + tauri_build::build(); +} diff --git a/packages/desktop/src-tauri/capabilities/default.json b/packages/desktop/src-tauri/capabilities/default.json new file mode 100644 index 00000000..c6973567 --- /dev/null +++ b/packages/desktop/src-tauri/capabilities/default.json @@ -0,0 +1,42 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "default", + "description": "Default capabilities for OpenChamber desktop runtime", + "windows": ["main"], + "permissions": [ + "core:default", + "core:window:default", + "core:window:allow-close", + "core:window:allow-set-title", + "core:window:allow-set-size", + "core:window:allow-set-position", + "core:window:allow-start-dragging", + "core:webview:default", + "core:webview:allow-webview-close", + "shell:allow-open", + "shell:allow-execute", + "dialog:allow-open", + "dialog:allow-save", + "dialog:allow-message", + "dialog:allow-ask", + "dialog:allow-confirm", + "fs:allow-read-text-file", + "fs:allow-read-file", + "fs:allow-write-text-file", + "fs:allow-write-file", + "fs:allow-read-dir", + "fs:allow-exists", + "fs:allow-create", + "fs:allow-mkdir", + "fs:allow-remove", + "fs:scope-app-index", + "fs:scope-home", + "notification:default", + "notification:allow-is-permission-granted", + "notification:allow-request-permission", + "notification:allow-notify", + "updater:default", + "updater:allow-check", + "updater:allow-download-and-install" + ] +} diff --git a/packages/desktop/src-tauri/icons/app-icon-checkpoint.svg b/packages/desktop/src-tauri/icons/app-icon-checkpoint.svg new file mode 100644 index 00000000..a95cb607 --- /dev/null +++ b/packages/desktop/src-tauri/icons/app-icon-checkpoint.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/desktop/src-tauri/icons/app-icon.png b/packages/desktop/src-tauri/icons/app-icon.png new file mode 100644 index 00000000..2ca31187 Binary files /dev/null and b/packages/desktop/src-tauri/icons/app-icon.png differ diff --git a/packages/desktop/src-tauri/icons/app-icon.svg b/packages/desktop/src-tauri/icons/app-icon.svg new file mode 100644 index 00000000..0fb426bf --- /dev/null +++ b/packages/desktop/src-tauri/icons/app-icon.svg @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/packages/desktop/src-tauri/icons/icon-rgba.png b/packages/desktop/src-tauri/icons/icon-rgba.png new file mode 100644 index 00000000..11311999 Binary files /dev/null and b/packages/desktop/src-tauri/icons/icon-rgba.png differ diff --git a/packages/desktop/src-tauri/icons/icon.icns b/packages/desktop/src-tauri/icons/icon.icns new file mode 100644 index 00000000..932b0a9c Binary files /dev/null and b/packages/desktop/src-tauri/icons/icon.icns differ diff --git a/packages/desktop/src-tauri/icons/icon.png b/packages/desktop/src-tauri/icons/icon.png new file mode 100644 index 00000000..737b9f14 Binary files /dev/null and b/packages/desktop/src-tauri/icons/icon.png differ diff --git a/packages/desktop/src-tauri/src/assistant_notifications.rs b/packages/desktop/src-tauri/src/assistant_notifications.rs new file mode 100644 index 00000000..2fc1bb6c --- /dev/null +++ b/packages/desktop/src-tauri/src/assistant_notifications.rs @@ -0,0 +1,280 @@ +use std::{collections::HashSet, time::Duration}; + +use anyhow::Result; +use futures_util::TryStreamExt; +use log::{debug, info, warn}; +use reqwest::Client; +use serde::Deserialize; +use serde_json::Value; +use tauri::{AppHandle, Manager}; +use tauri_plugin_notification::NotificationExt; +use tokio::{io::AsyncBufReadExt, sync::Mutex}; +use tokio_util::io::StreamReader; + +use crate::DesktopRuntime; + +#[derive(Deserialize)] +struct EventEnvelope { + #[serde(rename = "type")] + event_type: String, + #[serde(default)] + properties: Value, +} + +pub fn spawn_assistant_notifications( + app: AppHandle, + runtime: DesktopRuntime, +) -> tauri::async_runtime::JoinHandle<()> { + tauri::async_runtime::spawn(async move { + let client = Client::builder() + // Give SSE a very long overall timeout so idle periods don't abort the stream. + .timeout(Duration::from_secs(24 * 60 * 60)) + .tcp_keepalive(Some(Duration::from_secs(30))) + .build() + .expect("failed to build reqwest client"); + + let mut shutdown_rx = runtime.subscribe_shutdown(); + let notified_messages = Mutex::new(HashSet::::new()); + + loop { + tokio::select! { + _ = shutdown_rx.recv() => { + info!("[desktop:notify] Shutdown received, stopping SSE listener"); + break; + } + _ = async { + if let Err(err) = run_once(&app, &runtime, &client, ¬ified_messages).await { + warn!("[desktop:notify] SSE loop error: {err:?}"); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } => {} + } + } + }) +} + +async fn run_once( + app: &AppHandle, + runtime: &DesktopRuntime, + client: &Client, + notified_messages: &Mutex>, +) -> Result<()> { + let opencode = runtime.opencode_manager(); + + let port = match opencode.current_port() { + Some(port) => port, + None => { + warn!("[desktop:notify] OpenCode port unavailable; will retry"); + tokio::time::sleep(Duration::from_secs(2)).await; + return Ok(()); + } + }; + + let prefix = opencode.api_prefix(); + let mut url = format!("http://127.0.0.1:{port}{}/event", prefix); + + if let Some(dir) = opencode.get_working_directory().to_str().map(|s| s.to_string()) { + let mut parsed = reqwest::Url::parse(&url)?; + parsed + .query_pairs_mut() + .append_pair("directory", &dir); + url = parsed.to_string(); + } + + debug!("[desktop:notify] Connecting SSE for notifications: {url}"); + + let response = client + .get(&url) + .header("accept", "text/event-stream") + .header("accept-encoding", "identity") + .send() + .await?; + + debug!( + "[desktop:notify] SSE response status={} headers={:?}", + response.status(), + response.headers() + ); + + if !response.status().is_success() { + warn!( + "[desktop:notify] SSE connect failed with status {}", + response.status() + ); + tokio::time::sleep(Duration::from_secs(2)).await; + return Ok(()); + } + + let stream = response + .bytes_stream() + .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err)); + let mut reader = StreamReader::new(stream); + let mut buf = Vec::new(); + let mut data_lines: Vec = Vec::new(); + + loop { + buf.clear(); + let bytes_read = match reader.read_until(b'\n', &mut buf).await { + Ok(n) => n, + Err(err) => { + warn!("[desktop:notify] Read error in SSE stream: {err:?}"); + return Err(err.into()); + } + }; + if bytes_read == 0 { + break; + } + + let line = match std::str::from_utf8(&buf) { + Ok(s) => s.trim_end_matches(&['\r', '\n'][..]).to_string(), + Err(err) => { + warn!("[desktop:notify] Non-UTF8 SSE chunk: {err}"); + continue; + } + }; + + if line.is_empty() { + if data_lines.is_empty() { + continue; + } + let raw = data_lines.join("\n"); + data_lines.clear(); + + match serde_json::from_str::(&raw) { + Ok(event) => handle_event(app, event, notified_messages).await, + Err(err) => { + warn!("[desktop:notify] Failed to parse SSE data: {err}; raw={raw}"); + } + } + continue; + } + + if let Some(rest) = line.strip_prefix("data:") { + data_lines.push(rest.trim_start().to_string()); + } + } + + Ok(()) +} + +async fn handle_event( + app: &AppHandle, + event: EventEnvelope, + notified_messages: &Mutex>, +) { + if event.event_type.as_str() != "message.updated" { + return; + } + + let Some(info) = event.properties.get("info") else { + return; + }; + + let role = info.get("role").and_then(Value::as_str).unwrap_or_default(); + if role != "assistant" { + return; + } + + let finish = info.get("finish").and_then(Value::as_str); + if finish != Some("stop") { + return; + } + + let message_id = match info.get("id").and_then(Value::as_str) { + Some(id) => id.to_string(), + None => return, + }; + + { + let mut notified = notified_messages.lock().await; + if notified.contains(&message_id) { + return; + } + notified.insert(message_id.clone()); + } + + let raw_mode = info + .get("mode") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .unwrap_or("agent"); + let raw_model = info + .get("modelID") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .unwrap_or("assistant"); + + let title = format!("{} agent is ready", format_mode(raw_mode)); + let body = format!("{} completed the task", format_model_id(raw_model)); + + let should_notify = app + .get_webview_window("main") + .map(|window| { + let focused = window.is_focused().unwrap_or(false); + let minimized = window.is_minimized().unwrap_or(false); + // Only notify when the app is not in the foreground or is minimized + !focused || minimized + }) + .unwrap_or(true); + + if should_notify { + let _ = app + .notification() + .builder() + .title(title) + .body(body) + .sound("Glass") + .show(); + } +} + +fn format_mode(raw: &str) -> String { + if raw.is_empty() { + return "Agent".to_string(); + } + raw.split(&['-', '_', ' '][..]) + .filter(|s| !s.is_empty()) + .map(capitalize) + .collect::>() + .join(" ") +} + +fn format_model_id(raw: &str) -> String { + if raw.is_empty() { + return "Assistant".to_string(); + } + + let tokens: Vec<&str> = raw.split(&['-', '_'][..]).collect(); + let mut result: Vec = Vec::new(); + let mut i = 0; + + while i < tokens.len() { + let current = tokens[i]; + + if current.chars().all(|c| c.is_ascii_digit()) { + if i + 1 < tokens.len() && tokens[i + 1].chars().all(|c| c.is_ascii_digit()) { + let combined = format!("{}.{}", current, tokens[i + 1]); + result.push(combined); + i += 2; + continue; + } + } + + result.push(current.to_string()); + i += 1; + } + + result + .into_iter() + .map(|part| capitalize(&part)) + .collect::>() + .join(" ") +} + +fn capitalize(s: &str) -> String { + let mut chars = s.chars(); + match chars.next() { + Some(first) => first.to_uppercase().collect::() + chars.as_str(), + None => String::new(), + } +} diff --git a/packages/desktop/src-tauri/src/commands/files.rs b/packages/desktop/src-tauri/src/commands/files.rs new file mode 100644 index 00000000..9969a690 --- /dev/null +++ b/packages/desktop/src-tauri/src/commands/files.rs @@ -0,0 +1,443 @@ +use crate::{DesktopRuntime, SettingsStore}; +use serde::Serialize; +use std::{ + collections::{HashSet, VecDeque}, + path::{Path, PathBuf}, + time::UNIX_EPOCH, +}; +use tokio::fs; + +const DEFAULT_FILE_SEARCH_LIMIT: usize = 60; +const MAX_FILE_SEARCH_LIMIT: usize = 400; +const FILE_SEARCH_MAX_CONCURRENCY: usize = 5; +const FILE_SEARCH_EXCLUDED_DIRS: &[&str] = &[ + "node_modules", + ".git", + "dist", + "build", + ".next", + ".turbo", + ".cache", + "coverage", + "tmp", + "logs", +]; + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileListEntry { + name: String, + path: String, + is_directory: bool, + is_file: bool, + is_symbolic_link: bool, + size: Option, + modified_time: Option, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DirectoryListResult { + directory: String, + path: String, + entries: Vec, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CreateDirectoryResponse { + success: bool, + path: String, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileSearchHit { + name: String, + path: String, + relative_path: String, + extension: Option, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchFilesResponse { + root: String, + count: usize, + files: Vec, +} + +#[derive(Debug)] +enum FsCommandError { + NotFound, + AccessDenied, + NotDirectory, + OutsideWorkspace, + Other(String), +} + +impl FsCommandError { + fn to_list_message(&self) -> String { + match self { + FsCommandError::NotFound => "Directory not found".to_string(), + FsCommandError::AccessDenied | FsCommandError::OutsideWorkspace => { + "Access to directory denied".to_string() + } + FsCommandError::NotDirectory => "Specified path is not a directory".to_string(), + FsCommandError::Other(message) => { + let _ = message; + "Failed to list directory".to_string() + } + } + } + + fn to_search_message(&self) -> String { + match self { + FsCommandError::NotFound => "Directory not found".to_string(), + FsCommandError::AccessDenied | FsCommandError::OutsideWorkspace => { + "Access to directory denied".to_string() + } + FsCommandError::NotDirectory => "Specified path is not a directory".to_string(), + FsCommandError::Other(message) => { + let _ = message; + "Failed to search files".to_string() + } + } + } + + fn to_create_message(&self) -> String { + match self { + FsCommandError::AccessDenied | FsCommandError::OutsideWorkspace => { + "Access to directory denied".to_string() + } + FsCommandError::NotDirectory => "Parent path must be a directory".to_string(), + FsCommandError::Other(message) => { + let _ = message; + "Failed to create directory".to_string() + } + FsCommandError::NotFound => "Parent directory not found".to_string(), + } + } +} + +impl From for FsCommandError { + fn from(error: std::io::Error) -> Self { + match error.kind() { + std::io::ErrorKind::NotFound => FsCommandError::NotFound, + std::io::ErrorKind::PermissionDenied => FsCommandError::AccessDenied, + _ => FsCommandError::Other(error.to_string()), + } + } +} + +#[tauri::command] +pub async fn list_directory( + path: Option, + state: tauri::State<'_, DesktopRuntime>, +) -> Result { + let workspace_root = resolve_workspace_root(state.settings()).await; + let resolved_path = resolve_sandboxed_path(path, workspace_root.as_ref()) + .await + .map_err(|err| err.to_list_message())?; + + let metadata = fs::metadata(&resolved_path) + .await + .map_err(|err| FsCommandError::from(err).to_list_message())?; + + if !metadata.is_dir() { + return Err(FsCommandError::NotDirectory.to_list_message()); + } + + // Re-check boundary after canonicalization to guard against traversal + if let Some(root) = &workspace_root { + if !resolved_path.starts_with(root) { + return Err(FsCommandError::OutsideWorkspace.to_list_message()); + } + } + + let mut entries = Vec::new(); + let mut dir_entries = fs::read_dir(&resolved_path) + .await + .map_err(|err| FsCommandError::from(err).to_list_message())?; + + while let Some(entry) = dir_entries + .next_entry() + .await + .map_err(|err| FsCommandError::from(err).to_list_message())? + { + let file_type = entry + .file_type() + .await + .map_err(|err| FsCommandError::from(err).to_list_message())?; + + let entry_path = entry.path(); + let name = entry.file_name().to_string_lossy().to_string(); + + let mut is_directory = file_type.is_dir(); + let is_symlink = file_type.is_symlink(); + + if !is_directory && is_symlink { + if let Ok(link_meta) = fs::metadata(&entry_path).await { + is_directory = link_meta.is_dir(); + } + } + + let metadata = fs::metadata(&entry_path).await.ok(); + let size = metadata + .as_ref() + .filter(|meta| meta.is_file()) + .map(|meta| meta.len()); + let modified_time = metadata + .and_then(|meta| meta.modified().ok()) + .and_then(|mtime| mtime.duration_since(UNIX_EPOCH).ok()) + .map(|duration| duration.as_millis() as i64); + + entries.push(FileListEntry { + name, + path: normalize_path(&entry_path), + is_directory, + is_file: file_type.is_file(), + is_symbolic_link: is_symlink, + size, + modified_time, + }); + } + + Ok(DirectoryListResult { + directory: normalize_path(&resolved_path), + path: normalize_path(&resolved_path), + entries, + }) +} + +#[tauri::command] +pub async fn search_files( + directory: Option, + query: Option, + max_results: Option, + state: tauri::State<'_, DesktopRuntime>, +) -> Result { + let workspace_root = resolve_workspace_root(state.settings()).await; + let resolved_root = resolve_sandboxed_path(directory, workspace_root.as_ref()) + .await + .map_err(|err| err.to_search_message())?; + + let limit = clamp_search_limit(max_results); + let normalized_query = query.unwrap_or_default().trim().to_lowercase(); + let match_all = normalized_query.is_empty(); + + let mut files = Vec::new(); + let mut queue = VecDeque::new(); + let mut visited = HashSet::new(); + + queue.push_back(resolved_root.clone()); + visited.insert(resolved_root.clone()); + + while !queue.is_empty() && files.len() < limit { + for _ in 0..FILE_SEARCH_MAX_CONCURRENCY { + let Some(dir) = queue.pop_front() else { + break; + }; + + let mut entries = match fs::read_dir(&dir).await { + Ok(entries) => entries, + Err(_) => continue, + }; + + while let Ok(Some(entry)) = entries.next_entry().await { + let Ok(file_type) = entry.file_type().await else { + continue; + }; + + let name = entry.file_name(); + let name_str = name.to_string_lossy(); + if name_str.is_empty() || name_str.starts_with('.') { + continue; + } + + let entry_path = entry.path(); + if file_type.is_dir() { + if should_skip_directory(&name_str) { + continue; + } + if visited.insert(entry_path.clone()) && files.len() < limit { + queue.push_back(entry_path); + } + continue; + } + + if !file_type.is_file() { + continue; + } + + let relative_path = relative_path(&resolved_root, &entry_path); + if !match_all { + let lowercase_name = name_str.to_lowercase(); + let lowercase_path = relative_path.to_lowercase(); + if !lowercase_name.contains(&normalized_query) + && !lowercase_path.contains(&normalized_query) + { + continue; + } + } + + let extension = entry_path + .extension() + .and_then(|ext| ext.to_str()) + .map(|ext| ext.to_lowercase()); + + files.push(FileSearchHit { + name: name_str.to_string(), + path: normalize_path(&entry_path), + relative_path: relative_path.replace('\\', "/"), + extension, + }); + + if files.len() >= limit { + break; + } + } + + if files.len() >= limit { + break; + } + } + } + + Ok(SearchFilesResponse { + root: normalize_path(&resolved_root), + count: files.len(), + files, + }) +} + +#[tauri::command] +pub async fn create_directory( + path: String, + state: tauri::State<'_, DesktopRuntime>, +) -> Result { + let trimmed = path.trim(); + if trimmed.is_empty() { + return Err("Path is required".to_string()); + } + + let workspace_root = resolve_workspace_root(state.settings()).await; + let resolved_path = resolve_creatable_path(trimmed, workspace_root.as_ref()) + .await + .map_err(|err| err.to_create_message())?; + + fs::create_dir_all(&resolved_path) + .await + .map_err(|err| FsCommandError::from(err).to_create_message())?; + + Ok(CreateDirectoryResponse { + success: true, + path: normalize_path(&resolved_path), + }) +} + +async fn resolve_sandboxed_path( + path: Option, + workspace_root: Option<&PathBuf>, +) -> Result { + let candidate_input = path + .as_ref() + .map(|value| value.trim()) + .filter(|value| !value.is_empty()); + + let candidate_path = match (candidate_input, workspace_root) { + (Some(value), _) => PathBuf::from(value), + (None, Some(root)) => root.clone(), + (None, None) => default_home_directory(), + }; + + let resolved = if candidate_path.is_absolute() { + candidate_path + } else if let Some(root) = workspace_root { + root.join(candidate_path) + } else { + default_home_directory().join(candidate_path) + }; + + let canonicalized = fs::canonicalize(&resolved) + .await + .map_err(FsCommandError::from)?; + + if let Some(root) = workspace_root { + if !canonicalized.starts_with(root) { + return Err(FsCommandError::OutsideWorkspace); + } + } + + Ok(canonicalized) +} + +async fn resolve_creatable_path( + path: &str, + workspace_root: Option<&PathBuf>, +) -> Result { + let candidate = PathBuf::from(path); + if candidate.as_os_str().is_empty() { + return Err(FsCommandError::Other("Path is required".to_string())); + } + + let absolute = if candidate.is_absolute() { + candidate + } else if let Some(root) = workspace_root { + root.join(candidate) + } else { + default_home_directory().join(candidate) + }; + + let parent = absolute.parent().ok_or(FsCommandError::NotDirectory)?; + + let canonical_parent = fs::canonicalize(parent) + .await + .map_err(FsCommandError::from)?; + + if let Some(root) = workspace_root { + if !canonical_parent.starts_with(root) { + return Err(FsCommandError::OutsideWorkspace); + } + } + + Ok(absolute) +} + +async fn resolve_workspace_root(settings: &SettingsStore) -> Option { + if let Ok(Some(last_dir)) = settings.last_directory().await { + if let Ok(canonicalized) = fs::canonicalize(&last_dir).await { + return Some(canonicalized); + } + } + None +} + +fn default_home_directory() -> PathBuf { + dirs::home_dir().unwrap_or_else(|| PathBuf::from("/")) +} + +fn clamp_search_limit(value: Option) -> usize { + let limit = value.unwrap_or(DEFAULT_FILE_SEARCH_LIMIT); + limit.clamp(1, MAX_FILE_SEARCH_LIMIT) +} + +fn should_skip_directory(name: &str) -> bool { + if name.starts_with('.') { + return true; + } + FILE_SEARCH_EXCLUDED_DIRS + .iter() + .any(|dir| dir.eq_ignore_ascii_case(name)) +} + +fn normalize_path(path: &Path) -> String { + path.to_string_lossy().replace('\\', "/") +} + +fn relative_path(root: &Path, target: &Path) -> String { + target + .strip_prefix(root) + .map(|relative| normalize_path(relative)) + .unwrap_or_else(|_| normalize_path(target)) +} diff --git a/packages/desktop/src-tauri/src/commands/git.rs b/packages/desktop/src-tauri/src/commands/git.rs new file mode 100644 index 00000000..a824b4e5 --- /dev/null +++ b/packages/desktop/src-tauri/src/commands/git.rs @@ -0,0 +1,1673 @@ +use crate::{DesktopRuntime, SettingsStore}; +use anyhow::{anyhow, Context, Result}; +use log::{error, info, warn}; +use regex::Regex; +use reqwest::Client; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::LazyLock; +use tauri::State; +use tokio::fs; +use tokio::process::Command; + +const GIT_IDENTITY_STORAGE_FILE: &str = "git-identities.json"; + +// --- Structs mirroring TypeScript types --- + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitStatusFile { + pub path: String, + pub index: String, + pub working_dir: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitStatus { + pub current: String, + pub tracking: Option, + pub ahead: i32, + pub behind: i32, + pub files: Vec, + pub is_clean: bool, + pub diff_stats: Option>, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct DiffStat { + pub insertions: i32, + pub deletions: i32, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitBranchDetails { + pub current: bool, + pub name: String, + pub commit: String, + pub label: String, + pub tracking: Option, + pub ahead: Option, + pub behind: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitBranch { + pub all: Vec, + pub current: String, + pub branches: HashMap, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitCommitSummary { + pub changes: i32, + pub insertions: i32, + pub deletions: i32, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitCommitResult { + pub success: bool, + pub commit: String, + pub branch: String, + pub summary: GitCommitSummary, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitPushResult { + pub success: bool, + pub pushed: Vec, + pub repo: String, + #[serde(rename = "ref")] + pub ref_: Option, // "ref" is a keyword in Rust +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitPushRef { + pub local: String, + pub remote: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitPullResult { + pub success: bool, + pub summary: GitCommitSummary, + pub files: Vec, + pub insertions: i32, + pub deletions: i32, +} + +fn parse_shortstat(output: &str) -> GitCommitSummary { + let mut summary = GitCommitSummary { + changes: 0, + insertions: 0, + deletions: 0, + }; + + for line in output + .split('\n') + .map(|line| line.trim()) + .filter(|line| !line.is_empty()) + { + for part in line.split(',') { + let token = part.trim(); + if token.is_empty() { + continue; + } + + if token.contains("file changed") { + if let Some(value) = token.split_whitespace().next() { + summary.changes = value.parse().unwrap_or(0); + } + } else if token.contains("insertion") { + if let Some(value) = token.split_whitespace().next() { + summary.insertions = value.parse().unwrap_or(0); + } + } else if token.contains("deletion") { + if let Some(value) = token.split_whitespace().next() { + summary.deletions = value.parse().unwrap_or(0); + } + } + } + } + + summary +} + +async fn get_head_hash(root: &Path) -> Result { + let output = run_git(&["rev-parse", "HEAD"], root).await?; + Ok(output.trim().to_string()) +} + +async fn get_current_branch_name(root: &Path) -> Result { + let output = run_git(&["rev-parse", "--abbrev-ref", "HEAD"], root).await?; + Ok(output.trim().to_string()) +} + +async fn collect_shortstat_for_range(root: &Path, range: &str) -> Result { + let args = ["diff", "--shortstat", range]; + let output = run_git(&args, root).await.unwrap_or_default(); + Ok(parse_shortstat(&output)) +} + +async fn collect_changed_files_for_range(root: &Path, range: &str) -> Result> { + let args = ["diff", "--name-only", range]; + let output = run_git(&args, root).await.unwrap_or_default(); + Ok(output + .lines() + .map(|line| line.trim()) + .filter(|line| !line.is_empty()) + .map(|line| line.to_string()) + .collect()) +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitIdentityProfile { + pub id: String, + pub name: String, + pub user_name: String, + pub user_email: String, + pub ssh_key: Option, + pub color: Option, + pub icon: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitIdentityProfilesWrapper { + pub profiles: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitIdentitySummary { + pub user_name: Option, + pub user_email: Option, + pub ssh_command: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitLogEntry { + pub hash: String, + pub date: String, + pub message: String, + pub refs: String, + pub body: String, + #[serde(rename = "author_name")] + pub author_name: String, + #[serde(rename = "author_email")] + pub author_email: String, + pub files_changed: i32, + pub insertions: i32, + pub deletions: i32, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitLogResponse { + pub all: Vec, + pub latest: Option, + pub total: i32, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GitWorktreeInfo { + pub worktree: String, + pub head: Option, + pub branch: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct GeneratedCommitMessage { + pub subject: String, + pub highlights: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CommitFileEntry { + pub path: String, + pub insertions: i32, + pub deletions: i32, + pub is_binary: bool, + pub change_type: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct GitCommitFilesResponse { + pub files: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct CommitMessageResponse { + pub message: GeneratedCommitMessage, +} + +// --- Constants & Regexes --- + +static WORKTREE_REGEX: LazyLock = LazyLock::new(|| Regex::new(r"^worktree (.+)$").unwrap()); +static HEAD_REGEX: LazyLock = LazyLock::new(|| Regex::new(r"^HEAD (.+)$").unwrap()); +static BRANCH_REGEX: LazyLock = LazyLock::new(|| Regex::new(r"^branch (.+)$").unwrap()); +static FILES_CHANGED_REGEX: LazyLock = + LazyLock::new(|| Regex::new(r"(\d+)\s+files?\s+changed").unwrap()); +static INSERTIONS_REGEX: LazyLock = + LazyLock::new(|| Regex::new(r"(\d+)\s+insertions?\(\+\)").unwrap()); +static DELETIONS_REGEX: LazyLock = + LazyLock::new(|| Regex::new(r"(\d+)\s+deletions?\(-\)").unwrap()); + +// --- Helpers --- + +async fn run_git(args: &[&str], cwd: &Path) -> Result { + run_git_with_allowed_exit(args, cwd, &[]).await +} + +async fn run_git_with_allowed_exit( + args: &[&str], + cwd: &Path, + allowed_codes: &[i32], +) -> Result { + let output = Command::new("git") + .args(args) + .current_dir(cwd) + .env("GIT_OPTIONAL_LOCKS", "0") + .env("LC_ALL", "C") + .output() + .await + .context("Failed to execute git command")?; + + if !output.status.success() { + if let Some(code) = output.status.code() { + if allowed_codes.contains(&code) { + return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); + } + } + let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); + return Err(anyhow!("{}", stderr)); + } + + Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()) +} + +fn append_git_option(args: &mut Vec, value: &Value) { + match value { + Value::Null => {} + Value::Bool(false) => {} + Value::Bool(true) => {} + Value::Number(num) => args.push(num.to_string()), + Value::String(text) => { + let trimmed = text.trim(); + if !trimmed.is_empty() { + args.push(trimmed.to_string()); + } + } + Value::Array(items) => { + for item in items { + append_git_option(args, item); + } + } + Value::Object(map) => append_git_option_map(args, map), + } +} + +fn append_git_option_map(args: &mut Vec, map: &serde_json::Map) { + for (key, value) in map { + let flag = key.trim(); + if flag.is_empty() { + continue; + } + + match value { + Value::Null | Value::Bool(true) => args.push(flag.to_string()), + Value::Bool(false) => {} + Value::String(text) => args.push(format!("{flag}={text}")), + Value::Number(num) => args.push(format!("{flag}={num}")), + Value::Array(items) => { + if items.is_empty() { + args.push(flag.to_string()); + } else { + for item in items { + match item { + Value::Null | Value::Bool(true) => args.push(flag.to_string()), + Value::Bool(false) => {} + Value::String(text) => args.push(format!("{flag}={text}")), + Value::Number(num) => args.push(format!("{flag}={num}")), + other => append_git_option(args, other), + } + } + } + } + other => args.push(format!("{flag}={other}")), + } + } +} + +// Removed unused resolve_workspace_root function + +async fn validate_git_path(path: &str, _settings: &SettingsStore) -> Result { + let path_buf = PathBuf::from(path); + if !path_buf.exists() { + return Err(anyhow!("Directory does not exist: {}", path)); + } + + if !path_buf.is_absolute() { + return Err(anyhow!("Path must be absolute")); + } + + Ok(path_buf) +} + +// --- Identity Storage --- + +async fn get_identity_storage_path() -> Result { + let mut path = dirs::home_dir().ok_or_else(|| anyhow!("Could not find home directory"))?; + path.push(".config"); + path.push("openchamber"); + fs::create_dir_all(&path).await?; + path.push(GIT_IDENTITY_STORAGE_FILE); + Ok(path) +} + +async fn load_identities() -> Result> { + let path = get_identity_storage_path().await?; + info!("Loading identities from {:?}", path); + + if !path.exists() { + info!("Identities file does not exist at {:?}", path); + return Ok(Vec::new()); + } + + let content = fs::read_to_string(&path).await?; + info!("Read {} bytes from identities file", content.len()); + + let wrapper: serde_json::Value = match serde_json::from_str(&content) { + Ok(w) => w, + Err(e) => { + error!("Failed to parse identities JSON: {}", e); + return Err(e.into()); + } + }; + + // Handle both array and object wrapper format if needed, but spec says object with profiles array + if let Some(profiles) = wrapper.get("profiles") { + match serde_json::from_value::>(profiles.clone()) { + Ok(p) => { + info!("Successfully loaded {} profiles", p.len()); + Ok(p) + } + Err(e) => { + error!("Failed to deserialize profiles array: {}", e); + // Log the failing JSON segment for debugging + warn!("Profiles JSON: {}", profiles); + Err(e.into()) + } + } + } else { + warn!("No 'profiles' key found in identities JSON"); + Ok(Vec::new()) + } +} + +async fn save_identities(profiles: Vec) -> Result<()> { + let path = get_identity_storage_path().await?; + let wrapper = GitIdentityProfilesWrapper { profiles }; + let content = serde_json::to_string_pretty(&wrapper)?; + fs::write(path, content).await?; + Ok(()) +} + +// --- Commands --- + +#[tauri::command] +pub async fn check_is_git_repository( + directory: String, + state: State<'_, DesktopRuntime>, +) -> Result { + let path = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let git_dir = path.join(".git"); + Ok(git_dir.exists()) +} + +#[tauri::command] +pub async fn get_git_status( + directory: String, + state: State<'_, DesktopRuntime>, +) -> Result { + let path = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + + // 1. Get porcelain status + let status_output = run_git(&["status", "--porcelain", "-b", "-z"], &path) + .await + .map_err(|e| e.to_string())?; + + // Parse status output + let mut files = Vec::new(); + let mut current = String::new(); + let mut tracking = None; + let mut ahead = 0; + let mut behind = 0; + + let entries: Vec<&str> = status_output.split('\0').collect(); + + for entry in entries { + if entry.is_empty() { + continue; + } + + if entry.starts_with("## ") { + // Branch info: ## main...origin/main [ahead 1, behind 2] + let branch_line = &entry[3..]; + if let Some((local, remote_part)) = branch_line.split_once("...") { + current = local.to_string(); + // Parse remote part for ahead/behind + // Format: origin/main [ahead 1, behind 2] or origin/main + if let Some(bracket_start) = remote_part.find('[') { + tracking = Some(remote_part[..bracket_start].trim().to_string()); + let stats = &remote_part[bracket_start + 1..remote_part.len() - 1]; // inside brackets + for part in stats.split(", ") { + if let Some(val) = part.strip_prefix("ahead ") { + ahead = val.parse().unwrap_or(0); + } else if let Some(val) = part.strip_prefix("behind ") { + behind = val.parse().unwrap_or(0); + } + } + } else { + tracking = Some(remote_part.trim().to_string()); + } + } else { + // No remote or initial commit + current = branch_line.to_string(); + } + continue; + } + + // File entries: XY PATH or R ORIG_PATH -> PATH + if entry.len() >= 4 { + let index_status = &entry[0..1]; + let working_status = &entry[1..2]; + let file_path = &entry[3..]; + + // Simple-git parsing logic approximation + files.push(GitStatusFile { + path: file_path.to_string(), + index: index_status.trim().to_string(), + working_dir: working_status.trim().to_string(), + }); + } + } + + // 2. Get diff stats (staged and unstaged) + let mut diff_stats = HashMap::new(); + + let collect_stats = |output: String| { + let mut stats = HashMap::new(); + for line in output.lines() { + let parts: Vec<&str> = line.split('\t').collect(); + if parts.len() >= 3 { + let insertions = if parts[0] == "-" { + 0 + } else { + parts[0].parse().unwrap_or(0) + }; + let deletions = if parts[1] == "-" { + 0 + } else { + parts[1].parse().unwrap_or(0) + }; + let path = parts[2].to_string(); + stats.insert( + path, + DiffStat { + insertions, + deletions, + }, + ); + } + } + stats + }; + + let staged_stats_raw = run_git(&["diff", "--cached", "--numstat"], &path) + .await + .unwrap_or_default(); + let working_stats_raw = run_git(&["diff", "--numstat"], &path) + .await + .unwrap_or_default(); + + let staged_stats = collect_stats(staged_stats_raw); + let working_stats = collect_stats(working_stats_raw); + + // Merge stats + let mut all_paths: HashSet = staged_stats.keys().cloned().collect(); + all_paths.extend(working_stats.keys().cloned()); + + for p in all_paths { + let s = staged_stats.get(&p).unwrap_or(&DiffStat { + insertions: 0, + deletions: 0, + }); + let w = working_stats.get(&p).unwrap_or(&DiffStat { + insertions: 0, + deletions: 0, + }); + diff_stats.insert( + p, + DiffStat { + insertions: s.insertions + w.insertions, + deletions: s.deletions + w.deletions, + }, + ); + } + + // 3. Handle new/untracked files (manual calculation if needed, or skip if complex) + // Node implementation does manual read. For now, let's assume files with '??' or 'A' + // might need stats if they aren't in numstat. + // NOTE: untracked files don't show up in `git diff --numstat`. + // We can try `wc -l` logic but Rust fs read is safer. + + for file in &files { + if (file.working_dir == "?" || file.index == "A") && !diff_stats.contains_key(&file.path) { + let full_path = path.join(&file.path); + if let Ok(metadata) = fs::metadata(&full_path).await { + if metadata.is_file() { + if let Ok(content) = fs::read_to_string(&full_path).await { + let lines = content.lines().count() as i32; + diff_stats.insert( + file.path.clone(), + DiffStat { + insertions: lines, + deletions: 0, + }, + ); + } + } + } + } + } + + Ok(GitStatus { + current, + tracking, + ahead, + behind, + is_clean: files.is_empty(), + files, + diff_stats: Some(diff_stats), + }) +} + +#[tauri::command] +pub async fn get_git_diff( + directory: String, + path_str: String, + staged: Option, + context_lines: Option, + state: State<'_, DesktopRuntime>, +) -> Result { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + + let mut args = vec!["diff", "--no-color"]; + let context = format!("-U{}", context_lines.unwrap_or(3)); + args.push(&context); + + if staged.unwrap_or(false) { + args.push("--cached"); + } + + args.push("--"); + args.push(&path_str); + + let output = run_git(&args, &root).await.unwrap_or_default(); + + if output.trim().is_empty() && !staged.unwrap_or(false) { + // Try --no-index for untracked files + // git diff --no-index -- /dev/null path + let full_path = root.join(&path_str); + if full_path.exists() { + let args_no_index = vec![ + "diff", + "--no-color", + &context, + "--no-index", + "--", + "/dev/null", + &path_str, + ]; + return run_git_with_allowed_exit(&args_no_index, &root, &[1]) + .await + .map_err(|e| e.to_string()); + } + } + + Ok(output) +} + +#[tauri::command] +pub async fn get_git_file_diff( + directory: String, + path_str: String, + state: State<'_, DesktopRuntime>, +) -> Result<(String, String), String> { + use tokio::fs; + + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + + // Original from HEAD + let original_spec = format!("HEAD:{}", path_str); + let original_args = vec!["show", original_spec.as_str()]; + let original = run_git_with_allowed_exit(&original_args, &root, &[0, 128]) + .await + .unwrap_or_default(); + + // Modified from working tree (if file exists) + let full_path = root.join(&path_str); + let modified = if let Ok(metadata) = fs::metadata(&full_path).await { + if metadata.is_file() { + fs::read_to_string(&full_path).await.unwrap_or_default() + } else { + String::new() + } + } else { + String::new() + }; + + Ok((original, modified)) +} + +#[tauri::command] +pub async fn revert_git_file( + directory: String, + file_path: String, + state: State<'_, DesktopRuntime>, +) -> Result<(), String> { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + + // Check if tracked + let is_tracked = run_git(&["ls-files", "--error-unmatch", &file_path], &root) + .await + .is_ok(); + + if !is_tracked { + // Clean untracked + let _ = run_git(&["clean", "-f", "-d", "--", &file_path], &root).await; + // Fallback fs remove if git clean failed (e.g. ignored files) + let full_path = root.join(&file_path); + if full_path.exists() { + if full_path.is_dir() { + let _ = fs::remove_dir_all(full_path).await; + } else { + let _ = fs::remove_file(full_path).await; + } + } + } else { + // Restore staged + let _ = run_git(&["restore", "--staged", &file_path], &root).await; + // Restore working + let _ = run_git(&["restore", &file_path], &root).await; + } + + Ok(()) +} + +#[tauri::command] +pub async fn is_linked_worktree( + directory: String, + state: State<'_, DesktopRuntime>, +) -> Result { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let git_dir = run_git(&["rev-parse", "--git-dir"], &root) + .await + .unwrap_or_default(); + let common_dir = run_git(&["rev-parse", "--git-common-dir"], &root) + .await + .unwrap_or_default(); + Ok(git_dir.trim() != common_dir.trim()) +} + +#[tauri::command] +pub async fn get_git_branches( + directory: String, + state: State<'_, DesktopRuntime>, +) -> Result { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + + // Discover actual remote heads so we can drop stale remote-tracking refs + let allowed_remote_heads: Option> = match run_git(&["ls-remote", "--heads", "origin"], &root).await { + Ok(ls_remote) => { + let mut set = HashSet::new(); + for line in ls_remote.lines() { + if let Some((_, ref_name)) = line.split_once('\t') { + if let Some(stripped) = ref_name.trim().strip_prefix("refs/heads/") { + set.insert(stripped.to_string()); + } + } + } + Some(set) + } + Err(err) => { + warn!("Failed to list remote heads: {}", err); + None + } + }; + + // Structured for-each-ref output so we can mark remotes consistently with the web runtime + let output = run_git( + &[ + "for-each-ref", + "--format=%(refname)|%(refname:short)|%(objectname)|%(upstream:short)|%(HEAD)|%(upstream:track)", + "refs/heads", + "refs/remotes", + ], + &root, + ) + .await + .map_err(|e| e.to_string())?; + + let mut all = Vec::new(); + let mut current_branch = String::new(); + let mut branches = HashMap::new(); + + for line in output.lines() { + let parts: Vec<&str> = line.split('|').collect(); + if parts.len() < 6 { + continue; + } + + let full_ref = parts[0].trim(); + let short_name = parts[1].trim(); + let commit = parts[2].to_string(); + let upstream = parts[3].trim(); + let is_current = parts[4] == "*"; + let track_info = parts[5]; + + let is_remote = full_ref.starts_with("refs/remotes/"); + + let normalized_name = if is_remote { + let (remote_name, branch_name) = match short_name.split_once('/') { + Some(parts) => parts, + None => continue, // skip malformed remote ref without branch + }; + + if branch_name == "HEAD" { + continue; + } + + if let Some(allowed) = &allowed_remote_heads { + if !allowed.contains(branch_name) { + continue; + } + } + + format!("remotes/{}/{}", remote_name, branch_name) + } else { + short_name.to_string() + }; + + let tracking = if upstream.is_empty() { + None + } else { + Some(upstream.to_string()) + }; + + if is_current { + current_branch = normalized_name.clone(); + } + all.push(normalized_name.clone()); + + let mut ahead = None; + let mut behind = None; + + // Parse track info like "[ahead 1, behind 2]" + if !track_info.is_empty() { + let content = track_info.trim_matches(|c| c == '[' || c == ']'); + for part in content.split(", ") { + if let Some(val) = part.strip_prefix("ahead ") { + ahead = val.parse().ok(); + } else if let Some(val) = part.strip_prefix("behind ") { + behind = val.parse().ok(); + } + } + } + + branches.insert( + normalized_name.clone(), + GitBranchDetails { + current: is_current, + name: normalized_name, + commit, + label: short_name.to_string(), + tracking, + ahead, + behind, + }, + ); + } + + Ok(GitBranch { + all, + current: current_branch, + branches, + }) +} + +#[tauri::command] +pub async fn delete_git_branch( + directory: String, + branch: String, + force: Option, + state: State<'_, DesktopRuntime>, +) -> Result<(), String> { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let flag = if force.unwrap_or(false) { "-D" } else { "-d" }; + run_git(&["branch", flag, &branch], &root) + .await + .map_err(|e| e.to_string())?; + Ok(()) +} + +#[tauri::command] +pub async fn delete_remote_branch( + directory: String, + branch: String, + remote: Option, + state: State<'_, DesktopRuntime>, +) -> Result<(), String> { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let remote_name = remote.unwrap_or_else(|| "origin".to_string()); + + // branch might be refs/heads/foo or just foo + let clean_branch = branch.trim_start_matches("refs/heads/"); + + run_git(&["push", &remote_name, "--delete", clean_branch], &root) + .await + .map_err(|e| e.to_string())?; + Ok(()) +} + +#[tauri::command] +pub async fn list_git_worktrees( + directory: String, + state: State<'_, DesktopRuntime>, +) -> Result, String> { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let output = run_git(&["worktree", "list", "--porcelain"], &root) + .await + .map_err(|e| e.to_string())?; + + let mut worktrees = Vec::new(); + let mut current = GitWorktreeInfo { + worktree: String::new(), + head: None, + branch: None, + }; + + for line in output.lines() { + if let Some(cap) = WORKTREE_REGEX.captures(line) { + if !current.worktree.is_empty() { + worktrees.push(current.clone()); + current = GitWorktreeInfo { + worktree: String::new(), + head: None, + branch: None, + }; + } + current.worktree = cap[1].to_string(); + } else if let Some(cap) = HEAD_REGEX.captures(line) { + current.head = Some(cap[1].to_string()); + } else if let Some(cap) = BRANCH_REGEX.captures(line) { + current.branch = Some(cap[1].trim_start_matches("refs/heads/").to_string()); + } else if line.is_empty() { + if !current.worktree.is_empty() { + worktrees.push(current.clone()); + current = GitWorktreeInfo { + worktree: String::new(), + head: None, + branch: None, + }; + } + } + } + if !current.worktree.is_empty() { + worktrees.push(current); + } + + Ok(worktrees) +} + +#[tauri::command] +pub async fn add_git_worktree( + directory: String, + path_str: String, + branch: String, + create_branch: Option, + state: State<'_, DesktopRuntime>, +) -> Result<(), String> { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + + let mut args = vec!["worktree", "add"]; + if create_branch.unwrap_or(false) { + args.push("-b"); + args.push(&branch); + } + args.push(&path_str); + + if !create_branch.unwrap_or(false) { + args.push(&branch); + } + + run_git(&args, &root).await.map_err(|e| e.to_string())?; + Ok(()) +} + +#[tauri::command] +pub async fn remove_git_worktree( + directory: String, + path_str: String, + force: Option, + state: State<'_, DesktopRuntime>, +) -> Result<(), String> { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let mut args = vec!["worktree", "remove", &path_str]; + if force.unwrap_or(false) { + args.push("--force"); + } + run_git(&args, &root).await.map_err(|e| e.to_string())?; + Ok(()) +} + +#[tauri::command] +pub async fn ensure_openchamber_ignored( + directory: String, + state: State<'_, DesktopRuntime>, +) -> Result<(), String> { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let exclude_path = root.join(".git/info/exclude"); + + if let Some(parent) = exclude_path.parent() { + fs::create_dir_all(parent) + .await + .map_err(|e| e.to_string())?; + } + + let entry = "/.openchamber/\n"; + let mut content = fs::read_to_string(&exclude_path).await.unwrap_or_default(); + + if !content.contains("/.openchamber/") { + if !content.ends_with('\n') && !content.is_empty() { + content.push('\n'); + } + content.push_str(entry); + fs::write(&exclude_path, content) + .await + .map_err(|e| e.to_string())?; + } + Ok(()) +} + +#[tauri::command] +pub async fn create_git_commit( + directory: String, + message: String, + add_all: Option, + files: Option>, + state: State<'_, DesktopRuntime>, +) -> Result { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + + if add_all.unwrap_or(false) { + run_git(&["add", "."], &root) + .await + .map_err(|e| e.to_string())?; + } else if let Some(file_list) = files { + if !file_list.is_empty() { + let mut args = vec!["add"]; + args.extend(file_list.iter().map(|s| s.as_str())); + run_git(&args, &root).await.map_err(|e| e.to_string())?; + } + } + + run_git(&["commit", "-m", &message], &root) + .await + .map_err(|e| e.to_string())?; + + let commit_hash = get_head_hash(&root).await.map_err(|e| e.to_string())?; + let branch_name = get_current_branch_name(&root) + .await + .unwrap_or_else(|_| "HEAD".to_string()); + + let stat_output = run_git(&["log", "-1", "--pretty=", "--shortstat"], &root) + .await + .unwrap_or_default(); + let summary = parse_shortstat(&stat_output); + + Ok(GitCommitResult { + success: true, + commit: commit_hash, + branch: branch_name, + summary, + }) +} + +#[tauri::command] +pub async fn git_push( + directory: String, + remote: Option, + branch: Option, + options: Option, + state: State<'_, DesktopRuntime>, +) -> Result { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let remote_name = remote.unwrap_or_else(|| "origin".to_string()); + let mut branch_name = branch.unwrap_or_default(); + + let mut args = vec!["push".to_string(), remote_name.clone()]; + if branch_name.is_empty() { + branch_name = get_current_branch_name(&root).await.unwrap_or_default(); + } + if !branch_name.is_empty() { + args.push(branch_name.clone()); + } + + if let Some(extra) = options.as_ref() { + append_git_option(&mut args, extra); + } + + let arg_refs: Vec<&str> = args.iter().map(|value| value.as_str()).collect(); + + // TODO: Streaming? Frontend types.ts defines GitPushResult, but doesn't mention streaming response for this call, + // but Stage 2 plan says "streaming progress events for long operations". + // Implementing simple await for now as `simple-git` wrapper does in `git-service.js`. + + run_git(&arg_refs, &root).await.map_err(|e| e.to_string())?; + + Ok(GitPushResult { + success: true, + pushed: if branch_name.is_empty() { + vec![] + } else { + vec![GitPushRef { + local: branch_name.clone(), + remote: format!("{}/{}", remote_name, branch_name), + }] + }, + repo: remote_name, + ref_: if branch_name.is_empty() { + None + } else { + Some(branch_name) + }, + }) +} + +#[tauri::command] +pub async fn git_pull( + directory: String, + remote: Option, + branch: Option, + state: State<'_, DesktopRuntime>, +) -> Result { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let r = remote.unwrap_or_else(|| "origin".to_string()); + let b = branch.unwrap_or_default(); + + let mut args = vec!["pull", &r]; + if !b.is_empty() { + args.push(&b); + } + + let previous_head = get_head_hash(&root).await.ok(); + + run_git(&args, &root).await.map_err(|e| e.to_string())?; + + let (summary, files) = if let Some(previous) = previous_head { + let new_head = get_head_hash(&root).await.unwrap_or(previous.clone()); + if new_head != previous { + let range = format!("{previous}..{new_head}"); + let summary = collect_shortstat_for_range(&root, &range) + .await + .unwrap_or_else(|_| GitCommitSummary { + changes: 0, + insertions: 0, + deletions: 0, + }); + let files = collect_changed_files_for_range(&root, &range) + .await + .unwrap_or_default(); + (summary, files) + } else { + ( + GitCommitSummary { + changes: 0, + insertions: 0, + deletions: 0, + }, + vec![], + ) + } + } else { + ( + GitCommitSummary { + changes: 0, + insertions: 0, + deletions: 0, + }, + vec![], + ) + }; + + Ok(GitPullResult { + success: true, + summary: summary.clone(), + files, + insertions: summary.insertions, + deletions: summary.deletions, + }) +} + +#[tauri::command] +pub async fn git_fetch( + directory: String, + remote: Option, + state: State<'_, DesktopRuntime>, +) -> Result<(), String> { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let r = remote.unwrap_or_else(|| "origin".to_string()); + run_git(&["fetch", &r], &root) + .await + .map_err(|e| e.to_string())?; + Ok(()) +} + +#[tauri::command] +pub async fn checkout_branch( + directory: String, + branch: String, + state: State<'_, DesktopRuntime>, +) -> Result<(), String> { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + run_git(&["checkout", &branch], &root) + .await + .map_err(|e| e.to_string())?; + Ok(()) +} + +#[tauri::command] +pub async fn create_branch( + directory: String, + name: String, + start_point: Option, + state: State<'_, DesktopRuntime>, +) -> Result<(), String> { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let start = start_point.unwrap_or_else(|| "HEAD".to_string()); + run_git(&["checkout", "-b", &name, &start], &root) + .await + .map_err(|e| e.to_string())?; + Ok(()) +} + +#[tauri::command] +pub async fn get_git_log( + directory: String, + max_count: Option, + from: Option, + to: Option, + file: Option, + state: State<'_, DesktopRuntime>, +) -> Result { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + + let max = max_count.unwrap_or(50).to_string(); + let mut args = vec![ + "log", + "--max-count", + &max, + "--date=iso", + "--pretty=format:%H%x1f%an%x1f%ae%x1f%ad%x1f%s%x1e", + "--shortstat", + ]; + + let range; + if let (Some(f), Some(t)) = (&from, &to) { + range = format!("{}..{}", f, t); + args.push(&range); + } else if let Some(f) = &from { + range = format!("{}..HEAD", f); + args.push(&range); + } else if let Some(t) = &to { + args.push(t); + } + + if let Some(f) = &file { + args.push("--"); + args.push(f); + } + + let output = run_git(&args, &root).await.map_err(|e| e.to_string())?; + + let mut entries = Vec::new(); + let entries_raw: Vec<&str> = output.split('\x1e').collect(); + + let mut current_header = if !entries_raw.is_empty() { + entries_raw[0].trim() + } else { + "" + }; + + for i in 1..entries_raw.len() { + let chunk = entries_raw[i]; + + if current_header.is_empty() { + break; + } + + let header_parts: Vec<&str> = current_header.split('\x1f').collect(); + if header_parts.len() < 5 { + // Try to recover next header anyway before skipping + // But current_header is invalid, so we can't push an entry. + // We still need to update current_header for the next loop. + } else { + let hash = header_parts[0]; + let name = header_parts[1]; + let email = header_parts[2]; + let date = header_parts[3]; + let subject = header_parts[4]; + + let mut files_changed = 0; + let mut insertions = 0; + let mut deletions = 0; + + if let Some(cap) = FILES_CHANGED_REGEX.captures(chunk) { + files_changed = cap[1].parse().unwrap_or(0); + } + if let Some(cap) = INSERTIONS_REGEX.captures(chunk) { + insertions = cap[1].parse().unwrap_or(0); + } + if let Some(cap) = DELETIONS_REGEX.captures(chunk) { + deletions = cap[1].parse().unwrap_or(0); + } + + entries.push(GitLogEntry { + hash: hash.to_string(), + author_name: name.to_string(), + author_email: email.to_string(), + date: date.to_string(), + message: subject.to_string(), + body: String::new(), + refs: String::new(), + files_changed, + insertions, + deletions, + }); + } + + // Find next header by looking for the line containing \x1f (separator used in format) + // The chunk contains stats then the next header. + current_header = ""; + for line in chunk.lines().rev() { + let trimmed = line.trim(); + if !trimmed.is_empty() && trimmed.contains('\x1f') { + current_header = trimmed; + break; + } + } + } + + if entries.is_empty() && !output.is_empty() { + for line in output.lines() { + let parts: Vec<&str> = line.split('\x1f').collect(); + if parts.len() >= 5 { + entries.push(GitLogEntry { + hash: parts[0].to_string(), + author_name: parts[1].to_string(), + author_email: parts[2].to_string(), + date: parts[3].to_string(), + message: parts[4].to_string(), + body: "".to_string(), + refs: "".to_string(), + files_changed: 0, + insertions: 0, + deletions: 0, + }); + } + } + } + + Ok(GitLogResponse { + all: entries.clone(), + latest: entries.first().cloned(), + total: entries.len() as i32, + }) +} + +#[tauri::command] +pub async fn get_commit_files( + directory: String, + hash: String, + state: State<'_, DesktopRuntime>, +) -> Result { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + + // Get numstat for insertions/deletions per file + let numstat_output = run_git(&["show", "--numstat", "--format=", &hash], &root) + .await + .map_err(|e| e.to_string())?; + + let mut files = Vec::new(); + + for line in numstat_output.lines() { + let parts: Vec<&str> = line.split('\t').collect(); + if parts.len() < 3 { + continue; + } + + let insertions_raw = parts[0]; + let deletions_raw = parts[1]; + let file_path = parts[2..].join("\t"); + + if file_path.is_empty() { + continue; + } + + // Binary files show '-' for stats + let is_binary = insertions_raw == "-" && deletions_raw == "-"; + let insertions = if insertions_raw == "-" { + 0 + } else { + insertions_raw.parse().unwrap_or(0) + }; + let deletions = if deletions_raw == "-" { + 0 + } else { + deletions_raw.parse().unwrap_or(0) + }; + + files.push(CommitFileEntry { + path: file_path, + insertions, + deletions, + is_binary, + change_type: "M".to_string(), // Default, will update below + }); + } + + // Get accurate change types using --name-status + let name_status_output = run_git(&["show", "--name-status", "--format=", &hash], &root) + .await + .unwrap_or_default(); + + let mut status_map: HashMap = HashMap::new(); + for line in name_status_output.lines() { + let parts: Vec<&str> = line.split('\t').collect(); + if parts.len() >= 2 { + let status = parts[0].chars().next().unwrap_or('M').to_string(); + let path = parts.last().unwrap_or(&"").to_string(); + status_map.insert(path, status); + } + } + + // Update change types + for file in &mut files { + let base_path = if file.path.contains(" => ") { + file.path + .split(" => ") + .last() + .unwrap_or(&file.path) + .replace(['{', '}'], "") + } else { + file.path.clone() + }; + + if let Some(status) = status_map.get(&base_path).or_else(|| status_map.get(&file.path)) { + file.change_type = status.clone(); + } + } + + Ok(GitCommitFilesResponse { files }) +} + +#[tauri::command] +pub async fn get_git_identities() -> Result, String> { + load_identities().await.map_err(|e| e.to_string()) +} + +#[tauri::command] +pub async fn create_git_identity( + profile: GitIdentityProfile, +) -> Result { + let mut profiles = load_identities().await.map_err(|e| e.to_string())?; + if profiles.iter().any(|p| p.id == profile.id) { + return Err(format!("Profile with ID {} already exists", profile.id)); + } + profiles.push(profile.clone()); + save_identities(profiles).await.map_err(|e| e.to_string())?; + Ok(profile) +} + +#[tauri::command] +pub async fn update_git_identity( + id: String, + updates: GitIdentityProfile, +) -> Result { + let mut profiles = load_identities().await.map_err(|e| e.to_string())?; + if let Some(idx) = profiles.iter().position(|p| p.id == id) { + profiles[idx] = updates.clone(); + save_identities(profiles).await.map_err(|e| e.to_string())?; + Ok(updates) + } else { + Err(format!("Profile with ID {} not found", id)) + } +} + +#[tauri::command] +pub async fn delete_git_identity(id: String) -> Result<(), String> { + let mut profiles = load_identities().await.map_err(|e| e.to_string())?; + let len = profiles.len(); + profiles.retain(|p| p.id != id); + if profiles.len() == len { + return Err(format!("Profile with ID {} not found", id)); + } + save_identities(profiles).await.map_err(|e| e.to_string())?; + Ok(()) +} + +#[tauri::command] +pub async fn get_current_git_identity( + directory: String, + state: State<'_, DesktopRuntime>, +) -> Result { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + + let user_name = run_git(&["config", "user.name"], &root).await.ok(); + let user_email = run_git(&["config", "user.email"], &root).await.ok(); + let ssh_command = run_git(&["config", "core.sshCommand"], &root).await.ok(); + + Ok(GitIdentitySummary { + user_name: user_name.filter(|s| !s.is_empty()), + user_email: user_email.filter(|s| !s.is_empty()), + ssh_command: ssh_command.filter(|s| !s.is_empty()), + }) +} + +#[tauri::command] +pub async fn set_git_identity( + directory: String, + profile_id: String, + state: State<'_, DesktopRuntime>, +) -> Result { + let root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + let profiles = load_identities().await.map_err(|e| e.to_string())?; + + let profile = profiles + .into_iter() + .find(|p| p.id == profile_id) + .ok_or_else(|| format!("Profile {} not found", profile_id))?; + + run_git( + &["config", "--local", "user.name", &profile.user_name], + &root, + ) + .await + .map_err(|e| e.to_string())?; + run_git( + &["config", "--local", "user.email", &profile.user_email], + &root, + ) + .await + .map_err(|e| e.to_string())?; + + if let Some(key) = &profile.ssh_key { + let cmd = format!("ssh -i {}", key); + run_git(&["config", "--local", "core.sshCommand", &cmd], &root) + .await + .map_err(|e| e.to_string())?; + } else { + let _ = run_git(&["config", "--local", "--unset", "core.sshCommand"], &root).await; + } + + Ok(profile) +} + +#[tauri::command] +pub async fn generate_commit_message( + directory: String, + files: Vec, + state: State<'_, DesktopRuntime>, +) -> Result { + let _root = validate_git_path(&directory, state.settings()) + .await + .map_err(|e| e.to_string())?; + + // 1. Collect diffs + let mut diff_summaries = String::new(); + for file in files { + if let Ok(diff) = + get_git_diff(directory.clone(), file.clone(), None, None, state.clone()).await + { + let trimmed = if diff.len() > 4000 { + format!("{}\n...", &diff[..4000]) + } else { + diff + }; + diff_summaries.push_str(&format!("FILE: {}\n{}\n\n", file, trimmed)); + } + } + + if diff_summaries.is_empty() { + return Err("No diffs available for selected files".to_string()); + } + + // 2. Construct prompt (matching server/index.js) + let prompt = format!( + r#"You are drafting git commit notes for this codebase. Respond in JSON of the shape {{"subject": string, "highlights": string[]}} (ONLY the JSON in response, no markdown wrappers or anything except JSON) with these rules: +- subject follows our convention: type[optional-scope]: summary (examples: "feat: add diff virtualization", "fix(chat): restore enter key handling") +- allowed types: feat, fix, chore, style, refactor, perf, docs, test, build, ci (choose the best match or fallback to chore) +- summary must be imperative, concise, <= 70 characters, no trailing punctuation +- scope is optional; include only when obvious from filenames/folders; do not invent scopes +- focus on the most impactful user-facing change; if multiple capabilities ship together, align the subject with the dominant theme and use highlights to cover the other major outcomes +- highlights array should contain 2-3 plain sentences (<= 90 chars each) that describe distinct features or UI changes users will notice (e.g. "Add per-file revert action in Changes list"). Avoid subjective benefit statements, marketing tone, repeating the subject, or referencing helper function names. Highlight additions such as new controls/buttons, new actions (e.g. revert), or stored state changes explicitly. Skip highlights if fewer than two meaningful points exist. +- text must be plain (no markdown bullets); each highlight should start with an uppercase verb + +Diff summary: +{}"#, + diff_summaries + ); + + // 3. Call API + let client = Client::new(); + let res = client + .post("https://opencode.ai/zen/v1/chat/completions") + .json(&serde_json::json!({ + "model": "big-pickle", + "messages": [{ "role": "user", "content": prompt }], + "max_tokens": 3000, + "stream": false, + "reasoning": { + "effort": "low" + } + })) + .send() + .await + .map_err(|e| e.to_string())?; + + if !res.status().is_success() { + return Err(format!("API request failed: {}", res.status())); + } + + let body: serde_json::Value = res.json().await.map_err(|e| e.to_string())?; + let raw_content = body["choices"][0]["message"]["content"] + .as_str() + .unwrap_or("") + .trim(); + + // 4. Parse JSON + // Strip markdown code blocks if present + let cleaned = raw_content + .trim_start_matches("```json") + .trim_start_matches("```") + .trim_end_matches("```") + .trim(); + + let message: GeneratedCommitMessage = + serde_json::from_str(cleaned).map_err(|e| format!("Failed to parse AI response: {}", e))?; + + Ok(CommitMessageResponse { message }) +} diff --git a/packages/desktop/src-tauri/src/commands/logs.rs b/packages/desktop/src-tauri/src/commands/logs.rs new file mode 100644 index 00000000..8482b3eb --- /dev/null +++ b/packages/desktop/src-tauri/src/commands/logs.rs @@ -0,0 +1,25 @@ +use crate::logging::log_file_path; +use serde::Serialize; +use tokio::fs; + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DesktopLogFile { + pub file_name: String, + pub content: String, +} + +#[tauri::command] +pub async fn fetch_desktop_logs() -> Result { + let path = log_file_path().ok_or_else(|| "Log location unavailable".to_string())?; + let content = fs::read_to_string(&path) + .await + .map_err(|err| format!("Failed to read log file: {err}"))?; + let file_name = path + .file_name() + .and_then(|value| value.to_str()) + .unwrap_or("desktop.log") + .to_string(); + + Ok(DesktopLogFile { file_name, content }) +} diff --git a/packages/desktop/src-tauri/src/commands/mod.rs b/packages/desktop/src-tauri/src/commands/mod.rs new file mode 100644 index 00000000..f877e819 --- /dev/null +++ b/packages/desktop/src-tauri/src/commands/mod.rs @@ -0,0 +1,7 @@ +pub mod files; +pub mod git; +pub mod logs; +pub mod permissions; +pub mod settings; +pub mod terminal; +pub mod notifications; diff --git a/packages/desktop/src-tauri/src/commands/notifications.rs b/packages/desktop/src-tauri/src/commands/notifications.rs new file mode 100644 index 00000000..7ed331cf --- /dev/null +++ b/packages/desktop/src-tauri/src/commands/notifications.rs @@ -0,0 +1,37 @@ +use serde::Deserialize; +use tauri::{AppHandle, Runtime}; +use tauri_plugin_notification::NotificationExt; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NotificationPayload { + pub title: Option, + pub body: Option, +} + +#[tauri::command] +pub async fn desktop_notify( + app: AppHandle, + payload: Option, +) -> Result { + let title = payload + .as_ref() + .and_then(|p| p.title.as_deref()) + .unwrap_or("OpenChamber"); + let body = payload + .as_ref() + .and_then(|p| p.body.as_deref()) + .unwrap_or("Task completed"); + + match app + .notification() + .builder() + .title(title) + .body(body) + .sound("Glass") + .show() + { + Ok(_) => Ok(true), + Err(e) => Err(e.to_string()), + } +} diff --git a/packages/desktop/src-tauri/src/commands/permissions.rs b/packages/desktop/src-tauri/src/commands/permissions.rs new file mode 100644 index 00000000..0ed35905 --- /dev/null +++ b/packages/desktop/src-tauri/src/commands/permissions.rs @@ -0,0 +1,209 @@ +use log::{info, warn}; +use serde::{Deserialize, Serialize}; +use tauri::AppHandle; +use tauri::State; + +use crate::DesktopRuntime; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DirectoryPermissionRequest { + path: String, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DirectoryPermissionResult { + success: bool, + path: Option, + error: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StartAccessingResult { + success: bool, + error: Option, +} + +/// Process directory selection from frontend +/// Updates settings with lastDirectory +/// OpenCode restart is triggered separately via /api/opencode/directory endpoint +#[tauri::command] +pub async fn process_directory_selection( + path: String, + state: State<'_, DesktopRuntime>, +) -> Result { + use std::path::PathBuf; + + // Validate directory exists + let path_buf = PathBuf::from(&path); + if !path_buf.exists() { + return Ok(DirectoryPermissionResult { + success: false, + path: None, + error: Some("Directory does not exist".to_string()), + }); + } + + if !path_buf.is_dir() { + return Ok(DirectoryPermissionResult { + success: false, + path: None, + error: Some("Path is not a directory".to_string()), + }); + } + + // Update settings with lastDirectory + let mut settings = state + .settings() + .load() + .await + .map_err(|e| format!("Failed to load settings: {}", e))?; + + if let Some(obj) = settings.as_object_mut() { + obj.insert( + "lastDirectory".to_string(), + serde_json::Value::String(path.clone()), + ); + } + + state + .settings() + .save(settings) + .await + .map_err(|e| format!("Failed to save updated settings: {}", e))?; + + info!( + "[permissions] Updated settings with lastDirectory: {}", + path + ); + + Ok(DirectoryPermissionResult { + success: true, + path: Some(path), + error: None, + }) +} + +/// Legacy directory picker command (frontend handles actual dialog) +#[tauri::command] +pub async fn pick_directory( + _app_handle: AppHandle, + _state: State<'_, DesktopRuntime>, +) -> Result { + Ok(DirectoryPermissionResult { + success: false, + path: None, + error: Some( + "Use requestDirectoryAccess instead - it handles native dialog properly".to_string(), + ), + }) +} + +/// Request directory access (desktop implementation) +/// For unsandboxed apps, just validates the path is accessible +#[tauri::command] +pub async fn request_directory_access( + request: DirectoryPermissionRequest, + _state: State<'_, DesktopRuntime>, +) -> Result { + let path = request.path; + + let path_buf = std::path::PathBuf::from(&path); + if !path_buf.exists() { + return Ok(DirectoryPermissionResult { + success: false, + path: None, + error: Some("Directory does not exist".to_string()), + }); + } + + if !path_buf.is_dir() { + return Ok(DirectoryPermissionResult { + success: false, + path: None, + error: Some("Path is not a directory".to_string()), + }); + } + + // For unsandboxed apps, no bookmark needed - just verify access + match std::fs::read_dir(&path_buf) { + Ok(_) => Ok(DirectoryPermissionResult { + success: true, + path: Some(path), + error: None, + }), + Err(e) => Ok(DirectoryPermissionResult { + success: false, + path: None, + error: Some(format!("Cannot access directory: {}", e)), + }), + } +} + +/// Start accessing directory (desktop implementation) +#[tauri::command] +pub async fn start_accessing_directory( + path: String, + _state: State<'_, DesktopRuntime>, +) -> Result { + // Check if directory exists and is accessible + let path_buf = std::path::PathBuf::from(&path); + + if !path_buf.exists() { + return Ok(StartAccessingResult { + success: false, + error: Some("Directory does not exist".to_string()), + }); + } + + if !path_buf.is_dir() { + return Ok(StartAccessingResult { + success: false, + error: Some("Path is not a directory".to_string()), + }); + } + + // Try to read the directory to verify access + match std::fs::read_dir(&path_buf) { + Ok(_) => { + info!("Successfully started accessing directory: {}", path); + Ok(StartAccessingResult { + success: true, + error: None, + }) + } + Err(e) => { + warn!("Failed to access directory {}: {}", path, e); + Ok(StartAccessingResult { + success: false, + error: Some(format!("Failed to access directory: {}", e)), + }) + } + } +} + +/// Stop accessing directory (desktop implementation) +#[tauri::command] +pub async fn stop_accessing_directory( + _path: String, + _state: State<'_, DesktopRuntime>, +) -> Result { + // For Stage 1, just confirm the operation + // Full implementation would call stopAccessingSecurityScopedResource + info!("Stopped accessing directory"); + Ok(StartAccessingResult { + success: true, + error: None, + }) +} + +/// Restore bookmarks on app startup (no-op for unsandboxed apps) +#[tauri::command] +pub async fn restore_bookmarks_on_startup(_state: State<'_, DesktopRuntime>) -> Result<(), String> { + // For unsandboxed apps, no bookmarks needed + // Directory access is restored from settings.lastDirectory + info!("[permissions] Bookmark restore not needed for unsandboxed app"); + Ok(()) +} diff --git a/packages/desktop/src-tauri/src/commands/settings.rs b/packages/desktop/src-tauri/src/commands/settings.rs new file mode 100644 index 00000000..d8167d1e --- /dev/null +++ b/packages/desktop/src-tauri/src/commands/settings.rs @@ -0,0 +1,343 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::HashSet; +use tauri::State; + +use crate::DesktopRuntime; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SettingsLoadResult { + settings: Value, + source: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RestartResult { + restarted: bool, +} + +/// Load settings from disk (matches Express handler behavior) +#[tauri::command] +pub async fn load_settings(state: State<'_, DesktopRuntime>) -> Result { + let settings = state + .settings() + .load() + .await + .map_err(|e| format!("Failed to load settings: {}", e))?; + + Ok(SettingsLoadResult { + settings, + source: "desktop".to_string(), + }) +} + +/// Save settings to disk with merge logic matching Express implementation +#[tauri::command] +pub async fn save_settings( + changes: Value, + state: State<'_, DesktopRuntime>, +) -> Result { + // Load current settings + let current = state + .settings() + .load() + .await + .map_err(|e| format!("Failed to load current settings: {}", e))?; + + // Sanitize incoming changes + let sanitized_changes = sanitize_settings_update(&changes); + + // Merge changes into current settings + let merged = merge_persisted_settings(¤t, &sanitized_changes); + + // Save merged settings + state + .settings() + .save(merged.clone()) + .await + .map_err(|e| format!("Failed to save settings: {}", e))?; + + // Format response + Ok(format_settings_response(&merged)) +} + +/// Restart OpenCode CLI (matches Express /api/config/reload) +#[tauri::command] +pub async fn restart_opencode(state: State<'_, DesktopRuntime>) -> Result { + state + .opencode + .restart() + .await + .map_err(|e| format!("Failed to restart OpenCode: {}", e))?; + + Ok(RestartResult { restarted: true }) +} + +/// Sanitize settings update payload (port of Express sanitizeSettingsUpdate) +fn sanitize_settings_update(payload: &Value) -> Value { + let mut result = json!({}); + + if let Some(obj) = payload.as_object() { + let result_obj = result.as_object_mut().unwrap(); + + // String fields + if let Some(Value::String(s)) = obj.get("themeId") { + if !s.is_empty() { + result_obj.insert("themeId".to_string(), json!(s)); + } + } + if let Some(Value::String(s)) = obj.get("themeVariant") { + if s == "light" || s == "dark" { + result_obj.insert("themeVariant".to_string(), json!(s)); + } + } + if let Some(Value::String(s)) = obj.get("lightThemeId") { + if !s.is_empty() { + result_obj.insert("lightThemeId".to_string(), json!(s)); + } + } + if let Some(Value::String(s)) = obj.get("darkThemeId") { + if !s.is_empty() { + result_obj.insert("darkThemeId".to_string(), json!(s)); + } + } + if let Some(Value::String(s)) = obj.get("lastDirectory") { + if !s.is_empty() { + result_obj.insert("lastDirectory".to_string(), json!(s)); + } + } + if let Some(Value::String(s)) = obj.get("homeDirectory") { + if !s.is_empty() { + result_obj.insert("homeDirectory".to_string(), json!(s)); + } + } + if let Some(Value::String(s)) = obj.get("uiFont") { + if !s.is_empty() { + result_obj.insert("uiFont".to_string(), json!(s)); + } + } + if let Some(Value::String(s)) = obj.get("monoFont") { + if !s.is_empty() { + result_obj.insert("monoFont".to_string(), json!(s)); + } + } + if let Some(Value::String(s)) = obj.get("markdownDisplayMode") { + if !s.is_empty() { + result_obj.insert("markdownDisplayMode".to_string(), json!(s)); + } + } + + // Boolean fields + if let Some(Value::Bool(b)) = obj.get("useSystemTheme") { + result_obj.insert("useSystemTheme".to_string(), json!(b)); + } + if let Some(Value::Bool(b)) = obj.get("showReasoningTraces") { + result_obj.insert("showReasoningTraces".to_string(), json!(b)); + } + + // Array fields + if let Some(arr) = obj.get("approvedDirectories") { + result_obj.insert( + "approvedDirectories".to_string(), + normalize_string_array(arr), + ); + } + if let Some(arr) = obj.get("securityScopedBookmarks") { + result_obj.insert( + "securityScopedBookmarks".to_string(), + normalize_string_array(arr), + ); + } + if let Some(arr) = obj.get("pinnedDirectories") { + result_obj.insert("pinnedDirectories".to_string(), normalize_string_array(arr)); + } + + // Typography sizes object (partial) + if let Some(typo) = obj.get("typographySizes") { + if let Some(sanitized) = sanitize_typography_sizes_partial(typo) { + result_obj.insert("typographySizes".to_string(), sanitized); + } + } + } + + result +} + +/// Merge persisted settings (port of Express mergePersistedSettings) +fn merge_persisted_settings(current: &Value, changes: &Value) -> Value { + let mut result = current.clone(); + + if let (Some(result_obj), Some(changes_obj)) = (result.as_object_mut(), changes.as_object()) { + // First apply all changes + for (key, value) in changes_obj { + result_obj.insert(key.clone(), value.clone()); + } + + // Build approvedDirectories from base + additional + let base_approved = if let Some(arr) = changes_obj.get("approvedDirectories") { + extract_string_vec(arr) + } else if let Some(arr) = current.get("approvedDirectories") { + extract_string_vec(arr) + } else { + vec![] + }; + + let mut additional_approved = vec![]; + if let Some(Value::String(s)) = changes_obj.get("lastDirectory") { + if !s.is_empty() { + additional_approved.push(s.clone()); + } + } + if let Some(Value::String(s)) = changes_obj.get("homeDirectory") { + if !s.is_empty() { + additional_approved.push(s.clone()); + } + } + + let mut approved_set: HashSet = base_approved.into_iter().collect(); + for item in additional_approved { + approved_set.insert(item); + } + let approved_vec: Vec = approved_set.into_iter().collect(); + result_obj.insert("approvedDirectories".to_string(), json!(approved_vec)); + + // Security scoped bookmarks + let base_bookmarks = if let Some(arr) = changes_obj.get("securityScopedBookmarks") { + extract_string_vec(arr) + } else if let Some(arr) = current.get("securityScopedBookmarks") { + extract_string_vec(arr) + } else { + vec![] + }; + let bookmarks_set: HashSet = base_bookmarks.into_iter().collect(); + let bookmarks_vec: Vec = bookmarks_set.into_iter().collect(); + result_obj.insert("securityScopedBookmarks".to_string(), json!(bookmarks_vec)); + + // Merge typography sizes if present + if changes_obj.contains_key("typographySizes") { + let current_typo = current + .get("typographySizes") + .and_then(|v| v.as_object()) + .cloned() + .unwrap_or_default(); + let changes_typo = changes_obj + .get("typographySizes") + .and_then(|v| v.as_object()) + .cloned() + .unwrap_or_default(); + + let mut merged_typo = current_typo; + for (key, value) in changes_typo { + merged_typo.insert(key, value); + } + result_obj.insert("typographySizes".to_string(), json!(merged_typo)); + } + } + + result +} + +/// Format settings response (port of Express formatSettingsResponse) +fn format_settings_response(settings: &Value) -> Value { + let mut result = sanitize_settings_update(settings); + + if let Some(obj) = result.as_object_mut() { + // Ensure array fields are normalized + obj.insert( + "approvedDirectories".to_string(), + normalize_string_array(settings.get("approvedDirectories").unwrap_or(&json!([]))), + ); + obj.insert( + "securityScopedBookmarks".to_string(), + normalize_string_array( + settings + .get("securityScopedBookmarks") + .unwrap_or(&json!([])), + ), + ); + obj.insert( + "pinnedDirectories".to_string(), + normalize_string_array(settings.get("pinnedDirectories").unwrap_or(&json!([]))), + ); + + // Typography sizes + if let Some(sanitized_typo) = sanitize_typography_sizes_partial( + settings.get("typographySizes").unwrap_or(&json!(null)), + ) { + obj.insert("typographySizes".to_string(), sanitized_typo); + } + + // showReasoningTraces with fallback + let show_reasoning = settings + .get("showReasoningTraces") + .and_then(|v| v.as_bool()) + .or_else(|| { + // Get showReasoningTraces from sanitized result instead of the current mutable borrow + if let Some(Value::Bool(b)) = obj.get("showReasoningTraces") { + Some(*b) + } else { + None + } + }) + .unwrap_or(false); + obj.insert("showReasoningTraces".to_string(), json!(show_reasoning)); + } + + result +} + +/// Normalize string array helper +fn normalize_string_array(input: &Value) -> Value { + if let Some(arr) = input.as_array() { + let strings: Vec = arr + .iter() + .filter_map(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + .collect(); + let unique: HashSet = strings.into_iter().collect(); + json!(unique.into_iter().collect::>()) + } else { + json!([]) + } +} + +/// Sanitize typography sizes partial helper +fn sanitize_typography_sizes_partial(input: &Value) -> Option { + if let Some(obj) = input.as_object() { + let mut result = serde_json::Map::new(); + let mut populated = false; + + for key in &["markdown", "code", "uiHeader", "uiLabel", "meta", "micro"] { + if let Some(Value::String(s)) = obj.get(*key) { + if !s.is_empty() { + result.insert(key.to_string(), json!(s)); + populated = true; + } + } + } + + if populated { + Some(json!(result)) + } else { + None + } + } else { + None + } +} + +/// Extract string vector from JSON value +fn extract_string_vec(value: &Value) -> Vec { + if let Some(arr) = value.as_array() { + arr.iter() + .filter_map(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + .collect() + } else { + vec![] + } +} diff --git a/packages/desktop/src-tauri/src/commands/terminal.rs b/packages/desktop/src-tauri/src/commands/terminal.rs new file mode 100644 index 00000000..bca4563c --- /dev/null +++ b/packages/desktop/src-tauri/src/commands/terminal.rs @@ -0,0 +1,308 @@ +use log::error; +use portable_pty::{Child, CommandBuilder, MasterPty, NativePtySystem, PtySize, PtySystem}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::HashMap, + env, + io::{Read, Write}, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, + thread, +}; +use tauri::{Emitter, State, Window}; + +const DEFAULT_SHELL: &str = "/bin/zsh"; +const DEFAULT_TERM: &str = "xterm-256color"; +const DEFAULT_COLORTERM: &str = "truecolor"; +const DEFAULT_LOCALE: &str = "en_US.UTF-8"; +const TERM_PROGRAM_NAME: &str = "OpenChamber"; +const TERM_PROGRAM_VERSION: &str = env!("CARGO_PKG_VERSION"); + +pub struct TerminalSession { + pub master: Box, + pub writer: Arc>>, + pub child: Arc>>, +} + +pub struct TerminalState { + pub sessions: Arc>>, +} + +impl TerminalState { + pub fn new() -> Self { + Self { + sessions: Arc::new(Mutex::new(HashMap::new())), + } + } +} + +#[derive(Deserialize)] +pub struct CreateTerminalPayload { + pub cols: u16, + pub rows: u16, + pub cwd: Option, +} + +#[derive(Serialize)] +pub struct CreateTerminalResponse { + pub session_id: String, +} + +#[tauri::command] +pub async fn create_terminal_session( + payload: CreateTerminalPayload, + state: State<'_, TerminalState>, + window: Window, +) -> Result { + let pty_system = NativePtySystem::default(); + let size = PtySize { + rows: payload.rows, + cols: payload.cols, + pixel_width: 0, + pixel_height: 0, + }; + + let working_dir = resolve_working_directory(payload.cwd.as_deref())?; + let shell_path = resolve_shell(); + + let mut cmd = CommandBuilder::new(&shell_path); + if shell_accepts_login_flag(&shell_path) { + cmd.arg("-l"); + } + if let Some(cwd) = working_dir.to_str() { + cmd.cwd(cwd); + } + apply_terminal_environment(&mut cmd, &shell_path); + + let pair = pty_system.openpty(size).map_err(|e| e.to_string())?; + let child = pair + .slave + .spawn_command(cmd) + .map_err(|e| format!("Failed to spawn shell: {e}"))?; + drop(pair.slave); + + let reader = pair + .master + .try_clone_reader() + .map_err(|e| format!("Failed to clone PTY reader: {e}"))?; + let writer = Arc::new(Mutex::new( + pair.master + .take_writer() + .map_err(|e| format!("Failed to take PTY writer: {e}"))?, + )); + let master = pair.master; + let child = Arc::new(Mutex::new(child)); + + let session_id = uuid::Uuid::new_v4().to_string(); + state.sessions.lock().unwrap().insert( + session_id.clone(), + TerminalSession { + master, + writer: writer.clone(), + child: child.clone(), + }, + ); + + spawn_reader_thread(reader, window.clone(), session_id.clone()); + spawn_exit_watcher(child, window, state.sessions.clone(), session_id.clone()); + + Ok(CreateTerminalResponse { session_id }) +} + +#[tauri::command] +pub async fn send_terminal_input( + session_id: String, + data: String, + state: State<'_, TerminalState>, +) -> Result<(), String> { + let sessions = state.sessions.lock().unwrap(); + let Some(session) = sessions.get(&session_id) else { + return Err("Terminal session not found".to_string()); + }; + + let mut writer = session + .writer + .lock() + .map_err(|_| "Terminal busy".to_string())?; + writer + .write_all(data.as_bytes()) + .map_err(|e| format!("Failed to write to terminal: {e}"))?; + writer + .flush() + .map_err(|e| format!("Failed to flush terminal input: {e}"))?; + Ok(()) +} + +#[tauri::command] +pub async fn resize_terminal( + session_id: String, + cols: u16, + rows: u16, + state: State<'_, TerminalState>, +) -> Result<(), String> { + let mut sessions = state.sessions.lock().unwrap(); + let Some(session) = sessions.get_mut(&session_id) else { + return Err("Terminal session not found".to_string()); + }; + + session + .master + .resize(PtySize { + rows, + cols, + pixel_width: 0, + pixel_height: 0, + }) + .map_err(|e| format!("Failed to resize terminal: {e}"))?; + Ok(()) +} + +#[tauri::command] +pub async fn close_terminal( + session_id: String, + state: State<'_, TerminalState>, +) -> Result<(), String> { + let session = { + let mut sessions = state.sessions.lock().unwrap(); + sessions.remove(&session_id) + }; + + if let Some(session) = session { + if let Ok(mut child) = session.child.lock() { + let _ = child.kill(); + } + } + + Ok(()) +} + +fn spawn_reader_thread(mut reader: Box, window: Window, session_id: String) { + thread::spawn(move || { + let mut buffer = [0u8; 4096]; + let event_name = format!("terminal://{}", session_id); + loop { + match reader.read(&mut buffer) { + Ok(0) => break, + Ok(n) => { + let data = String::from_utf8_lossy(&buffer[..n]).to_string(); + if data.is_empty() { + continue; + } + + if let Err(error) = + window.emit(&event_name, serde_json::json!({ "type": "data", "data": data })) + { + error!("Failed to emit terminal data: {error}"); + break; + } + } + Err(error) => { + error!("Terminal read error: {error}"); + break; + } + } + } + }); +} + +fn spawn_exit_watcher( + child: Arc>>, + window: Window, + sessions: Arc>>, + session_id: String, +) { + thread::spawn(move || { + let status = { + let mut guard = child.lock().expect("terminal child poisoned"); + guard.wait() + }; + + let (exit_code, signal) = match status { + Ok(status) => ( + status.exit_code() as i32, + status.signal().map(|sig| sig.to_string()), + ), + Err(err) => { + error!("Failed to wait for terminal exit: {err}"); + (1, Some("Terminal crashed".to_string())) + } + }; + + let event_name = format!("terminal://{}", session_id); + let payload = serde_json::json!({ + "type": "exit", + "exitCode": exit_code, + "signal": signal + }); + let _ = window.emit(&event_name, payload); + + let mut sessions = sessions.lock().unwrap(); + sessions.remove(&session_id); + }); +} + +fn resolve_shell() -> String { + env::var("SHELL") + .ok() + .filter(|value| !value.trim().is_empty()) + .unwrap_or_else(|| DEFAULT_SHELL.to_string()) +} + +fn shell_accepts_login_flag(shell_path: &str) -> bool { + let shell_name = Path::new(shell_path) + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or(shell_path) + .to_lowercase(); + + matches!( + shell_name.as_str(), + name if name.contains("zsh") + || name.contains("bash") + || name.contains("sh") + || name.contains("fish") + || name.contains("ksh") + ) +} + +fn resolve_working_directory(input: Option<&str>) -> Result { + let maybe_path = input + .map(|value| PathBuf::from(value)) + .or_else(|| dirs::home_dir()); + + let Some(path) = maybe_path else { + return Err("Unable to determine working directory".to_string()); + }; + + if !path.exists() || !path.is_dir() { + return Err(format!( + "Working directory is not accessible: {}", + path.display() + )); + } + + Ok(path) +} + +fn apply_terminal_environment(cmd: &mut CommandBuilder, shell_path: &str) { + cmd.env( + "TERM", + env::var("TERM").unwrap_or_else(|_| DEFAULT_TERM.to_string()), + ); + cmd.env( + "COLORTERM", + env::var("COLORTERM").unwrap_or_else(|_| DEFAULT_COLORTERM.to_string()), + ); + cmd.env( + "LC_ALL", + env::var("LC_ALL").unwrap_or_else(|_| DEFAULT_LOCALE.to_string()), + ); + cmd.env( + "LANG", + env::var("LANG").unwrap_or_else(|_| DEFAULT_LOCALE.to_string()), + ); + cmd.env("TERM_PROGRAM", TERM_PROGRAM_NAME); + cmd.env("TERM_PROGRAM_VERSION", TERM_PROGRAM_VERSION); + cmd.env("OPENCHAMBER_DESKTOP", "1"); + cmd.env("SHELL", shell_path); +} diff --git a/packages/desktop/src-tauri/src/lib.rs b/packages/desktop/src-tauri/src/lib.rs new file mode 100644 index 00000000..e69de29b diff --git a/packages/desktop/src-tauri/src/logging.rs b/packages/desktop/src-tauri/src/logging.rs new file mode 100644 index 00000000..dbc2dba9 --- /dev/null +++ b/packages/desktop/src-tauri/src/logging.rs @@ -0,0 +1,20 @@ +use std::path::PathBuf; + +#[cfg(target_os = "macos")] +const PLATFORM_LOG_SEGMENTS: &[&str] = &["Library", "Logs", "OpenChamber"]; +#[cfg(not(target_os = "macos"))] +const PLATFORM_LOG_SEGMENTS: &[&str] = &[".config", "openchamber", "logs"]; + +pub fn log_directory() -> Option { + let mut path = dirs::home_dir()?; + for segment in PLATFORM_LOG_SEGMENTS { + path.push(segment); + } + Some(path) +} + +pub fn log_file_path() -> Option { + let mut dir = log_directory()?; + dir.push("desktop.log"); + Some(dir) +} diff --git a/packages/desktop/src-tauri/src/main.rs b/packages/desktop/src-tauri/src/main.rs new file mode 100644 index 00000000..9172e40b --- /dev/null +++ b/packages/desktop/src-tauri/src/main.rs @@ -0,0 +1,1084 @@ +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +mod commands; +mod logging; +mod assistant_notifications; +mod session_activity; +mod opencode_config; +mod opencode_manager; +mod window_state; + +use std::{collections::HashMap, path::PathBuf, sync::Arc, time::{Duration, Instant}}; + +use anyhow::{anyhow, Result}; +use axum::{ + body::{to_bytes, Body}, + extract::{OriginalUri, State}, + http::{Method, Request, Response, StatusCode}, + response::IntoResponse, + routing::{any, get, post}, + Json, Router, +}; +use assistant_notifications::spawn_assistant_notifications; +use session_activity::spawn_session_activity_tracker; +use commands::files::{create_directory, list_directory, search_files}; +use commands::git::{ + add_git_worktree, check_is_git_repository, checkout_branch, create_branch, create_git_commit, + create_git_identity, delete_git_branch, delete_git_identity, delete_remote_branch, + ensure_openchamber_ignored, generate_commit_message, get_commit_files, get_current_git_identity, + get_git_branches, get_git_diff, get_git_file_diff, get_git_identities, get_git_log, get_git_status, + git_fetch, git_pull, git_push, is_linked_worktree, list_git_worktrees, remove_git_worktree, + revert_git_file, set_git_identity, update_git_identity, +}; +use commands::logs::fetch_desktop_logs; +use commands::permissions::{ + pick_directory, process_directory_selection, request_directory_access, + restore_bookmarks_on_startup, start_accessing_directory, stop_accessing_directory, +}; +use commands::notifications::desktop_notify; +use commands::settings::{load_settings, restart_opencode, save_settings}; +use commands::terminal::{ + close_terminal, create_terminal_session, resize_terminal, send_terminal_input, TerminalState, +}; +use futures_util::StreamExt as FuturesStreamExt; +use log::{error, info, warn}; +use opencode_manager::OpenCodeManager; +use portpicker::pick_unused_port; +use reqwest::{header, Body as ReqwestBody, Client}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use tauri::{Emitter, Manager, WebviewWindow}; +use tauri_plugin_dialog::init as dialog_plugin; +use tauri_plugin_fs::init as fs_plugin; +use tauri_plugin_log::{Target, TargetKind}; +use tauri_plugin_notification::init as notification_plugin; +use tauri_plugin_shell::init as shell_plugin; +use tokio::{ + fs, + net::TcpListener, + sync::{broadcast, Mutex}, +}; +use tower_http::cors::CorsLayer; +use window_state::{load_window_state, persist_window_state, WindowStateManager}; + +#[cfg(target_os = "macos")] +use window_vibrancy::{apply_vibrancy, NSVisualEffectMaterial}; + +const PROXY_BODY_LIMIT: usize = 32 * 1024 * 1024; // 32MB +const CLIENT_RELOAD_DELAY_MS: u64 = 800; +const MODELS_DEV_API_URL: &str = "https://models.dev/api.json"; +const MODELS_METADATA_CACHE_TTL: Duration = Duration::from_secs(5 * 60); +const MODELS_METADATA_REQUEST_TIMEOUT: Duration = Duration::from_secs(8); + +#[derive(Clone)] +pub(crate) struct DesktopRuntime { + server_port: u16, + shutdown_tx: broadcast::Sender<()>, + opencode: Arc, + settings: Arc, +} + +impl DesktopRuntime { + async fn initialize() -> Result { + let settings = Arc::new(SettingsStore::new()?); + + // Read lastDirectory from settings before starting OpenCode + let initial_dir = settings.last_directory().await.ok().flatten(); + + let opencode = Arc::new(OpenCodeManager::new_with_directory(initial_dir.clone())); + + // Try to start OpenCode if CLI is available + if opencode.is_cli_available() { + if let Err(e) = opencode.ensure_running().await { + warn!("[desktop] Failed to start OpenCode: {}", e); + } + } else { + info!("[desktop] OpenCode CLI not available - running in limited mode"); + } + + let client = Client::builder().build()?; + + let (shutdown_tx, shutdown_rx) = broadcast::channel(2); + let server_port = + pick_unused_port().ok_or_else(|| anyhow!("No free port available"))? as u16; + let server_state = ServerState { + client, + opencode: opencode.clone(), + server_port, + directory_change_lock: Arc::new(Mutex::new(())), + models_metadata_cache: Arc::new(Mutex::new(ModelsMetadataCache::default())), + }; + + spawn_http_server(server_port, server_state, shutdown_rx); + + Ok(Self { + server_port, + shutdown_tx, + opencode, + settings, + }) + } + + async fn shutdown(&self) { + let _ = self.shutdown_tx.send(()); + let _ = self.opencode.shutdown().await; + } + + pub(crate) fn settings(&self) -> &SettingsStore { + self.settings.as_ref() + } + + pub(crate) fn subscribe_shutdown(&self) -> broadcast::Receiver<()> { + self.shutdown_tx.subscribe() + } + + pub(crate) fn opencode_manager(&self) -> Arc { + self.opencode.clone() + } +} + +#[derive(Clone)] +struct ServerState { + client: Client, + opencode: Arc, + server_port: u16, + directory_change_lock: Arc>, + models_metadata_cache: Arc>, +} + +#[derive(Default)] +struct ModelsMetadataCache { + payload: Option, + fetched_at: Option, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ConfigActionResponse { + success: bool, + requires_reload: bool, + message: String, + reload_delay_ms: u64, +} + +#[derive(Serialize)] +struct ConfigErrorResponse { + error: String, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ConfigMetadataResponse { + name: String, + sources: opencode_config::ConfigSources, + is_built_in: bool, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct HealthResponse { + status: &'static str, + server_port: u16, + opencode_port: Option, + api_prefix: String, + is_opencode_ready: bool, + cli_available: bool, +} + +#[derive(Serialize)] +struct ServerInfoPayload { + server_port: u16, + opencode_port: Option, + api_prefix: String, + cli_available: bool, +} + +#[tauri::command] +async fn desktop_server_info( + state: tauri::State<'_, DesktopRuntime>, +) -> Result { + Ok(ServerInfoPayload { + server_port: state.server_port, + opencode_port: state.opencode.current_port(), + api_prefix: state.opencode.api_prefix(), + cli_available: state.opencode.is_cli_available(), + }) +} + +#[tauri::command] +async fn desktop_restart_opencode(state: tauri::State<'_, DesktopRuntime>) -> Result<(), String> { + state + .opencode + .restart() + .await + .map_err(|err| err.to_string()) +} + +#[tauri::command] +async fn desktop_open_devtools(window: WebviewWindow) -> Result<(), String> { + window.open_devtools(); + Ok(()) +} + +#[cfg(target_os = "macos")] +fn prevent_app_nap() { + use objc2_foundation::{NSActivityOptions, NSProcessInfo, NSString}; + + // NSActivityUserInitiated (0x00FFFFFF) | NSActivityLatencyCritical (0xFF00000000) + let options = NSActivityOptions(0x00FFFFFF | 0xFF00000000); + let reason = NSString::from_str("Prevent App Nap"); + + let process_info = NSProcessInfo::processInfo(); + let activity = process_info.beginActivityWithOptions_reason(options, &reason); + + // Leak the activity token to keep it active indefinitely + std::mem::forget(activity); + + info!("[macos] App Nap prevention enabled via objc2"); +} + +fn main() { + let mut log_builder = tauri_plugin_log::Builder::default() + .level(log::LevelFilter::Info) + .clear_targets() + .target(Target::new(TargetKind::Stdout)) + .target(Target::new(TargetKind::Webview)); + + if let Some(dir) = logging::log_directory() { + log_builder = log_builder.target(Target::new(TargetKind::Folder { + path: dir, + file_name: Some("desktop".into()), + })); + } + + let app = tauri::Builder::default() + .plugin(shell_plugin()) + .plugin(dialog_plugin()) + .plugin(fs_plugin()) + .plugin(notification_plugin()) + .plugin(tauri_plugin_updater::Builder::new().build()) + .plugin(log_builder.build()) + .setup(|app| { + #[cfg(target_os = "macos")] + prevent_app_nap(); + + let runtime = tauri::async_runtime::block_on(DesktopRuntime::initialize())?; + app.manage(runtime.clone()); + + // Background assistant completion notifications (SSE) independent of the webview lifecycle + let app_handle = app.app_handle(); + spawn_assistant_notifications(app_handle.clone(), runtime.clone()); + spawn_session_activity_tracker(app_handle.clone(), runtime.clone()); + + if let Some(window) = app.get_webview_window("main") { + #[cfg(target_os = "macos")] + { + if let Err(error) = + apply_vibrancy(&window, NSVisualEffectMaterial::Sidebar, None, Some(24.0)) + { + warn!("[desktop:vibrancy] Failed to apply macOS vibrancy: {}", error); + } else { + info!("[desktop:vibrancy] Applied macOS Sidebar vibrancy to main window"); + } + } + } + + app.manage(TerminalState::new()); + + let stored_state = tauri::async_runtime::block_on(load_window_state()).unwrap_or(None); + let manager = WindowStateManager::new(stored_state.clone().unwrap_or_default()); + app.manage(manager.clone()); + + if let Some(saved) = stored_state { + if let Some(window) = app.get_webview_window("main") { + let _ = window_state::apply_window_state(&window, &saved); + } + } + + // Restore bookmarks on startup (macOS security-scoped access) + // We'll do this synchronously within the setup to avoid lifetime issues + tauri::async_runtime::block_on(async { + if let Err(e) = + restore_bookmarks_on_startup(app.state::().clone()).await + { + warn!("Failed to restore bookmarks on startup: {}", e); + } + }); + + Ok(()) + }) + .invoke_handler(tauri::generate_handler![ + desktop_server_info, + desktop_restart_opencode, + desktop_open_devtools, + load_settings, + save_settings, + restart_opencode, + list_directory, + search_files, + create_directory, + request_directory_access, + start_accessing_directory, + stop_accessing_directory, + pick_directory, + restore_bookmarks_on_startup, + process_directory_selection, + check_is_git_repository, + get_git_status, + get_git_diff, + get_git_file_diff, + revert_git_file, + is_linked_worktree, + get_git_branches, + delete_git_branch, + delete_remote_branch, + list_git_worktrees, + add_git_worktree, + remove_git_worktree, + ensure_openchamber_ignored, + create_git_commit, + git_push, + git_pull, + git_fetch, + checkout_branch, + create_branch, + get_git_log, + get_commit_files, + get_git_identities, + create_git_identity, + update_git_identity, + delete_git_identity, + get_current_git_identity, + set_git_identity, + generate_commit_message, + create_terminal_session, + send_terminal_input, + resize_terminal, + close_terminal, + fetch_desktop_logs, + desktop_notify, + ]) + .on_window_event(|window, event| { + let window_state_manager = window.state::().inner().clone(); + + match event { + tauri::WindowEvent::Focused(true) => { + // Clear dock badge and underlying badge state when the window gains focus + let _ = window.set_badge_count(None); + let _ = window.app_handle().emit("openchamber:clear-badge-sessions", ()); + } + tauri::WindowEvent::Moved(position) => { + let is_maximized = window.is_maximized().unwrap_or(false); + window_state_manager.update_position( + position.x as f64, + position.y as f64, + is_maximized, + ); + } + tauri::WindowEvent::Resized(size) => { + let is_maximized = window.is_maximized().unwrap_or(false); + window_state_manager.update_size( + size.width as f64, + size.height as f64, + is_maximized, + ); + } + tauri::WindowEvent::CloseRequested { api, .. } => { + api.prevent_close(); + let runtime = window.state::().inner().clone(); + let window_handle = window.clone(); + let manager_clone = window_state_manager.clone(); + tauri::async_runtime::spawn(async move { + if let Err(err) = persist_window_state(&window_handle, &manager_clone).await + { + warn!("Failed to persist window state: {}", err); + } + runtime.shutdown().await; + let _ = window_handle.app_handle().exit(0); + }); + } + _ => {} + } + }) + .build(tauri::generate_context!()) + .expect("failed to build Tauri application"); + + app.run(|_app_handle, _event| {}); +} + + +fn spawn_http_server(port: u16, state: ServerState, shutdown_rx: broadcast::Receiver<()>) { + tauri::async_runtime::spawn(async move { + if let Err(error) = run_http_server(port, state, shutdown_rx).await { + error!("[desktop:http] server stopped: {error:?}"); + } + }); +} + +async fn run_http_server( + port: u16, + state: ServerState, + mut shutdown_rx: broadcast::Receiver<()>, +) -> Result<()> { + let router = Router::new() + .route("/health", get(health_handler)) + .route("/api/openchamber/models-metadata", get(models_metadata_handler)) + .route("/api/opencode/directory", post(change_directory_handler)) + .route("/api", any(proxy_to_opencode)) + .route("/api/{*rest}", any(proxy_to_opencode)) + .with_state(state) + .layer(CorsLayer::permissive()); + + let addr = format!("127.0.0.1:{port}"); + let listener = TcpListener::bind(&addr).await?; + info!("[desktop:http] listening on http://{addr}"); + + axum::serve(listener, router) + .with_graceful_shutdown(async move { + let _ = shutdown_rx.recv().await; + }) + .await?; + + Ok(()) +} + +async fn health_handler(State(state): State) -> Json { + Json(HealthResponse { + status: "ok", + server_port: state.server_port, + opencode_port: state.opencode.current_port(), + api_prefix: state.opencode.api_prefix(), + is_opencode_ready: state.opencode.is_ready(), + cli_available: opencode_manager::check_cli_exists(), + }) +} + +async fn models_metadata_handler(State(state): State) -> Result, StatusCode> { + let now = Instant::now(); + let cached_payload: Option = { + let cache = state.models_metadata_cache.lock().await; + if let (Some(payload), Some(fetched_at)) = (&cache.payload, cache.fetched_at) { + if now.duration_since(fetched_at) < MODELS_METADATA_CACHE_TTL { + return Ok(Json(payload.clone())); + } + } + cache.payload.clone() + }; + + let response = state + .client + .get(MODELS_DEV_API_URL) + .header(header::ACCEPT, "application/json") + .timeout(MODELS_METADATA_REQUEST_TIMEOUT) + .send() + .await + .map_err(|error| { + warn!("[desktop:http] Failed to fetch models metadata: {error}"); + StatusCode::BAD_GATEWAY + })?; + + if !response.status().is_success() { + warn!( + "[desktop:http] models.dev responded with status {}", + response.status() + ); + if let Some(payload) = cached_payload { + return Ok(Json(payload)); + } + return Err(StatusCode::BAD_GATEWAY); + } + + let payload = response.json::().await.map_err(|error| { + warn!("[desktop:http] Failed to parse models.dev payload: {error}"); + StatusCode::BAD_GATEWAY + })?; + + { + let mut cache = state.models_metadata_cache.lock().await; + cache.payload = Some(payload.clone()); + cache.fetched_at = Some(Instant::now()); + } + + Ok(Json(payload)) +} + +#[derive(Deserialize)] +struct DirectoryChangeRequest { + path: String, +} + +#[derive(Serialize)] +struct DirectoryChangeResponse { + success: bool, + restarted: bool, + path: String, +} + +fn json_response(status: StatusCode, payload: T) -> Response { + (status, Json(payload)).into_response() +} + +fn config_error_response(status: StatusCode, message: impl Into) -> Response { + json_response(status, ConfigErrorResponse { + error: message.into(), + }) +} + +async fn parse_request_payload(req: Request) -> Result, Response> { + let (_, body) = req.into_parts(); + let body_bytes = to_bytes(body, PROXY_BODY_LIMIT) + .await + .map_err(|_| config_error_response(StatusCode::BAD_REQUEST, "Invalid request body"))?; + + if body_bytes.is_empty() { + return Ok(HashMap::new()); + } + + serde_json::from_slice::>(&body_bytes) + .map_err(|_| config_error_response(StatusCode::BAD_REQUEST, "Malformed JSON payload")) +} + +async fn refresh_opencode_after_config_change( + state: &ServerState, + reason: &str, +) -> Result<(), Response> { + info!("[desktop:config] Restarting OpenCode after {}", reason); + state + .opencode + .restart() + .await + .map_err(|err| config_error_response( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Failed to restart OpenCode: {}", err), + ))?; + Ok(()) +} + +async fn handle_agent_route( + state: &ServerState, + method: Method, + req: Request, + name: String, +) -> Result, StatusCode> { + match method { + Method::GET => { + match opencode_config::get_agent_sources(&name).await { + Ok(sources) => Ok(json_response( + StatusCode::OK, + ConfigMetadataResponse { + name, + is_built_in: !sources.md.exists && !sources.json.exists, + sources, + }, + )), + Err(err) => { + error!("[desktop:config] Failed to read agent sources: {}", err); + Ok(config_error_response( + StatusCode::INTERNAL_SERVER_ERROR, + "Failed to read agent configuration", + )) + } + } + } + Method::POST => { + let payload = match parse_request_payload(req).await { + Ok(data) => data, + Err(resp) => return Ok(resp), + }; + + match opencode_config::create_agent(&name, &payload).await { + Ok(()) => { + if let Err(resp) = + refresh_opencode_after_config_change(state, "agent creation").await + { + return Ok(resp); + } + + Ok(json_response( + StatusCode::OK, + ConfigActionResponse { + success: true, + requires_reload: true, + message: format!( + "Agent {} created successfully. Reloading interface...", + name + ), + reload_delay_ms: CLIENT_RELOAD_DELAY_MS, + }, + )) + } + Err(err) => { + error!("[desktop:config] Failed to create agent {}: {}", name, err); + Ok(config_error_response( + StatusCode::INTERNAL_SERVER_ERROR, + err.to_string(), + )) + } + } + } + Method::PATCH => { + let payload = match parse_request_payload(req).await { + Ok(data) => data, + Err(resp) => return Ok(resp), + }; + + match opencode_config::update_agent(&name, &payload).await { + Ok(()) => { + if let Err(resp) = + refresh_opencode_after_config_change(state, "agent update").await + { + return Ok(resp); + } + + Ok(json_response( + StatusCode::OK, + ConfigActionResponse { + success: true, + requires_reload: true, + message: format!( + "Agent {} updated successfully. Reloading interface...", + name + ), + reload_delay_ms: CLIENT_RELOAD_DELAY_MS, + }, + )) + } + Err(err) => { + error!("[desktop:config] Failed to update agent {}: {}", name, err); + Ok(config_error_response( + StatusCode::INTERNAL_SERVER_ERROR, + err.to_string(), + )) + } + } + } + Method::DELETE => match opencode_config::delete_agent(&name).await { + Ok(()) => { + if let Err(resp) = + refresh_opencode_after_config_change(state, "agent deletion").await + { + return Ok(resp); + } + + Ok(json_response( + StatusCode::OK, + ConfigActionResponse { + success: true, + requires_reload: true, + message: format!( + "Agent {} deleted successfully. Reloading interface...", + name + ), + reload_delay_ms: CLIENT_RELOAD_DELAY_MS, + }, + )) + } + Err(err) => { + error!("[desktop:config] Failed to delete agent {}: {}", name, err); + Ok(config_error_response( + StatusCode::INTERNAL_SERVER_ERROR, + err.to_string(), + )) + } + }, + _ => Ok(StatusCode::METHOD_NOT_ALLOWED.into_response()), + } +} + +async fn handle_command_route( + state: &ServerState, + method: Method, + req: Request, + name: String, +) -> Result, StatusCode> { + match method { + Method::GET => { + match opencode_config::get_command_sources(&name).await { + Ok(sources) => Ok(json_response( + StatusCode::OK, + ConfigMetadataResponse { + name, + is_built_in: !sources.md.exists && !sources.json.exists, + sources, + }, + )), + Err(err) => { + error!("[desktop:config] Failed to read command sources: {}", err); + Ok(config_error_response( + StatusCode::INTERNAL_SERVER_ERROR, + "Failed to read command configuration", + )) + } + } + } + Method::POST => { + let payload = match parse_request_payload(req).await { + Ok(data) => data, + Err(resp) => return Ok(resp), + }; + + match opencode_config::create_command(&name, &payload).await { + Ok(()) => { + if let Err(resp) = + refresh_opencode_after_config_change(state, "command creation").await + { + return Ok(resp); + } + + Ok(json_response( + StatusCode::OK, + ConfigActionResponse { + success: true, + requires_reload: true, + message: format!( + "Command {} created successfully. Reloading interface...", + name + ), + reload_delay_ms: CLIENT_RELOAD_DELAY_MS, + }, + )) + } + Err(err) => { + error!("[desktop:config] Failed to create command {}: {}", name, err); + Ok(config_error_response( + StatusCode::INTERNAL_SERVER_ERROR, + err.to_string(), + )) + } + } + } + Method::PATCH => { + let payload = match parse_request_payload(req).await { + Ok(data) => data, + Err(resp) => return Ok(resp), + }; + + match opencode_config::update_command(&name, &payload).await { + Ok(()) => { + if let Err(resp) = + refresh_opencode_after_config_change(state, "command update").await + { + return Ok(resp); + } + + Ok(json_response( + StatusCode::OK, + ConfigActionResponse { + success: true, + requires_reload: true, + message: format!( + "Command {} updated successfully. Reloading interface...", + name + ), + reload_delay_ms: CLIENT_RELOAD_DELAY_MS, + }, + )) + } + Err(err) => { + error!("[desktop:config] Failed to update command {}: {}", name, err); + Ok(config_error_response( + StatusCode::INTERNAL_SERVER_ERROR, + err.to_string(), + )) + } + } + } + Method::DELETE => match opencode_config::delete_command(&name).await { + Ok(()) => { + if let Err(resp) = + refresh_opencode_after_config_change(state, "command deletion").await + { + return Ok(resp); + } + + Ok(json_response( + StatusCode::OK, + ConfigActionResponse { + success: true, + requires_reload: true, + message: format!( + "Command {} deleted successfully. Reloading interface...", + name + ), + reload_delay_ms: CLIENT_RELOAD_DELAY_MS, + }, + )) + } + Err(err) => { + error!("[desktop:config] Failed to delete command {}: {}", name, err); + let status = if err.to_string().contains("not found") { + StatusCode::NOT_FOUND + } else { + StatusCode::INTERNAL_SERVER_ERROR + }; + Ok(config_error_response(status, err.to_string())) + } + }, + _ => Ok(StatusCode::METHOD_NOT_ALLOWED.into_response()), + } +} + +async fn handle_config_routes( + state: ServerState, + path: &str, + method: Method, + req: Request, +) -> Result, StatusCode> { + if let Some(name) = path.strip_prefix("/api/config/agents/") { + let trimmed = name.trim(); + if trimmed.is_empty() { + return Ok(config_error_response( + StatusCode::BAD_REQUEST, + "Agent name is required", + )); + } + return handle_agent_route(&state, method, req, trimmed.to_string()).await; + } + + if let Some(name) = path.strip_prefix("/api/config/commands/") { + let trimmed = name.trim(); + if trimmed.is_empty() { + return Ok(config_error_response( + StatusCode::BAD_REQUEST, + "Command name is required", + )); + } + return handle_command_route(&state, method, req, trimmed.to_string()).await; + } + + if path == "/api/config/reload" && method == Method::POST { + if let Err(resp) = + refresh_opencode_after_config_change(&state, "manual configuration reload").await + { + return Ok(resp); + } + + return Ok(json_response( + StatusCode::OK, + ConfigActionResponse { + success: true, + requires_reload: true, + message: "Configuration reloaded successfully. Refreshing interface..." + .to_string(), + reload_delay_ms: CLIENT_RELOAD_DELAY_MS, + }, + )); + } + + Ok(StatusCode::NOT_FOUND.into_response()) +} + +async fn change_directory_handler( + State(state): State, + Json(payload): Json, +) -> Result, StatusCode> { + // Acquire lock to prevent concurrent directory changes + let _lock = state.directory_change_lock.lock().await; + + let requested_path = payload.path.trim(); + if requested_path.is_empty() { + warn!("[desktop:http] ERROR: Empty path provided"); + return Err(StatusCode::BAD_REQUEST); + } + + let resolved_path = PathBuf::from(requested_path); + + // Validate directory exists and is accessible + match fs::metadata(&resolved_path).await { + Ok(metadata) => { + if !metadata.is_dir() { + warn!( + "[desktop:http] ERROR: Path is not a directory: {:?}", + resolved_path + ); + return Err(StatusCode::BAD_REQUEST); + } + } + Err(err) => { + warn!( + "[desktop:http] ERROR: Cannot access path: {:?} - {}", + resolved_path, err + ); + return Err(StatusCode::NOT_FOUND); + } + } + + let current_dir = state.opencode.get_working_directory(); + let is_running = state.opencode.current_port().is_some(); + + // If already on this directory and OpenCode is running, no restart needed + if current_dir == resolved_path && is_running { + return Ok(Json(DirectoryChangeResponse { + success: true, + restarted: false, + path: resolved_path.to_string_lossy().to_string(), + })); + } + + info!("[desktop:http] Changing directory to {:?}", resolved_path); + + // Update working directory and restart OpenCode + state + .opencode + .set_working_directory(resolved_path.clone()) + .await + .map_err(|e| { + error!( + "[desktop:http] ERROR: Failed to set working directory: {}", + e + ); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + state.opencode.restart().await.map_err(|e| { + error!("[desktop:http] ERROR: Failed to restart OpenCode: {}", e); + StatusCode::INTERNAL_SERVER_ERROR + })?; + + Ok(Json(DirectoryChangeResponse { + success: true, + restarted: true, + path: resolved_path.to_string_lossy().to_string(), + })) +} + +async fn proxy_to_opencode( + State(state): State, + original: OriginalUri, + req: Request, +) -> Result, StatusCode> { + let origin_path = original.0.path().to_string(); + let method = req.method().clone(); + + let is_desktop_config_route = origin_path.starts_with("/api/config/agents/") + || origin_path.starts_with("/api/config/commands/") + || origin_path == "/api/config/reload"; + + if is_desktop_config_route { + return handle_config_routes(state, &origin_path, method, req).await; + } + + let port = state.opencode.current_port().ok_or_else(|| { + error!("[desktop:http] PROXY FAILED: OpenCode not running (no port)"); + StatusCode::SERVICE_UNAVAILABLE + })?; + + let query = original.0.query(); + let rewritten_path = state.opencode.rewrite_path(&origin_path); + let mut target = format!("http://127.0.0.1:{port}{rewritten_path}"); + if let Some(q) = query { + target.push('?'); + target.push_str(q); + } + + let (parts, body) = req.into_parts(); + let method = parts.method.clone(); + let mut builder = state.client.request(method, &target); + + let mut headers = parts.headers; + headers.insert(header::HOST, format!("127.0.0.1:{port}").parse().unwrap()); + if headers + .get(header::ACCEPT) + .and_then(|v| v.to_str().ok()) + .map(|val| val.contains("text/event-stream")) + .unwrap_or(false) + { + headers.insert(header::CONNECTION, "keep-alive".parse().unwrap()); + } + + for (key, value) in headers.iter() { + if key == &header::CONTENT_LENGTH { + continue; + } + builder = builder.header(key, value); + } + + let body_bytes = to_bytes(body, PROXY_BODY_LIMIT) + .await + .map_err(|_| StatusCode::BAD_GATEWAY)?; + + let response = if body_bytes.is_empty() { + builder.send().await.map_err(|_| StatusCode::BAD_GATEWAY)? + } else { + builder + .body(ReqwestBody::from(body_bytes)) + .send() + .await + .map_err(|_| StatusCode::BAD_GATEWAY)? + }; + + let status = response.status(); + let mut resp_builder = Response::builder().status(status); + for (key, value) in response.headers() { + if key.as_str().eq_ignore_ascii_case("connection") { + continue; + } + resp_builder = resp_builder.header(key, value); + } + + let stream = response.bytes_stream().map(|chunk| { + chunk + .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err)) + .map(axum::body::Bytes::from) + }); + let body = Body::from_stream(stream); + resp_builder.body(body).map_err(|_| StatusCode::BAD_GATEWAY) +} + +#[derive(Clone)] +pub(crate) struct SettingsStore { + path: PathBuf, + guard: Arc>, +} + +impl SettingsStore { + pub(crate) fn new() -> Result { + // Use ~/.config/openchamber for consistency with Electron/web versions + let home = dirs::home_dir().ok_or_else(|| anyhow!("No home directory"))?; + let mut dir = home; + dir.push(".config"); + dir.push("openchamber"); + std::fs::create_dir_all(&dir).ok(); + dir.push("settings.json"); + Ok(Self { + path: dir, + guard: Arc::new(Mutex::new(())), + }) + } + + pub(crate) async fn load(&self) -> Result { + let _lock = self.guard.lock().await; + match fs::read(&self.path).await { + Ok(bytes) => { + let value = + serde_json::from_slice(&bytes).unwrap_or(Value::Object(Default::default())); + Ok(value) + } + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + Ok(Value::Object(Default::default())) + } + Err(err) => Err(err.into()), + } + } + + pub(crate) async fn save(&self, payload: Value) -> Result<()> { + let _lock = self.guard.lock().await; + if let Some(parent) = self.path.parent() { + fs::create_dir_all(parent).await.ok(); + } + let bytes = serde_json::to_vec_pretty(&payload)?; + fs::write(&self.path, bytes).await?; + Ok(()) + } + + pub(crate) async fn last_directory(&self) -> Result> { + let settings = self.load().await?; + let candidate = settings + .get("lastDirectory") + .and_then(|value| value.as_str()) + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(PathBuf::from); + Ok(candidate) + } +} diff --git a/packages/desktop/src-tauri/src/opencode_config.rs b/packages/desktop/src-tauri/src/opencode_config.rs new file mode 100644 index 00000000..a3b3208b --- /dev/null +++ b/packages/desktop/src-tauri/src/opencode_config.rs @@ -0,0 +1,794 @@ +use anyhow::{anyhow, Result}; +use log::info; +use once_cell::sync::Lazy; +use regex::Regex; +use serde::Serialize; +use serde_json::{Map, Value}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use tokio::fs; + +static PROMPT_FILE_PATTERN: Lazy = + Lazy::new(|| Regex::new(r"(?i)^\{file:(.+)\}$").expect("valid regex")); + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceInfo { + pub exists: bool, + pub path: Option, + pub fields: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfigSources { + pub md: SourceInfo, + pub json: SourceInfo, +} + +/// Get OpenCode config directory path +fn get_config_dir() -> PathBuf { + dirs::home_dir() + .expect("Cannot determine home directory") + .join(".config") + .join("opencode") +} + +/// Get agent directory path +fn get_agent_dir() -> PathBuf { + get_config_dir().join("agent") +} + +/// Get command directory path +fn get_command_dir() -> PathBuf { + get_config_dir().join("command") +} + +/// Get config file path +fn get_config_file() -> PathBuf { + get_config_dir().join("opencode.json") +} + +/// Ensure required directories exist +async fn ensure_dirs() -> Result<()> { + let config_dir = get_config_dir(); + let agent_dir = get_agent_dir(); + let command_dir = get_command_dir(); + + fs::create_dir_all(&config_dir).await?; + fs::create_dir_all(&agent_dir).await?; + fs::create_dir_all(&command_dir).await?; + + Ok(()) +} + +/// Check if a value is a prompt file reference like {file:./prompts/agent.txt} +fn is_prompt_file_reference(value: &str) -> bool { + PROMPT_FILE_PATTERN.is_match(value.trim()) +} + +/// Resolve a prompt file reference to an absolute path +fn resolve_prompt_file_path(reference: &str) -> Option { + let trimmed = reference.trim(); + let captures = PROMPT_FILE_PATTERN.captures(trimmed)?; + let target = captures.get(1)?.as_str().trim(); + + if target.is_empty() { + return None; + } + + let path = if target.starts_with("./") { + get_config_dir().join(&target[2..]) + } else if Path::new(target).is_absolute() { + PathBuf::from(target) + } else { + get_config_dir().join(target) + }; + + Some(path) +} + +/// Write content to a prompt file +async fn write_prompt_file(file_path: &Path, content: &str) -> Result<()> { + if let Some(parent) = file_path.parent() { + fs::create_dir_all(parent).await?; + } + fs::write(file_path, content).await?; + info!("Updated prompt file: {}", file_path.display()); + Ok(()) +} + +/// Strip JSON comments from content +fn strip_json_comments(content: &str) -> String { + let mut result = String::new(); + let mut in_string = false; + let mut escape_next = false; + let mut chars = content.chars().peekable(); + + while let Some(ch) = chars.next() { + if escape_next { + result.push(ch); + escape_next = false; + continue; + } + + if ch == '\\' && in_string { + result.push(ch); + escape_next = true; + continue; + } + + if ch == '"' { + in_string = !in_string; + result.push(ch); + continue; + } + + if !in_string { + if ch == '/' { + if let Some(&next_ch) = chars.peek() { + if next_ch == '/' { + // Line comment - skip until end of line + chars.next(); // consume the second '/' + while let Some(c) = chars.next() { + if c == '\n' { + result.push('\n'); + break; + } + } + continue; + } else if next_ch == '*' { + // Block comment - skip until */ + chars.next(); // consume the '*' + let mut prev = ' '; + while let Some(c) = chars.next() { + if prev == '*' && c == '/' { + break; + } + prev = c; + } + continue; + } + } + } + } + + result.push(ch); + } + + result +} + +/// Read opencode.json configuration file +pub async fn read_config() -> Result { + let config_file = get_config_file(); + + if !config_file.exists() { + return Ok(Value::Object(serde_json::Map::new())); + } + + let content = fs::read_to_string(&config_file).await?; + let normalized = strip_json_comments(&content).trim().to_string(); + + if normalized.is_empty() { + return Ok(Value::Object(serde_json::Map::new())); + } + + serde_json::from_str(&normalized).map_err(|e| anyhow!("Failed to parse config: {}", e)) +} + +/// Write opencode.json configuration file with backup +pub async fn write_config(config: &Value) -> Result<()> { + let config_file = get_config_file(); + + // Create/overwrite single backup before writing + if config_file.exists() { + let file_name = config_file + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(|| anyhow!("Invalid config file name"))?; + + let backup_path = config_file.with_file_name(format!("{file_name}.openchamber.backup")); + fs::copy(&config_file, &backup_path).await?; + info!("Created config backup: {}", backup_path.display()); + } + + let json_string = serde_json::to_string_pretty(config)?; + fs::write(&config_file, json_string).await?; + info!("Successfully wrote config file"); + + Ok(()) +} + +/// Markdown file data +#[derive(Debug)] +struct MdData { + frontmatter: HashMap, + body: String, +} + +/// Parse markdown file with YAML frontmatter +async fn parse_md_file(file_path: &Path) -> Result { + let content = fs::read_to_string(file_path).await?; + + // Match YAML frontmatter: ---\n...\n---\n + let re = Regex::new(r"(?s)^---\r?\n(.*?)\r?\n---\r?\n(.*)$").expect("valid regex"); + + if let Some(captures) = re.captures(&content) { + let yaml_str = captures.get(1).map(|m| m.as_str()).unwrap_or(""); + let body = captures.get(2).map(|m| m.as_str()).unwrap_or("").trim(); + + let frontmatter: HashMap = + serde_yaml::from_str(yaml_str).unwrap_or_default(); + + Ok(MdData { + frontmatter, + body: body.to_string(), + }) + } else { + // No frontmatter, treat entire content as body + Ok(MdData { + frontmatter: HashMap::new(), + body: content.trim().to_string(), + }) + } +} + +/// Write markdown file with YAML frontmatter +async fn write_md_file( + file_path: &Path, + frontmatter: &HashMap, + body: &str, +) -> Result<()> { + let yaml_str = serde_yaml::to_string(frontmatter)?; + let content = format!("---\n{}---\n\n{}", yaml_str, body); + + fs::write(file_path, content).await?; + info!("Successfully wrote markdown file: {}", file_path.display()); + + Ok(()) +} + +/// Get information about where agent configuration is stored +pub async fn get_agent_sources(agent_name: &str) -> Result { + ensure_dirs().await?; + + let md_path = get_agent_dir().join(format!("{}.md", agent_name)); + let md_exists = md_path.exists(); + + let mut md_fields = Vec::new(); + if md_exists { + let md_data = parse_md_file(&md_path).await?; + md_fields.extend(md_data.frontmatter.keys().cloned()); + if !md_data.body.trim().is_empty() { + md_fields.push("prompt".to_string()); + } + } + + let config = read_config().await?; + let json_section = config + .get("agent") + .and_then(|v| v.as_object()) + .and_then(|obj| obj.get(agent_name)); + + let json_fields = json_section + .and_then(|value| value.as_object()) + .map(|obj| obj.keys().cloned().collect::>()) + .unwrap_or_default(); + + let sources = ConfigSources { + md: SourceInfo { + exists: md_exists, + path: md_exists.then(|| md_path.display().to_string()), + fields: md_fields, + }, + json: SourceInfo { + exists: json_section.is_some(), + path: Some(get_config_file().display().to_string()), + fields: json_fields, + }, + }; + + Ok(sources) +} + +/// Create new agent as .md file +pub async fn create_agent(agent_name: &str, config: &HashMap) -> Result<()> { + ensure_dirs().await?; + + let md_path = get_agent_dir().join(format!("{}.md", agent_name)); + + // Check if agent already exists + if md_path.exists() { + return Err(anyhow!("Agent {} already exists as .md file", agent_name)); + } + + let existing_config = read_config().await?; + if let Some(agents) = existing_config.get("agent").and_then(|v| v.as_object()) { + if agents.contains_key(agent_name) { + return Err(anyhow!( + "Agent {} already exists in opencode.json", + agent_name + )); + } + } + + // Extract prompt from config + let mut frontmatter = config.clone(); + let prompt = frontmatter + .remove("prompt") + .and_then(|v| v.as_str().map(|s| s.to_string())) + .unwrap_or_default(); + + // Write .md file + write_md_file(&md_path, &frontmatter, &prompt).await?; + info!("Created new agent: {}", agent_name); + + Ok(()) +} + +/// Update existing agent using field-level logic +pub async fn update_agent(agent_name: &str, updates: &HashMap) -> Result<()> { + ensure_dirs().await?; + + let md_path = get_agent_dir().join(format!("{}.md", agent_name)); + let md_exists = md_path.exists(); + + let mut md_data = if md_exists { + Some(parse_md_file(&md_path).await?) + } else { + None + }; + + let mut config = read_config().await?; + let mut existing_agent = config + .get("agent") + .and_then(|v| v.as_object()) + .and_then(|obj| obj.get(agent_name)) + .and_then(|v| v.as_object()) + .cloned() + .unwrap_or_else(Map::new); + let had_json_fields = !existing_agent.is_empty(); + + let mut md_modified = false; + let mut json_modified = false; + + for (field, value) in updates.iter() { + // Handle explicit removals (null payload) for scalar/frontmatter/JSON fields + if value.is_null() { + if md_exists { + if let Some(ref mut data) = md_data { + if data.frontmatter.remove(field).is_some() { + md_modified = true; + } + } + } + if existing_agent.remove(field).is_some() { + json_modified = true; + } + continue; + } + + // Special handling for prompt field + if field == "prompt" { + let normalized_value = value.as_str().unwrap_or("").to_string(); + + if md_exists { + if let Some(ref mut data) = md_data { + data.body = normalized_value.clone(); + md_modified = true; + } + } else if let Some(prompt_ref) = existing_agent.get("prompt").and_then(|v| v.as_str()) + { + if is_prompt_file_reference(prompt_ref) { + if let Some(prompt_file_path) = resolve_prompt_file_path(prompt_ref) { + write_prompt_file(&prompt_file_path, &normalized_value).await?; + } else { + return Err(anyhow!( + "Invalid prompt file reference for agent {}", + agent_name + )); + } + continue; + } + } + + // Write prompt directly to JSON entry (file ref or inline string) + existing_agent.insert("prompt".to_string(), Value::String(normalized_value)); + json_modified = true; + + continue; + } + + // Check where field is currently defined + let in_md = md_data + .as_ref() + .map(|data| data.frontmatter.contains_key(field)) + .unwrap_or(false); + let in_json = existing_agent.contains_key(field); + + if in_md { + // Update in .md frontmatter + if let Some(ref mut data) = md_data { + data.frontmatter.insert(field.clone(), value.clone()); + md_modified = true; + } + } else if in_json { + // Update in opencode.json while preserving existing fields + existing_agent.insert(field.clone(), value.clone()); + json_modified = true; + } else { + // Field not defined - apply priority rules + if md_exists && !existing_agent.is_empty() { + // Both exist → add to opencode.json (higher priority) without dropping other keys + existing_agent.insert(field.clone(), value.clone()); + json_modified = true; + } else if md_exists { + // Only .md exists → add to frontmatter + if let Some(ref mut data) = md_data { + data.frontmatter.insert(field.clone(), value.clone()); + md_modified = true; + } + } else { + // Only JSON or built-in → add/create section in opencode.json + existing_agent.insert(field.clone(), value.clone()); + json_modified = true; + } + } + } + + // Write changes + if md_modified { + if let Some(data) = md_data { + write_md_file(&md_path, &data.frontmatter, &data.body).await?; + } + } + + if json_modified { + // Avoid creating a new JSON section for agents that already live exclusively in .md + if md_exists && !had_json_fields { + json_modified = false; + } + } + + if json_modified { + if !config.is_object() { + config = Value::Object(Map::new()); + } + + let config_obj = config.as_object_mut().unwrap(); + let agents_entry = config_obj + .entry("agent".to_string()) + .or_insert_with(|| Value::Object(Map::new())); + + if !agents_entry.is_object() { + *agents_entry = Value::Object(Map::new()); + } + + let agents_obj = agents_entry.as_object_mut().unwrap(); + agents_obj.insert(agent_name.to_string(), Value::Object(existing_agent)); + + write_config(&config).await?; + } + + info!( + "Updated agent: {} (md: {}, json: {})", + agent_name, md_modified, json_modified + ); + + Ok(()) +} + +/// Delete agent configuration +pub async fn delete_agent(agent_name: &str) -> Result<()> { + let md_path = get_agent_dir().join(format!("{}.md", agent_name)); + let mut deleted = false; + + // 1. Delete .md file if exists + if md_path.exists() { + fs::remove_file(&md_path).await?; + info!("Deleted agent .md file: {}", md_path.display()); + deleted = true; + } + + // 2. Remove section from opencode.json if exists + let mut config = read_config().await?; + if let Some(agents) = config.get_mut("agent").and_then(|v| v.as_object_mut()) { + if agents.remove(agent_name).is_some() { + write_config(&config).await?; + info!("Removed agent from opencode.json: {}", agent_name); + deleted = true; + } + } + + // 3. If nothing was deleted (built-in agent), disable it + if !deleted { + if !config.is_object() { + config = Value::Object(serde_json::Map::new()); + } + let config_obj = config.as_object_mut().unwrap(); + if !config_obj.contains_key("agent") { + config_obj.insert("agent".to_string(), Value::Object(serde_json::Map::new())); + } + let agents = config_obj.get_mut("agent").unwrap(); + if !agents.is_object() { + *agents = Value::Object(serde_json::Map::new()); + } + let mut disable_obj = serde_json::Map::new(); + disable_obj.insert("disable".to_string(), Value::Bool(true)); + agents + .as_object_mut() + .unwrap() + .insert(agent_name.to_string(), Value::Object(disable_obj)); + write_config(&config).await?; + info!("Disabled built-in agent: {}", agent_name); + } + + Ok(()) +} + +/// Get information about where command configuration is stored +pub async fn get_command_sources(command_name: &str) -> Result { + ensure_dirs().await?; + + let md_path = get_command_dir().join(format!("{}.md", command_name)); + let md_exists = md_path.exists(); + + let mut md_fields = Vec::new(); + if md_exists { + let md_data = parse_md_file(&md_path).await?; + md_fields.extend(md_data.frontmatter.keys().cloned()); + if !md_data.body.trim().is_empty() { + md_fields.push("template".to_string()); + } + } + + let config = read_config().await?; + let json_section = config + .get("command") + .and_then(|v| v.as_object()) + .and_then(|obj| obj.get(command_name)); + + let json_fields = json_section + .and_then(|value| value.as_object()) + .map(|obj| obj.keys().cloned().collect::>()) + .unwrap_or_default(); + + let sources = ConfigSources { + md: SourceInfo { + exists: md_exists, + path: md_exists.then(|| md_path.display().to_string()), + fields: md_fields, + }, + json: SourceInfo { + exists: json_section.is_some(), + path: Some(get_config_file().display().to_string()), + fields: json_fields, + }, + }; + + Ok(sources) +} + +/// Create new command as .md file +pub async fn create_command(command_name: &str, config: &HashMap) -> Result<()> { + ensure_dirs().await?; + + let md_path = get_command_dir().join(format!("{}.md", command_name)); + + // Check if command already exists + if md_path.exists() { + return Err(anyhow!( + "Command {} already exists as .md file", + command_name + )); + } + + let existing_config = read_config().await?; + if let Some(commands) = existing_config.get("command").and_then(|v| v.as_object()) { + if commands.contains_key(command_name) { + return Err(anyhow!( + "Command {} already exists in opencode.json", + command_name + )); + } + } + + // Extract template from config + let mut frontmatter = config.clone(); + let template = frontmatter + .remove("template") + .and_then(|v| v.as_str().map(|s| s.to_string())) + .unwrap_or_default(); + + // Write .md file + write_md_file(&md_path, &frontmatter, &template).await?; + info!("Created new command: {}", command_name); + + Ok(()) +} + +/// Update existing command using field-level logic +pub async fn update_command( + command_name: &str, + updates: &HashMap, +) -> Result<()> { + ensure_dirs().await?; + + let md_path = get_command_dir().join(format!("{}.md", command_name)); + let md_exists = md_path.exists(); + + let mut md_data = if md_exists { + Some(parse_md_file(&md_path).await?) + } else { + None + }; + + let mut config = read_config().await?; + let mut existing_command = config + .get("command") + .and_then(|v| v.as_object()) + .and_then(|obj| obj.get(command_name)) + .and_then(|v| v.as_object()) + .cloned() + .unwrap_or_else(Map::new); + let had_json_fields = !existing_command.is_empty(); + + let mut md_modified = false; + let mut json_modified = false; + + for (field, value) in updates.iter() { + // Handle explicit removals (null payload) for scalar/frontmatter/JSON fields + if value.is_null() { + if md_exists { + if let Some(ref mut data) = md_data { + if data.frontmatter.remove(field).is_some() { + md_modified = true; + } + } + } + if existing_command.remove(field).is_some() { + json_modified = true; + } + continue; + } + + // Special handling for template field + if field == "template" { + let normalized_value = value.as_str().unwrap_or("").to_string(); + + if md_exists { + if let Some(ref mut data) = md_data { + data.body = normalized_value.clone(); + md_modified = true; + } + continue; + } else if let Some(template_ref) = existing_command.get("template").and_then(|v| v.as_str()) { + if is_prompt_file_reference(template_ref) { + if let Some(template_file_path) = resolve_prompt_file_path(template_ref) { + write_prompt_file(&template_file_path, &normalized_value).await?; + } else { + return Err(anyhow!( + "Invalid template file reference for command {}", + command_name + )); + } + continue; + } + } + + // Write template directly to JSON entry (file ref or inline string) + existing_command.insert("template".to_string(), Value::String(normalized_value)); + json_modified = true; + + continue; + } + + // Check where field is currently defined + let in_md = md_data + .as_ref() + .map(|data| data.frontmatter.contains_key(field)) + .unwrap_or(false); + let in_json = existing_command.contains_key(field); + + if in_md { + // Update in .md frontmatter + if let Some(ref mut data) = md_data { + data.frontmatter.insert(field.clone(), value.clone()); + md_modified = true; + } + } else if in_json { + // Update in opencode.json while preserving existing fields + existing_command.insert(field.clone(), value.clone()); + json_modified = true; + } else { + // Field not defined - apply priority rules + if md_exists && !existing_command.is_empty() { + // Both exist → add to opencode.json (higher priority) + existing_command.insert(field.clone(), value.clone()); + json_modified = true; + } else if md_exists { + // Only .md exists → add to frontmatter + if let Some(ref mut data) = md_data { + data.frontmatter.insert(field.clone(), value.clone()); + md_modified = true; + } + } else { + // Only JSON or built-in → add/create section in opencode.json + existing_command.insert(field.clone(), value.clone()); + json_modified = true; + } + } + } + + // Write changes + if md_modified { + if let Some(data) = md_data { + write_md_file(&md_path, &data.frontmatter, &data.body).await?; + } + } + + if json_modified { + // Avoid creating a new JSON section for commands that already live exclusively in .md + if md_exists && !had_json_fields { + json_modified = false; + } + } + + if json_modified { + if !config.is_object() { + config = Value::Object(Map::new()); + } + + let config_obj = config.as_object_mut().unwrap(); + let commands_entry = config_obj + .entry("command".to_string()) + .or_insert_with(|| Value::Object(Map::new())); + + if !commands_entry.is_object() { + *commands_entry = Value::Object(Map::new()); + } + + let commands_obj = commands_entry.as_object_mut().unwrap(); + commands_obj.insert(command_name.to_string(), Value::Object(existing_command)); + + write_config(&config).await?; + } + + info!( + "Updated command: {} (md: {}, json: {})", + command_name, md_modified, json_modified + ); + + Ok(()) +} + +/// Delete command configuration +pub async fn delete_command(command_name: &str) -> Result<()> { + let md_path = get_command_dir().join(format!("{}.md", command_name)); + let mut deleted = false; + + // 1. Delete .md file if exists + if md_path.exists() { + fs::remove_file(&md_path).await?; + info!("Deleted command .md file: {}", md_path.display()); + deleted = true; + } + + // 2. Remove section from opencode.json if exists + let mut config = read_config().await?; + if let Some(commands) = config.get_mut("command").and_then(|v| v.as_object_mut()) { + if commands.remove(command_name).is_some() { + write_config(&config).await?; + info!("Removed command from opencode.json: {}", command_name); + deleted = true; + } + } + + // 3. If nothing was deleted, throw error + if !deleted { + return Err(anyhow!("Command \"{}\" not found", command_name)); + } + + Ok(()) +} diff --git a/packages/desktop/src-tauri/src/opencode_manager.rs b/packages/desktop/src-tauri/src/opencode_manager.rs new file mode 100644 index 00000000..4f8f2240 --- /dev/null +++ b/packages/desktop/src-tauri/src/opencode_manager.rs @@ -0,0 +1,577 @@ +use anyhow::{anyhow, Result}; +use log::{debug, info, warn}; +use once_cell::sync::Lazy; +use parking_lot::RwLock; +use regex::Regex; +use reqwest::Client; +use std::{ + collections::HashMap, + path::{Path, PathBuf}, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + time::Duration, +}; +use tokio::{ + io::{AsyncBufReadExt, BufReader}, + process::{Child, Command}, + sync::Mutex, + time::timeout, +}; + +static URL_REGEX: Lazy = Lazy::new(|| { + Regex::new(r#"https?://[^:\s]+:(?P\d+)(?P/[^\s"']*)?"#).expect("valid regex") +}); + +const FIRST_SIGNAL_TIMEOUT_MS: u64 = 750; +const READY_CHECK_TIMEOUT_MS: u64 = 20000; +const READY_CHECK_INTERVAL_MS: u64 = 400; + +#[derive(Clone)] +pub struct OpenCodeManager { + binary: Option, + args: Vec, + env: HashMap, + working_dir: Arc>, + desired_port: u16, + child: Arc>>, + port: Arc>>, + api_prefix: Arc>, + is_ready: Arc, + shutting_down: Arc, + http_client: Client, +} + +fn normalize_api_prefix(prefix: &str) -> String { + let trimmed = prefix.trim(); + if trimmed.is_empty() || trimmed == "/" { + return String::new(); + } + + let mut normalized = trimmed.trim_end_matches('/').to_string(); + if !normalized.starts_with('/') { + normalized.insert(0, '/'); + } + normalized +} + +impl OpenCodeManager { + pub fn new_with_directory(initial_dir: Option) -> Self { + let desired_port = std::env::var("OPENCHAMBER_OPENCODE_PORT") + .ok() + .and_then(|raw| raw.parse::().ok()) + .unwrap_or(0); + + let binary = resolve_opencode_binary(); + + if let Some(ref bin) = binary { + if !Path::new(bin).is_absolute() { + info!("[desktop:opencode] using PATH-resolved binary: {}", bin); + } else { + info!("[desktop:opencode] using binary: {}", bin); + } + } else { + warn!("[desktop:opencode] OpenCode CLI not found - app will run in limited mode"); + } + + let mut args = vec![ + "serve".to_string(), + "--port".to_string(), + desired_port.to_string(), + ]; + if let Ok(config) = std::env::var("OPENCHAMBER_OPENCODE_CONFIG") { + if !config.is_empty() { + args.push("--config".to_string()); + args.push(config); + } + } + + let env = build_augmented_env(); + let working_dir = initial_dir + .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))); + + info!( + "[desktop:opencode] Initial working directory: {:?}", + working_dir + ); + + Self { + binary, + args, + env, + working_dir: Arc::new(RwLock::new(working_dir)), + desired_port, + child: Arc::new(Mutex::new(None)), + port: Arc::new(RwLock::new(None)), + api_prefix: Arc::new(RwLock::new(String::new())), + is_ready: Arc::new(AtomicBool::new(false)), + shutting_down: Arc::new(AtomicBool::new(false)), + http_client: Client::builder() + .timeout(Duration::from_secs(5)) + .build() + .unwrap(), + } + } + + pub fn is_cli_available(&self) -> bool { + self.binary.is_some() + } + + pub async fn ensure_running(&self) -> Result<()> { + if self.binary.is_none() { + return Err(anyhow!("OpenCode CLI is not available")); + } + + let mut guard = self.child.lock().await; + if let Some(child) = guard.as_mut() { + if child.try_wait()?.is_none() && self.is_ready.load(Ordering::SeqCst) { + return Ok(()); + } + } + + self.is_ready.store(false, Ordering::SeqCst); + let child = self.spawn_process().await?; + *guard = Some(child); + drop(guard); + + // Wait for port detection from logs + if self.desired_port == 0 { + self.wait_for_port_detection().await?; + } + + // Detect API prefix early so proxy can forward correctly + let _ = self.detect_api_prefix().await; + + // Wait for OpenCode to become ready by polling endpoints + self.wait_for_ready().await?; + + self.is_ready.store(true, Ordering::SeqCst); + if let Some(port) = self.current_port() { + info!("[desktop:opencode] ready on port {port}"); + } + Ok(()) + } + + pub async fn restart(&self) -> Result<()> { + info!("[desktop:opencode] restarting..."); + self.is_ready.store(false, Ordering::SeqCst); + + self.graceful_stop().await?; + + // Brief delay to let OS release resources + tokio::time::sleep(Duration::from_millis(250)).await; + + // Reset state + if self.desired_port == 0 { + *self.port.write() = None; + } + *self.api_prefix.write() = String::new(); + + self.ensure_running().await + } + + pub async fn shutdown(&self) -> Result<()> { + self.shutting_down.store(true, Ordering::SeqCst); + self.is_ready.store(false, Ordering::SeqCst); + self.graceful_stop().await + } + + pub async fn set_working_directory(&self, new_dir: PathBuf) -> Result<()> { + *self.working_dir.write() = new_dir; + Ok(()) + } + + pub fn get_working_directory(&self) -> PathBuf { + self.working_dir.read().clone() + } + + async fn detect_api_prefix(&self) -> Result<()> { + let Some(port) = self.current_port() else { + return Err(anyhow!("Cannot detect API prefix without port")); + }; + + // Try empty prefix first (OpenCode default), then /api (some installations) + let candidates = ["", "/api"]; + for candidate in candidates { + let base = if candidate.is_empty() { + format!("http://127.0.0.1:{port}") + } else { + format!("http://127.0.0.1:{port}{candidate}") + }; + + let url = format!("{base}/config"); + match self.http_client.get(&url).send().await { + Ok(resp) if resp.status().is_success() => { + // Validate it's actually JSON config, not HTML + if let Ok(text) = resp.text().await { + if text.trim().starts_with('{') || text.trim().starts_with('[') { + info!("[desktop:opencode] Detected API prefix: {:?}", candidate); + *self.api_prefix.write() = normalize_api_prefix(candidate); + return Ok(()); + } + } + } + _ => continue, + } + } + + info!("[desktop:opencode] No API prefix detected, using empty prefix"); + *self.api_prefix.write() = String::new(); + Ok(()) + } + + pub fn current_port(&self) -> Option { + *self.port.read() + } + + pub fn api_prefix(&self) -> String { + self.api_prefix.read().clone() + } + + pub fn is_ready(&self) -> bool { + self.is_ready.load(Ordering::SeqCst) + } + + pub fn rewrite_path(&self, incoming_path: &str) -> String { + // Strip /api prefix to get OpenCode path + let result = incoming_path + .strip_prefix("/api") + .map(|rest| if rest.is_empty() { "/" } else { rest }) + .unwrap_or(incoming_path) + .to_string(); + + debug!( + "[opencode_manager] rewrite_path: '{}' -> '{}'", + incoming_path, result + ); + result + } + + async fn spawn_process(&self) -> Result { + let binary = self.binary.as_ref().ok_or_else(|| { + anyhow!("Cannot spawn process: OpenCode CLI is not available") + })?; + + info!( + "[desktop:opencode] launching {} {:?}", + binary, self.args + ); + + let working_dir = self.working_dir.read().clone(); + let mut cmd = Command::new(binary); + cmd.args(&self.args) + .current_dir(&working_dir) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .kill_on_drop(false); + + for (key, value) in &self.env { + cmd.env(key, value); + } + + let mut child = cmd.spawn().map_err(|e| { + if e.kind() == std::io::ErrorKind::NotFound { + anyhow!( + "OpenCode binary '{}' not found. Set OPENCODE_BINARY or ensure it's in PATH.", + binary + ) + } else { + anyhow!("Failed to spawn OpenCode: {}", e) + } + })?; + + // Set port immediately if pre-configured + if self.desired_port > 0 { + *self.port.write() = Some(self.desired_port); + } + + // Wait for first signal (stdout/stderr) within 750ms to confirm startup + let first_signal_received = Arc::new(AtomicBool::new(false)); + + if let Some(stdout) = child.stdout.take() { + let signal_flag = first_signal_received.clone(); + self.spawn_output_reader(stdout, "stdout", move || { + signal_flag.store(true, Ordering::SeqCst); + }); + } + + if let Some(stderr) = child.stderr.take() { + let signal_flag = first_signal_received.clone(); + self.spawn_output_reader(stderr, "stderr", move || { + signal_flag.store(true, Ordering::SeqCst); + }); + } + + // Wait for first signal or timeout + let start = std::time::Instant::now(); + while start.elapsed() < Duration::from_millis(FIRST_SIGNAL_TIMEOUT_MS) { + if first_signal_received.load(Ordering::SeqCst) { + break; + } + if let Ok(Some(_)) = child.try_wait() { + return Err(anyhow!("OpenCode process exited immediately after spawn")); + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + + Ok(child) + } + + fn spawn_output_reader( + &self, + stream: impl tokio::io::AsyncRead + Unpin + Send + 'static, + label: &'static str, + on_first_line: F, + ) where + F: FnOnce() + Send + 'static, + { + let manager = self.clone(); + let first_line_flag = Arc::new(Mutex::new(Some(on_first_line))); + + tauri::async_runtime::spawn(async move { + let reader = BufReader::new(stream); + let mut lines = reader.lines(); + while let Ok(Some(line)) = lines.next_line().await { + // Trigger first signal callback + if let Some(callback) = first_line_flag.lock().await.take() { + callback(); + } + + debug!("[opencode:{label}] {line}"); + manager.ingest_output_line(&line); + } + }); + } + + fn ingest_output_line(&self, line: &str) { + if let Some(captures) = URL_REGEX.captures(line) { + if let Some(port_match) = captures + .name("port") + .and_then(|m| m.as_str().parse::().ok()) + { + *self.port.write() = Some(port_match); + } + + if let Some(path_match) = captures.name("path") { + let value = path_match.as_str(); + if !value.is_empty() && value != "/" { + *self.api_prefix.write() = value.to_string(); + } + } + } + } + + async fn wait_for_port_detection(&self) -> Result<()> { + let start = std::time::Instant::now(); + let timeout_duration = Duration::from_secs(15); + + while start.elapsed() < timeout_duration { + if self.current_port().is_some() { + return Ok(()); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + + Err(anyhow!("OpenCode did not report port within 15 seconds")) + } + + async fn wait_for_ready(&self) -> Result<()> { + let Some(port) = self.current_port() else { + return Err(anyhow!("Cannot check readiness without port")); + }; + + let deadline = tokio::time::Instant::now() + Duration::from_millis(READY_CHECK_TIMEOUT_MS); + let mut last_error: Option = None; + + while tokio::time::Instant::now() < deadline { + let api_prefix = self.api_prefix(); + + // Try /health, /config, /agent endpoints + match self.check_endpoints(port, &api_prefix).await { + Ok(()) => { + // Once ready, attempt to detect and persist the API prefix for proxying + let _ = self.detect_api_prefix().await; + return Ok(()); + } + Err(e) => { + last_error = Some(e.to_string()); + } + } + + tokio::time::sleep(Duration::from_millis(READY_CHECK_INTERVAL_MS)).await; + } + + Err(anyhow!( + "OpenCode not ready after {}ms: {}", + READY_CHECK_TIMEOUT_MS, + last_error.unwrap_or_else(|| "no error details".to_string()) + )) + } + + async fn check_endpoints(&self, port: u16, prefix: &str) -> Result<()> { + let base_url = format!("http://127.0.0.1:{port}{prefix}"); + + // Check /health + let health_url = format!("{base_url}/health"); + let health_resp = self.http_client.get(&health_url).send().await?; + if !health_resp.status().is_success() { + return Err(anyhow!("/health returned {}", health_resp.status())); + } + + // Check /config + let config_url = format!("{base_url}/config"); + let config_resp = self.http_client.get(&config_url).send().await?; + if !config_resp.status().is_success() { + return Err(anyhow!("/config returned {}", config_resp.status())); + } + + // Check /agent + let agent_url = format!("{base_url}/agent"); + let agent_resp = self.http_client.get(&agent_url).send().await?; + if !agent_resp.status().is_success() { + return Err(anyhow!("/agent returned {}", agent_resp.status())); + } + + Ok(()) + } + + async fn graceful_stop(&self) -> Result<()> { + let mut guard = self.child.lock().await; + let Some(mut child) = guard.take() else { + return Ok(()); + }; + + if child.try_wait()?.is_some() { + // Already exited + return Ok(()); + } + + // SIGTERM + #[cfg(unix)] + { + use nix::{ + sys::signal::{kill, Signal}, + unistd::Pid, + }; + if let Some(id) = child.id() { + let _ = kill(Pid::from_raw(id as i32), Signal::SIGTERM); + info!("[desktop:opencode] sent SIGTERM"); + } + } + #[cfg(windows)] + { + let _ = child.kill().await; + } + + // Wait 3 seconds for graceful exit + match timeout(Duration::from_secs(3), child.wait()).await { + Ok(_) => { + info!("[desktop:opencode] exited gracefully"); + return Ok(()); + } + Err(_) => { + warn!("[desktop:opencode] did not exit after SIGTERM, sending SIGKILL"); + } + } + + // SIGKILL + let _ = child.kill().await; + + // Wait up to 5 seconds for hard kill + match timeout(Duration::from_secs(5), child.wait()).await { + Ok(_) => { + info!("[desktop:opencode] exited after SIGKILL"); + } + Err(_) => { + warn!("[desktop:opencode] unresponsive after SIGKILL, continuing anyway"); + } + } + + Ok(()) + } +} + +/// Check if CLI binary exists (can be called dynamically for polling) +pub fn check_cli_exists() -> bool { + if std::env::var("OPENCHAMBER_DISABLE_CLI").is_ok() { + return false; + } + resolve_opencode_binary().is_some() +} + +fn resolve_opencode_binary() -> Option { + if std::env::var("OPENCHAMBER_DISABLE_CLI").is_ok() { + return None; + } + + // Check explicit override + if let Ok(value) = std::env::var("OPENCODE_BINARY") { + if !value.is_empty() && Path::new(&value).exists() { + info!("[desktop:opencode] using binary from OPENCODE_BINARY: {}", value); + return Some(value); + } + } + + // Find in PATH + if let Ok(output) = std::process::Command::new("which") + .arg("opencode") + .output() + { + if output.status.success() { + let path = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if !path.is_empty() { + info!("[desktop:opencode] found binary in PATH: {}", path); + return Some(path); + } + } + } + + warn!("[desktop:opencode] opencode binary not found in PATH"); + None +} + +fn build_augmented_env() -> HashMap { + let mut env: HashMap = std::env::vars().collect(); + if let Ok(login_path) = detect_login_shell_path() { + let current = env.get("PATH").cloned().unwrap_or_default(); + env.insert("PATH".to_string(), merge_paths(&login_path, ¤t)); + } + env +} + +fn merge_paths(login_path: &str, current: &str) -> String { + let mut segments = Vec::new(); + let mut seen = std::collections::HashSet::new(); + + for part in login_path.split(':').chain(current.split(':')) { + if part.is_empty() || seen.contains(part) { + continue; + } + seen.insert(part.to_string()); + segments.push(part); + } + + segments.join(":") +} + +fn detect_login_shell_path() -> Result { + #[cfg(not(unix))] + { + Err(anyhow!("login shell path unsupported")) + } + #[cfg(unix)] + { + use std::process::Command; + let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".into()); + let output = Command::new(&shell) + .arg("-lic") + .arg("echo -n $PATH") + .output()?; + if output.status.success() { + Ok(String::from_utf8_lossy(&output.stdout).to_string()) + } else { + Err(anyhow!("shell PATH detection failed")) + } + } +} diff --git a/packages/desktop/src-tauri/src/session_activity.rs b/packages/desktop/src-tauri/src/session_activity.rs new file mode 100644 index 00000000..dfedd9d0 --- /dev/null +++ b/packages/desktop/src-tauri/src/session_activity.rs @@ -0,0 +1,326 @@ +use std::{ + collections::HashMap, + sync::Arc, + time::Duration, +}; + +use anyhow::Result; +use futures_util::TryStreamExt; +use log::{debug, info, warn}; +use reqwest::Client; +use serde::Deserialize; +use serde_json::Value; +use tauri::{AppHandle, Emitter}; +use tokio::sync::Mutex; +use tokio_util::io::StreamReader; + +use crate::DesktopRuntime; + +#[derive(Deserialize)] +struct EventEnvelope { + #[serde(rename = "type")] + event_type: String, + #[serde(default)] + properties: Value, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ActivityPhase { + Idle, + Busy, + Cooldown, +} + +pub fn spawn_session_activity_tracker( + app: AppHandle, + runtime: DesktopRuntime, +) -> tauri::async_runtime::JoinHandle<()> { + tauri::async_runtime::spawn(async move { + let client = Client::builder() + .timeout(Duration::from_secs(24 * 60 * 60)) + .tcp_keepalive(Some(Duration::from_secs(30))) + .build() + .expect("failed to build reqwest client"); + + let mut shutdown_rx = runtime.subscribe_shutdown(); + let phases = Arc::new(Mutex::new(HashMap::::new())); + let cooldowns = Arc::new(Mutex::new(HashMap::>::new())); + + loop { + tokio::select! { + _ = shutdown_rx.recv() => { + info!("[desktop:activity] Shutdown received, stopping SSE listener"); + break; + } + _ = async { + // Reset stale phases to idle before connecting so UI doesn't stay stuck on "working" after wake. + reset_and_emit_all_phases(&app, phases.clone(), cooldowns.clone()).await; + + if let Err(err) = run_once(&app, &runtime, &client, phases.clone(), cooldowns.clone()).await { + warn!("[desktop:activity] SSE loop error: {err:?}"); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } => {} + } + } + }) +} + +async fn run_once( + app: &AppHandle, + runtime: &DesktopRuntime, + client: &Client, + phases: Arc>>, + cooldowns: Arc>>>, +) -> Result<()> { + let opencode = runtime.opencode_manager(); + + let port = match opencode.current_port() { + Some(port) => port, + None => { + warn!("[desktop:activity] OpenCode port unavailable; will retry"); + tokio::time::sleep(Duration::from_secs(2)).await; + return Ok(()); + } + }; + + let prefix = opencode.api_prefix(); + let mut url = format!("http://127.0.0.1:{port}{}/event", prefix); + + if let Some(dir) = opencode.get_working_directory().to_str().map(|s| s.to_string()) { + let mut parsed = reqwest::Url::parse(&url)?; + parsed + .query_pairs_mut() + .append_pair("directory", &dir); + url = parsed.to_string(); + } + + debug!("[desktop:activity] Connecting SSE for activity phases: {url}"); + + let response = client + .get(&url) + .header("accept", "text/event-stream") + .header("accept-encoding", "identity") + .send() + .await?; + + debug!( + "[desktop:activity] SSE response status={} headers={:?}", + response.status(), + response.headers() + ); + + if !response.status().is_success() { + warn!( + "[desktop:activity] SSE connect failed with status {}", + response.status() + ); + tokio::time::sleep(Duration::from_secs(2)).await; + return Ok(()); + } + + use tokio::io::AsyncBufReadExt; + + let stream = response + .bytes_stream() + .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err)); + let mut reader = StreamReader::new(stream); + let mut buf = Vec::new(); + let mut data_lines: Vec = Vec::new(); + + loop { + buf.clear(); + let bytes_read = match reader.read_until(b'\n', &mut buf).await { + Ok(n) => n, + Err(err) => { + warn!("[desktop:activity] Read error in SSE stream: {err:?}"); + return Err(err.into()); + } + }; + if bytes_read == 0 { + break; + } + + let line = match std::str::from_utf8(&buf) { + Ok(s) => s.trim_end_matches(&['\r', '\n'][..]).to_string(), + Err(err) => { + warn!("[desktop:activity] Non-UTF8 SSE chunk: {err}"); + continue; + } + }; + + if line.is_empty() { + if data_lines.is_empty() { + continue; + } + let raw = data_lines.join("\n"); + data_lines.clear(); + + match serde_json::from_str::(&raw) { + Ok(event) => handle_event(app, event, phases.clone(), cooldowns.clone()).await, + Err(err) => { + warn!("[desktop:activity] Failed to parse SSE data: {err}; raw={raw}"); + } + } + continue; + } + + if let Some(rest) = line.strip_prefix("data:") { + data_lines.push(rest.trim_start().to_string()); + } + } + + Ok(()) +} + +async fn handle_event( + app: &AppHandle, + event: EventEnvelope, + phases: Arc>>, + cooldowns: Arc>>>, +) { + match event.event_type.as_str() { + "session.status" => { + let session_id = event + .properties + .get("sessionID") + .and_then(Value::as_str) + .map(|s| s.to_string()); + let status = event + .properties + .get("status") + .and_then(|s| s.get("type")) + .and_then(Value::as_str); + + if let (Some(id), Some(status_type)) = (session_id, status) { + let phase = if status_type == "busy" || status_type == "retry" { + ActivityPhase::Busy + } else { + ActivityPhase::Idle + }; + set_phase(app, &id, phase, phases.clone(), cooldowns.clone()).await; + } + } + "message.updated" => { + if let Some(info) = event.properties.get("info") { + let role = info.get("role").and_then(Value::as_str).unwrap_or_default(); + if role != "assistant" { + return; + } + + let finish = info.get("finish").and_then(Value::as_str); + if finish != Some("stop") { + return; + } + + let session_id = info + .get("sessionID") + .and_then(Value::as_str) + .map(|s| s.to_string()); + + if let Some(id) = session_id { + // If current phase is busy, move to cooldown for 2s then idle + let current = { phases.lock().await.get(&id).cloned() }; + if matches!(current, Some(ActivityPhase::Busy)) { + set_phase(app, &id, ActivityPhase::Cooldown, phases.clone(), cooldowns.clone()).await; + + let app_clone = app.clone(); + let phases_clone = phases.clone(); + let cooldowns_clone = cooldowns.clone(); + let id_clone = id.clone(); + let handle = tauri::async_runtime::spawn(async move { + tokio::time::sleep(Duration::from_secs(2)).await; + let current = { phases_clone.lock().await.get(&id_clone).cloned() }; + if matches!(current, Some(ActivityPhase::Cooldown)) { + set_phase(&app_clone, &id_clone, ActivityPhase::Idle, phases_clone, cooldowns_clone).await; + } + }); + + // Store cooldown handle to cancel if phase changes earlier + let mut cd = cooldowns.lock().await; + if let Some(prev) = cd.remove(&id) { + prev.abort(); + } + cd.insert(id, handle); + } + } + } + } + _ => {} + } +} + +async fn set_phase( + app: &AppHandle, + session_id: &str, + phase: ActivityPhase, + phases: Arc>>, + cooldowns: Arc>>>, +) { + { + let mut map = phases.lock().await; + let current = map.get(session_id); + if current == Some(&phase) { + return; + } + map.insert(session_id.to_string(), phase.clone()); + + // Cancel cooldown timer when leaving cooldown + if !matches!(phase, ActivityPhase::Cooldown) { + if let Some(handle) = cooldowns.lock().await.remove(session_id) { + handle.abort(); + } + } + } + + // Emit to webview so UI stays in sync + let payload = serde_json::json!({ + "sessionId": session_id, + "phase": match phase { + ActivityPhase::Idle => "idle", + ActivityPhase::Busy => "busy", + ActivityPhase::Cooldown => "cooldown", + } + }); + + let _ = app.emit("openchamber:session-activity", payload); +} + +async fn reset_and_emit_all_phases( + app: &AppHandle, + phases: Arc>>, + cooldowns: Arc>>>, +) { + // Cancel any cooldown timers and set all phases to idle to avoid stale "busy" after wake. + { + let mut cd = cooldowns.lock().await; + for handle in cd.values() { + handle.abort(); + } + cd.clear(); + } + + let snapshot = { + let mut guard = phases.lock().await; + for value in guard.values_mut() { + *value = ActivityPhase::Idle; + } + guard.clone() + }; + + if snapshot.is_empty() { + return; + } + + for (session_id, phase) in snapshot { + let payload = serde_json::json!({ + "sessionId": session_id, + "phase": match phase { + ActivityPhase::Idle => "idle", + ActivityPhase::Busy => "busy", + ActivityPhase::Cooldown => "cooldown", + } + }); + let _ = app.emit("openchamber:session-activity", payload); + } +} diff --git a/packages/desktop/src-tauri/src/window_state.rs b/packages/desktop/src-tauri/src/window_state.rs new file mode 100644 index 00000000..5bd81745 --- /dev/null +++ b/packages/desktop/src-tauri/src/window_state.rs @@ -0,0 +1,167 @@ +use anyhow::{anyhow, Result}; +use serde::{Deserialize, Serialize}; +use std::{ + path::PathBuf, + sync::{Arc, Mutex}, +}; +use tauri::{LogicalPosition, LogicalSize, WebviewWindow, Window}; +use tokio::fs as async_fs; + +const WINDOW_STATE_FILE: &str = "window-state.json"; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WindowState { + pub width: f64, + pub height: f64, + pub x: f64, + pub y: f64, + pub is_maximized: bool, +} + +impl Default for WindowState { + fn default() -> Self { + Self { + width: 1280.0, + height: 800.0, + x: 0.0, + y: 0.0, + is_maximized: false, + } + } +} + +#[derive(Serialize, Deserialize)] +struct WindowStateFile { + #[serde(rename = "windowState")] + pub window_state: WindowState, +} + +#[derive(Clone)] +pub struct WindowStateManager { + inner: Arc>, +} + +impl WindowStateManager { + pub fn new(initial: WindowState) -> Self { + Self { + inner: Arc::new(Mutex::new(initial)), + } + } + + pub fn snapshot(&self) -> WindowState { + self.inner.lock().expect("window state poisoned").clone() + } + + pub fn update_position(&self, x: f64, y: f64, is_maximized: bool) { + if is_maximized { + return; + } + if let Ok(mut state) = self.inner.lock() { + if !state.is_maximized { + state.x = x; + state.y = y; + } + } + } + + pub fn update_size(&self, width: f64, height: f64, is_maximized: bool) { + if let Ok(mut state) = self.inner.lock() { + if !is_maximized { + state.width = width; + state.height = height; + } + state.is_maximized = is_maximized; + } + } +} + +fn state_file_path() -> Result { + let mut path = dirs::home_dir().ok_or_else(|| anyhow!("No home directory"))?; + path.push(".config"); + path.push("openchamber"); + path.push(WINDOW_STATE_FILE); + Ok(path) +} + +pub async fn load_window_state() -> Result> { + let path = state_file_path()?; + match async_fs::read(&path).await { + Ok(bytes) => { + let file: WindowStateFile = serde_json::from_slice(&bytes)?; + Ok(Some(file.window_state)) + } + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(err) => Err(err.into()), + } +} + +pub async fn save_window_state(state: &WindowState) -> Result<()> { + let path = state_file_path()?; + if let Some(parent) = path.parent() { + async_fs::create_dir_all(parent).await?; + } + let payload = WindowStateFile { + window_state: state.clone(), + }; + let data = serde_json::to_vec_pretty(&payload)?; + async_fs::write(&path, data).await?; + Ok(()) +} + +pub fn apply_window_state(window: &WebviewWindow, state: &WindowState) -> Result<()> { + let mut normalized = state.clone(); + clamp_to_visible_region(window, &mut normalized); + + if normalized.width > 0.0 && normalized.height > 0.0 { + let _ = window.set_size(LogicalSize::new(normalized.width, normalized.height)); + } + let _ = window.set_position(LogicalPosition::new(normalized.x, normalized.y)); + if state.is_maximized { + let _ = window.maximize(); + } else { + let _ = window.unmaximize(); + } + Ok(()) +} + +pub async fn persist_window_state(window: &Window, manager: &WindowStateManager) -> Result<()> { + let mut snapshot = manager.snapshot(); + let is_maximized = window.is_maximized().unwrap_or(snapshot.is_maximized); + snapshot.is_maximized = is_maximized; + + if !is_maximized { + let scale_factor = window.scale_factor().unwrap_or(1.0); + if let Ok(size) = window.outer_size() { + let logical: LogicalSize = size.to_logical(scale_factor); + snapshot.width = logical.width.max(200.0); + snapshot.height = logical.height.max(200.0); + } + if let Ok(position) = window.outer_position() { + let logical: LogicalPosition = position.to_logical(scale_factor); + snapshot.x = logical.x; + snapshot.y = logical.y; + } + } + + save_window_state(&snapshot).await +} + +fn clamp_to_visible_region(window: &WebviewWindow, state: &mut WindowState) { + let monitor = match window.current_monitor() { + Ok(Some(monitor)) => monitor, + _ => return, + }; + let scale_factor = monitor.scale_factor(); + let monitor_size: LogicalSize = monitor.size().to_logical(scale_factor); + let monitor_position: LogicalPosition = monitor.position().to_logical(scale_factor); + + state.width = state.width.clamp(400.0, monitor_size.width); + state.height = state.height.clamp(300.0, monitor_size.height); + + let max_x = monitor_position.x + (monitor_size.width - state.width).max(0.0); + let max_y = monitor_position.y + (monitor_size.height - state.height).max(0.0); + + state.x = state.x.clamp(monitor_position.x, max_x); + state.y = state.y.clamp(monitor_position.y, max_y); +} diff --git a/packages/desktop/src-tauri/tauri.conf.json b/packages/desktop/src-tauri/tauri.conf.json new file mode 100644 index 00000000..efaf61d6 --- /dev/null +++ b/packages/desktop/src-tauri/tauri.conf.json @@ -0,0 +1,60 @@ +{ + "$schema": "../node_modules/@tauri-apps/cli/schema.json", + "productName": "OpenChamber", + "version": "1.0.0", + "identifier": "ai.opencode.openchamber", + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm build", + "devUrl": "http://127.0.0.1:1421", + "frontendDist": "../dist" + }, + "app": { + "windows": [ + { + "label": "main", + "title": "OpenChamber", + "transparent": true, + "width": 1280, + "height": 800, + "resizable": true, + "fullscreen": false, + "decorations": true, + "hiddenTitle": true, + "titleBarStyle": "Overlay", + "trafficLightPosition": { + "x": 17, + "y": 26 + }, + "visible": true, + "backgroundThrottling": "disabled" + } + ], + "security": { + "csp": null + }, + "macOSPrivateApi": true + }, + "bundle": { + "active": true, + "icon": [ + "icons/icon.icns", + "icons/icon.png" + ], + "macOS": { + "exceptionDomain": "localhost", + "minimumSystemVersion": "14.0", + "signingIdentity": null, + "infoPlist": "Info.plist" + }, + "createUpdaterArtifacts": true + }, + "plugins": { + "updater": { + "endpoints": [ + "https://github.com/btriapitsyn/openchamber/releases/latest/download/latest.json" + ], + "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEU0NjI5NDJGNEU0QzFEMTYKUldRV0hVeE9MNVJpNUdRemdsbm8wQ2YxQkU4KzBOOEg3TkpXZzIzb244N3Y0R3I4N2FtUk1NMUEK" + } + } +} diff --git a/packages/desktop/src/api/diagnostics.ts b/packages/desktop/src/api/diagnostics.ts new file mode 100644 index 00000000..169df787 --- /dev/null +++ b/packages/desktop/src/api/diagnostics.ts @@ -0,0 +1,32 @@ + +import type { DiagnosticsAPI } from '@openchamber/ui/lib/api/types'; + +type LogResponse = { + fileName?: string; + content?: string; +}; + +const normalizePayload = (payload: LogResponse): { fileName: string; content: string } => ({ + fileName: typeof payload.fileName === 'string' && payload.fileName.trim().length > 0 ? payload.fileName : 'desktop.log', + content: typeof payload.content === 'string' ? payload.content : '', +}); + +export const createDesktopDiagnosticsAPI = (): DiagnosticsAPI => ({ + async downloadLogs() { + try { + const { safeInvoke } = await import('../lib/tauriCallbackManager'); + const result = await safeInvoke('fetch_desktop_logs', {}, { + timeout: 10000, + onCancel: () => { + console.warn('[DiagnosticsAPI] Fetch desktop logs operation timed out'); + } + }); + return normalizePayload(result ?? {}); + } catch (error) { + if (error instanceof Error) { + throw error; + } + throw new Error('Failed to download desktop logs'); + } + }, +}); diff --git a/packages/desktop/src/api/files.ts b/packages/desktop/src/api/files.ts new file mode 100644 index 00000000..27f3e11c --- /dev/null +++ b/packages/desktop/src/api/files.ts @@ -0,0 +1,114 @@ + +import { safeInvoke } from '../lib/tauriCallbackManager'; +import type { DirectoryListResult, FileSearchQuery, FileSearchResult, FilesAPI } from '@openchamber/ui/lib/api/types'; + +type ListDirectoryResponse = DirectoryListResult & { + path?: string; + entries: Array< + DirectoryListResult['entries'][number] & { + isFile?: boolean; + isSymbolicLink?: boolean; + } + >; +}; + +type SearchFilesResponse = { + root: string; + count: number; + files: Array<{ + name: string; + path: string; + relativePath: string; + extension?: string; + }>; +}; + +const normalizePath = (path: string): string => path.replace(/\\/g, '/'); + +const normalizeDirectoryPayload = (result: ListDirectoryResponse): DirectoryListResult => ({ + directory: normalizePath(result.directory || result.path || ''), + entries: Array.isArray(result.entries) + ? result.entries.map((entry) => ({ + name: entry.name || '', + path: normalizePath(entry.path || ''), + isDirectory: entry.isDirectory ?? false, + size: entry.size ?? 0, + modified: (entry as { modified?: string }).modified ?? new Date().toISOString(), + })) + : [], +}); + +export const createDesktopFilesAPI = (): FilesAPI => ({ + async listDirectory(path: string): Promise { + try { + const result = await safeInvoke('list_directory', { + path: normalizePath(path), + includeHidden: false + }, { + timeout: 10000, + onCancel: () => { + console.warn('[FilesAPI] List directory operation timed out'); + } + }); + + return normalizeDirectoryPayload(result); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(message || 'Failed to list directory'); + } + }, + + async search(payload: FileSearchQuery): Promise { + try { + const normalizedDirectory = + typeof payload.directory === 'string' && payload.directory.length > 0 + ? normalizePath(payload.directory) + : undefined; + + const result = await safeInvoke('search_files', { + directory: normalizedDirectory, + query: payload.query, + max_results: payload.maxResults || 100 + }, { + timeout: 15000, + onCancel: () => { + console.warn('[FilesAPI] Search files operation timed out'); + } + }); + + if (!result || !Array.isArray(result.files)) { + return []; + } + + return result.files.map((file) => ({ + path: normalizePath(file.path), + preview: file.relativePath ? [normalizePath(file.relativePath)] : undefined, + })); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(message || 'Failed to search files'); + } + }, + + async createDirectory(path: string): Promise<{ success: boolean; path: string }> { + try { + const normalizedPath = normalizePath(path); + const result = await safeInvoke<{ success: boolean; path: string }>('create_directory', { + path: normalizedPath + }, { + timeout: 5000, + onCancel: () => { + console.warn('[FilesAPI] Create directory operation timed out'); + } + }); + + return { + success: Boolean(result?.success), + path: result?.path ? normalizePath(result.path) : normalizedPath, + }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(message || 'Failed to create directory'); + } + }, +}); \ No newline at end of file diff --git a/packages/desktop/src/api/git.ts b/packages/desktop/src/api/git.ts new file mode 100644 index 00000000..2edb2c68 --- /dev/null +++ b/packages/desktop/src/api/git.ts @@ -0,0 +1,230 @@ + +import { safeInvoke } from '../lib/tauriCallbackManager'; +import type { + GitAPI, + GitStatus, + GitDiffResponse, + GetGitDiffOptions, + GitFileDiffResponse, + GitBranch, + GitDeleteBranchPayload, + GitDeleteRemoteBranchPayload, + GeneratedCommitMessage, + GitWorktreeInfo, + GitAddWorktreePayload, + GitRemoveWorktreePayload, + CreateGitCommitOptions, + GitCommitResult, + GitPushResult, + GitPullResult, + GitLogOptions, + GitLogResponse, + GitCommitFilesResponse, + GitIdentitySummary, + GitIdentityProfile +} from '@openchamber/ui/lib/api/types'; + +async function safeGitInvoke(command: string, args?: Record): Promise { + try { + return await safeInvoke(command, args, { + timeout: 120000, + onCancel: () => { + console.warn(`[GitAPI] Git operation ${command} did not complete within 120s; it may still be running.`); + } + }); + } catch (error) { + const message = typeof error === 'string' ? error : (error as Error).message || 'Unknown error'; + throw new Error(message); + } +} + +export const createDesktopGitAPI = (): GitAPI => ({ + async checkIsGitRepository(directory: string): Promise { + return safeGitInvoke('check_is_git_repository', { directory }); + }, + + async getGitStatus(directory: string): Promise { + return safeGitInvoke('get_git_status', { directory }); + }, + + async getGitDiff(directory: string, options: GetGitDiffOptions): Promise { + const diff = await safeGitInvoke('get_git_diff', { + directory, + pathStr: options.path, + staged: options.staged, + contextLines: options.contextLines + }); + return { diff }; + }, + + async getGitFileDiff(directory: string, options: { path: string }): Promise { + const [original, modified] = await safeGitInvoke<[string, string]>('get_git_file_diff', { + directory, + pathStr: options.path, + }); + return { + original: original ?? '', + modified: modified ?? '', + path: options.path, + }; + }, + + async revertGitFile(directory: string, filePath: string): Promise { + return safeGitInvoke('revert_git_file', { directory, filePath }); + }, + + async isLinkedWorktree(directory: string): Promise { + return safeGitInvoke('is_linked_worktree', { directory }); + }, + + async getGitBranches(directory: string): Promise { + return safeGitInvoke('get_git_branches', { directory }); + }, + + async deleteGitBranch(directory: string, payload: GitDeleteBranchPayload): Promise<{ success: boolean }> { + await safeGitInvoke('delete_git_branch', { + directory, + branch: payload.branch, + force: payload.force + }); + return { success: true }; + }, + + async deleteRemoteBranch(directory: string, payload: GitDeleteRemoteBranchPayload): Promise<{ success: boolean }> { + await safeGitInvoke('delete_remote_branch', { + directory, + branch: payload.branch, + remote: payload.remote + }); + return { success: true }; + }, + + async generateCommitMessage(directory: string, files: string[]): Promise<{ message: GeneratedCommitMessage }> { + const response = await safeGitInvoke<{ message: GeneratedCommitMessage }>('generate_commit_message', { + directory, + files + }); + return response; + }, + + async listGitWorktrees(directory: string): Promise { + return safeGitInvoke('list_git_worktrees', { directory }); + }, + + async addGitWorktree(directory: string, payload: GitAddWorktreePayload): Promise<{ success: boolean; path: string; branch: string }> { + await safeGitInvoke('add_git_worktree', { + directory, + pathStr: payload.path, + branch: payload.branch, + createBranch: payload.createBranch + }); + return { success: true, path: payload.path, branch: payload.branch }; + }, + + async removeGitWorktree(directory: string, payload: GitRemoveWorktreePayload): Promise<{ success: boolean }> { + await safeGitInvoke('remove_git_worktree', { + directory, + pathStr: payload.path, + force: payload.force + }); + return { success: true }; + }, + + async ensureOpenChamberIgnored(directory: string): Promise { + return safeGitInvoke('ensure_openchamber_ignored', { directory }); + }, + + async createGitCommit(directory: string, message: string, options?: CreateGitCommitOptions): Promise { + return safeGitInvoke('create_git_commit', { + directory, + message, + addAll: options?.addAll, + files: options?.files + }); + }, + + async gitPush(directory: string, options?: { remote?: string; branch?: string; options?: string[] | Record }): Promise { + return safeGitInvoke('git_push', { + directory, + remote: options?.remote, + branch: options?.branch, + options: options?.options + }); + }, + + async gitPull(directory: string, options?: { remote?: string; branch?: string }): Promise { + return safeGitInvoke('git_pull', { + directory, + remote: options?.remote, + branch: options?.branch + }); + }, + + async gitFetch(directory: string, options?: { remote?: string; branch?: string }): Promise<{ success: boolean }> { + await safeGitInvoke('git_fetch', { + directory, + remote: options?.remote + }); + return { success: true }; + }, + + async checkoutBranch(directory: string, branch: string): Promise<{ success: boolean; branch: string }> { + await safeGitInvoke('checkout_branch', { directory, branch }); + return { success: true, branch }; + }, + + async createBranch(directory: string, name: string, startPoint?: string): Promise<{ success: boolean; branch: string }> { + await safeGitInvoke('create_branch', { + directory, + name, + startPoint + }); + return { success: true, branch: name }; + }, + + async getGitLog(directory: string, options?: GitLogOptions): Promise { + return safeGitInvoke('get_git_log', { + directory, + maxCount: options?.maxCount, + from: options?.from, + to: options?.to, + file: options?.file + }); + }, + + async getCommitFiles(directory: string, hash: string): Promise { + return safeGitInvoke('get_commit_files', { + directory, + hash + }); + }, + + async getCurrentGitIdentity(directory: string): Promise { + try { + return await safeGitInvoke('get_current_git_identity', { directory }); + } catch { + return null; + } + }, + + async setGitIdentity(directory: string, profileId: string): Promise<{ success: boolean; profile: GitIdentityProfile }> { + const profile = await safeGitInvoke('set_git_identity', { directory, profileId }); + return { success: true, profile }; + }, + + async getGitIdentities(): Promise { + return safeGitInvoke('get_git_identities'); + }, + + async createGitIdentity(profile: GitIdentityProfile): Promise { + return safeGitInvoke('create_git_identity', { profile }); + }, + + async updateGitIdentity(id: string, updates: GitIdentityProfile): Promise { + return safeGitInvoke('update_git_identity', { id, updates }); + }, + + async deleteGitIdentity(id: string): Promise { + return safeGitInvoke('delete_git_identity', { id }); + }, +}); diff --git a/packages/desktop/src/api/index.ts b/packages/desktop/src/api/index.ts new file mode 100644 index 00000000..949c3110 --- /dev/null +++ b/packages/desktop/src/api/index.ts @@ -0,0 +1,57 @@ +import type { RuntimeAPIs, TerminalHandlers } from '@openchamber/ui/lib/api/types'; +import { createDesktopTerminalAPI } from './terminal'; +import { createDesktopGitAPI } from './git'; +import { createDesktopFilesAPI } from './files'; +import { createDesktopSettingsAPI } from './settings'; +import { createDesktopPermissionsAPI } from './permissions'; +import { createDesktopDiagnosticsAPI } from './diagnostics'; +import { createDesktopNotificationsAPI } from './notifications'; +import { createDesktopToolsAPI } from './tools'; + +const activeTerminalConnections = new Set(); + +export const createDesktopAPIs = (): RuntimeAPIs & { cleanup?: () => void } => { + const terminalAPI = createDesktopTerminalAPI(); + const originalConnect = terminalAPI.connect.bind(terminalAPI); + + const wrappedTerminalAPI = { + ...terminalAPI, + connect: (sessionId: string, handlers: TerminalHandlers) => { + activeTerminalConnections.add(sessionId); + const connection = originalConnect(sessionId, handlers); + + const originalClose = connection.close; + return { + ...connection, + close: () => { + activeTerminalConnections.delete(sessionId); + originalClose(); + }, + }; + }, + }; + + return { + runtime: { platform: 'desktop', isDesktop: true, label: 'tauri-bootstrap' }, + terminal: wrappedTerminalAPI, + git: createDesktopGitAPI(), + files: createDesktopFilesAPI(), + settings: createDesktopSettingsAPI(), + permissions: createDesktopPermissionsAPI(), + notifications: createDesktopNotificationsAPI(), + diagnostics: createDesktopDiagnosticsAPI(), + tools: createDesktopToolsAPI(), + cleanup: () => { + console.info('[DesktopAPIs] Performing cleanup...'); + + const activeConnections = Array.from(activeTerminalConnections); + activeConnections.forEach(sessionId => { + console.info(`[DesktopAPIs] Closing terminal session: ${sessionId}`); + + activeTerminalConnections.delete(sessionId); + }); + + console.info(`[DesktopAPIs] Cleanup completed, closed ${activeConnections.length} terminal connections`); + }, + }; +}; diff --git a/packages/desktop/src/api/notifications.ts b/packages/desktop/src/api/notifications.ts new file mode 100644 index 00000000..71f6f0b6 --- /dev/null +++ b/packages/desktop/src/api/notifications.ts @@ -0,0 +1,58 @@ + +import type { NotificationsAPI, NotificationPayload } from '@openchamber/ui/lib/api/types'; +import { isPermissionGranted, requestPermission } from '@tauri-apps/plugin-notification'; +import { safeInvoke } from '../lib/tauriCallbackManager'; + +export const requestInitialNotificationPermission = async (): Promise => { + try { + if (typeof window !== 'undefined' && 'Notification' in window) { + const permission = await Notification.requestPermission(); + if (permission !== 'granted') { + console.warn('[notifications] Notification permission not granted'); + } + } + } catch (error) { + console.error('[notifications] Failed to request permission:', error); + } +}; + +export const createDesktopNotificationsAPI = (): NotificationsAPI => ({ + async notifyAgentCompletion(payload?: NotificationPayload): Promise { + try { + let granted = await isPermissionGranted(); + if (!granted) { + const permission = await requestPermission(); + granted = permission === 'granted'; + } + + if (!granted) { + console.warn('[notifications] Cannot send notification: Permission denied'); + return false; + } + + await safeInvoke( + 'desktop_notify', + { payload }, + { + timeout: 5000, + onCancel: () => { + console.warn('[NotificationsAPI] Notify operation timed out'); + }, + }, + ); + return true; + } catch (error) { + console.error('[notifications] Failed to send notification:', error); + return false; + } + }, + + async canNotify(): Promise { + try { + return await isPermissionGranted(); + } catch (error) { + console.warn('[notifications] Failed to check notification permission:', error); + return false; + } + } +}); diff --git a/packages/desktop/src/api/permissions.ts b/packages/desktop/src/api/permissions.ts new file mode 100644 index 00000000..32e874c7 --- /dev/null +++ b/packages/desktop/src/api/permissions.ts @@ -0,0 +1,49 @@ +import type { DirectoryPermissionRequest, DirectoryPermissionResult, PermissionsAPI, StartAccessingResult } from '@openchamber/ui/lib/api/types'; + +export const createDesktopPermissionsAPI = (): PermissionsAPI => ({ + async requestDirectoryAccess(request: DirectoryPermissionRequest): Promise { + try { + const { safeInvoke } = await import('../lib/tauriCallbackManager'); + const result = await safeInvoke('request_directory_access', { request }, { + timeout: 30000, + onCancel: () => { + console.warn('[PermissionsAPI] Request directory access operation timed out'); + } + }); + return result; + } catch (error) { + console.error('[desktop] Error requesting directory access:', error); + return { success: false, error: error instanceof Error ? error.message : String(error) }; + } + }, + async startAccessingDirectory(path: string): Promise { + try { + const { safeInvoke } = await import('../lib/tauriCallbackManager'); + const result = await safeInvoke('start_accessing_directory', { path }, { + timeout: 10000, + onCancel: () => { + console.warn('[PermissionsAPI] Start accessing directory operation timed out'); + } + }); + return result; + } catch (error) { + console.error('[desktop] Error starting directory access:', error); + return { success: false, error: error instanceof Error ? error.message : String(error) }; + } + }, + async stopAccessingDirectory(path: string): Promise { + try { + const { safeInvoke } = await import('../lib/tauriCallbackManager'); + const result = await safeInvoke('stop_accessing_directory', { path }, { + timeout: 5000, + onCancel: () => { + console.warn('[PermissionsAPI] Stop accessing directory operation timed out'); + } + }); + return result; + } catch (error) { + console.error('[desktop] Error stopping directory access:', error); + return { success: false, error: error instanceof Error ? error.message : String(error) }; + } + }, +}); diff --git a/packages/desktop/src/api/settings.ts b/packages/desktop/src/api/settings.ts new file mode 100644 index 00000000..69049d2d --- /dev/null +++ b/packages/desktop/src/api/settings.ts @@ -0,0 +1,58 @@ +import type { SettingsAPI, SettingsLoadResult, SettingsPayload } from '@openchamber/ui/lib/api/types'; + +const sanitizePayload = (data: unknown): SettingsPayload => { + if (!data || typeof data !== 'object') { + return {}; + } + return data as SettingsPayload; +}; + +export const createDesktopSettingsAPI = (): SettingsAPI => ({ + async load(): Promise { + try { + const { safeInvoke } = await import('../lib/tauriCallbackManager'); + const result = await safeInvoke<{ settings: unknown; source: 'desktop' | 'web' }>('load_settings', {}, { + timeout: 5000, + onCancel: () => { + console.warn('[SettingsAPI] Load settings operation timed out'); + } + }); + return { + settings: sanitizePayload(result.settings), + source: result.source, + }; + } catch (error) { + throw new Error(`Failed to load settings: ${error instanceof Error ? error.message : String(error)}`); + } + }, + + async save(changes: Partial): Promise { + try { + const { safeInvoke } = await import('../lib/tauriCallbackManager'); + const result = await safeInvoke('save_settings', { changes }, { + timeout: 5000, + onCancel: () => { + console.warn('[SettingsAPI] Save settings operation timed out'); + } + }); + return sanitizePayload(result); + } catch (error) { + throw new Error(`Failed to save settings: ${error instanceof Error ? error.message : String(error)}`); + } + }, + + async restartOpenCode(): Promise<{ restarted: boolean }> { + try { + const { safeInvoke } = await import('../lib/tauriCallbackManager'); + const result = await safeInvoke<{ restarted: boolean }>('restart_opencode', {}, { + timeout: 10000, + onCancel: () => { + console.warn('[SettingsAPI] Restart OpenCode operation timed out'); + } + }); + return { restarted: result.restarted }; + } catch (error) { + throw new Error(`Failed to restart OpenCode: ${error instanceof Error ? error.message : String(error)}`); + } + }, +}); diff --git a/packages/desktop/src/api/terminal.ts b/packages/desktop/src/api/terminal.ts new file mode 100644 index 00000000..2a8b960c --- /dev/null +++ b/packages/desktop/src/api/terminal.ts @@ -0,0 +1,123 @@ +import { safeInvoke, safeListen } from '../lib/tauriCallbackManager'; +import type { + TerminalAPI, + TerminalHandlers, + CreateTerminalOptions, + ResizeTerminalPayload, + TerminalSession, + TerminalStreamEvent +} from '@openchamber/ui/lib/api/types'; + +async function safeTerminalInvoke(command: string, args?: Record): Promise { + try { + return await safeInvoke(command, args, { + timeout: 10000, + onCancel: () => { + console.warn(`[TerminalAPI] Command ${command} timed out`); + } + }); + } catch (error) { + const message = typeof error === 'string' ? error : (error as Error).message || 'Unknown error'; + throw new Error(message); + } +} + +export const createDesktopTerminalAPI = (): TerminalAPI => ({ + async createSession(options: CreateTerminalOptions): Promise { + const cols = options.cols ?? 80; + const rows = options.rows ?? 24; + + const res = await safeTerminalInvoke<{ session_id: string }>('create_terminal_session', { + payload: { + cols, + rows, + cwd: options.cwd + } + }); + + return { + sessionId: res.session_id, + cols, + rows + }; + }, + + connect(sessionId: string, handlers: TerminalHandlers) { + let unlistenFn: (() => void) | undefined; + let cancelled = false; + let isConnected = false; + + const stopListening = () => { + if (unlistenFn) { + unlistenFn(); + unlistenFn = undefined; + isConnected = false; + } + }; + + const startListening = async () => { + try { + const unlisten = await safeListen(`terminal://${sessionId}`, (event) => { + if (cancelled) { + return; + } + + handlers.onEvent(event.payload); + + if (event.payload?.type === 'exit') { + stopListening(); + } + }); + + if (cancelled) { + unlisten(); + return; + } + + unlistenFn = unlisten; + isConnected = true; + handlers.onEvent({ type: 'connected' }); + } catch (err) { + console.error('Failed to listen to terminal events:', err); + if (!cancelled) { + handlers.onError?.(err instanceof Error ? err : new Error(String(err))); + } + } + }; + + startListening(); + + return { + close: () => { + cancelled = true; + stopListening(); + }, + isConnected: () => isConnected, + }; + }, + + async sendInput(sessionId: string, input: string): Promise { + await safeTerminalInvoke('send_terminal_input', { + + sessionId, + session_id: sessionId, + data: input, + }); + }, + + async resize(payload: ResizeTerminalPayload): Promise { + await safeTerminalInvoke('resize_terminal', { + sessionId: payload.sessionId, + session_id: payload.sessionId, + cols: payload.cols, + rows: payload.rows, + }); + }, + + async close(sessionId: string): Promise { + await safeTerminalInvoke('close_terminal', { + sessionId, + session_id: sessionId, + }); + }, +}); diff --git a/packages/desktop/src/api/tools.ts b/packages/desktop/src/api/tools.ts new file mode 100644 index 00000000..97f373a6 --- /dev/null +++ b/packages/desktop/src/api/tools.ts @@ -0,0 +1,22 @@ +import type { ToolsAPI } from '@openchamber/ui/lib/api/types'; + +export const createDesktopToolsAPI = (): ToolsAPI => ({ + async getAvailableTools(): Promise { + + const response = await fetch('/api/experimental/tool/ids'); + + if (!response.ok) { + throw new Error(`Tools API returned ${response.status} ${response.statusText}`); + } + + const data = await response.json(); + + if (!Array.isArray(data)) { + throw new Error('Tools API returned invalid data format'); + } + + return data + .filter((tool: unknown): tool is string => typeof tool === 'string' && tool !== 'invalid') + .sort(); + }, +}); diff --git a/packages/desktop/src/api/updater.ts b/packages/desktop/src/api/updater.ts new file mode 100644 index 00000000..1dc99bdc --- /dev/null +++ b/packages/desktop/src/api/updater.ts @@ -0,0 +1,105 @@ +export interface UpdateInfo { + available: boolean; + version?: string; + currentVersion: string; + body?: string; + date?: string; +} + +export interface UpdateProgress { + downloaded: number; + total?: number; +} + +interface Update { + version: string; + body?: string; + date?: string; + downloadAndInstall: ( + onEvent?: (event: DownloadEvent) => void + ) => Promise; +} + +type DownloadEvent = + | { event: 'Started'; data: { contentLength?: number } } + | { event: 'Progress'; data: { chunkLength: number } } + | { event: 'Finished' }; + +let cachedUpdate: Update | null = null; + +export async function checkForUpdates(): Promise { + try { + const { check } = await import('@tauri-apps/plugin-updater'); + const update = await check(); + cachedUpdate = update; + + if (!update) { + return { + available: false, + currentVersion: await getCurrentVersion(), + }; + } + + return { + available: true, + version: update.version, + currentVersion: await getCurrentVersion(), + body: update.body ?? undefined, + date: update.date ?? undefined, + }; + } catch (error) { + console.error('[updater] Failed to check for updates:', error); + return { + available: false, + currentVersion: await getCurrentVersion(), + }; + } +} + +export async function downloadUpdate( + onProgress?: (progress: UpdateProgress) => void +): Promise { + let update = cachedUpdate; + if (!update) { + const { check } = await import('@tauri-apps/plugin-updater'); + const checked = await check(); + if (!checked) { + throw new Error('No update available'); + } + update = checked; + cachedUpdate = checked; + } + + let downloaded = 0; + let total: number | undefined; + + await update.downloadAndInstall((event: DownloadEvent) => { + switch (event.event) { + case 'Started': + total = event.data.contentLength; + onProgress?.({ downloaded: 0, total }); + break; + case 'Progress': + downloaded += event.data.chunkLength; + onProgress?.({ downloaded, total }); + break; + case 'Finished': + onProgress?.({ downloaded: total ?? downloaded, total }); + break; + } + }); +} + +export async function restartToUpdate(): Promise { + const { relaunch } = await import('@tauri-apps/plugin-process'); + await relaunch(); +} + +async function getCurrentVersion(): Promise { + try { + const { getVersion } = await import('@tauri-apps/api/app'); + return await getVersion(); + } catch { + return 'unknown'; + } +} diff --git a/packages/desktop/src/lib/bridge.ts b/packages/desktop/src/lib/bridge.ts new file mode 100644 index 00000000..56cb8231 --- /dev/null +++ b/packages/desktop/src/lib/bridge.ts @@ -0,0 +1,157 @@ + +import { safeInvoke, cleanupAllTauriCallbacks } from './tauriCallbackManager'; + +type ServerInfo = { + server_port: number; + opencode_port?: number | null; + api_prefix?: string | null; + cli_available?: boolean; +}; + +declare global { + interface Window { + __OPENCHAMBER_DESKTOP_SERVER__?: { + origin: string; + opencodePort: number | null; + apiPrefix: string; + cliAvailable: boolean; + }; + } +} + +let bridgePromise: Promise | null = null; + +export function initializeDesktopBridge(): Promise { + if (!bridgePromise) { + bridgePromise = setupBridge(); + } + return bridgePromise; +} + +async function setupBridge(): Promise { + try { + const info = await safeInvoke('desktop_server_info', {}, { + timeout: 10000, + onCancel: () => { + console.warn('[Bridge] Server info request timed out'); + } + }); + const origin = `http://127.0.0.1:${info.server_port}`; + + window.__OPENCHAMBER_DESKTOP_SERVER__ = { + origin, + opencodePort: info.opencode_port ?? null, + apiPrefix: info.api_prefix ?? '', + cliAvailable: info.cli_available ?? false, + }; + + patchFetch(origin); + patchEventSource(origin); + + const cleanupDevtools = registerDevtoolsShortcut(); + + if (typeof window !== 'undefined') { + (window as { __openchamberCleanup?: () => void }).__openchamberCleanup = () => { + cleanupDevtools(); + }; + } + } catch (error) { + console.error('[bridge] Failed to initialize bridge:', error); + + if (typeof window !== 'undefined' && (window as { __openchamberCleanup?: () => void }).__openchamberCleanup) { + try { + (window as { __openchamberCleanup?: () => void }).__openchamberCleanup?.(); + } catch (cleanupError) { + console.warn('[bridge] Cleanup during failed initialization failed:', cleanupError); + } + delete (window as { __openchamberCleanup?: () => void }).__openchamberCleanup; + } + + cleanupAllTauriCallbacks(); + + throw error; + } +} + +function patchFetch(origin: string) { + const originalFetch = window.fetch.bind(window); + + const rewrite = (value: string): string => { + if (value.startsWith('http://') || value.startsWith('https://')) { + return value; + } + if (value.startsWith('//')) { + return `http:${value}`; + } + if (value.startsWith('/')) { + return `${origin}${value}`; + } + return value; + }; + + window.fetch = (input: RequestInfo | URL, init?: RequestInit) => { + if (typeof input === 'string') { + return originalFetch(rewrite(input), init); + } + + if (input instanceof Request) { + const rewritten = rewrite(input.url); + if (rewritten === input.url) { + return originalFetch(input, init); + } + const cloned = new Request(rewritten, input); + return originalFetch(cloned, init); + } + + if (input instanceof URL) { + return originalFetch(rewrite(input.toString()), init); + } + + return originalFetch(input, init); + }; +} + +function patchEventSource(origin: string) { + if (typeof window.EventSource === 'undefined') { + return; + } + + const OriginalEventSource = window.EventSource; + + class DesktopEventSource extends OriginalEventSource { + constructor(url: string | URL, eventSourceInit?: EventSourceInit) { + const normalized = typeof url === 'string' ? url : url.toString(); + super(normalized.startsWith('/') ? `${origin}${normalized}` : normalized, eventSourceInit); + } + } + + Object.defineProperty(DesktopEventSource, 'name', { value: 'DesktopEventSource' }); + Object.setPrototypeOf(DesktopEventSource.prototype, OriginalEventSource.prototype); + Object.setPrototypeOf(DesktopEventSource, OriginalEventSource); + + window.EventSource = DesktopEventSource as unknown as typeof EventSource; +} + +function registerDevtoolsShortcut() { + const handler = (event: KeyboardEvent) => { + const key = event.key?.toLowerCase(); + if ((event.metaKey || event.ctrlKey) && event.altKey && key === 'i') { + event.preventDefault(); + + const devtoolsPromise = safeInvoke('desktop_open_devtools', {}, { + timeout: 2000, + onCancel: () => { + console.warn('[Bridge] Devtools invocation timed out'); + } + }); + devtoolsPromise.catch(() => { + + }); + } + }; + window.addEventListener('keydown', handler); + + return () => { + window.removeEventListener('keydown', handler); + }; +} diff --git a/packages/desktop/src/lib/tauriCallbackManager.ts b/packages/desktop/src/lib/tauriCallbackManager.ts new file mode 100644 index 00000000..0e706cb6 --- /dev/null +++ b/packages/desktop/src/lib/tauriCallbackManager.ts @@ -0,0 +1,308 @@ + + +import { invoke } from '@tauri-apps/api/core'; +import { listen, type UnlistenFn } from '@tauri-apps/api/event'; + +interface PendingCallback { + id: string; + timestamp: number; + type: 'invoke' | 'listen'; + cleanup?: () => void; + timeout?: NodeJS.Timeout; +} + +interface CallbackManagerConfig { + maxCallbackAge?: number; + cleanupInterval?: number; + invokeTimeout?: number; + listenTimeout?: number; +} + +class TauriCallbackManager { + private callbacks = new Map(); + private isShuttingDown = false; + private cleanupTimer?: NodeJS.Timeout; + private config: Required; + private windowUnloadHandler?: () => void; + + constructor(config: CallbackManagerConfig = {}) { + this.config = { + maxCallbackAge: 30000, + cleanupInterval: 5000, + invokeTimeout: 10000, + listenTimeout: 30000, + ...config, + }; + + this.setupWindowUnloadHandler(); + this.startCleanupTimer(); + } + + register(callback: Omit): string { + if (this.isShuttingDown) { + console.warn('[TauriCallbackManager] Attempted to register callback during shutdown'); + return callback.id; + } + + const fullCallback: PendingCallback = { + ...callback, + timestamp: Date.now(), + }; + + this.callbacks.set(callback.id, fullCallback); + + if (callback.type === 'listen' && this.config.listenTimeout > 0) { + const timeout = setTimeout(() => { + this.cleanupCallback(callback.id, 'timeout'); + }, this.config.listenTimeout); + fullCallback.timeout = timeout; + } + + return callback.id; + } + + unregister(callbackId: string): void { + const callback = this.callbacks.get(callbackId); + if (!callback) { + return; + } + + if (callback.timeout) { + clearTimeout(callback.timeout); + } + + if (callback.cleanup) { + try { + callback.cleanup(); + } catch (error) { + console.warn('[TauriCallbackManager] Cleanup function failed:', error); + } + } + + this.callbacks.delete(callbackId); + } + + private cleanupCallback(callbackId: string, reason: 'timeout' | 'shutdown' | 'expired'): void { + const callback = this.callbacks.get(callbackId); + if (!callback) { + return; + } + + if (reason === 'expired') { + console.warn(`[TauriCallbackManager] Callback ${callbackId} expired and was cleaned up`); + } + + this.unregister(callbackId); + } + + cleanupAll(): void { + this.isShuttingDown = true; + + if (this.cleanupTimer) { + clearInterval(this.cleanupTimer); + this.cleanupTimer = undefined; + } + + const callbackIds = Array.from(this.callbacks.keys()); + callbackIds.forEach(id => this.cleanupCallback(id, 'shutdown')); + + this.callbacks.clear(); + } + + private startCleanupTimer(): void { + this.cleanupTimer = setInterval(() => { + if (this.isShuttingDown) { + return; + } + + const now = Date.now(); + const expiredCallbacks: string[] = []; + + this.callbacks.forEach((callback, id) => { + const age = now - callback.timestamp; + if (age > this.config.maxCallbackAge) { + expiredCallbacks.push(id); + } + }); + + expiredCallbacks.forEach(id => this.cleanupCallback(id, 'expired')); + }, this.config.cleanupInterval); + } + + private setupWindowUnloadHandler(): void { + if (typeof window === 'undefined') { + return; + } + + this.windowUnloadHandler = () => { + console.info('[TauriCallbackManager] Window unloading, cleaning up callbacks...'); + this.cleanupAll(); + }; + + window.addEventListener('beforeunload', this.windowUnloadHandler); + window.addEventListener('pagehide', this.windowUnloadHandler); + } + + removeWindowHandlers(): void { + if (this.windowUnloadHandler && typeof window !== 'undefined') { + window.removeEventListener('beforeunload', this.windowUnloadHandler); + window.removeEventListener('pagehide', this.windowUnloadHandler); + this.windowUnloadHandler = undefined; + } + } + + getStats(): { total: number; invoke: number; listen: number } { + const stats = { total: 0, invoke: 0, listen: 0 }; + + this.callbacks.forEach(callback => { + stats.total++; + stats[callback.type]++; + }); + + return stats; + } +} + +let globalCallbackManager: TauriCallbackManager | null = null; + +export function getTauriCallbackManager(config?: CallbackManagerConfig): TauriCallbackManager { + if (!globalCallbackManager) { + globalCallbackManager = new TauriCallbackManager(config); + } + return globalCallbackManager; +} + +export async function safeInvoke( + command: string, + args?: Record, + options?: { + timeout?: number; + onCancel?: () => void; + } +): Promise { + const manager = getTauriCallbackManager(); + const callbackId = `invoke:${command}:${Date.now()}:${Math.random().toString(36).slice(2)}`; + + let timeoutHandle: NodeJS.Timeout | undefined; + let settled = false; + + manager.register({ + id: callbackId, + type: 'invoke', + }); + + const clearAndUnregister = () => { + if (timeoutHandle) { + clearTimeout(timeoutHandle); + timeoutHandle = undefined; + } + manager.unregister(callbackId); + }; + + if (!options?.timeout || options.timeout <= 0) { + try { + const result = await invoke(command, args); + clearAndUnregister(); + return result; + } catch (error) { + clearAndUnregister(); + throw error; + } + } + + return new Promise((resolve, reject) => { + timeoutHandle = setTimeout(() => { + if (settled) { + return; + } + settled = true; + + console.warn(`[safeInvoke] Command ${command} timed out after ${options.timeout}ms`); + try { + options.onCancel?.(); + } catch (error) { + console.warn('[safeInvoke] onCancel handler threw:', error); + } + + clearAndUnregister(); + reject(new Error(`Command ${command} timed out after ${options.timeout}ms`)); + }, options.timeout); + + invoke(command, args) + .then((result) => { + if (settled) { + + return; + } + settled = true; + clearAndUnregister(); + resolve(result); + }) + .catch((error) => { + if (settled) { + return; + } + settled = true; + clearAndUnregister(); + reject(error); + }); + }); +} + +export async function safeListen( + event: string, + handler: (event: { payload: T }) => void, + options?: { + timeout?: number; + onCancel?: () => void; + } +): Promise { + const manager = getTauriCallbackManager(); + const callbackId = `listen:${event}:${Date.now()}:${Math.random().toString(36).slice(2)}`; + + try { + + manager.register({ + id: callbackId, + type: 'listen', + cleanup: options?.onCancel, + }); + + const unlisten = await listen(event, (event) => { + + const currentManager = getTauriCallbackManager(); + if (currentManager.getStats().total === 0) { + return; + } + + try { + handler(event); + } catch (error) { + console.error(`[safeListen] Handler error for event ${event}:`, error); + } + }); + + const enhancedUnlisten = () => { + try { + unlisten(); + } catch (error) { + console.warn(`[safeListen] Failed to unlisten from ${event}:`, error); + } + manager.unregister(callbackId); + }; + + return enhancedUnlisten; + } catch (error) { + + manager.unregister(callbackId); + throw error; + } +} + +export function cleanupAllTauriCallbacks(): void { + if (globalCallbackManager) { + globalCallbackManager.cleanupAll(); + globalCallbackManager.removeWindowHandlers(); + globalCallbackManager = null; + } +} diff --git a/packages/desktop/src/main.tsx b/packages/desktop/src/main.tsx new file mode 100644 index 00000000..c27e1344 --- /dev/null +++ b/packages/desktop/src/main.tsx @@ -0,0 +1,254 @@ +import { createDesktopAPIs } from './api'; +import { requestInitialNotificationPermission } from './api/notifications'; +import { checkForUpdates, downloadUpdate, restartToUpdate, type UpdateInfo, type UpdateProgress } from './api/updater'; +import { initializeDesktopBridge } from './lib/bridge'; + +import { invoke } from '@tauri-apps/api/core'; +import { listen } from '@tauri-apps/api/event'; +import type { RuntimeAPIs } from '@openchamber/ui/lib/api/types'; +import type { DesktopApi, DesktopSettings } from '@openchamber/ui/lib/desktop'; +import '@openchamber/ui/index.css'; +import '@openchamber/ui/styles/fonts'; + +if (!(window as typeof globalThis & { process?: unknown }).process) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (window as typeof globalThis & { process?: any }).process = { + env: {}, + platform: 'darwin', + version: 'v20.0.0', + versions: {}, + cwd: () => '/', + nextTick: (fn: () => void) => Promise.resolve().then(() => fn()), + }; +} + +declare global { + interface Window { + __OPENCHAMBER_RUNTIME_APIS__?: RuntimeAPIs; + __OPENCHAMBER_HOME__?: string; + opencodeDesktop?: DesktopApi; + } +} + +const cleanupFunctions: Array<() => void | Promise> = []; + +try { + await initializeDesktopBridge(); + + const activityUnlisten = await listen('openchamber:session-activity', (event) => { + window.dispatchEvent(new CustomEvent('openchamber:session-activity', { detail: event.payload })); + }); + cleanupFunctions.push(() => activityUnlisten()); + + requestInitialNotificationPermission().catch(err => { + console.error('[main] Failed to request notification permission:', err); + }); + + window.__OPENCHAMBER_RUNTIME_APIS__ = createDesktopAPIs(); + + cleanupFunctions.push(() => { + console.info('[main] Cleaning up runtime APIs'); + + if (window.__OPENCHAMBER_RUNTIME_APIS__) { + /* cleanup placeholder */ + } + }); + +} catch (error) { + console.error('[main] FATAL: Failed to initialize desktop runtime:', error); + + for (const cleanup of cleanupFunctions) { + try { + const result = cleanup(); + if (result instanceof Promise) { + await result; + } + } catch (cleanupError) { + console.warn('[main] Cleanup function failed during error handling:', cleanupError); + } + } + + document.body.innerHTML = ` +
+

Desktop Runtime Initialization Failed

+
+${error instanceof Error ? error.stack : String(error)}
+      
+

Press Cmd+Option+I to open DevTools for more details

+
+ `; + throw error; +} + +let homeDirectory: string | undefined; +try { + const { homeDir } = await import('@tauri-apps/api/path'); + homeDirectory = await homeDir(); +} catch { + homeDirectory = undefined; +} + +if (homeDirectory) { + window.__OPENCHAMBER_HOME__ = homeDirectory; +} + +window.opencodeDesktop = { + homeDirectory, + async getServerInfo() { + const server = window.__OPENCHAMBER_DESKTOP_SERVER__; + return { + webPort: server?.origin ? parseInt(server.origin.split(':')[2] || '0', 10) : null, + openCodePort: server?.opencodePort ?? null, + host: '127.0.0.1', + ready: true, + cliAvailable: server?.cliAvailable ?? false, + }; + }, + async getSettings(): Promise { + try { + const result = await invoke<{ settings: DesktopSettings; source: string }>('load_settings'); + return result.settings; + } catch (error) { + console.error('[desktop] Error loading settings:', error); + return {} as DesktopSettings; + } + }, + async updateSettings(changes: Partial): Promise { + try { + const result = await invoke('save_settings', { changes }); + return result; + } catch (error) { + console.error('[desktop] Error updating settings:', error); + return {}; + } + }, + async restartOpenCode() { + try { + await invoke('restart_opencode'); + return { success: true }; + } catch (error) { + console.error('[desktop] Error restarting OpenCode:', error); + return { success: false }; + } + }, + async shutdown() { + return { success: false }; + }, + async getHomeDirectory() { + return { success: true, path: homeDirectory || null }; + }, + markRendererReady() { + + }, + async requestDirectoryAccess() { + try { + + const { open } = await import('@tauri-apps/plugin-dialog'); + const selected = await open({ + directory: true, + multiple: false, + title: 'Select Working Directory' + }); + + if (!selected || typeof selected !== 'string') { + return { success: false, error: 'Directory selection cancelled' }; + } + + const result = await invoke<{ success: boolean; path?: string; error?: string }>('process_directory_selection', { + path: selected + }); + + return result; + } catch (error) { + console.error('[desktop] Error requesting directory access:', error); + return { success: false, error: error instanceof Error ? error.message : String(error) }; + } + }, + async startAccessingDirectory(directoryPath: string) { + try { + const result = await invoke<{ success: boolean; error?: string }>('start_accessing_directory', { path: directoryPath }); + return result; + } catch (error) { + console.error('[desktop] Error starting directory access:', error); + return { success: false, error: error instanceof Error ? error.message : String(error) }; + } + }, + + async stopAccessingDirectory(directoryPath: string) { + try { + const result = await invoke<{ success: boolean; error?: string }>('stop_accessing_directory', { path: directoryPath }); + return result; + } catch (error) { + console.error('[desktop] Error stopping directory access:', error); + return { success: false, error: error instanceof Error ? error.message : String(error) }; + } + }, + async notifyAssistantCompletion(payload) { + try { + const { createDesktopNotificationsAPI } = await import('./api/notifications'); + const result = await createDesktopNotificationsAPI().notifyAgentCompletion(payload); + return { success: result }; + } catch (error) { + console.error('[desktop] Error sending notification:', error); + return { success: false }; + } + }, + async checkForUpdates(): Promise { + return checkForUpdates(); + }, + async downloadUpdate(onProgress?: (progress: UpdateProgress) => void): Promise { + return downloadUpdate(onProgress); + }, + async restartToUpdate(): Promise { + return restartToUpdate(); + } +}; + +console.info('[main] window.opencodeDesktop assigned'); + +if (typeof window !== 'undefined') { + const handleBeforeUnload = () => { + console.info('[main] App is unloading, performing cleanup...'); + + cleanupFunctions.forEach((cleanup) => { + try { + const result = cleanup(); + if (result instanceof Promise) { + + result.catch(cleanupError => { + console.warn('[main] Cleanup function failed during unload:', cleanupError); + }); + } + } catch (cleanupError) { + console.warn('[main] Cleanup function failed during unload:', cleanupError); + } + }); + + console.info('[main] Cleanup initiated'); + }; + + window.addEventListener('beforeunload', handleBeforeUnload); + + window.addEventListener('pagehide', handleBeforeUnload); + + cleanupFunctions.push(() => { + window.removeEventListener('beforeunload', handleBeforeUnload); + window.removeEventListener('pagehide', handleBeforeUnload); + }); +} + +try { + await import('@openchamber/ui/main'); +} catch (error) { + console.error('[main] FATAL: Failed to load UI module:', error); + document.body.innerHTML = ` +
+

UI Module Load Failed

+
+${error instanceof Error ? error.stack : String(error)}
+      
+

Check DevTools console for details

+
+ `; + throw error; +} diff --git a/packages/desktop/tsconfig.json b/packages/desktop/tsconfig.json new file mode 100644 index 00000000..994cb50c --- /dev/null +++ b/packages/desktop/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "moduleDetection": "force", + "verbatimModuleSyntax": true, + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "jsx": "react-jsx", + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "baseUrl": ".", + "types": ["vite/client"], + "paths": { + "@/*": ["../ui/src/*"], + "@desktop/*": ["./src/*"], + "@openchamber/ui/*": ["../ui/src/*"], + "@openchamber/desktop/*": ["./src/*"] + } + }, + "include": ["src", "../ui/src", "../ui/src/types/**/*"] +} diff --git a/packages/desktop/vite.config.ts b/packages/desktop/vite.config.ts new file mode 100644 index 00000000..16557984 --- /dev/null +++ b/packages/desktop/vite.config.ts @@ -0,0 +1,75 @@ +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { themeStoragePlugin } from '../../vite-theme-plugin'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +export default defineConfig({ + root: path.resolve(__dirname, '.'), + plugins: [react(), themeStoragePlugin()], + resolve: { + alias: { + '@desktop': path.resolve(__dirname, './src'), + '@openchamber/ui': path.resolve(__dirname, '../ui/src'), + '@': path.resolve(__dirname, '../ui/src'), + '@opencode-ai/sdk': path.resolve(__dirname, '../../node_modules/@opencode-ai/sdk/dist/client.js'), + }, + }, + define: { + 'process.env': {}, + 'process.platform': JSON.stringify('darwin'), + 'process.version': JSON.stringify('v20.0.0'), + 'process.versions': JSON.stringify({}), + global: 'globalThis', + }, + optimizeDeps: { + include: ['@opencode-ai/sdk'], + exclude: [ + '@tauri-apps/plugin-dialog', + '@tauri-apps/api/core', + '@tauri-apps/api/path', + ], + }, + server: { + host: '127.0.0.1', + port: 1421, + strictPort: true, + hmr: { + protocol: 'ws', + host: '127.0.0.1', + port: 1421, + }, + }, + build: { + outDir: path.resolve(__dirname, 'dist'), + emptyOutDir: true, + chunkSizeWarningLimit: 1200, + rollupOptions: { + output: { + manualChunks(id) { + if (!id.includes('node_modules')) return undefined; + + const match = id.split('node_modules/')[1]; + if (!match) return undefined; + + const segments = match.split('/'); + const packageName = match.startsWith('@') ? `${segments[0]}/${segments[1]}` : segments[0]; + + if (packageName === 'react' || packageName === 'react-dom') return 'vendor-react'; + if (packageName === 'zustand' || packageName === 'zustand/middleware') return 'vendor-zustand'; + + if (packageName === '@opencode-ai/sdk') return 'vendor-opencode-sdk'; + if (packageName.includes('remark') || packageName.includes('rehype') || packageName === 'react-markdown') return 'vendor-markdown'; + if (packageName.startsWith('@radix-ui')) return 'vendor-radix'; + if (packageName.includes('react-syntax-highlighter') || packageName.includes('highlight.js')) return 'vendor-syntax'; + if (packageName.startsWith('@tauri-apps')) return 'vendor-tauri'; + + const sanitized = packageName.replace(/^@/, '').replace(/\//g, '-'); + return `vendor-${sanitized}`; + }, + }, + }, + }, +}); diff --git a/packages/ui/package.json b/packages/ui/package.json new file mode 100644 index 00000000..a66c8ad2 --- /dev/null +++ b/packages/ui/package.json @@ -0,0 +1,77 @@ +{ + "name": "@openchamber/ui", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "src/main.tsx", + "scripts": { + "dev": "tsc --noEmit --watch", + "build": "tsc --noEmit", + "type-check": "tsc --noEmit", + "lint": "eslint \"./src/**/*.{ts,tsx}\" --config ../../eslint.config.js" + }, + "dependencies": { + "@fontsource/ibm-plex-mono": "^5.2.7", + "@fontsource/ibm-plex-sans": "^5.1.1", + "@ibm/plex": "^6.4.1", + "@opencode-ai/sdk": "^1.0.65", + "@radix-ui/react-collapsible": "^1.1.12", + "@radix-ui/react-dialog": "^1.1.15", + "@radix-ui/react-dropdown-menu": "^2.1.16", + "@radix-ui/react-scroll-area": "^1.2.10", + "@radix-ui/react-select": "^2.2.6", + "@radix-ui/react-separator": "^1.1.7", + "@radix-ui/react-slot": "^1.2.3", + "@radix-ui/react-toggle": "^1.1.10", + "@radix-ui/react-tooltip": "^1.2.8", + "@remixicon/react": "^4.7.0", + "@types/react-syntax-highlighter": "^15.5.13", + "@xterm/addon-fit": "^0.10.0", + "@xterm/xterm": "^5.3.0", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "cmdk": "^1.1.1", + "express": "^5.1.0", + "http-proxy-middleware": "^3.0.5", + "motion": "^12.23.24", + "next-themes": "^0.4.6", + "node-pty": "^1.0.0", + "react": "^19.1.1", + "react-dom": "^19.1.1", + "@monaco-editor/react": "^4.6.0", + "react-syntax-highlighter": "^15.6.6", + "simple-git": "^3.28.0", + "sonner": "^2.0.7", + "streamdown": "^1.6.10", + "strip-json-comments": "^5.0.3", + "tailwind-merge": "^3.3.1", + "yaml": "^2.8.1", + "zustand": "^5.0.8" + }, + "devDependencies": { + "@eslint/js": "^9.33.0", + "@tailwindcss/postcss": "^4.0.0", + "@tauri-apps/api": "^2.9.0", + "@types/node": "^24.3.1", + "@types/react": "^19.1.10", + "@types/react-dom": "^19.1.7", + "@vitejs/plugin-react": "^5.0.0", + "autoprefixer": "^10.4.21", + "concurrently": "^9.2.1", + "cors": "^2.8.5", + "cross-env": "^7.0.3", + "electron": "^38.2.0", + "electron-builder": "^24.13.3", + "eslint": "^9.33.0", + "eslint-plugin-react-hooks": "^5.2.0", + "eslint-plugin-react-refresh": "^0.4.20", + "globals": "^16.3.0", + "nodemon": "^3.1.7", + "tailwindcss": "^4.0.0", + "tsx": "^4.20.6", + "tw-animate-css": "^1.3.8", + "typescript": "~5.8.3", + "typescript-eslint": "^8.39.1", + "vite": "^7.1.2" + } +} diff --git a/packages/ui/src/App.css b/packages/ui/src/App.css new file mode 100644 index 00000000..b9d355df --- /dev/null +++ b/packages/ui/src/App.css @@ -0,0 +1,42 @@ +#root { + max-width: 1280px; + margin: 0 auto; + padding: 2rem; + text-align: center; +} + +.logo { + height: 6em; + padding: 1.5em; + will-change: filter; + transition: filter 300ms; +} +.logo:hover { + filter: drop-shadow(0 0 2em #646cffaa); +} +.logo.react:hover { + filter: drop-shadow(0 0 2em #61dafbaa); +} + +@keyframes logo-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +@media (prefers-reduced-motion: no-preference) { + a:nth-of-type(2) .logo { + animation: logo-spin infinite 20s linear; + } +} + +.card { + padding: 2em; +} + +.read-the-docs { + color: #888; +} diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsx new file mode 100644 index 00000000..54457498 --- /dev/null +++ b/packages/ui/src/App.tsx @@ -0,0 +1,188 @@ +import React from 'react'; +import { MainLayout } from '@/components/layout/MainLayout'; +import { FireworksProvider } from '@/contexts/FireworksContext'; +import { Toaster } from '@/components/ui/sonner'; +import { MemoryDebugPanel } from '@/components/ui/MemoryDebugPanel'; +import { ErrorBoundary } from '@/components/ui/ErrorBoundary'; +import { useEventStream } from '@/hooks/useEventStream'; +import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts'; +import { useMessageSync } from '@/hooks/useMessageSync'; +import { useSessionStatusBootstrap } from '@/hooks/useSessionStatusBootstrap'; +import { GitPollingProvider } from '@/hooks/useGitPolling'; +import { useConfigStore } from '@/stores/useConfigStore'; +import { useSessionStore } from '@/stores/useSessionStore'; +import { useDirectoryStore } from '@/stores/useDirectoryStore'; +import { opencodeClient } from '@/lib/opencode/client'; +import { useFontPreferences } from '@/hooks/useFontPreferences'; +import { CODE_FONT_OPTION_MAP, DEFAULT_MONO_FONT, DEFAULT_UI_FONT, UI_FONT_OPTION_MAP } from '@/lib/fontOptions'; +import { ConfigUpdateOverlay } from '@/components/ui/ConfigUpdateOverlay'; +import { RuntimeAPIProvider } from '@/contexts/RuntimeAPIProvider'; +import { registerRuntimeAPIs } from '@/contexts/runtimeAPIRegistry'; +import { OnboardingScreen } from '@/components/onboarding/OnboardingScreen'; +import { isCliAvailable } from '@/lib/desktop'; +import type { RuntimeAPIs } from '@/lib/api/types'; + +type AppProps = { + apis: RuntimeAPIs; +}; + +function App({ apis }: AppProps) { + const { initializeApp, loadProviders, isInitialized } = useConfigStore(); + const { error, clearError, loadSessions } = useSessionStore(); + const currentDirectory = useDirectoryStore((state) => state.currentDirectory); + const isSwitchingDirectory = useDirectoryStore((state) => state.isSwitchingDirectory); + const [showMemoryDebug, setShowMemoryDebug] = React.useState(false); + const { uiFont, monoFont } = useFontPreferences(); + const [isDesktopRuntime, setIsDesktopRuntime] = React.useState(() => apis.runtime.isDesktop); + const [cliAvailable, setCliAvailable] = React.useState(() => { + if (!apis.runtime.isDesktop) return true; + return isCliAvailable(); + }); + + React.useEffect(() => { + setIsDesktopRuntime(apis.runtime.isDesktop); + }, [apis.runtime.isDesktop]); + + React.useEffect(() => { + registerRuntimeAPIs(apis); + return () => registerRuntimeAPIs(null); + }, [apis]); + + React.useEffect(() => { + if (typeof document === 'undefined') { + return; + } + const root = document.documentElement; + const uiStack = UI_FONT_OPTION_MAP[uiFont]?.stack ?? UI_FONT_OPTION_MAP[DEFAULT_UI_FONT].stack; + const monoStack = CODE_FONT_OPTION_MAP[monoFont]?.stack ?? CODE_FONT_OPTION_MAP[DEFAULT_MONO_FONT].stack; + + root.style.setProperty('--font-sans', uiStack); + root.style.setProperty('--font-heading', uiStack); + root.style.setProperty('--font-family-sans', uiStack); + root.style.setProperty('--font-mono', monoStack); + root.style.setProperty('--font-family-mono', monoStack); + root.style.setProperty('--ui-regular-font-weight', '400'); + + if (document.body) { + document.body.style.fontFamily = uiStack; + } + }, [uiFont, monoFont]); + + React.useEffect(() => { + if (isInitialized) { + const hideInitialLoading = () => { + const loadingElement = document.getElementById('initial-loading'); + if (loadingElement) { + loadingElement.classList.add('fade-out'); + + setTimeout(() => { + loadingElement.remove(); + }, 300); + } + }; + + const timer = setTimeout(hideInitialLoading, 150); + return () => clearTimeout(timer); + } + }, [isInitialized]); + + React.useEffect(() => { + const fallbackTimer = setTimeout(() => { + const loadingElement = document.getElementById('initial-loading'); + if (loadingElement && !isInitialized) { + loadingElement.classList.add('fade-out'); + setTimeout(() => { + loadingElement.remove(); + }, 300); + } + }, 5000); + + return () => clearTimeout(fallbackTimer); + }, [isInitialized]); + + React.useEffect(() => { + const init = async () => { + await initializeApp(); + await loadProviders(); + }; + + init(); + }, [initializeApp, loadProviders]); + + React.useEffect(() => { + if (isSwitchingDirectory) { + return; + } + + const syncDirectoryAndSessions = async () => { + opencodeClient.setDirectory(currentDirectory); + + await loadSessions(); + }; + + syncDirectoryAndSessions(); + }, [currentDirectory, isSwitchingDirectory, loadSessions]); + + useEventStream(); + + useKeyboardShortcuts(); + + useMessageSync(); + + useSessionStatusBootstrap(); + + React.useEffect(() => { + const handleKeyDown = (e: KeyboardEvent) => { + if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'M') { + e.preventDefault(); + setShowMemoryDebug(prev => !prev); + } + }; + + window.addEventListener('keydown', handleKeyDown); + return () => window.removeEventListener('keydown', handleKeyDown); + }, []); + + React.useEffect(() => { + if (error) { + + setTimeout(() => clearError(), 5000); + } + }, [error, clearError]); + + const handleCliAvailable = React.useCallback(() => { + setCliAvailable(true); + window.location.reload(); + }, []); + + if (isDesktopRuntime && !cliAvailable) { + return ( + +
+ +
+
+ ); + } + + return ( + + + + +
+ + + + {showMemoryDebug && ( + setShowMemoryDebug(false)} /> + )} +
+
+
+
+
+ ); +} + +export default App; diff --git a/packages/ui/src/assets/provider-logos/gocode.svg b/packages/ui/src/assets/provider-logos/gocode.svg new file mode 100644 index 00000000..7af2fbdf --- /dev/null +++ b/packages/ui/src/assets/provider-logos/gocode.svg @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/packages/ui/src/assets/provider-logos/kimi-for-coding.svg b/packages/ui/src/assets/provider-logos/kimi-for-coding.svg new file mode 100644 index 00000000..fb56ac10 --- /dev/null +++ b/packages/ui/src/assets/provider-logos/kimi-for-coding.svg @@ -0,0 +1 @@ +MoonshotAI \ No newline at end of file diff --git a/packages/ui/src/components/auth/SessionAuthGate.tsx b/packages/ui/src/components/auth/SessionAuthGate.tsx new file mode 100644 index 00000000..15be9273 --- /dev/null +++ b/packages/ui/src/components/auth/SessionAuthGate.tsx @@ -0,0 +1,258 @@ +import React from 'react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { OpenCodeIcon } from '@/components/ui/OpenCodeIcon'; +import { isDesktopRuntime } from '@/lib/desktop'; +import { syncDesktopSettings, initializeAppearancePreferences } from '@/lib/persistence'; +import { applyPersistedDirectoryPreferences } from '@/lib/directoryPersistence'; + +const STATUS_CHECK_ENDPOINT = '/auth/session'; + +const fetchSessionStatus = async (): Promise => { + return fetch(STATUS_CHECK_ENDPOINT, { + method: 'GET', + credentials: 'include', + headers: { + Accept: 'application/json', + }, + }); +}; + +const submitPassword = async (password: string): Promise => { + return fetch(STATUS_CHECK_ENDPOINT, { + method: 'POST', + credentials: 'include', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + }, + body: JSON.stringify({ password }), + }); +}; + +const AuthShell: React.FC<{ children: React.ReactNode }> = ({ children }) => ( +
+
+
+
+ {children} +
+
+); + +const LoadingScreen: React.FC<{ message?: string }> = ({ message = 'Preparing workspace…' }) => ( + +
+

{message}

+
+
+); + +const ErrorScreen: React.FC<{ onRetry: () => void }> = ({ onRetry }) => ( + +
+
+
+ +
+

Unable to reach server

+

+ We couldn't verify the UI session. Check that the service is running and try again. +

+ +
+
+
+); + +interface SessionAuthGateProps { + children: React.ReactNode; +} + +type GateState = 'pending' | 'authenticated' | 'locked' | 'error'; + +export const SessionAuthGate: React.FC = ({ children }) => { + const desktopRuntime = React.useMemo(() => isDesktopRuntime(), []); + const [state, setState] = React.useState(() => (desktopRuntime ? 'authenticated' : 'pending')); + const [password, setPassword] = React.useState(''); + const [isSubmitting, setIsSubmitting] = React.useState(false); + const [errorMessage, setErrorMessage] = React.useState(''); + const passwordInputRef = React.useRef(null); + const hasResyncedRef = React.useRef(desktopRuntime); + + const checkStatus = React.useCallback(async () => { + if (desktopRuntime) { + setState('authenticated'); + return; + } + + setState((prev) => (prev === 'authenticated' ? prev : 'pending')); + try { + const response = await fetchSessionStatus(); + if (response.ok) { + setState('authenticated'); + setErrorMessage(''); + return; + } + if (response.status === 401) { + setState('locked'); + return; + } + setState('error'); + } catch (error) { + console.warn('Failed to check session status:', error); + setState('error'); + } + }, [desktopRuntime]); + + React.useEffect(() => { + if (desktopRuntime) { + return; + } + void checkStatus(); + }, [checkStatus, desktopRuntime]); + + React.useEffect(() => { + if (!desktopRuntime && state === 'locked') { + hasResyncedRef.current = false; + } + }, [desktopRuntime, state]); + + React.useEffect(() => { + if (state === 'locked' && passwordInputRef.current) { + passwordInputRef.current.focus(); + passwordInputRef.current.select(); + } + }, [state]); + + React.useEffect(() => { + if (desktopRuntime) { + return; + } + if (state === 'authenticated' && !hasResyncedRef.current) { + hasResyncedRef.current = true; + void (async () => { + await syncDesktopSettings(); + await initializeAppearancePreferences(); + await applyPersistedDirectoryPreferences(); + })(); + } + }, [desktopRuntime, state]); + + const handleSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + if (!password || isSubmitting) { + return; + } + + setIsSubmitting(true); + setErrorMessage(''); + + try { + const response = await submitPassword(password); + if (response.ok) { + setPassword(''); + setState('authenticated'); + return; + } + + if (response.status === 401) { + setErrorMessage('Incorrect password. Try again.'); + setState('locked'); + return; + } + + setErrorMessage('Unexpected response from server.'); + setState('error'); + } catch (error) { + console.warn('Failed to submit UI password:', error); + setErrorMessage('Network error. Check connection and retry.'); + setState('error'); + } finally { + setIsSubmitting(false); + } + }; + + if (state === 'pending') { + return ; + } + + if (state === 'error') { + return void checkStatus()} />; + } + + if (state === 'locked') { + return ( + +
+
+
+ +
+
+

Unlock OpenChamber

+

+ Enter the password configured for this web session. +

+
+
+ +
+
+ + { + setPassword(event.target.value); + if (errorMessage) { + setErrorMessage(''); + } + }} + aria-invalid={Boolean(errorMessage) || undefined} + aria-describedby={errorMessage ? 'oc-ui-auth-error' : undefined} + disabled={isSubmitting} + /> + {errorMessage && ( +

+ {errorMessage} +

+ )} +
+ + +
+
+
+ ); + } + + return <>{children}; +}; diff --git a/packages/ui/src/components/chat/AgentMentionAutocomplete.tsx b/packages/ui/src/components/chat/AgentMentionAutocomplete.tsx new file mode 100644 index 00000000..a241222b --- /dev/null +++ b/packages/ui/src/components/chat/AgentMentionAutocomplete.tsx @@ -0,0 +1,152 @@ +import React from 'react'; +import { cn } from '@/lib/utils'; +import { useConfigStore } from '@/stores/useConfigStore'; +import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay'; + +interface AgentInfo { + name: string; + description?: string; + mode?: string | null; +} + +export interface AgentMentionAutocompleteHandle { + handleKeyDown: (key: string) => void; +} + +interface AgentMentionAutocompleteProps { + searchQuery: string; + onAgentSelect: (agentName: string) => void; + onClose: () => void; +} + +const isMentionable = (mode?: string | null): boolean => { + if (!mode) { + return false; + } + return mode !== 'primary'; +}; + +export const AgentMentionAutocomplete = React.forwardRef(({ + searchQuery, + onAgentSelect, + onClose, +}, ref) => { + const containerRef = React.useRef(null); + const [selectedIndex, setSelectedIndex] = React.useState(0); + const [agents, setAgents] = React.useState([]); + const { agents: allAgents } = useConfigStore(); + + React.useEffect(() => { + const filtered = allAgents + .filter((agent) => isMentionable(agent.mode)) + .map((agent) => ({ + name: agent.name, + description: agent.description, + mode: agent.mode ?? undefined, + })); + + const normalizedQuery = searchQuery.trim().toLowerCase(); + const matches = normalizedQuery.length + ? filtered.filter((agent) => agent.name.toLowerCase().includes(normalizedQuery)) + : filtered; + + matches.sort((a, b) => a.name.localeCompare(b.name)); + + setAgents(matches); + setSelectedIndex(0); + }, [allAgents, searchQuery]); + + React.useEffect(() => { + const handlePointerDown = (event: MouseEvent | TouchEvent) => { + const target = event.target as Node | null; + if (!target || !containerRef.current) { + return; + } + if (!containerRef.current.contains(target)) { + onClose(); + } + }; + + document.addEventListener('pointerdown', handlePointerDown, true); + return () => { + document.removeEventListener('pointerdown', handlePointerDown, true); + }; + }, [onClose]); + + React.useImperativeHandle(ref, () => ({ + handleKeyDown: (key: string) => { + if (key === 'Escape') { + onClose(); + return; + } + + if (!agents.length) { + return; + } + + if (key === 'ArrowDown') { + setSelectedIndex((prev) => (prev + 1) % agents.length); + return; + } + + if (key === 'ArrowUp') { + setSelectedIndex((prev) => (prev - 1 + agents.length) % agents.length); + return; + } + + if (key === 'Enter' || key === 'Tab') { + const agent = agents[(selectedIndex + agents.length) % agents.length]; + if (agent) { + onAgentSelect(agent.name); + } + } + }, + }), [agents, onAgentSelect, onClose, selectedIndex]); + + const renderAgent = (agent: AgentInfo, index: number) => ( +
onAgentSelect(agent.name)} + onMouseEnter={() => setSelectedIndex(index)} +> +
+
+ #{agent.name} +
+ {agent.description && ( +
+ {agent.description} +
+ )} +
+
+ ); + + return ( +
+ + {agents.length ? ( +
+ {agents.map((agent, index) => renderAgent(agent, index))} +
+ ) : ( +
+ No agents found +
+ )} +
+
+ ↑↓ navigate • Enter select • Esc close +
+
+ ); +}); + +AgentMentionAutocomplete.displayName = 'AgentMentionAutocomplete'; diff --git a/packages/ui/src/components/chat/ChatContainer.tsx b/packages/ui/src/components/chat/ChatContainer.tsx new file mode 100644 index 00000000..f6a5964a --- /dev/null +++ b/packages/ui/src/components/chat/ChatContainer.tsx @@ -0,0 +1,255 @@ +import React from 'react'; +import { RiArrowDownLine } from '@remixicon/react'; + +import { ChatInput } from './ChatInput'; +import { useSessionStore } from '@/stores/useSessionStore'; +import { Skeleton } from '@/components/ui/skeleton'; +import { OpenChamberLogo } from '@/components/ui/OpenChamberLogo'; +import MessageList from './MessageList'; +import { ScrollShadow } from '@/components/ui/ScrollShadow'; +import { useChatScrollManager } from '@/hooks/useChatScrollManager'; +import { useDeviceInfo } from '@/lib/device'; +import { Button } from '@/components/ui/button'; +import { OverlayScrollbar } from '@/components/ui/OverlayScrollbar'; + +export const ChatContainer: React.FC = () => { + const { + currentSessionId, + messages, + permissions, + streamingMessageIds, + isLoading, + loadMessages, + loadMoreMessages, + updateViewportAnchor, + sessionMemoryState, + isSyncing, + messageStreamStates, + trimToViewportWindow, + sessionActivityPhase, + } = useSessionStore(); + + const streamingMessageId = React.useMemo(() => { + if (!currentSessionId) return null; + return streamingMessageIds.get(currentSessionId) ?? null; + }, [currentSessionId, streamingMessageIds]); + + const { isMobile } = useDeviceInfo(); + + const sessionMessages = React.useMemo(() => { + + return currentSessionId ? messages.get(currentSessionId) || [] : []; + }, [currentSessionId, messages]); + + const sessionPermissions = React.useMemo(() => { + return currentSessionId ? permissions.get(currentSessionId) || [] : []; + }, [currentSessionId, permissions]); + + const { + scrollRef, + handleMessageContentChange, + getAnimationHandlers, + showScrollButton, + scrollToBottom, + spacerHeight, + pendingAnchorId, + hasActiveAnchor, + } = useChatScrollManager({ + currentSessionId, + sessionMessages, + streamingMessageId, + sessionMemoryState, + updateViewportAnchor, + isSyncing, + isMobile, + messageStreamStates, + sessionPermissions, + trimToViewportWindow, + sessionActivityPhase, + }); + + const memoryState = React.useMemo(() => { + if (!currentSessionId) { + return null; + } + return sessionMemoryState.get(currentSessionId) ?? null; + }, [currentSessionId, sessionMemoryState]); + const hasMoreAbove = Boolean(memoryState?.hasMoreAbove); + const [isLoadingOlder, setIsLoadingOlder] = React.useState(false); + React.useEffect(() => { + setIsLoadingOlder(false); + }, [currentSessionId]); + + const lastScrolledSessionRef = React.useRef(null); + React.useLayoutEffect(() => { + if (!currentSessionId || currentSessionId === lastScrolledSessionRef.current) { + return; + } + lastScrolledSessionRef.current = currentSessionId; + + const container = scrollRef.current; + if (container) { + container.scrollTop = container.scrollHeight - container.clientHeight; + } + }, [currentSessionId, scrollRef]); + + const handleLoadOlder = React.useCallback(async () => { + if (!currentSessionId || isLoadingOlder) { + return; + } + + const container = scrollRef.current; + const prevHeight = container?.scrollHeight ?? null; + const prevTop = container?.scrollTop ?? null; + + setIsLoadingOlder(true); + try { + await loadMoreMessages(currentSessionId, 'up'); + if (container && prevHeight !== null && prevTop !== null) { + const heightDiff = container.scrollHeight - prevHeight; + container.scrollTop = prevTop + heightDiff; + } + } finally { + setIsLoadingOlder(false); + } + }, [currentSessionId, isLoadingOlder, loadMoreMessages, scrollRef]); + + React.useEffect(() => { + if (!currentSessionId) { + return; + } + + const hasSessionMessages = messages.has(currentSessionId); + const existingMessages = hasSessionMessages ? messages.get(currentSessionId) ?? [] : []; + + if (existingMessages.length > 0) { + return; + } + + const load = async () => { + try { + await loadMessages(currentSessionId); + } finally { + if (typeof window === 'undefined') { + scrollToBottom(); + } else { + window.requestAnimationFrame(() => { + scrollToBottom(); + }); + } + } + }; + + void load(); + }, [currentSessionId, loadMessages, messages, scrollToBottom]); + + if (!currentSessionId) { + return ( +
+
+ +
+
+ ); + } + + if (isLoading && sessionMessages.length === 0 && !streamingMessageId) { + const hasMessagesEntry = messages.has(currentSessionId); + if (!hasMessagesEntry) { + return ( +
+
+
+ {[1, 2, 3].map((i) => ( +
+ +
+ + +
+
+ ))} +
+
+ +
+ ); + } + } + + if (sessionMessages.length === 0 && !streamingMessageId) { + return ( +
+
+ +
+
+ +
+
+ ); + } + + return ( +
+
+ +
+ +
+ + {} + {spacerHeight > 0 && hasActiveAnchor && ( + + + +
+
+ +
+ {showScrollButton && sessionMessages.length > 0 && ( +
+ +
+ )} + +
+
+ ); +}; diff --git a/packages/ui/src/components/chat/ChatEmptyState.tsx b/packages/ui/src/components/chat/ChatEmptyState.tsx new file mode 100644 index 00000000..0d01c2e8 --- /dev/null +++ b/packages/ui/src/components/chat/ChatEmptyState.tsx @@ -0,0 +1,13 @@ +import React from 'react'; + +import { OpenChamberLogo } from '@/components/ui/OpenChamberLogo'; + +const ChatEmptyState: React.FC = () => { + return ( +
+ +
+ ); +}; + +export default React.memo(ChatEmptyState); diff --git a/packages/ui/src/components/chat/ChatErrorBoundary.tsx b/packages/ui/src/components/chat/ChatErrorBoundary.tsx new file mode 100644 index 00000000..1d86a179 --- /dev/null +++ b/packages/ui/src/components/chat/ChatErrorBoundary.tsx @@ -0,0 +1,88 @@ +import React from 'react'; +import { RiChat3Line, RiRestartLine } from '@remixicon/react'; +import { Button } from '../ui/button'; +import { Card, CardContent, CardHeader, CardTitle } from '../ui/card'; + +interface ChatErrorBoundaryState { + hasError: boolean; + error?: Error; + errorInfo?: React.ErrorInfo; +} + +interface ChatErrorBoundaryProps { + children: React.ReactNode; + sessionId?: string; +} + +export class ChatErrorBoundary extends React.Component { + constructor(props: ChatErrorBoundaryProps) { + super(props); + this.state = { hasError: false }; + } + + static getDerivedStateFromError(error: Error): ChatErrorBoundaryState { + return { hasError: true, error }; + } + + componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { + this.setState({ error, errorInfo }); + + if (process.env.NODE_ENV === 'development') { + console.error('Chat error caught by boundary:', error, errorInfo); + } + } + + handleReset = () => { + this.setState({ hasError: false, error: undefined, errorInfo: undefined }); + }; + + render() { + if (this.state.hasError) { + return ( +
+ + + + + Chat Error + + + +

+ The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data. +

+ + {this.props.sessionId && ( +
+ Session: {this.props.sessionId} +
+ )} + + {this.state.error && ( +
+ Error details +
+                    {this.state.error.toString()}
+                  
+
+ )} + +
+ +
+ +
+ If the problem persists, try refreshing the page. +
+
+
+
+ ); + } + + return this.props.children; + } +} \ No newline at end of file diff --git a/packages/ui/src/components/chat/ChatInput.tsx b/packages/ui/src/components/chat/ChatInput.tsx new file mode 100644 index 00000000..a7a16407 --- /dev/null +++ b/packages/ui/src/components/chat/ChatInput.tsx @@ -0,0 +1,882 @@ +import React from 'react'; +import { Textarea } from '@/components/ui/textarea'; +import { RiAiAgentLine, RiCloseCircleLine, RiFileUploadLine, RiSendPlane2Line } from '@remixicon/react'; +import { useSessionStore } from '@/stores/useSessionStore'; +import { useConfigStore } from '@/stores/useConfigStore'; +import { useUIStore } from '@/stores/useUIStore'; +import type { EditPermissionMode } from '@/stores/types/sessionTypes'; +import { getEditModeColors } from '@/lib/permissions/editModeColors'; +import { FileAttachmentButton, AttachedFilesList } from './FileAttachment'; +import { FileMentionAutocomplete, type FileMentionHandle } from './FileMentionAutocomplete'; +import { CommandAutocomplete, type CommandAutocompleteHandle } from './CommandAutocomplete'; +import { AgentMentionAutocomplete, type AgentMentionAutocompleteHandle } from './AgentMentionAutocomplete'; +import { cn } from '@/lib/utils'; +import { ServerFilePicker } from './ServerFilePicker'; +import { ModelControls } from './ModelControls'; +import { parseAgentMentions } from '@/lib/messages/agentMentions'; +import { WorkingPlaceholder } from './message/parts/WorkingPlaceholder'; +import { useAssistantStatus } from '@/hooks/useAssistantStatus'; +import { toast } from 'sonner'; +import { useFileStore } from '@/stores/fileStore'; +import { calculateEditPermissionUIState, type BashPermissionSetting } from '@/lib/permissions/editPermissionDefaults'; + +const MAX_VISIBLE_TEXTAREA_LINES = 8; + +interface ChatInputProps { + onOpenSettings?: () => void; + scrollToBottom?: (options?: { instant?: boolean }) => void; +} + +const isPrimaryMode = (mode?: string) => mode === 'primary' || mode === 'all' || mode === undefined || mode === null; + +export const ChatInput: React.FC = ({ onOpenSettings, scrollToBottom }) => { + const [message, setMessage] = React.useState(''); + const [isDragging, setIsDragging] = React.useState(false); + const [showFileMention, setShowFileMention] = React.useState(false); + const [mentionQuery, setMentionQuery] = React.useState(''); + const [showCommandAutocomplete, setShowCommandAutocomplete] = React.useState(false); + const [commandQuery, setCommandQuery] = React.useState(''); + const [showAgentAutocomplete, setShowAgentAutocomplete] = React.useState(false); + const [agentQuery, setAgentQuery] = React.useState(''); + const [textareaSize, setTextareaSize] = React.useState<{ height: number; maxHeight: number } | null>(null); + const textareaRef = React.useRef(null); + const dropZoneRef = React.useRef(null); + const mentionRef = React.useRef(null); + const commandRef = React.useRef(null); + const agentRef = React.useRef(null); + + const sendMessage = useSessionStore((state) => state.sendMessage); + const currentSessionId = useSessionStore((state) => state.currentSessionId); + const abortCurrentOperation = useSessionStore((state) => state.abortCurrentOperation); + const acknowledgeSessionAbort = useSessionStore((state) => state.acknowledgeSessionAbort); + const abortPromptSessionId = useSessionStore((state) => state.abortPromptSessionId); + const abortPromptExpiresAt = useSessionStore((state) => state.abortPromptExpiresAt); + const clearAbortPrompt = useSessionStore((state) => state.clearAbortPrompt); + const attachedFiles = useSessionStore((state) => state.attachedFiles); + const addAttachedFile = useSessionStore((state) => state.addAttachedFile); + const addServerFile = useSessionStore((state) => state.addServerFile); + const clearAttachedFiles = useSessionStore((state) => state.clearAttachedFiles); + const saveSessionAgentSelection = useSessionStore((state) => state.saveSessionAgentSelection); + + const { currentProviderId, currentModelId, currentAgentName, agents, setAgent } = useConfigStore(); + const { isMobile } = useUIStore(); + const { working } = useAssistantStatus(); + const [showAbortStatus, setShowAbortStatus] = React.useState(false); + const abortTimeoutRef = React.useRef | null>(null); + const prevWasAbortedRef = React.useRef(false); + + const currentAgent = React.useMemo(() => { + if (!currentAgentName) { + return undefined; + } + return agents.find((agent) => agent.name === currentAgentName); + }, [agents, currentAgentName]); + + const agentDefaultEditMode = React.useMemo(() => { + const agentPermissionRaw = currentAgent?.permission?.edit; + let defaultMode: EditPermissionMode = 'ask'; + + if (agentPermissionRaw === 'allow' || agentPermissionRaw === 'ask' || agentPermissionRaw === 'deny' || agentPermissionRaw === 'full') { + defaultMode = agentPermissionRaw; + } + + const editToolConfigured = currentAgent ? (currentAgent.tools?.['edit'] !== false) : false; + if (!currentAgent || !editToolConfigured) { + defaultMode = 'deny'; + } + + return defaultMode; + }, [currentAgent]); + + const sessionAgentEditOverride = useSessionStore( + React.useCallback((state) => { + if (!currentSessionId || !currentAgentName) { + return undefined; + } + const sessionMap = state.sessionAgentEditModes.get(currentSessionId); + return sessionMap?.get(currentAgentName); + }, [currentSessionId, currentAgentName]) + ); + + const agentWebfetchPermission = currentAgent?.permission?.webfetch; + const agentBashPermission = currentAgent?.permission?.bash as BashPermissionSetting | undefined; + + const permissionUiState = React.useMemo(() => calculateEditPermissionUIState({ + agentDefaultEditMode, + webfetchPermission: agentWebfetchPermission, + bashPermission: agentBashPermission, + }), [agentDefaultEditMode, agentWebfetchPermission, agentBashPermission]); + + const selectionContextReady = Boolean(currentSessionId && currentAgentName); + + const effectiveEditPermission = React.useMemo(() => { + if (selectionContextReady && sessionAgentEditOverride && permissionUiState.modeAvailability[sessionAgentEditOverride]) { + return sessionAgentEditOverride; + } + return permissionUiState.cascadeDefaultMode; + }, [permissionUiState, selectionContextReady, sessionAgentEditOverride]); + + const chatInputAccent = React.useMemo(() => getEditModeColors(effectiveEditPermission), [effectiveEditPermission]); + + const chatInputWrapperStyle = React.useMemo(() => { + if (!chatInputAccent) { + return undefined; + } + return { + borderColor: chatInputAccent.border ?? chatInputAccent.text, + borderWidth: chatInputAccent.borderWidth ?? 1, + }; + }, [chatInputAccent]); + + const hasContent = message.trim() || attachedFiles.length > 0; + + const canAbort = working.isWorking; + + const isAbortPromptActive = React.useMemo(() => { + if (!currentSessionId) return false; + return abortPromptSessionId === currentSessionId && Boolean(abortPromptExpiresAt); + }, [abortPromptSessionId, abortPromptExpiresAt, currentSessionId]); + const canShowAbortButton = canAbort && (isMobile || isAbortPromptActive); + + const handleSubmit = async (e?: React.FormEvent) => { + e?.preventDefault(); + + if (!hasContent || !currentSessionId) return; + + const messageToSend = message.replace(/^\n+|\n+$/g, ''); + + scrollToBottom?.({ instant: true }); + + const normalizedCommand = messageToSend.trimStart(); + if (normalizedCommand.startsWith('/')) { + const commandName = normalizedCommand + .slice(1) + .trim() + .split(/\s+/)[0] + ?.toLowerCase(); + if (commandName === 'summarize') { + scrollToBottom?.({ instant: true }); + } + } + + if (!currentProviderId || !currentModelId) { + + console.warn('Cannot send message: provider or model not selected'); + return; + } + + const { sanitizedText, mention } = parseAgentMentions(messageToSend, agents); + const agentMentionName = mention?.name; + + const attachmentsToSend = attachedFiles.map((file) => ({ ...file })); + if (attachmentsToSend.length > 0) { + clearAttachedFiles(); + } + + setMessage(''); + + await sendMessage(sanitizedText, currentProviderId, currentModelId, currentAgentName, attachmentsToSend, agentMentionName) + .catch((error: unknown) => { + const rawMessage = + error instanceof Error + ? error.message + : typeof error === 'string' + ? error + : String(error ?? ''); + const normalized = rawMessage.toLowerCase(); + + console.error('Message send failed:', rawMessage || error); + + const isSoftNetworkError = + normalized.includes('timeout') || + normalized.includes('timed out') || + normalized.includes('may still be processing') || + normalized.includes('being processed') || + normalized.includes('failed to fetch') || + normalized.includes('networkerror') || + normalized.includes('network error') || + normalized.includes('gateway timeout') || + normalized === 'failed to send message'; + + if (isSoftNetworkError) { + + return; + } + + if (attachmentsToSend.length > 0) { + useFileStore.setState({ attachedFiles: attachmentsToSend }); + } + toast.error(rawMessage || 'Message failed to send. Attachments restored.'); + }); + + textareaRef.current?.focus(); + + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + + if (showCommandAutocomplete && commandRef.current) { + if (e.key === 'Enter' || e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'Escape' || e.key === 'Tab') { + e.preventDefault(); + commandRef.current.handleKeyDown(e.key); + return; + } + } + + if (showAgentAutocomplete && agentRef.current) { + if (e.key === 'Enter' || e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'Escape' || e.key === 'Tab') { + e.preventDefault(); + agentRef.current.handleKeyDown(e.key); + return; + } + } + + if (showFileMention && mentionRef.current) { + if (e.key === 'Enter' || e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'Escape' || e.key === 'Tab') { + e.preventDefault(); + mentionRef.current.handleKeyDown(e.key); + return; + } + } + + if (e.key === 'Tab' && !showCommandAutocomplete && !showFileMention) { + e.preventDefault(); + cycleAgent(); + return; + } + + if (e.key === 'Enter' && !e.shiftKey && !isMobile) { + e.preventDefault(); + handleSubmit(); + } + }; + + const startAbortIndicator = React.useCallback(() => { + if (abortTimeoutRef.current) { + clearTimeout(abortTimeoutRef.current); + abortTimeoutRef.current = null; + } + + setShowAbortStatus(true); + + abortTimeoutRef.current = setTimeout(() => { + setShowAbortStatus(false); + abortTimeoutRef.current = null; + }, 1800); + }, []); + + const handleAbort = React.useCallback(() => { + clearAbortPrompt(); + startAbortIndicator(); + + void abortCurrentOperation(); + }, [abortCurrentOperation, clearAbortPrompt, startAbortIndicator]); + + const cycleAgent = () => { + const primaryAgents = agents.filter(agent => isPrimaryMode(agent.mode)); + + if (primaryAgents.length <= 1) return; + + const currentIndex = primaryAgents.findIndex(agent => agent.name === currentAgentName); + const nextIndex = (currentIndex + 1) % primaryAgents.length; + const nextAgent = primaryAgents[nextIndex]; + + setAgent(nextAgent.name); + + if (currentSessionId) { + + saveSessionAgentSelection(currentSessionId, nextAgent.name); + } + }; + + const adjustTextareaHeight = React.useCallback(() => { + const textarea = textareaRef.current; + if (!textarea) { + return; + } + + textarea.style.height = 'auto'; + + const view = textarea.ownerDocument?.defaultView; + const computedStyle = view ? view.getComputedStyle(textarea) : null; + const lineHeight = computedStyle ? parseFloat(computedStyle.lineHeight) : NaN; + const paddingTop = computedStyle ? parseFloat(computedStyle.paddingTop) : NaN; + const paddingBottom = computedStyle ? parseFloat(computedStyle.paddingBottom) : NaN; + const fallbackLineHeight = 22; + const fallbackPadding = 16; + const paddingTotal = Number.isNaN(paddingTop) || Number.isNaN(paddingBottom) + ? fallbackPadding + : paddingTop + paddingBottom; + const targetLineHeight = Number.isNaN(lineHeight) ? fallbackLineHeight : lineHeight; + const maxHeight = targetLineHeight * MAX_VISIBLE_TEXTAREA_LINES + paddingTotal; + const scrollHeight = textarea.scrollHeight || textarea.offsetHeight; + const nextHeight = Math.min(scrollHeight, maxHeight); + + textarea.style.height = `${nextHeight}px`; + textarea.style.maxHeight = `${maxHeight}px`; + + setTextareaSize((prev) => { + if (prev && prev.height === nextHeight && prev.maxHeight === maxHeight) { + return prev; + } + return { height: nextHeight, maxHeight }; + }); + }, []); + + React.useLayoutEffect(() => { + adjustTextareaHeight(); + }, [adjustTextareaHeight, message, isMobile]); + + const updateAutocompleteState = React.useCallback((value: string, cursorPosition: number) => { + if (value.startsWith('/')) { + const firstSpace = value.indexOf(' '); + const firstNewline = value.indexOf('\n'); + const commandEnd = Math.min( + firstSpace === -1 ? value.length : firstSpace, + firstNewline === -1 ? value.length : firstNewline + ); + + if (cursorPosition <= commandEnd && firstSpace === -1) { + const commandText = value.substring(1, commandEnd); + setCommandQuery(commandText); + setShowCommandAutocomplete(true); + setShowFileMention(false); + setShowAgentAutocomplete(false); + } else { + setShowCommandAutocomplete(false); + } + return; + } + + setShowCommandAutocomplete(false); + + const textBeforeCursor = value.substring(0, cursorPosition); + + const lastHashSymbol = textBeforeCursor.lastIndexOf('#'); + if (lastHashSymbol !== -1) { + const charBefore = lastHashSymbol > 0 ? textBeforeCursor[lastHashSymbol - 1] : null; + const textAfterHash = textBeforeCursor.substring(lastHashSymbol + 1); + const hasSeparator = textAfterHash.includes(' ') || textAfterHash.includes('\n'); + const isWordBoundary = !charBefore || /\s/.test(charBefore); + + if (isWordBoundary && !hasSeparator) { + setAgentQuery(textAfterHash); + setShowAgentAutocomplete(true); + setShowFileMention(false); + return; + } + } + + setShowAgentAutocomplete(false); + setAgentQuery(''); + + const lastAtSymbol = textBeforeCursor.lastIndexOf('@'); + if (lastAtSymbol !== -1) { + const textAfterAt = textBeforeCursor.substring(lastAtSymbol + 1); + if (!textAfterAt.includes(' ') && !textAfterAt.includes('\n')) { + setMentionQuery(textAfterAt); + setShowFileMention(true); + } else { + setShowFileMention(false); + } + } else { + setShowFileMention(false); + } + }, [setAgentQuery, setCommandQuery, setMentionQuery, setShowAgentAutocomplete, setShowCommandAutocomplete, setShowFileMention]); + + const insertTextAtSelection = React.useCallback((text: string) => { + if (!text) { + return; + } + + const textarea = textareaRef.current; + if (!textarea) { + const nextValue = message + text; + setMessage(nextValue); + updateAutocompleteState(nextValue, nextValue.length); + requestAnimationFrame(() => adjustTextareaHeight()); + return; + } + + const start = textarea.selectionStart ?? message.length; + const end = textarea.selectionEnd ?? message.length; + const nextValue = `${message.substring(0, start)}${text}${message.substring(end)}`; + setMessage(nextValue); + const cursorPosition = start + text.length; + + requestAnimationFrame(() => { + const currentTextarea = textareaRef.current; + if (currentTextarea) { + currentTextarea.selectionStart = cursorPosition; + currentTextarea.selectionEnd = cursorPosition; + } + adjustTextareaHeight(); + }); + + updateAutocompleteState(nextValue, cursorPosition); + }, [adjustTextareaHeight, message, updateAutocompleteState]); + + const handleTextChange = (e: React.ChangeEvent) => { + const value = e.target.value; + const cursorPosition = e.target.selectionStart ?? value.length; + setMessage(value); + adjustTextareaHeight(); + updateAutocompleteState(value, cursorPosition); + }; + + const handlePaste = React.useCallback(async (e: React.ClipboardEvent) => { + const fileMap = new Map(); + + Array.from(e.clipboardData.files || []).forEach(file => { + if (file.type.startsWith('image/')) { + fileMap.set(`${file.name}-${file.size}`, file); + } + }); + + Array.from(e.clipboardData.items || []).forEach(item => { + if (item.kind === 'file' && item.type.startsWith('image/')) { + const file = item.getAsFile(); + if (file) { + fileMap.set(`${file.name}-${file.size}`, file); + } + } + }); + + const imageFiles = Array.from(fileMap.values()); + if (imageFiles.length === 0) { + return; + } + + if (!currentSessionId) { + return; + } + + e.preventDefault(); + + const pastedText = e.clipboardData.getData('text'); + if (pastedText) { + insertTextAtSelection(pastedText); + } + + let attachedCount = 0; + + for (const file of imageFiles) { + const sizeBefore = useSessionStore.getState().attachedFiles.length; + try { + await addAttachedFile(file); + const sizeAfter = useSessionStore.getState().attachedFiles.length; + if (sizeAfter > sizeBefore) { + attachedCount += 1; + } + } catch (error) { + console.error('Clipboard image attach failed', error); + toast.error(error instanceof Error ? error.message : 'Failed to attach image from clipboard'); + } + } + + if (attachedCount > 0) { + toast.success(`Attached ${attachedCount} image${attachedCount > 1 ? 's' : ''} from clipboard`); + } + }, [addAttachedFile, currentSessionId, insertTextAtSelection]); + + const handleFileSelect = (file: { name: string; path: string }) => { + + const cursorPosition = textareaRef.current?.selectionStart || 0; + const textBeforeCursor = message.substring(0, cursorPosition); + const lastAtSymbol = textBeforeCursor.lastIndexOf('@'); + + if (lastAtSymbol !== -1) { + const newMessage = + message.substring(0, lastAtSymbol) + + file.name + + message.substring(cursorPosition); + setMessage(newMessage); + } + + setShowFileMention(false); + setMentionQuery(''); + + textareaRef.current?.focus(); + }; + + const handleAgentSelect = (agentName: string) => { + const textarea = textareaRef.current; + const cursorPosition = textarea?.selectionStart ?? message.length; + const textBeforeCursor = message.substring(0, cursorPosition); + const lastHashSymbol = textBeforeCursor.lastIndexOf('#'); + + if (lastHashSymbol !== -1) { + const newMessage = + message.substring(0, lastHashSymbol) + + `#${agentName} ` + + message.substring(cursorPosition); + setMessage(newMessage); + + const nextCursor = lastHashSymbol + agentName.length + 2; + requestAnimationFrame(() => { + if (textareaRef.current) { + textareaRef.current.selectionStart = nextCursor; + textareaRef.current.selectionEnd = nextCursor; + } + adjustTextareaHeight(); + updateAutocompleteState(newMessage, nextCursor); + }); + } + + setShowAgentAutocomplete(false); + setAgentQuery(''); + + textareaRef.current?.focus(); + }; + + const handleCommandSelect = (command: { name: string; description?: string; agent?: string; model?: string }) => { + + setMessage(`/${command.name} `); + + const textareaElement = textareaRef.current as HTMLTextAreaElement & { _commandMetadata?: typeof command }; + if (textareaElement) { + textareaElement._commandMetadata = command; + } + + setShowCommandAutocomplete(false); + setCommandQuery(''); + + setTimeout(() => { + if (textareaRef.current) { + textareaRef.current.focus(); + textareaRef.current.setSelectionRange(textareaRef.current.value.length, textareaRef.current.value.length); + } + }, 0); + }; + + React.useEffect(() => { + + if (currentSessionId && textareaRef.current && !isMobile) { + textareaRef.current.focus(); + } + }, [currentSessionId, isMobile]); + + React.useEffect(() => { + if (abortPromptSessionId && abortPromptSessionId !== currentSessionId) { + clearAbortPrompt(); + } + }, [abortPromptSessionId, currentSessionId, clearAbortPrompt]); + + const handleDragOver = (e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + if (currentSessionId && !isDragging) { + setIsDragging(true); + } + }; + + const handleDragLeave = (e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + if (e.currentTarget === e.target) { + setIsDragging(false); + } + }; + + const handleDrop = async (e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + setIsDragging(false); + + if (!currentSessionId) return; + + const files = Array.from(e.dataTransfer.files); + let attachedCount = 0; + + for (const file of files) { + const sizeBefore = useSessionStore.getState().attachedFiles.length; + try { + await addAttachedFile(file); + const sizeAfter = useSessionStore.getState().attachedFiles.length; + if (sizeAfter > sizeBefore) { + attachedCount += 1; + } + } catch (error) { + console.error('File attach failed', error); + toast.error(error instanceof Error ? error.message : 'Failed to attach file'); + } + } + + if (attachedCount > 0) { + toast.success(`Attached ${attachedCount} file${attachedCount > 1 ? 's' : ''}`); + } + }; + + const handleServerFilesSelected = React.useCallback(async (files: Array<{ path: string; name: string }>) => { + let attachedCount = 0; + + for (const file of files) { + const sizeBefore = useSessionStore.getState().attachedFiles.length; + try { + await addServerFile(file.path, file.name); + const sizeAfter = useSessionStore.getState().attachedFiles.length; + if (sizeAfter > sizeBefore) { + attachedCount += 1; + } + } catch (error) { + console.error('Server file attach failed', error); + toast.error(error instanceof Error ? error.message : 'Failed to attach file'); + } + } + + if (attachedCount > 0) { + toast.success(`Attached ${attachedCount} file${attachedCount > 1 ? 's' : ''}`); + } + }, [addServerFile]); + + const footerGapClass = 'gap-x-1.5 gap-y-0'; + const footerPaddingClass = isMobile ? 'px-1.5 py-1.5' : 'px-2.5 py-1.5'; + const footerHeightClass = isMobile ? 'h-9 w-9' : 'h-7 w-7'; + const iconSizeClass = isMobile ? 'h-5 w-5' : 'h-[18px] w-[18px]'; + + const iconButtonBaseClass = cn( + footerHeightClass, + 'flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0' + ); + + const actionButton = ( + + ); + + const projectFileButton = ( + + + + ); + + const settingsButton = onOpenSettings ? ( + + ) : null; + + const attachmentsControls = ( + <> + + {projectFileButton} + {settingsButton} + + ); + + const workingStatusText = working.statusText; + + React.useEffect(() => { + const pendingAbortBanner = Boolean(working.wasAborted); + if (!prevWasAbortedRef.current && pendingAbortBanner && !showAbortStatus) { + startAbortIndicator(); + if (currentSessionId) { + acknowledgeSessionAbort(currentSessionId); + } + } + prevWasAbortedRef.current = pendingAbortBanner; + }, [ + acknowledgeSessionAbort, + currentSessionId, + showAbortStatus, + startAbortIndicator, + working.wasAborted, + ]); + + React.useEffect(() => { + return () => { + if (abortTimeoutRef.current) { + clearTimeout(abortTimeoutRef.current); + abortTimeoutRef.current = null; + } + }; + }, []); + + const shouldRenderPlaceholder = !showAbortStatus && (working.wasAborted || !working.abortActive); + + return ( + +
+
+
+ {showAbortStatus ? ( +
+ + +
+ ) : shouldRenderPlaceholder ? ( + + ) : null} +
+ + {canShowAbortButton ? ( +
+ {isMobile ? ( + + ) : ( + + )} +
+ ) : null} +
+
+ {isDragging && ( +
+
+ +

Drop files here to attach

+
+
+ )} + +
+ {} + {showCommandAutocomplete && ( + setShowCommandAutocomplete(false)} + /> + )} + {} + {showAgentAutocomplete && ( + setShowAgentAutocomplete(false)} + /> + )} + {} + {showFileMention && ( + setShowFileMention(false)} + /> + )} +