This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-18 14:52:00 +02:00
1 parent aa071d173e
commit e11a140768
39 files changed
+11539

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
+24
View File
@@ -0,0 +1,24 @@
## Description
<!-- Describe your changes in detail. What problem does this solve? -->
## Related Issues
<!-- Link any related issues: Fixes #123, Closes #456 -->
---
## Contributor License Agreement
<!--
🚨 DO NOT DELETE THE TEXT BELOW 🚨
Keep the "Contributor License Agreement" confirmation text intact.
Deleting it will trigger the CLA-Bot to INVALIDATE your PR.
Your PR will NOT be reviewed or merged until you check the box below confirming that you have read and agree to the terms of the CLA.
-->
- [ ] By submitting this pull request, I confirm that I have read and fully agree to the [Contributor License Agreement (CLA)](https://github.com/open-webui/computer-desktop/blob/main/CONTRIBUTOR_LICENSE_AGREEMENT), and I am providing my contributions under its terms.
> [!NOTE]
> Deleting the CLA section will lead to immediate closure of your PR and it will not be merged in.
+385
View File
@@ -0,0 +1,385 @@
name: Build and Release Electron App (electron-builder)
on:
push:
branches:
- release
jobs:
compile:
name: Compile (Typecheck + Vite Build)
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Typecheck and Build
run: npm run build
- name: Upload Compiled Output
uses: actions/upload-artifact@v4
with:
name: compiled-output
path: out/
retention-days: 1
package:
name: Package (${{ matrix.os }}-${{ matrix.arch }})
needs: compile
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
arch: x64
- os: ubuntu-24.04-arm
arch: arm64
- os: windows-latest
arch: x64
- os: windows-11-arm
arch: arm64
- os: macos-latest
arch: x64
- os: macos-latest
arch: arm64
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Download Compiled Output
uses: actions/download-artifact@v4
with:
name: compiled-output
path: out/
# ── Apple codesigning (macOS only) ──
- name: Install Apple codesigning certificate
id: apple_cert
if: matrix.os == 'macos-latest'
continue-on-error: true
env:
BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }}
P12_PASSWORD: ${{ secrets.P12_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: |
if [ -z "$BUILD_CERTIFICATE_BASE64" ]; then
echo "No certificate provided, will build unsigned"
exit 1
fi
CERTIFICATE_PATH=$RUNNER_TEMP/build_certificate.p12
KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db
echo -n "$BUILD_CERTIFICATE_BASE64" | base64 --decode > $CERTIFICATE_PATH
security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
security set-keychain-settings -lut 21600 $KEYCHAIN_PATH
security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
security import $CERTIFICATE_PATH -P "$P12_PASSWORD" -A -t cert -f pkcs12 -k $KEYCHAIN_PATH
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
security list-keychain -d user -s $KEYCHAIN_PATH
# ── Platform packaging ──
- name: Package for Windows
id: win_build
if: runner.os == 'Windows'
continue-on-error: true
run: npx electron-builder --win --${{ matrix.arch }} --publish never
- name: Package for Windows (unsigned fallback)
if: runner.os == 'Windows' && steps.win_build.outcome == 'failure'
env:
WIN_CSC_LINK: ''
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
run: |
rm -rf dist/
npx electron-builder --win --${{ matrix.arch }} --publish never
- name: Package for macOS (signed + notarized)
id: mac_build
if: matrix.os == 'macos-latest' && steps.apple_cert.outcome == 'success'
continue-on-error: true
env:
CSC_LINK: ${{ secrets.BUILD_CERTIFICATE_BASE64 }}
CSC_KEY_PASSWORD: ${{ secrets.P12_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: npx electron-builder --mac --${{ matrix.arch }} -c.mac.notarize=true --publish never
- name: Package for macOS (unsigned fallback)
if: matrix.os == 'macos-latest' && (steps.apple_cert.outcome != 'success' || steps.mac_build.outcome == 'failure')
env:
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
run: |
rm -rf dist/
npx electron-builder --mac --${{ matrix.arch }} --publish never
- name: Package for Linux
if: runner.os == 'Linux'
run: |
npx electron-builder --linux AppImage deb snap --${{ matrix.arch }} --publish never
# ── Windows code signing ──
- name: Azure Trusted Signing (Windows Only)
if: runner.os == 'Windows'
continue-on-error: true
uses: azure/trusted-signing-action@v0.5.1
with:
azure-tenant-id: ${{ secrets.AZURE_TENANT_ID }}
azure-client-id: ${{ secrets.AZURE_CLIENT_ID }}
azure-client-secret: ${{ secrets.AZURE_CLIENT_SECRET }}
endpoint: https://eus.codesigning.azure.net/
trusted-signing-account-name: open-webui
certificate-profile-name: open-webui
files-folder: dist
files-folder-filter: exe
# ── Upload release artifacts ──
- name: Upload Artifacts
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.os }}-${{ matrix.arch }}
path: |
dist/*.exe
dist/*.dmg
dist/*.zip
dist/*.pkg
dist/*.deb
dist/*.AppImage
dist/*.snap
dist/*.tar.gz
dist/*.blockmap
dist/latest*.yml
if-no-files-found: warn
release:
name: Create GitHub Release
needs: package
if: >-
github.event_name == 'push' &&
github.ref == 'refs/heads/release' &&
!cancelled() &&
needs.package.result != 'failure'
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout Repository
uses: actions/checkout@v4
with:
sparse-checkout: |
package.json
CHANGELOG.md
sparse-checkout-cone-mode: false
- name: Get version from package.json
id: version
run: |
VERSION=$(node -p "require('./package.json').version")
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "Release version: $VERSION"
- name: Extract changelog for this version
id: changelog
run: |
VERSION="${{ steps.version.outputs.version }}"
NOTES=$(awk "/^## \[$VERSION\]/{found=1; next} /^## \[/{if(found) exit} found{print}" CHANGELOG.md)
if [ -z "$NOTES" ]; then
NOTES="Release v$VERSION"
fi
echo "$NOTES" > /tmp/release_notes.md
echo "Changelog notes:"
cat /tmp/release_notes.md
- name: Download Artifacts
uses: actions/download-artifact@v4
with:
pattern: '*-*'
merge-multiple: false
- name: Install js-yaml for manifest merging
run: npm install --no-save js-yaml
- name: Merge macOS latest-mac.yml (x64 + arm64)
run: |
X64_YML="macos-latest-x64/latest-mac.yml"
ARM_YML="macos-latest-arm64/latest-mac.yml"
if [ -f "$X64_YML" ] && [ -f "$ARM_YML" ]; then
echo "Merging latest-mac.yml from both architectures"
node -e "
const fs = require('fs');
const yaml = require('js-yaml');
const x64 = yaml.load(fs.readFileSync('$X64_YML', 'utf8'));
const arm = yaml.load(fs.readFileSync('$ARM_YML', 'utf8'));
const all = [...(x64.files || []), ...(arm.files || [])];
const map = new Map();
for (const f of all) map.set(f.url, f);
x64.files = [...map.values()];
const out = yaml.dump(x64, { lineWidth: -1 });
fs.writeFileSync('$X64_YML', out);
console.log(out);
"
rm -f "$ARM_YML"
else
echo "Skipping merge — need both $X64_YML and $ARM_YML"
ls -la macos-latest-*/latest-mac.yml 2>/dev/null || true
fi
- name: Merge Linux latest-linux.yml (x64 + arm64)
run: |
X64_YML="ubuntu-latest-x64/latest-linux.yml"
ARM_YML="ubuntu-24.04-arm-arm64/latest-linux-arm64.yml"
if [ -f "$X64_YML" ] && [ -f "$ARM_YML" ]; then
echo "Merging latest-linux.yml from both architectures"
node -e "
const fs = require('fs');
const yaml = require('js-yaml');
const x64 = yaml.load(fs.readFileSync('$X64_YML', 'utf8'));
const arm = yaml.load(fs.readFileSync('$ARM_YML', 'utf8'));
const all = [...(x64.files || []), ...(arm.files || [])];
const map = new Map();
for (const f of all) map.set(f.url, f);
x64.files = [...map.values()];
const out = yaml.dump(x64, { lineWidth: -1 });
fs.writeFileSync('$X64_YML', out);
console.log(out);
"
rm -f "$ARM_YML"
else
echo "Skipping merge — need both $X64_YML and $ARM_YML"
ls -la ubuntu-*-*/latest-linux*.yml 2>/dev/null || true
fi
- name: Merge Windows latest.yml (x64 + arm64)
run: |
X64_YML="windows-latest-x64/latest.yml"
ARM_YML="windows-11-arm-arm64/latest.yml"
if [ -f "$X64_YML" ] && [ -f "$ARM_YML" ]; then
echo "Merging latest.yml from both architectures"
node -e "
const fs = require('fs');
const yaml = require('js-yaml');
const x64 = yaml.load(fs.readFileSync('$X64_YML', 'utf8'));
const arm = yaml.load(fs.readFileSync('$ARM_YML', 'utf8'));
const all = [...(x64.files || []), ...(arm.files || [])];
const map = new Map();
for (const f of all) map.set(f.url, f);
x64.files = [...map.values()];
const out = yaml.dump(x64, { lineWidth: -1 });
fs.writeFileSync('$X64_YML', out);
console.log(out);
"
rm -f "$ARM_YML"
else
echo "Skipping merge — need both $X64_YML and $ARM_YML"
ls -la windows-*-*/latest.yml 2>/dev/null || true
fi
- name: Reconcile update manifest hashes
run: |
node -e "
const fs = require('fs');
const crypto = require('crypto');
const yaml = require('js-yaml');
const path = require('path');
const manifests = [
{ prefix: 'macos-latest-', file: 'latest-mac.yml' },
{ prefix: 'ubuntu-', file: 'latest-linux.yml' },
{ prefix: 'windows-', file: 'latest.yml' },
];
const allDirs = fs.readdirSync('.').filter(d => {
try { return fs.statSync(d).isDirectory(); } catch { return false; }
});
for (const { prefix, file } of manifests) {
const dirs = allDirs.filter(d => d.startsWith(prefix));
let ymlPath = null;
for (const dir of dirs) {
const p = path.join(dir, file);
if (fs.existsSync(p)) { ymlPath = p; break; }
}
if (!ymlPath) { console.log('No ' + file + ' found, skipping'); continue; }
const manifest = yaml.load(fs.readFileSync(ymlPath, 'utf8'));
let fixed = 0;
for (const entry of manifest.files) {
for (const dir of dirs) {
const filePath = path.join(dir, entry.url);
if (fs.existsSync(filePath)) {
const buf = fs.readFileSync(filePath);
const hash = crypto.createHash('sha512').update(buf).digest('base64');
if (hash !== entry.sha512) {
console.log('[' + file + '] Fix: ' + entry.url);
entry.sha512 = hash;
entry.size = buf.length;
fixed++;
}
break;
}
}
}
if (manifest.path) {
for (const dir of dirs) {
const filePath = path.join(dir, manifest.path);
if (fs.existsSync(filePath)) {
const buf = fs.readFileSync(filePath);
manifest.sha512 = crypto.createHash('sha512').update(buf).digest('base64');
break;
}
}
}
const out = yaml.dump(manifest, { lineWidth: -1 });
fs.writeFileSync(ymlPath, out);
console.log('[' + file + '] ' + (fixed ? 'Fixed ' + fixed + ' entries' : 'All hashes OK'));
}
"
- name: Create Release
uses: softprops/action-gh-release@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: v${{ steps.version.outputs.version }}
name: v${{ steps.version.outputs.version }}
body_path: /tmp/release_notes.md
draft: false
prerelease: false
files: |
windows-*-*/*.exe
windows-*-*/*.blockmap
windows-*-*/latest*.yml
macos-latest-*/*.dmg
macos-latest-*/*.zip
macos-latest-*/*.pkg
macos-latest-*/*.blockmap
macos-latest-*/latest*.yml
ubuntu-*-*/*.deb
ubuntu-*-*/*.AppImage
ubuntu-*-*/*.snap
ubuntu-*-*/*.tar.gz
ubuntu-*-*/latest*.yml
+9
View File
@@ -0,0 +1,9 @@
_old
.vscode
node_modules
dist
out
.DS_Store
.eslintcache
*.log*
*.tsbuildinfo
+1
View File
@@ -0,0 +1 @@
+6
View File
@@ -0,0 +1,6 @@
out
dist
pnpm-lock.yaml
LICENSE.md
tsconfig.json
tsconfig.*.json
+10
View File
@@ -0,0 +1,10 @@
singleQuote: true
semi: false
printWidth: 100
trailingComma: none
plugins:
- prettier-plugin-svelte
overrides:
- files: '*.svelte'
options:
parser: svelte
+14
View File
@@ -0,0 +1,14 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.0.1] - 2026-06-17
### Added
- Automatic Python and cptr installation with live progress
- Settings, theme sync, auto-update, and factory reset
- Cross-platform support (macOS, Windows, Linux; x64 and ARM64)
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-dyld-environment-variables</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.debugger</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
<key>com.apple.security.files.user-selected.read-only</key>
<true/>
<key>com.apple.security.inherit</key>
<true/>
<key>com.apple.security.automation.apple-events</key>
<true/>
</dict>
</plist>
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

+4
View File
@@ -0,0 +1,4 @@
provider: github
owner: open-webui
repo: computer-desktop
updaterCacheDirName: computer-desktop-updater
+67
View File
@@ -0,0 +1,67 @@
appId: com.openwebui.computer-desktop
productName: Computer
directories:
buildResources: build
files:
- '!**/.vscode/*'
- '!src/*'
- '!electron.vite.config.{js,ts,mjs,cjs}'
- '!svelte.config.mjs'
- '!{.eslintcache,eslint.config.mjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,README.md}'
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}'
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
extraResources:
- from: CHANGELOG.md
to: CHANGELOG.md
asarUnpack:
- resources/**
- node_modules/node-pty/**
win:
executableName: computer
nsis:
artifactName: ${name}-${arch}-setup.${ext}
shortcutName: ${productName}
uninstallDisplayName: ${productName}
createDesktopShortcut: always
mac:
target:
- target: dmg
- target: zip
arch:
- x64
- arm64
artifactName: ${name}-${arch}-mac.${ext}
entitlements: build/entitlements.mac.plist
entitlementsInherit: build/entitlements.mac.plist
extendInfo:
- NSDocumentsFolderUsageDescription: Application requests access to the user's Documents folder.
- NSDownloadsFolderUsageDescription: Application requests access to the user's Downloads folder.
dmg:
artifactName: ${name}-${arch}.${ext}
title: ${productName}
contents:
- x: 225
y: 250
type: file
- x: 400
y: 240
type: link
path: /Applications
linux:
target:
- AppImage
- snap
- deb
maintainer: openwebui.com
category: Utility
deb:
artifactName: ${name}_${arch}.${ext}
snap:
artifactName: ${name}_${arch}.${ext}
appImage:
artifactName: ${name}_${arch}.${ext}
npmRebuild: true
publish:
provider: github
owner: open-webui
repo: computer-desktop
+32
View File
@@ -0,0 +1,32 @@
import { resolve } from 'path'
import { defineConfig } from 'electron-vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import tailwindcss from '@tailwindcss/vite'
if (process.platform === 'linux') {
process.env.ELECTRON_DISABLE_SANDBOX = '1'
}
export default defineConfig({
main: {},
preload: {
build: {
rollupOptions: {
input: {
index: resolve(__dirname, 'src/preload/index.ts'),
'content-preload': resolve(__dirname, 'src/preload/content-preload.ts')
}
}
}
},
renderer: {
build: {
rollupOptions: {
input: {
index: resolve(__dirname, 'src/renderer/index.html')
}
}
},
plugins: [tailwindcss(), svelte()]
}
})
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-dyld-environment-variables</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.debugger</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
<key>com.apple.security.files.user-selected.read-only</key>
<true/>
<key>com.apple.security.inherit</key>
<true/>
<key>com.apple.security.automation.apple-events</key>
<true/>
</dict>
</plist>
+25
View File
@@ -0,0 +1,25 @@
import { defineConfig } from 'eslint/config'
import tseslint from '@electron-toolkit/eslint-config-ts'
import eslintConfigPrettier from '@electron-toolkit/eslint-config-prettier'
import eslintPluginSvelte from 'eslint-plugin-svelte'
export default defineConfig(
{ ignores: ['**/node_modules', '**/dist', '**/out'] },
tseslint.configs.recommended,
eslintPluginSvelte.configs['flat/recommended'],
{
files: ['**/*.svelte'],
languageOptions: {
parserOptions: {
parser: tseslint.parser
}
}
},
{
files: ['**/*.{tsx,svelte}'],
rules: {
'svelte/no-unused-svelte-ignore': 'off'
}
},
eslintConfigPrettier
)
+8592
View File
File diff suppressed because it is too large. Load diff
+54
View File
@@ -0,0 +1,54 @@
{
"name": "computer-desktop",
"version": "0.0.1",
"license": "SEE LICENSE IN LICENSE",
"description": "Computer Desktop",
"main": "./out/main/index.js",
"author": "Open WebUI Inc.",
"homepage": "https://cptr.sh",
"scripts": {
"format": "prettier --plugin prettier-plugin-svelte --write .",
"lint": "eslint --cache .",
"typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false",
"svelte-check": "svelte-check --tsconfig ./tsconfig.json",
"typecheck": "npm run typecheck:node && npm run svelte-check",
"start": "electron-vite preview",
"dev": "electron-vite dev",
"build": "npm run typecheck && electron-vite build",
"postinstall": "electron-builder install-app-deps",
"build:unpack": "npm run build && electron-builder --dir",
"build:win": "npm run build && electron-builder --win",
"build:mac": "npm run build && electron-builder --mac",
"build:linux": "npm run build && electron-builder --linux"
},
"dependencies": {
"@electron-toolkit/preload": "^3.0.2",
"@electron-toolkit/utils": "^4.0.0",
"@tailwindcss/vite": "^4.2.1",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"electron-log": "^5.4.3",
"electron-updater": "^6.3.9",
"node-pty": "^1.1.0",
"tailwindcss": "^4.2.1",
"tar": "^7.5.11"
},
"devDependencies": {
"@electron-toolkit/eslint-config-prettier": "^3.0.0",
"@electron-toolkit/eslint-config-ts": "^3.1.0",
"@electron-toolkit/tsconfig": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^6.2.0",
"@types/node": "^22.19.1",
"electron": "^39.2.6",
"electron-builder": "^26.0.12",
"electron-vite": "^5.0.0",
"eslint": "^9.39.1",
"eslint-plugin-svelte": "^3.13.1",
"prettier": "^3.7.4",
"prettier-plugin-svelte": "^3.4.0",
"svelte": "^5.45.6",
"svelte-check": "^4.3.4",
"typescript": "^5.9.3",
"vite": "^7.2.6"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

+630
View File
@@ -0,0 +1,630 @@
// @ts-nocheck
import {
app,
shell,
session,
clipboard,
nativeImage,
BrowserWindow,
globalShortcut,
MessageChannelMain,
Notification,
Menu,
ipcMain,
Tray
} from 'electron'
import path, { join } from 'path'
import { readFile, statfs } from 'fs/promises'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import {
getLogFilePath,
checkUrlAndOpen,
clearAllServerLogs,
getConfig,
getUserDataPath,
getInstallDir,
getServerLog,
getServerPIDs,
getServerPty,
installPackage,
installPython,
isPackageInstalled,
isPythonInstalled,
getPackageVersion,
uninstallPackage,
isUvInstalled,
openUrl,
resetApp,
setConfig,
startServer,
stopAllServers,
uninstallPython,
type AppConfig
} from './utils'
import { initUpdater, checkForUpdates, downloadUpdate, installUpdate } from './updater'
import log from 'electron-log'
log.transports.file.resolvePathFn = () => getLogFilePath('main')
import icon from '../../resources/icon.png?asset'
import { existsSync, writeFileSync, unlinkSync } from 'fs'
if (process.platform === 'linux') {
app.commandLine.appendSwitch('no-sandbox')
app.commandLine.appendSwitch('disable-dev-shm-usage')
app.commandLine.appendSwitch('ozone-platform-hint', 'auto')
app.commandLine.appendSwitch('use-gl', 'angle')
app.commandLine.appendSwitch('use-angle', 'swiftshader')
app.commandLine.appendSwitch('disable-gpu-sandbox')
}
// ─── GPU Crash Recovery ─────────────────────────────────
const gpuCrashMarkerPath = join(app.getPath('userData'), '.gpu-sandbox-disabled')
const gpuSandboxDisabled = existsSync(gpuCrashMarkerPath)
if (gpuSandboxDisabled) {
app.commandLine.appendSwitch('disable-gpu-sandbox')
}
app.disableDomainBlockingFor3DAPIs()
// ─── State ──────────────────────────────────────────────
let mainWindow: BrowserWindow | null = null
let tray: Tray | null = null
let isQuiting = false
let CONFIG: AppConfig | null = null
let SERVER_URL: string | null = null
let SERVER_STATUS: string | null = null
let SERVER_REACHABLE = false
let SERVER_PID: number | null = null
// ─── Windows ────────────────────────────────────────────
const DEFAULT_WINDOW_WIDTH = 1280
const DEFAULT_WINDOW_HEIGHT = 800
const MIN_WINDOW_WIDTH = 480
const MIN_WINDOW_HEIGHT = 360
const BOUNDS_SAVE_DEBOUNCE_MS = 500
const MIN_VISIBLE_OVERLAP_PX = 100
let lastNormalBounds: Electron.Rectangle | null = null
let boundsDebounceTimer: ReturnType<typeof setTimeout> | null = null
function debounceSaveWindowBounds(win: BrowserWindow): void {
if (boundsDebounceTimer) clearTimeout(boundsDebounceTimer)
boundsDebounceTimer = setTimeout(() => {
if (win.isDestroyed()) return
const maximized = win.isMaximized()
const bounds = maximized ? (lastNormalBounds ?? win.getNormalBounds()) : win.getBounds()
setConfig({ windowBounds: bounds, windowMaximized: maximized }).catch((err) =>
log.warn('Failed to save window bounds:', err)
)
}, BOUNDS_SAVE_DEBOUNCE_MS)
}
function isBoundsOnVisibleDisplay(bounds: { x: number; y: number }): boolean {
const { screen } = require('electron')
const targetPoint = { x: bounds.x + MIN_VISIBLE_OVERLAP_PX / 2, y: bounds.y + MIN_VISIBLE_OVERLAP_PX / 2 }
const display = screen.getDisplayNearestPoint(targetPoint)
const { x, y, width, height } = display.workArea
return (
bounds.x + MIN_VISIBLE_OVERLAP_PX > x &&
bounds.x < x + width &&
bounds.y + MIN_VISIBLE_OVERLAP_PX > y &&
bounds.y < y + height
)
}
function createMainWindow(show = true): void {
const saved = CONFIG?.windowBounds
const windowOpts: Electron.BrowserWindowConstructorOptions = {
width: saved?.width ?? DEFAULT_WINDOW_WIDTH,
height: saved?.height ?? DEFAULT_WINDOW_HEIGHT,
minWidth: MIN_WINDOW_WIDTH,
minHeight: MIN_WINDOW_HEIGHT,
icon: path.join(__dirname, 'assets/icon.png'),
show: false,
titleBarStyle: process.platform === 'win32' ? 'default' : 'hidden',
trafficLightPosition: { x: 10, y: 10 },
autoHideMenuBar: true,
vibrancy: 'under-window',
visualEffectState: 'active',
backgroundColor: '#00000000',
...(process.platform === 'win32' ? { frame: true } : {}),
...(process.platform === 'linux' ? { icon } : {}),
...(process.platform !== 'darwin' ? { titleBarOverlay: true } : {}),
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false,
webviewTag: true
}
}
if (saved?.x != null && saved?.y != null && isBoundsOnVisibleDisplay(saved)) {
windowOpts.x = saved.x
windowOpts.y = saved.y
}
mainWindow = new BrowserWindow(windowOpts)
mainWindow.setIcon(icon)
if (CONFIG?.windowMaximized) {
mainWindow.maximize()
}
if (!app.isPackaged) {
mainWindow.webContents.openDevTools()
}
if (show) {
mainWindow.on('ready-to-show', () => {
mainWindow?.show()
})
}
mainWindow.webContents.setWindowOpenHandler((details) => {
openUrl(details.url)
return { action: 'deny' }
})
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
} else {
mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
}
// Persist window bounds
const onBoundsChanged = (): void => {
if (!mainWindow || mainWindow.isDestroyed()) return
if (!mainWindow.isMaximized()) lastNormalBounds = mainWindow.getBounds()
debounceSaveWindowBounds(mainWindow)
}
mainWindow.on('resize', onBoundsChanged)
mainWindow.on('move', onBoundsChanged)
mainWindow.on('maximize', onBoundsChanged)
mainWindow.on('unmaximize', onBoundsChanged)
mainWindow.on('close', (event) => {
if (!isQuiting) {
if (CONFIG?.runInBackground === false) {
isQuiting = true
app.quit()
} else {
event.preventDefault()
mainWindow?.hide()
}
}
})
}
// ─── Tray ───────────────────────────────────────────────
const updateTray = () => {
if (!tray) return
const trayMenuTemplate = [
{
label: 'Show Computer',
click: () => {
mainWindow?.show()
mainWindow?.focus()
}
},
{ type: 'separator' },
...(SERVER_STATUS === 'started' && SERVER_URL
? [{
label: `Server: ${SERVER_URL}`,
click: () => { if (SERVER_URL) clipboard.writeText(SERVER_URL) }
}, { type: 'separator' }]
: []),
{
label: 'Quit Computer',
accelerator: 'CommandOrControl+Q',
click: async () => {
await stopServerHandler()
isQuiting = true
app.quit()
}
}
]
tray?.setContextMenu(Menu.buildFromTemplate(trayMenuTemplate))
}
// ─── Server Lifecycle ───────────────────────────────────
let activePtyDataDisposable: { dispose: () => void } | null = null
const startServerHandler = async (): Promise<boolean> => {
if (SERVER_STATUS === 'starting' || SERVER_STATUS === 'started') return true
await stopServerHandler()
SERVER_STATUS = 'starting'
sendToRenderer('status:server', SERVER_STATUS)
try {
CONFIG = await getConfig()
// Auto-update cptr before starting
const autoUpdate = CONFIG?.localServer?.autoUpdate !== false
if (autoUpdate && isPackageInstalled('cptr')) {
try {
log.info('[server] Auto-updating cptr package…')
sendToRenderer('status:install', 'Updating cptr…')
await installPackage('cptr', undefined, (status: string) => {
sendToRenderer('status:install', status)
})
sendToRenderer('status:install', '')
} catch (e) {
log.warn('[server] Auto-update failed, starting existing version:', e)
sendToRenderer('status:install', '')
}
}
const { url, pid } = await startServer(
CONFIG?.localServer?.serveOnLocalNetwork ?? false,
CONFIG?.localServer?.port ?? null
)
SERVER_URL = url
SERVER_PID = pid
SERVER_STATUS = 'started'
sendToRenderer('status:server', SERVER_STATUS)
connectPtyPort(pid)
updateTray()
checkUrlAndOpen(SERVER_URL, async () => {
SERVER_REACHABLE = true
sendToRenderer('server:ready', { url: SERVER_URL })
updateTray()
})
return true
} catch (error) {
log.error('Failed to start server:', error)
SERVER_STATUS = 'failed'
sendToRenderer('status:server', SERVER_STATUS)
sendToRenderer('error', { message: `Failed to start server: ${error?.message}` })
updateTray()
return false
}
}
const activePtyDisposables: Map<number, { dispose: () => void }> = new Map()
const connectPtyPort = (pid?: number): void => {
const targetPid = pid ?? SERVER_PID
if (!mainWindow) return
const { port1, port2 } = new MessageChannelMain()
if (!targetPid) {
port1.postMessage({ type: 'output', data: '[No active server process]\r\n' })
mainWindow.webContents.postMessage('pty:port', { pid: 0 }, [port2])
return
}
activePtyDisposables.get(targetPid)?.dispose()
activePtyDisposables.delete(targetPid)
const ptyProcess = getServerPty(targetPid)
const buffer = getServerLog(targetPid)
if (buffer?.length) {
for (const chunk of buffer) {
port1.postMessage({ type: 'output', data: chunk })
}
}
if (ptyProcess) {
const disposable = ptyProcess.onData((data: string) => {
port1.postMessage({ type: 'output', data })
})
activePtyDisposables.set(targetPid, disposable)
port1.on('message', (event) => {
const msg = event.data
if (msg.type === 'input') ptyProcess.write(msg.data)
else if (msg.type === 'resize') ptyProcess.resize(msg.cols, msg.rows)
})
port1.start()
}
mainWindow.webContents.postMessage('pty:port', { pid: targetPid }, [port2])
}
const stopServerHandler = async (): Promise<boolean> => {
try {
await stopAllServers()
if (SERVER_STATUS) SERVER_STATUS = 'stopped'
SERVER_REACHABLE = false
SERVER_URL = null
sendToRenderer('status:server', SERVER_STATUS)
updateTray()
return true
} catch (error) {
log.error('Failed to stop server:', error)
return false
}
}
const resetAppHandler = async () => {
try {
await stopServerHandler()
SERVER_STATUS = null
await new Promise((resolve) => setTimeout(resolve, 1000))
await resetApp()
CONFIG = await getConfig()
new Notification({ title: 'Computer', body: 'Application has been reset.' }).show()
} catch (error) {
log.error('Failed to reset:', error)
}
}
// ─── Helpers ────────────────────────────────────────────
const sendToRenderer = (type: string, data?: any) => {
mainWindow?.webContents.send('main:data', { type, data })
}
// ─── App Lifecycle ──────────────────────────────────────
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
app.quit()
} else {
app.on('second-instance', () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore()
mainWindow.show()
mainWindow.focus()
}
})
app.setAboutPanelOptions({
applicationName: 'Computer',
iconPath: icon,
applicationVersion: app.getVersion(),
version: app.getVersion(),
website: 'https://cptr.sh',
copyright: `© ${new Date().getFullYear()} Open WebUI`
})
app.whenReady().then(async () => {
CONFIG = await getConfig()
log.info('Config:', CONFIG)
app.name = 'Computer'
if (process.platform === 'darwin' && app.dock) {
app.dock.setIcon(icon)
}
electronApp.setAppUserModelId('com.openwebui.computer-desktop')
// GPU crash recovery
app.on('child-process-gone', (_event, details) => {
if (details.type === 'GPU' && (details.reason === 'crashed' || details.reason === 'launch-failed' || details.reason === 'abnormal-exit')) {
if (!gpuSandboxDisabled) {
try { writeFileSync(gpuCrashMarkerPath, new Date().toISOString(), 'utf-8') } catch {}
app.relaunch({ args: [...process.argv.slice(1), '--disable-gpu-sandbox'] })
app.exit(0)
}
}
})
// Trust self-signed certs
app.on('certificate-error', (event, _webContents, _url, _error, _certificate, callback) => {
event.preventDefault()
callback(true)
})
session.defaultSession.setCertificateVerifyProc((_request, callback) => { callback(0) })
app.on('session-created', (newSession) => {
newSession.setCertificateVerifyProc((_request, callback) => { callback(0) })
newSession.setPermissionRequestHandler((_webContents, permission, callback) => {
callback(['media', 'notifications', 'clipboard-read', 'clipboard-sanitized-write'].includes(permission))
})
})
app.on('browser-window-created', (_, window) => {
optimizer.watchWindowShortcuts(window)
window.webContents.on('render-process-gone', (_event, details) => {
if (details.reason !== 'clean-exit') window.webContents.reload()
})
})
// Webview external link handling
app.on('web-contents-created', (_event, contents) => {
if (contents.getType() === 'webview') {
contents.setWindowOpenHandler(({ url }) => {
openUrl(url)
return { action: 'deny' }
})
contents.on('will-navigate', (event, url) => {
try {
const currentOrigin = new URL(contents.getURL()).origin
const targetOrigin = new URL(url).origin
if (targetOrigin !== currentOrigin) {
event.preventDefault()
openUrl(url)
}
} catch {}
})
}
})
// ─── IPC Handlers ─────────────────────────────────
ipcMain.handle('get:version', () => app.getVersion())
ipcMain.handle('app:info', () => ({
version: app.getVersion(),
platform: process.platform,
arch: process.arch
}))
ipcMain.handle('app:contentPreloadPath', () => {
return `file://${join(__dirname, '../preload/content-preload.js')}`
})
ipcMain.handle('app:defaultDataPath', () => join(getUserDataPath(), 'data'))
ipcMain.handle('app:installDir', () => getInstallDir())
ipcMain.handle('system:diskSpace', async () => {
try {
const stats = await statfs(getUserDataPath())
return { free: stats.bavail * stats.bsize }
} catch { return { free: -1 } }
})
ipcMain.handle('get:config', () => getConfig())
ipcMain.handle('set:config', async (_event, config) => {
await setConfig(config)
CONFIG = await getConfig()
updateTray()
})
// Python/uv
ipcMain.handle('install:python', async () => {
try {
sendToRenderer('status:install', 'Downloading Python…')
const res = await installPython(undefined, (status: string) => {
sendToRenderer('status:install', status)
})
sendToRenderer('status:python', res)
return res
} catch (error) {
sendToRenderer('status:python', false)
sendToRenderer('error', { message: error?.message ?? 'Python installation failed.' })
return false
}
})
ipcMain.handle('status:python', async () => {
return (await isPythonInstalled()) && (await isUvInstalled())
})
// Package
ipcMain.handle('install:package', async () => {
try {
sendToRenderer('status:install', 'Installing cptr…')
await installPackage('cptr', undefined, (status: string) => {
sendToRenderer('status:install', status)
})
sendToRenderer('status:package', true)
updateTray()
return true
} catch (error) {
sendToRenderer('status:package', false)
sendToRenderer('error', { message: error?.message ?? 'Package installation failed.' })
return false
}
})
ipcMain.handle('status:package', async () => isPackageInstalled('cptr'))
// Server
ipcMain.handle('server:start', () => startServerHandler())
ipcMain.handle('server:stop', () => stopServerHandler())
ipcMain.handle('server:restart', async () => {
await stopServerHandler()
return startServerHandler()
})
ipcMain.handle('server:logs', () => (SERVER_PID ? getServerLog(SERVER_PID) : []))
ipcMain.handle('server:logs:clear', () => clearAllServerLogs())
ipcMain.handle('server:info', () => ({
url: SERVER_URL,
status: SERVER_STATUS,
pid: SERVER_PID,
reachable: SERVER_REACHABLE
}))
// PTY
ipcMain.handle('pty:list', () => getServerPIDs())
ipcMain.handle('pty:connect', (_event, pid?: number) => connectPtyPort(pid))
// Updater
ipcMain.handle('updater:check', () => checkForUpdates())
ipcMain.handle('updater:download', () => downloadUpdate())
ipcMain.handle('updater:install', () => installUpdate())
// Changelog
ipcMain.handle('app:changelog', async () => {
try {
const changelogPath = app.isPackaged
? join(process.resourcesPath, 'CHANGELOG.md')
: join(app.getAppPath(), 'CHANGELOG.md')
return await readFile(changelogPath, 'utf-8')
} catch { return null }
})
// Misc
ipcMain.handle('app:reset', () => resetAppHandler())
ipcMain.handle('package:version', (_event, packageName: string) => getPackageVersion(packageName))
ipcMain.handle('package:uninstall', async (_event, packageName: string) => {
const result = uninstallPackage(packageName)
updateTray()
return result
})
ipcMain.handle('open:browser', async (_event, { url }) => {
if (url) await openUrl(url)
})
ipcMain.handle('open:path', async (_event, folderPath: string) => {
if (folderPath) await shell.openPath(folderPath)
})
ipcMain.handle('notification', async (_event, { title, body }) => {
new Notification({ title, body }).show()
})
ipcMain.handle('app:launchAtLogin:get', () => {
return app.getLoginItemSettings().openAtLogin
})
ipcMain.handle('app:launchAtLogin:set', (_event, enabled: boolean) => {
app.setLoginItemSettings({ openAtLogin: enabled })
})
// ─── Startup ──────────────────────────────────────
const trayIcon = nativeImage.createFromPath(icon)
tray = new Tray(trayIcon.resize({ width: 16, height: 16 }))
tray.setToolTip('Computer')
updateTray()
// Global shortcut — bring to front
if (CONFIG.globalShortcut) {
try {
globalShortcut.register(CONFIG.globalShortcut, () => {
if (mainWindow) { mainWindow.show(); mainWindow.focus() }
else createMainWindow()
})
} catch {}
}
createMainWindow()
if (mainWindow) {
initUpdater(mainWindow)
}
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createMainWindow()
else { mainWindow?.show(); mainWindow?.focus() }
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
app.on('before-quit', async () => {
isQuiting = true
await stopServerHandler()
globalShortcut.unregisterAll()
mainWindow = null
tray?.destroy()
tray = null
})
}
+51
View File
@@ -0,0 +1,51 @@
import { autoUpdater, type UpdateInfo } from 'electron-updater'
import log from 'electron-log'
import { app, BrowserWindow } from 'electron'
let mainWin: BrowserWindow | null = null
const send = (type: string, data?: any): void => {
mainWin?.webContents.send('main:data', { type, data })
}
export function initUpdater(window: BrowserWindow): void {
mainWin = window
autoUpdater.logger = log
autoUpdater.autoDownload = false
autoUpdater.autoInstallOnAppQuit = true
autoUpdater.on('update-available', (info: UpdateInfo) => {
send('update:available', { version: info.version })
})
autoUpdater.on('update-downloaded', () => {
send('update:downloaded')
})
autoUpdater.on('error', (error: Error) => {
send('update:error', { message: error?.message ?? 'Update error' })
})
if (app.isPackaged) {
autoUpdater.checkForUpdates().catch((err) => {
log.warn('Auto update check failed:', err)
})
}
}
export async function checkForUpdates(): Promise<void> {
if (!app.isPackaged) {
send('update:not-available')
return
}
await autoUpdater.checkForUpdates()
}
export async function downloadUpdate(): Promise<void> {
await autoUpdater.downloadUpdate()
}
export function installUpdate(): void {
autoUpdater.quitAndInstall(false, true)
}
+741
View File
@@ -0,0 +1,741 @@
// @ts-nocheck
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import net from 'net'
import * as tar from 'tar'
import { app, shell, Notification, net as electronNet } from 'electron'
import { execFileSync, execFile, execSync } from 'child_process'
import log from 'electron-log'
log.transports.file.resolvePathFn = () => getLogFilePath('main')
const serverLogger = log.create({ logId: 'server' })
serverLogger.transports.file.resolvePath = () => getLogFilePath('server')
// ─── Paths ──────────────────────────────────────────────
export const getLogFilePath = (name: string = 'main'): string => {
const logDir = path.join(getUserDataPath(), 'logs')
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true })
}
return path.join(logDir, `${name}.log`)
}
export const getAppPath = (): string => {
let appPath = app.getAppPath()
if (app.isPackaged) {
appPath = path.dirname(appPath)
}
return path.normalize(appPath)
}
export const getUserHomePath = (): string => {
return path.normalize(app.getPath('home'))
}
export const getUserDataPath = (): string => {
const userDataDir = app.getPath('userData')
if (!fs.existsSync(userDataDir)) {
try {
fs.mkdirSync(userDataDir, { recursive: true })
} catch (error) {
log.error(error)
}
}
return path.normalize(userDataDir)
}
export const getInstallDir = (): string => {
const configPath = path.join(getUserDataPath(), 'config.json')
let customDir = ''
try {
if (fs.existsSync(configPath)) {
const data = JSON.parse(fs.readFileSync(configPath, 'utf8'))
customDir = data.installDir || ''
}
} catch {}
const installDir = customDir || getUserDataPath()
if (!fs.existsSync(installDir)) {
try {
fs.mkdirSync(installDir, { recursive: true })
} catch (error) {
log.error(error)
}
}
return path.normalize(installDir)
}
export const openUrl = (url: string) => {
if (!url) {
throw new Error('No URL provided to open in browser.')
}
log.info('Opening URL in browser:', url)
if (url.startsWith('http://0.0.0.0')) {
url = url.replace('http://0.0.0.0', 'http://localhost')
}
shell.openExternal(url)
}
// ─── Port Utils ─────────────────────────────────────────
export const portInUse = async (port: number, host: string = '127.0.0.1'): Promise<boolean> => {
return new Promise((resolve) => {
const server = net.createServer()
server.once('error', (err: NodeJS.ErrnoException) => {
// EADDRINUSE means the port is taken
resolve(err.code === 'EADDRINUSE')
})
server.once('listening', () => {
server.close(() => resolve(false))
})
server.listen(port, host)
})
}
// ─── Python Download & Install ──────────────────────────
const getPlatformString = () => {
const platformMap = {
darwin: 'apple-darwin',
win32: 'pc-windows-msvc',
linux: 'unknown-linux-gnu'
}
return platformMap[os.platform()] || 'unknown-linux-gnu'
}
const getArchString = () => {
const archMap = {
x64: 'x86_64',
arm64: 'aarch64',
ia32: 'i686'
}
return archMap[os.arch()] || 'x86_64'
}
const generateDownloadUrl = () => {
const baseUrl = 'https://github.com/astral-sh/python-build-standalone/releases/download'
const releaseDate = '20260310'
const pythonVersion = '3.12.13'
const archString = getArchString()
const platformString = getPlatformString()
const filename = `cpython-${pythonVersion}+${releaseDate}-${archString}-${platformString}-install_only.tar.gz`
return `${baseUrl}/${releaseDate}/${filename}`
}
export const downloadFileWithProgress = async (url, downloadPath, onProgress) => {
try {
const response = await fetch(url)
if (!response || !response.ok) {
throw new Error(`HTTP error! status: ${response?.status}`)
}
const totalSize = parseInt(response.headers.get('content-length'), 10)
let downloadedSize = 0
const reader = response.body.getReader()
const chunks = []
while (true) {
const { done, value } = await reader.read()
if (done) break
chunks.push(value)
downloadedSize += value.length
if (onProgress && totalSize) {
onProgress((downloadedSize / totalSize) * 100, downloadedSize, totalSize)
}
}
const buffer = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)))
fs.writeFileSync(downloadPath, buffer)
log.info('File downloaded successfully:', downloadPath)
return downloadPath
} catch (error) {
try {
if (fs.existsSync(downloadPath)) {
fs.unlinkSync(downloadPath)
}
} catch {}
log.error('Download failed:', error)
throw error
}
}
export const getPythonDownloadPath = (): string => {
return path.join(getUserDataPath(), 'python.tar.gz')
}
export const getPythonInstallationDir = (): string => {
const pythonDir = path.join(getInstallDir(), 'python')
if (!fs.existsSync(pythonDir)) {
try {
fs.mkdirSync(pythonDir, { recursive: true })
} catch (error) {
log.error(error)
}
}
return path.normalize(pythonDir)
}
const downloadPython = async (onProgress = null) => {
const url = generateDownloadUrl()
const downloadPath = getPythonDownloadPath()
log.info(`Detected system: ${os.platform()} ${os.arch()}`)
log.info(`Download path: ${downloadPath}`)
log.info(`URL: ${url}`)
if (fs.existsSync(downloadPath)) {
log.info(`File already exists: ${downloadPath}`)
return downloadPath
}
try {
const result = await downloadFileWithProgress(url, downloadPath, onProgress)
log.info(`Python downloaded successfully to: ${result}`)
return result
} catch (error) {
log.error(`Download failed: ${error?.message}`)
throw error
}
}
const checkInternet = async () => {
try {
await fetch('https://api.openwebui.com', { method: 'GET' })
return true
} catch {
return false
}
}
export const installPython = async (installationDir?: string, onStatus?: (status: string) => void): Promise<boolean> => {
const pythonDownloadPath = getPythonDownloadPath()
if (!fs.existsSync(pythonDownloadPath)) {
if (!(await checkInternet())) {
throw new Error(
'An active internet connection is required. Please connect to the internet and try again.'
)
}
let lastReportedPct = -1
await downloadPython((progress, downloaded, total) => {
const pct = Math.floor(progress)
if (pct === lastReportedPct) return
lastReportedPct = pct
const mb = (downloaded / 1024 / 1024).toFixed(1)
const totalMb = (total / 1024 / 1024).toFixed(1)
log.info(`Downloading Python: ${pct}% (${mb}/${totalMb} MB)`)
onStatus?.(`Downloading Python… ${pct}% (${mb}/${totalMb} MB)`)
})
}
if (!fs.existsSync(pythonDownloadPath)) {
log.error('Python download not found')
return false
}
installationDir = installationDir || getPythonInstallationDir()
try {
onStatus?.('Extracting Python…')
const installBase = getInstallDir()
await tar.x({ cwd: installBase, file: pythonDownloadPath })
} catch (error) {
log.error(error)
try { fs.unlinkSync(pythonDownloadPath) } catch {}
throw new Error('Failed to extract Python. The download may be corrupted. Please try again.')
}
if (!isPythonInstalled(installationDir)) {
throw new Error('Python was not found after installation. Try restarting the app or freeing disk space.')
}
try {
onStatus?.('Installing uv package manager…')
const pythonPath = getPythonPath(installationDir)
await new Promise<void>((resolve, reject) => {
execFile(
pythonPath,
['-m', 'pip', 'install', 'uv'],
{ encoding: 'utf-8', env: pythonEnv() },
(error) => {
if (error) reject(error)
else resolve()
}
)
})
log.info('Successfully installed uv package')
return true
} catch (error) {
log.error('Failed to install uv:', error)
throw new Error(`Failed to install the uv package manager: ${error?.message || 'unknown error'}`)
}
}
export const getPythonExecutablePath = (envPath: string) => {
if (process.platform === 'win32') {
return path.normalize(path.join(envPath, 'python.exe'))
}
return path.normalize(path.join(envPath, 'bin', 'python'))
}
export const getPythonPath = (installationDir?: string) => {
return path.normalize(getPythonExecutablePath(installationDir || getPythonInstallationDir()))
}
const pythonEnv = (extra: Record<string, string> = {}): Record<string, string> => {
const base: Record<string, string> = { ...process.env }
if (process.platform === 'win32') {
const pythonDir = getPythonInstallationDir()
const currentPath = process.env['PATH'] || process.env['Path'] || ''
base['PATH'] = `${pythonDir};${currentPath}`
base['PYTHONIOENCODING'] = 'utf-8'
}
return { ...base, ...extra }
}
export const isPythonInstalled = (installationDir?: string) => {
const pythonPath = getPythonPath(installationDir)
if (!fs.existsSync(pythonPath)) return false
try {
const pythonVersion = execFileSync(pythonPath, ['--version'], {
encoding: 'utf-8',
env: pythonEnv()
})
log.info('Installed Python Version:', pythonVersion.trim())
return true
} catch {
return false
}
}
export const isUvInstalled = (installationDir?: string) => {
const pythonPath = getPythonPath(installationDir)
try {
const result = execFileSync(pythonPath, ['-m', 'uv', '--version'], {
encoding: 'utf-8',
env: pythonEnv()
})
log.info('Installed uv Version:', result.trim())
return true
} catch {
return false
}
}
export const uninstallPython = (installationDir?: string): boolean => {
installationDir = installationDir || getPythonInstallationDir()
if (!fs.existsSync(installationDir)) return false
try {
fs.rmSync(installationDir, { recursive: true, force: true })
log.info('Python installation removed:', installationDir)
} catch (error) {
log.error('Failed to remove Python installation', error)
return false
}
try {
fs.rmSync(getPythonDownloadPath(), { recursive: true })
} catch (error) {
log.error('Failed to remove Python download', error)
return false
}
return true
}
// ─── Package Management ─────────────────────────────────
export const installPackage = (packageName: string, version?: string, onStatus?: (status: string) => void): Promise<boolean> => {
return new Promise((resolve, reject) => {
if (!isPythonInstalled()) {
return reject(new Error('Python is not installed.'))
}
const pythonPath = getPythonPath()
const commandProcess = execFile(
pythonPath,
['-m', 'uv', 'pip', 'install', ...(version ? [`${packageName}==${version}`] : [packageName, '-U'])],
{ env: pythonEnv() }
)
let lastLine = ''
commandProcess.stdout?.on('data', (data) => {
const line = data.toString().trim()
log.info(line)
if (line) { lastLine = line; onStatus?.(line) }
})
commandProcess.stderr?.on('data', (data) => {
const line = data.toString().trim()
log.info(line)
if (line) { lastLine = line; onStatus?.(line) }
})
commandProcess.on('exit', (code) => {
if (code === 0) resolve(true)
else reject(new Error(lastLine || `Package installation failed (exit code ${code}).`))
})
commandProcess.on('error', (error) => {
reject(new Error(`Failed to run package installer: ${error.message}`))
})
})
}
export const isPackageInstalled = (packageName: string): boolean => {
const pythonPath = getPythonPath()
if (!fs.existsSync(pythonPath)) return false
try {
const info = execFileSync(pythonPath, ['-m', 'uv', 'pip', 'show', packageName], {
encoding: 'utf-8',
env: pythonEnv()
})
return info.includes(`Name: ${packageName}`)
} catch {
return false
}
}
export const getPackageVersion = (packageName: string): string | null => {
const pythonPath = getPythonPath()
if (!fs.existsSync(pythonPath)) return null
try {
const info = execFileSync(pythonPath, ['-m', 'uv', 'pip', 'show', packageName], {
encoding: 'utf-8',
env: pythonEnv()
})
const match = info.match(/^Version:\s*(.+)$/m)
return match ? match[1].trim() : null
} catch {
return null
}
}
export const uninstallPackage = (packageName: string): boolean => {
const pythonPath = getPythonPath()
if (!fs.existsSync(pythonPath)) return false
try {
execFileSync(pythonPath, ['-m', 'uv', 'pip', 'uninstall', packageName], {
encoding: 'utf-8',
env: pythonEnv()
})
return true
} catch (error) {
log.error(`Failed to uninstall ${packageName}:`, error)
return false
}
}
// ─── Server Management ──────────────────────────────────
import * as pty from 'node-pty'
const serverPIDs: Set<number> = new Set()
const serverLogs: Map<number, string[]> = new Map()
let serverPtyProcesses: Map<number, pty.IPty> = new Map()
export const getServerPIDs = (): number[] => Array.from(serverPIDs)
export const getServerPty = (pid: number): pty.IPty | undefined => serverPtyProcesses.get(pid)
export const startServer = async (
expose = false,
port = null
): Promise<{ url: string; pid: number }> => {
await stopAllServers()
const config = await getConfig()
const configEnvVars = config.envVars ?? {}
const host = expose ? '0.0.0.0' : '127.0.0.1'
if (!isPythonInstalled()) throw new Error('Python is not installed')
if (!isPackageInstalled('cptr')) throw new Error('cptr package is not installed')
const pythonPath = getPythonPath()
if (!fs.existsSync(pythonPath)) {
throw new Error(`Python executable not found at: ${pythonPath}`)
}
const commandArgs = ['-m', 'uv', 'run', 'cptr', 'run', '--headless', '--host', host]
// Find available port
let desiredPort = port || 8000
let availablePort = desiredPort
while (await portInUse(availablePort, host)) {
availablePort++
if (availablePort > desiredPort + 100) {
throw new Error('No available ports found')
}
}
commandArgs.push('--port', availablePort.toString())
log.info('Starting cptr server...', pythonPath, commandArgs.join(' '))
let ptyProcess: pty.IPty
try {
ptyProcess = pty.spawn(pythonPath, commandArgs, {
name: 'xterm-256color',
cols: 200,
rows: 50,
env: pythonEnv({
...(configEnvVars ?? {}),
PYTHONUNBUFFERED: '1'
})
})
} catch (error) {
throw new Error(`Failed to spawn PTY with ${pythonPath}: ${error?.message ?? error}`)
}
const pid = ptyProcess.pid
const rawBuffer: string[] = []
serverPIDs.add(pid)
serverLogs.set(pid, rawBuffer)
serverPtyProcesses.set(pid, ptyProcess)
// Parse startup token from PTY output (cptr prints: ➜ http://host:port/?token=<hex>)
let startupToken: string | null = null
ptyProcess.onData((data: string) => {
rawBuffer.push(data)
serverLogger.info(`[PID:${pid}] ${data.replace(/[\r\n]+/g, ' ').trim()}`)
if (!startupToken) {
const tokenMatch = data.match(/[?&]token=([a-f0-9]+)/)
if (tokenMatch) {
startupToken = tokenMatch[1]
log.info(`[server] Captured startup token: ${startupToken.substring(0, 8)}…`)
}
}
})
ptyProcess.onExit(({ exitCode, signal }) => {
const exitMsg = `\r\n[Process exited with code ${exitCode}${signal ? ` signal ${signal}` : ''}]\r\n`
rawBuffer.push(exitMsg)
serverLogger.info(`[PID:${pid}] Exited code=${exitCode} signal=${signal}`)
serverPIDs.delete(pid)
serverPtyProcesses.delete(pid)
})
// Wait briefly for the token to appear in PTY output
for (let i = 0; i < 30 && !startupToken; i++) {
await new Promise((resolve) => setTimeout(resolve, 200))
}
let effectiveHost = host
if (!expose && host === '0.0.0.0') effectiveHost = '127.0.0.1'
const baseUrl = `http://${effectiveHost}:${availablePort}`
const url = startupToken ? `${baseUrl}/?token=${startupToken}` : baseUrl
log.info(`Server started with PID: ${pid}, URL: ${url}`)
return { url, pid }
}
export async function stopAllServers(): Promise<void> {
log.info('Stopping all servers...')
const pidsToStop = Array.from(serverPIDs)
if (pidsToStop.length === 0) return
for (const pid of pidsToStop) {
const ptyProc = serverPtyProcesses.get(pid)
if (ptyProc) {
try { ptyProc.kill() } catch (e) { log.warn(`Failed to kill PTY process ${pid}:`, e) }
} else {
await terminateProcessTree(pid, false)
}
}
await sleep(2000)
for (const pid of pidsToStop) {
if (isProcessRunning(pid)) {
await terminateProcessTree(pid, true)
}
}
for (const pid of pidsToStop) {
if (!isProcessRunning(pid)) {
serverPIDs.delete(pid)
serverLogs.delete(pid)
serverPtyProcesses.delete(pid)
} else {
log.warn(`Process ${pid} may still be running after termination attempts`)
}
}
}
export const clearAllServerLogs = (): void => {
for (const logs of serverLogs.values()) {
logs.length = 0
}
}
async function terminateProcessTree(pid: number, forceKill: boolean = false): Promise<void> {
const maxRetries = 3
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
if (process.platform === 'win32') {
const commands = forceKill
? [`taskkill /PID ${pid} /T /F`]
: [`taskkill /PID ${pid} /T`, `taskkill /PID ${pid} /T /F`]
for (const cmd of commands) {
try { execSync(cmd, { timeout: 5000, stdio: 'ignore' }); await sleep(500) } catch {}
}
} else {
const signals = forceKill ? ['SIGKILL'] : ['SIGTERM', 'SIGKILL']
for (const signal of signals) {
try {
process.kill(-pid, signal)
await sleep(500)
if (isProcessRunning(pid)) { process.kill(pid, signal); await sleep(500) }
} catch {}
}
}
if (!isProcessRunning(pid)) return
} catch (error) {
log.warn(`Attempt ${attempt}/${maxRetries} failed for PID ${pid}:`, error)
}
if (attempt < maxRetries) await sleep(1000)
}
}
function isProcessRunning(pid: number): boolean {
try { process.kill(pid, 0); return true } catch { return false }
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
export function getServerLog(pid: number): string[] {
return serverLogs.get(pid) || []
}
// ─── URL Validation ─────────────────────────────────────
export const checkUrlAndOpen = async (url: string, callback: Function = async () => {}) => {
const maxAttempts = 120
const interval = 1000
let attempts = 0
const checkUrl = async (): Promise<boolean> => {
try {
// Try health endpoint first, fall back to root
const checkEndpoint = `${url}/api/health`
const response = await electronNet.fetch(checkEndpoint, {
method: 'GET',
signal: AbortSignal.timeout(3000)
})
return response.ok
} catch {
try {
const response = await electronNet.fetch(url, {
method: 'GET',
signal: AbortSignal.timeout(3000)
})
return response.ok || response.status === 302 || response.status === 301
} catch {
return false
}
}
}
const pollUrl = async () => {
while (attempts < maxAttempts) {
attempts++
log.info(`[poll] Checking ${url} (attempt ${attempts}/${maxAttempts})…`)
if (await checkUrl()) {
log.info(`[poll] URL ${url} is now available after ${attempts} attempts`)
await callback()
return
}
await new Promise((resolve) => setTimeout(resolve, interval))
}
log.warn(`[poll] URL check timed out after ${maxAttempts} attempts`)
}
pollUrl().catch((error) => {
log.error('Error in URL polling:', error)
})
}
// ─── Config ─────────────────────────────────────────────
export interface AppConfig {
version: number
runInBackground: boolean
globalShortcut: string
installDir: string
dataDir: string
localServer: {
port: number
serveOnLocalNetwork: boolean
autoUpdate: boolean
}
envVars: Record<string, string>
windowBounds: { x: number; y: number; width: number; height: number } | null
windowMaximized: boolean
}
const DEFAULT_CONFIG: AppConfig = {
version: 1,
runInBackground: true,
globalShortcut: 'Alt+CommandOrControl+O',
installDir: '',
dataDir: '',
localServer: {
port: 8000,
serveOnLocalNetwork: false,
autoUpdate: true
},
envVars: {},
windowBounds: null,
windowMaximized: false
}
export const getConfig = async (): Promise<AppConfig> => {
const configPath = path.join(getUserDataPath(), 'config.json')
try {
if (fs.existsSync(configPath)) {
const data = await fs.promises.readFile(configPath, 'utf8')
return { ...DEFAULT_CONFIG, ...JSON.parse(data) }
}
return { ...DEFAULT_CONFIG }
} catch (error) {
log.error('Error reading config, using defaults:', error)
return { ...DEFAULT_CONFIG }
}
}
let configWriteLock: Promise<void> = Promise.resolve()
export const setConfig = async (config: Partial<AppConfig>): Promise<void> => {
const previous = configWriteLock
let resolve: () => void
configWriteLock = new Promise<void>((r) => { resolve = r })
await previous
const configPath = path.join(getUserDataPath(), 'config.json')
const tmpPath = configPath + '.tmp'
try {
const existing = await getConfig()
const merged = { ...existing, ...config }
await fs.promises.writeFile(tmpPath, JSON.stringify(merged, null, 2))
await fs.promises.rename(tmpPath, configPath)
} catch (error) {
log.error('Error writing config:', error)
try { if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath) } catch {}
throw error
} finally {
resolve!()
}
}
export const resetApp = async (): Promise<void> => {
await uninstallPython()
log.info('Uninstalled Python environment')
const configPath = path.join(getUserDataPath(), 'config.json')
if (fs.existsSync(configPath)) {
try { fs.unlinkSync(configPath) } catch (error) { log.error('Failed to remove config file:', error) }
}
try {
const { session } = require('electron')
await session.defaultSession.clearStorageData()
await session.defaultSession.clearCache()
log.info('Cleared Electron session data')
} catch (error) {
log.error('Failed to clear Electron session data:', error)
}
}
+22
View File
@@ -0,0 +1,22 @@
// Content preload — injected into the webview to relay auth tokens and theme
const { ipcRenderer } = require('electron')
window.addEventListener('message', (event) => {
if (event.data?.type === 'auth-token') {
ipcRenderer.sendToHost('auth-token', event.data.token)
}
})
// Watch for theme changes on <html> class (cptr toggles 'dark' class)
window.addEventListener('DOMContentLoaded', () => {
const html = document.documentElement
// Send initial theme
ipcRenderer.sendToHost('theme-change', html.classList.contains('dark') ? 'dark' : 'light')
// Observe class changes
const observer = new MutationObserver(() => {
ipcRenderer.sendToHost('theme-change', html.classList.contains('dark') ? 'dark' : 'light')
})
observer.observe(html, { attributes: true, attributeFilter: ['class'] })
})
+8
View File
@@ -0,0 +1,8 @@
import { ElectronAPI } from '@electron-toolkit/preload'
declare global {
interface Window {
electron: ElectronAPI
api: unknown
}
}
+101
View File
@@ -0,0 +1,101 @@
import { ipcRenderer, contextBridge } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
// ─── PTY MessagePort ────────────────────────────────────
let activePtyPort: MessagePort | null = null
let ptyOutputCallback: ((data: string) => void) | null = null
ipcRenderer.on('pty:port', (event, _data) => {
const [port] = event.ports
if (!port) return
if (activePtyPort) activePtyPort.close()
activePtyPort = port
port.onmessage = (ev: MessageEvent) => {
if (ev.data?.type === 'output' && ptyOutputCallback) ptyOutputCallback(ev.data.data)
}
port.start()
})
const api = {
onData: (callback: (data: any) => void) => {
const handler = (_: any, data: any): void => callback(data)
ipcRenderer.on('main:data', handler)
return () => ipcRenderer.removeListener('main:data', handler)
},
// App
getAppInfo: () => ipcRenderer.invoke('app:info'),
getVersion: () => ipcRenderer.invoke('get:version'),
resetApp: () => ipcRenderer.invoke('app:reset'),
getDefaultDataPath: () => ipcRenderer.invoke('app:defaultDataPath'),
getInstallDir: () => ipcRenderer.invoke('app:installDir'),
getContentPreloadPath: () => ipcRenderer.invoke('app:contentPreloadPath'),
getDiskSpace: () => ipcRenderer.invoke('system:diskSpace'),
getLaunchAtLogin: () => ipcRenderer.invoke('app:launchAtLogin:get'),
setLaunchAtLogin: (enabled: boolean) => ipcRenderer.invoke('app:launchAtLogin:set', enabled),
openInBrowser: (url: string) => ipcRenderer.invoke('open:browser', { url }),
openPath: (folderPath: string) => ipcRenderer.invoke('open:path', folderPath),
// Config
getConfig: () => ipcRenderer.invoke('get:config'),
setConfig: (config: Record<string, any>) => ipcRenderer.invoke('set:config', config),
// Python/uv
installPython: () => ipcRenderer.invoke('install:python'),
getPythonStatus: () => ipcRenderer.invoke('status:python'),
// Package
installPackage: () => ipcRenderer.invoke('install:package'),
getPackageStatus: () => ipcRenderer.invoke('status:package'),
// Server
startServer: () => ipcRenderer.invoke('server:start'),
stopServer: () => ipcRenderer.invoke('server:stop'),
restartServer: () => ipcRenderer.invoke('server:restart'),
getServerInfo: () => ipcRenderer.invoke('server:info'),
getServerLogs: () => ipcRenderer.invoke('server:logs'),
clearServerLogs: () => ipcRenderer.invoke('server:logs:clear'),
// PTY
listPtys: () => ipcRenderer.invoke('pty:list'),
connectPty: (onOutput: (data: string) => void, pid?: number) => {
ptyOutputCallback = onOutput
ipcRenderer.invoke('pty:connect', pid)
},
writePty: (data: string) => {
activePtyPort?.postMessage({ type: 'input', data })
},
resizePty: (cols: number, rows: number) => {
activePtyPort?.postMessage({ type: 'resize', cols, rows })
},
disconnectPty: () => {
ptyOutputCallback = null
if (activePtyPort) { activePtyPort.close(); activePtyPort = null }
},
// Package
getPackageVersion: (packageName: string) => ipcRenderer.invoke('package:version', packageName),
uninstallPackage: (packageName: string) => ipcRenderer.invoke('package:uninstall', packageName),
// Updater
checkForUpdates: () => ipcRenderer.invoke('updater:check'),
downloadUpdate: () => ipcRenderer.invoke('updater:download'),
installUpdate: () => ipcRenderer.invoke('updater:install'),
// Changelog
getChangelog: () => ipcRenderer.invoke('app:changelog')
}
if (process.contextIsolated) {
try {
contextBridge.exposeInMainWorld('electron', electronAPI)
contextBridge.exposeInMainWorld('electronAPI', api)
} catch (error) {
console.error(error)
}
} else {
// @ts-ignore
window.electron = electronAPI
// @ts-ignore
window.electronAPI = api
}
+19
View File
@@ -0,0 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Computer</title>
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self' https://fonts.googleapis.com https://fonts.gstatic.com"
/>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+244
View File
@@ -0,0 +1,244 @@
<script lang="ts">
import { onMount, tick } from 'svelte'
import { appInfo, config, serverInfo, appState } from './lib/stores'
import Settings from './lib/components/Settings.svelte'
import Spinner from './lib/components/Spinner.svelte'
let statusText = $state('')
let errorText = $state('')
let serverUrl = $state('')
let contentPreloadPath = $state('')
let settingsOpen = $state(false)
let logsOpen = $state(false)
let logLines = $state<string[]>([])
let logEl: HTMLElement | undefined = $state()
let ptyConnected = $state(false)
let installing = $state(false)
let webviewEl: HTMLElement | undefined = $state()
function applyTheme(mode: 'dark' | 'light') {
document.documentElement.classList.toggle('dark', mode === 'dark')
}
function appendLog(raw: string) {
// Strip ANSI codes for clean display
const clean = raw.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').replace(/\r\n/g, '\n').replace(/\r/g, '\n')
const lines = clean.split('\n').filter(l => l.trim())
if (lines.length) {
logLines = [...logLines, ...lines].slice(-500)
tick().then(() => {
if (logEl) logEl.scrollTop = logEl.scrollHeight
})
}
}
function connectPty() {
const api = window?.electronAPI
if (!api) return
api.connectPty((data: string) => appendLog(data))
ptyConnected = true
}
onMount(async () => {
const api = window?.electronAPI
if (!api) return
appInfo.set(await api.getAppInfo())
config.set(await api.getConfig())
contentPreloadPath = await api.getContentPreloadPath()
// Set up PTY listener immediately so it's ready when the port arrives
connectPty()
api.onData((data: any) => {
if (data.type === 'status:server') {
serverInfo.update((info) => ({ ...info, status: data.data }))
}
if (data.type === 'server:ready') {
serverUrl = data.data?.url
serverInfo.update((info) => ({ ...info, reachable: true, url: data.data?.url }))
appState.set('ready')
}
if (data.type === 'status:install') {
statusText = data.data || ''
if (data.data) appendLog(data.data)
}
if (data.type === 'error') {
errorText = data.data?.message || ''
if (data.data?.message) appendLog(`Error: ${data.data.message}`)
setTimeout(() => { errorText = '' }, 8000)
}
})
const pythonOk = await api.getPythonStatus()
const packageOk = await api.getPackageStatus()
if (pythonOk && packageOk) {
appState.set('starting')
statusText = 'Starting cptr…'
appendLog('Starting cptr…')
await api.startServer()
} else {
appState.set('setup')
}
setInterval(async () => {
serverInfo.set(await api.getServerInfo())
}, 3000)
})
async function handleGetStarted() {
const api = window?.electronAPI
if (!api) return
appState.set('starting')
installing = true
errorText = ''
logLines = []
try {
statusText = 'Installing Python…'
const pythonOk = await api.installPython()
if (!pythonOk) { appState.set('setup'); installing = false; return }
statusText = 'Installing cptr…'
const packageOk = await api.installPackage()
if (!packageOk) { appState.set('setup'); installing = false; return }
installing = false
statusText = ''
appendLog('Starting cptr…')
await api.startServer()
} catch (err: any) {
errorText = err?.message || 'Setup failed'
installing = false
appState.set('setup')
}
}
</script>
<main class="w-full h-full bg-white dark:bg-black text-gray-900 dark:text-white relative font-sans">
<!-- Title bar drag region -->
<div class="drag-region h-8 shrink-0 flex items-center border-b border-gray-200 dark:border-white/[0.06]">
<div class="flex-1"></div>
<div class="flex items-center gap-2 pr-2.5 no-drag">
{#if $appState === 'ready' || $appState === 'starting'}
<button
class="text-gray-400 dark:text-gray-600 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 bg-transparent border-none no-drag"
aria-label="Logs"
onclick={() => { logsOpen = !logsOpen; if (logsOpen && !ptyConnected) connectPty() }}
>
<svg class="w-[14px] h-[14px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M6.75 7.5l3 2.25-3 2.25m4.5 0h3m-9 8.25h13.5A2.25 2.25 0 0021 18V6a2.25 2.25 0 00-2.25-2.25H5.25A2.25 2.25 0 003 6v12a2.25 2.25 0 002.25 2.25z" />
</svg>
</button>
{/if}
<button
class="text-gray-400 dark:text-gray-600 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 bg-transparent border-none no-drag"
aria-label="Settings"
onclick={() => settingsOpen = true}
>
<svg class="w-[14px] h-[14px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 010 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 010-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28z" />
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
</button>
</div>
</div>
{#if $appState === 'setup'}
<div class="flex flex-col items-center justify-center h-[calc(100dvh-32px)] p-6 animate-in">
<div class="w-full max-w-md">
<h1 class="text-lg tracking-tight mb-1">Computer</h1>
<p class="text-[13px] text-gray-500 dark:text-gray-500 mb-6 leading-relaxed">
Your computer, from anywhere.
</p>
{#if errorText}
<p class="text-[12px] text-red-500 mb-4">{errorText}</p>
{/if}
<button
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 no-drag"
onclick={handleGetStarted}
>
Get Started
</button>
</div>
</div>
{:else if $appState === 'starting'}
{#if logsOpen}
<div class="flex flex-col h-[calc(100dvh-32px)]">
<div bind:this={logEl} class="flex-1 overflow-y-auto p-4 font-mono text-[11px] text-gray-400 dark:text-gray-600 leading-relaxed bg-gray-50 dark:bg-gray-950 scrollbar-hover">
{#each logLines as line}
<div class="whitespace-pre-wrap break-all">{line}</div>
{/each}
{#if logLines.length === 0}
<p class="text-gray-300 dark:text-gray-700">No log output yet.</p>
{/if}
</div>
</div>
{:else}
<div class="flex flex-col items-center justify-center h-[calc(100dvh-32px)] gap-3">
<Spinner size={20} />
{#if installing && statusText}
<p class="text-xs text-gray-400 dark:text-gray-600 max-w-xs truncate text-center">{statusText}</p>
{/if}
</div>
{/if}
{:else if $appState === 'ready' && serverUrl}
{#if logsOpen}
<div class="flex flex-col h-[calc(100dvh-{$appInfo?.platform === 'darwin' ? '32' : '32'}px)]">
<div
bind:this={logEl}
class="flex-1 overflow-y-auto p-4 font-mono text-[11px] text-gray-400 dark:text-gray-600 leading-relaxed bg-gray-50 dark:bg-gray-950 scrollbar-hover"
>
{#each logLines as line}
<div class="whitespace-pre-wrap break-all">{line}</div>
{/each}
{#if logLines.length === 0}
<p class="text-gray-300 dark:text-gray-700">No log output yet.</p>
{/if}
</div>
</div>
{:else}
<div class="h-[calc(100dvh-{$appInfo?.platform === 'darwin' ? '32' : '32'}px)]">
<webview
bind:this={webviewEl}
src={serverUrl}
class="w-full h-full"
preload={contentPreloadPath}
allowpopups
onipc-message={(e: any) => {
if (e.channel === 'theme-change' && e.args?.[0]) {
applyTheme(e.args[0])
}
}}
></webview>
</div>
{/if}
{/if}
{#if settingsOpen}
<Settings onclose={() => settingsOpen = false} />
{/if}
</main>
<style>
.animate-in {
animation: fadeIn 0.15s ease-out;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(4px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
+100
View File
@@ -0,0 +1,100 @@
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
@theme {
--font-sans: 'Inter', -apple-system, BlinkMacSystemFont, ui-sans-serif, system-ui, sans-serif;
--font-mono: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
/* Exact cptr gray scale - pure neutral, zero chroma */
--color-gray-50: oklch(0.98 0 0);
--color-gray-100: oklch(0.94 0 0);
--color-gray-200: oklch(0.92 0 0);
--color-gray-300: oklch(0.85 0 0);
--color-gray-400: oklch(0.77 0 0);
--color-gray-500: oklch(0.69 0 0);
--color-gray-600: oklch(0.51 0 0);
--color-gray-700: oklch(0.42 0 0);
--color-gray-800: oklch(0.32 0 0);
--color-gray-850: oklch(0.27 0 0);
--color-gray-900: oklch(0.2 0 0);
--color-gray-950: oklch(0.16 0 0);
}
@layer base {
*,
::after,
::before,
::backdrop,
::file-selector-button {
border-color: var(--color-gray-200, currentColor);
}
html,
body {
height: 100dvh;
margin: 0;
overflow: hidden;
overscroll-behavior: none;
scrollbar-width: none;
-ms-overflow-style: none;
}
html::-webkit-scrollbar,
body::-webkit-scrollbar {
display: none;
}
html {
color-scheme: dark light;
touch-action: manipulation;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
user-select: none;
}
button {
@apply cursor-pointer;
}
}
.drag-region {
-webkit-app-region: drag;
}
.drag-region a,
.drag-region button {
-webkit-app-region: no-drag;
}
.no-drag {
-webkit-app-region: no-drag;
}
/* Scrollbar - cptr style */
::-webkit-scrollbar-thumb {
--tw-border-opacity: 1;
background-color: rgba(215, 215, 215, 0.6);
border-color: rgba(255, 255, 255, var(--tw-border-opacity));
border-radius: 9999px;
border-width: 1px;
}
.dark ::-webkit-scrollbar-thumb {
background-color: rgba(67, 67, 67, 0.6);
border-color: rgba(0, 0, 0, var(--tw-border-opacity));
}
::-webkit-scrollbar {
height: 0.45rem;
width: 0.45rem;
}
::-webkit-scrollbar-track {
background-color: transparent;
border-radius: 9999px;
}
#app {
height: 100dvh;
}
+2
View File
@@ -0,0 +1,2 @@
/// <reference types="svelte" />
/// <reference types="vite/client" />
@@ -0,0 +1,236 @@
<script lang="ts">
import { config } from '../stores'
import { onMount } from 'svelte'
let { onclose } = $props<{ onclose: () => void }>()
let port = $state($config?.localServer?.port ?? 8000)
let serveOnLocalNetwork = $state($config?.localServer?.serveOnLocalNetwork ?? false)
let autoUpdate = $state($config?.localServer?.autoUpdate !== false)
let runInBackground = $state($config?.runInBackground !== false)
let launchAtLogin = $state(false)
let version = $state('')
let cptrVersion = $state('')
let saving = $state(false)
let advancedOpen = $state(false)
onMount(async () => {
const api = window?.electronAPI
if (!api) return
launchAtLogin = await api.getLaunchAtLogin?.() ?? false
version = (await api.getAppInfo())?.version ?? ''
cptrVersion = await api.getPackageVersion?.('cptr') ?? ''
})
async function save() {
saving = true
try {
const api = window?.electronAPI
if (!api) return
await api.setConfig({
localServer: { port, serveOnLocalNetwork, autoUpdate },
runInBackground
})
config.set(await api.getConfig())
onclose()
} finally {
saving = false
}
}
async function toggleLaunchAtLogin() {
launchAtLogin = !launchAtLogin
await window?.electronAPI?.setLaunchAtLogin?.(launchAtLogin)
}
async function handleReset() {
if (!confirm('This will remove Python, cptr, and all data. Continue?')) return
await window?.electronAPI?.resetApp()
window.location.reload()
}
</script>
<svelte:window onkeydown={(e) => { if (e.key === 'Escape') onclose() }} />
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="fixed inset-0 bg-black/50 z-[100] flex items-center justify-center"
onmousedown={onclose}
onkeydown={() => {}}
>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="bg-white dark:bg-[#0a0a0a] dark:border dark:border-white/8 rounded-3xl overflow-hidden shadow-2xl w-full max-w-lg mx-4 h-[480px] flex flex-col"
onmousedown={(e) => e.stopPropagation()}
onkeydown={() => {}}
>
<!-- Scrollable content -->
<div class="flex-1 min-h-0 overflow-y-auto scrollbar-hover p-4">
<h2 class="text-xs font-medium text-gray-900 dark:text-white mb-3">Settings</h2>
<h3 class="text-[10px] uppercase tracking-wide text-gray-400 dark:text-gray-600 mb-1.5">Server</h3>
<div class="flex flex-col gap-2">
<label class="flex items-center justify-between">
<span class="text-[11px] text-gray-600 dark:text-gray-400">Port</span>
<input
type="number"
bind:value={port}
class="w-14 bg-transparent text-[11px] font-mono text-gray-700 dark:text-gray-300 outline-none text-right"
/>
</label>
<label class="flex items-center justify-between cursor-pointer">
<span class="text-[11px] text-gray-600 dark:text-gray-400">Serve on local network</span>
<button
type="button" role="switch" aria-checked={serveOnLocalNetwork}
class="relative w-7 h-4 rounded-full transition-colors duration-150 shrink-0
{serveOnLocalNetwork ? 'bg-gray-900 dark:bg-white' : 'bg-gray-300 dark:bg-gray-700'}"
onclick={() => serveOnLocalNetwork = !serveOnLocalNetwork}
>
<span class="toggle-knob {serveOnLocalNetwork ? 'on' : ''}"></span>
</button>
</label>
<label class="flex items-center justify-between cursor-pointer">
<span class="text-[11px] text-gray-600 dark:text-gray-400">Auto-update on start</span>
<button
type="button" role="switch" aria-checked={autoUpdate}
class="relative w-7 h-4 rounded-full transition-colors duration-150 shrink-0
{autoUpdate ? 'bg-gray-900 dark:bg-white' : 'bg-gray-300 dark:bg-gray-700'}"
onclick={() => autoUpdate = !autoUpdate}
>
<span class="toggle-knob {autoUpdate ? 'on' : ''}"></span>
</button>
</label>
</div>
<h3 class="text-[10px] uppercase tracking-wide text-gray-400 dark:text-gray-600 mb-1.5 mt-4">General</h3>
<div class="flex flex-col gap-2">
<label class="flex items-center justify-between cursor-pointer">
<span class="text-[11px] text-gray-600 dark:text-gray-400">Run in background</span>
<button
type="button" role="switch" aria-checked={runInBackground}
class="relative w-7 h-4 rounded-full transition-colors duration-150 shrink-0
{runInBackground ? 'bg-gray-900 dark:bg-white' : 'bg-gray-300 dark:bg-gray-700'}"
onclick={() => runInBackground = !runInBackground}
>
<span class="toggle-knob {runInBackground ? 'on' : ''}"></span>
</button>
</label>
<label class="flex items-center justify-between cursor-pointer">
<span class="text-[11px] text-gray-600 dark:text-gray-400">Launch at login</span>
<button
type="button" role="switch" aria-checked={launchAtLogin}
class="relative w-7 h-4 rounded-full transition-colors duration-150 shrink-0
{launchAtLogin ? 'bg-gray-900 dark:bg-white' : 'bg-gray-300 dark:bg-gray-700'}"
onclick={toggleLaunchAtLogin}
>
<span class="toggle-knob {launchAtLogin ? 'on' : ''}"></span>
</button>
</label>
</div>
<!-- About -->
<h3 class="text-[10px] uppercase tracking-wide text-gray-400 dark:text-gray-600 mb-1 mt-4">About</h3>
<div class="flex items-baseline gap-2">
<a
href="https://github.com/open-webui/computer"
target="_blank"
rel="noopener noreferrer"
class="text-xs font-semibold text-gray-900 dark:text-white hover:underline"
>Computer Desktop</a>
{#if version}
<span class="text-[11px] text-gray-400 dark:text-gray-600 font-mono">v{version}</span>
{/if}
{#if cptrVersion}
<span class="text-[11px] text-gray-300 dark:text-gray-600">&middot;</span>
<span class="text-[11px] text-gray-400 dark:text-gray-600 font-mono">cptr v{cptrVersion}</span>
{/if}
</div>
<p class="text-[11px] text-gray-500 mt-0.5 mb-3">Your computer, from anywhere.</p>
<p class="text-[11px] text-gray-500 font-mono">
<a
href="https://github.com/open-webui/computer/blob/main/LICENSE"
target="_blank"
rel="noopener noreferrer"
class="underline hover:text-gray-700 dark:hover:text-gray-300"
>Open Use License</a>
</p>
<div class="flex items-center gap-1.5 pt-4">
<span class="text-[11px] text-gray-400 dark:text-gray-600 mr-1">Share</span>
<a href="https://x.com/intent/tweet?text={encodeURIComponent('Check out Computer Desktop. Your computer, from anywhere.')}&url={encodeURIComponent('https://github.com/open-webui/computer')}" target="_blank" rel="noopener noreferrer" class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-500 transition-colors">X</a>
<span class="text-[11px] text-gray-200 dark:text-gray-700">&middot;</span>
<a href="https://reddit.com/submit?url={encodeURIComponent('https://github.com/open-webui/computer')}&title={encodeURIComponent('Check out Computer Desktop. Your computer, from anywhere.')}" target="_blank" rel="noopener noreferrer" class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-500 transition-colors">Reddit</a>
<span class="text-[11px] text-gray-200 dark:text-gray-700">&middot;</span>
<a href="https://www.linkedin.com/sharing/share-offsite/?url={encodeURIComponent('https://github.com/open-webui/computer')}" target="_blank" rel="noopener noreferrer" class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-500 transition-colors">LinkedIn</a>
</div>
<!-- Advanced -->
<div class="pt-3">
<button
class="flex items-center gap-1.5 bg-transparent border-none text-gray-900 dark:text-white p-0 cursor-pointer"
onclick={() => advancedOpen = !advancedOpen}
>
<svg
class="w-2.5 h-2.5 opacity-30 transition-transform duration-200 {advancedOpen ? 'rotate-90' : ''}"
fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
</svg>
<span class="text-[11px] opacity-50">Advanced</span>
</button>
{#if advancedOpen}
<div class="mt-2 flex items-center justify-between">
<div>
<div class="text-[11px] text-gray-600 dark:text-gray-400">Factory Reset</div>
<div class="text-[10px] text-gray-400 dark:text-gray-600 mt-0.5">Remove all data</div>
</div>
<button
class="text-[11px] opacity-40 hover:opacity-70 px-2.5 py-1 bg-black/[0.04] dark:bg-white/[0.06] transition border-none text-gray-900 dark:text-white rounded-lg"
onclick={handleReset}
>Reset</button>
</div>
{/if}
</div>
</div>
<!-- Fixed save footer -->
<div class="shrink-0 px-4 py-3 flex justify-end">
<button
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100
disabled:opacity-30 disabled:pointer-events-none"
onclick={save}
disabled={saving}
>
{#if saving}Saving…{:else}Save{/if}
</button>
</div>
</div>
</div>
<style>
.toggle-knob {
position: absolute;
top: 2px;
left: 2px;
width: 12px;
height: 12px;
border-radius: 9999px;
background: #fff;
transition: all 0.15s ease;
}
:global(.dark) .toggle-knob {
background: var(--color-gray-500);
}
.toggle-knob.on {
left: 14px;
background: #fff;
}
:global(.dark) .toggle-knob.on {
background: #000;
}
</style>
@@ -0,0 +1,40 @@
<script lang="ts">
interface Props {
size?: number | string
class?: string
}
let { size = 16, class: className = '' }: Props = $props()
const px = typeof size === 'number' ? size : parseFloat(size) * 4
const bw = px <= 12 ? 1.5 : 2
</script>
<div
class="spinner {className}"
style="width:{px}px;height:{px}px;border-width:{bw}px"
role="status"
aria-label="Loading"
></div>
<style>
.spinner {
display: inline-block;
border-style: solid;
border-color: var(--color-gray-300);
border-top-color: var(--color-gray-600);
border-radius: 9999px;
animation: spin 0.75s linear infinite;
flex-shrink: 0;
}
:global(.dark) .spinner {
border-color: var(--color-gray-700);
border-top-color: var(--color-gray-400);
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>
+6
View File
@@ -0,0 +1,6 @@
import { writable } from 'svelte/store'
export const appInfo = writable(null)
export const config = writable(null)
export const serverInfo = writable(null)
export const appState = writable('loading') // loading | setup | starting | ready
+19
View File
@@ -0,0 +1,19 @@
import { mount } from 'svelte'
import './app.css'
import App from './App.svelte'
// System dark mode — toggle .dark class on <html>
function applySystemTheme() {
const dark = window.matchMedia('(prefers-color-scheme: dark)').matches
document.documentElement.classList.toggle('dark', dark)
}
applySystemTheme()
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', applySystemTheme)
const app = mount(App, {
target: document.getElementById('app')!
})
export default app
+7
View File
@@ -0,0 +1,7 @@
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'
export default {
// Consult https://svelte.dev/docs#compile-time-svelte-preprocess
// for more information about preprocessors
preprocess: vitePreprocess()
}
+4
View File
@@ -0,0 +1,4 @@
{
"files": [],
"references": [{ "path": "./tsconfig.node.json" }, { "path": "./tsconfig.web.json" }]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "@electron-toolkit/tsconfig/tsconfig.node.json",
"include": ["electron.vite.config.*", "src/main/**/*", "src/preload/**/*"],
"compilerOptions": {
"composite": true,
"types": ["electron-vite/node"]
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"extends": "@electron-toolkit/tsconfig/tsconfig.web.json",
"include": [
"src/renderer/src/env.d.ts",
"src/renderer/src/**/*",
"src/renderer/src/**/*.svelte",
"src/preload/*.d.ts"
],
"compilerOptions": {
"verbatimModuleSyntax": true,
"useDefineForClassFields": true,
"strict": false,
"allowJs": true,
"checkJs": true,
"lib": ["ESNext", "DOM", "DOM.Iterable"]
}
}