This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-06 10:54:27 +01:00
1 parent 209446617b
commit 69d416c909
21 files changed
+877 -191

No files matched your search

+50 -9
View File
@@ -5,6 +5,10 @@ on:
branches: [main]
workflow_dispatch:
concurrency:
group: docker-${{ github.ref }}
cancel-in-progress: false
env:
IMAGE: ghcr.io/${{ github.repository }}
@@ -14,6 +18,7 @@ permissions:
jobs:
detect-version-change:
if: github.ref == 'refs/heads/release'
runs-on: ubuntu-latest
outputs:
version_changed: ${{ steps.check.outputs.changed }}
@@ -58,9 +63,8 @@ jobs:
echo "No version change detected"
fi
build-and-push:
needs: detect-version-change
if: needs.detect-version-change.outputs.version_changed == 'true'
build-and-push-dev:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -76,18 +80,55 @@ jobs:
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels)
- name: Extract metadata (dev tags, labels)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.IMAGE }}
tags: |
type=raw,value=latest
type=raw,value=${{ needs.detect-version-change.outputs.version }}
type=semver,pattern={{major}}.{{minor}},value=v${{ needs.detect-version-change.outputs.version }}
type=sha,prefix=
type=raw,value=dev
type=sha,prefix=dev-
- name: Build and push
- name: Build and push dev image
uses: docker/build-push-action@v6
with:
context: .
push: true
platforms: linux/amd64,linux/arm64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-and-push-release:
needs: detect-version-change
if: github.ref == 'refs/heads/release' && needs.detect-version-change.outputs.version_changed == 'true'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (release tags, labels)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.IMAGE }}
tags: |
type=raw,value=latest
type=raw,value=${{ needs.detect-version-change.outputs.version }}
type=semver,pattern={{major}}.{{minor}},value=v${{ needs.detect-version-change.outputs.version }}
- name: Build and push release image
uses: docker/build-push-action@v6
with:
context: .
+114
View File
@@ -0,0 +1,114 @@
name: Publish to PyPI
on:
pull_request:
types: [closed]
branches: [release]
permissions:
contents: read
jobs:
detect-version-change:
if: github.event.pull_request.merged == true && github.event.pull_request.head.ref == 'main'
runs-on: ubuntu-latest
outputs:
version_changed: ${{ steps.check.outputs.changed }}
version: ${{ steps.check.outputs.version }}
steps:
- name: Checkout current commit
uses: actions/checkout@v4
with:
fetch-depth: 2 # need parent to diff against
- name: Check for version bump
id: check
run: |
# Extract version from current commit
CURRENT=$(python3 -c "
import re, pathlib
text = pathlib.Path('pyproject.toml').read_text()
m = re.search(r'^version\s*=\s*\"([^\"]+)\"', text, re.M)
print(m.group(1))
")
# Extract version from previous commit
git show HEAD~1:pyproject.toml > /tmp/prev_pyproject.toml 2>/dev/null || true
if [ -f /tmp/prev_pyproject.toml ]; then
PREVIOUS=$(python3 -c "
import re, pathlib
text = pathlib.Path('/tmp/prev_pyproject.toml').read_text()
m = re.search(r'^version\s*=\s*\"([^\"]+)\"', text, re.M)
print(m.group(1) if m else '')
")
else
PREVIOUS=""
fi
echo "current=$CURRENT"
echo "previous=$PREVIOUS"
if [ "$CURRENT" != "$PREVIOUS" ] && [ -n "$CURRENT" ]; then
echo "changed=true" >> "$GITHUB_OUTPUT"
echo "version=$CURRENT" >> "$GITHUB_OUTPUT"
echo "Version changed: $PREVIOUS -> $CURRENT"
else
echo "changed=false" >> "$GITHUB_OUTPUT"
echo "No version change detected"
fi
build:
needs: detect-version-change
if: needs.detect-version-change.outputs.version_changed == 'true'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
cache-dependency-path: cptr/frontend/package-lock.json
- name: Build frontend
working-directory: cptr/frontend
run: |
npm ci
npm run build
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install build tools
run: pip install hatchling build
- name: Build package
run: python -m build
- name: Upload dist artifacts
uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
publish:
needs: [detect-version-change, build]
runs-on: ubuntu-latest
environment: pypi # GitHub environment for deployment protection
permissions:
id-token: write # required for trusted publishing (OIDC)
steps:
- name: Download dist artifacts
uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
# No API token needed - uses OIDC trusted publishing.
# Configure at: https://pypi.org/manage/project/cptr/settings/publishing/
+104
View File
@@ -0,0 +1,104 @@
# ─────────────────────────────────────────────────────────────────────────────
# Release — Create GitHub release from CHANGELOG, trigger Docker builds
# Runs only when main is merged into the release branch and pyproject.toml
# version changes.
# ─────────────────────────────────────────────────────────────────────────────
name: Release
on:
pull_request:
types: [closed]
branches: [release]
concurrency:
group: release-${{ github.event.pull_request.base.ref || github.ref }}
cancel-in-progress: false
jobs:
# ── Detect version bump in pyproject.toml ─────────────────────────────────
detect-version-change:
if: github.event.pull_request.merged == true && github.event.pull_request.head.ref == 'main'
runs-on: ubuntu-latest
outputs:
version_changed: ${{ steps.check.outputs.changed }}
version: ${{ steps.check.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Check for version bump
id: check
run: |
CURRENT=$(python3 -c "
import re, pathlib
text = pathlib.Path('pyproject.toml').read_text()
m = re.search(r'^version\s*=\s*\"([^\"]+)\"', text, re.M)
print(m.group(1))
")
git show HEAD~1:pyproject.toml > /tmp/prev_pyproject.toml 2>/dev/null || true
if [ -f /tmp/prev_pyproject.toml ]; then
PREVIOUS=$(python3 -c "
import re, pathlib
text = pathlib.Path('/tmp/prev_pyproject.toml').read_text()
m = re.search(r'^version\s*=\s*\"([^\"]+)\"', text, re.M)
print(m.group(1) if m else '')
")
else
PREVIOUS=""
fi
echo "current=$CURRENT"
echo "previous=$PREVIOUS"
if [ "$CURRENT" != "$PREVIOUS" ] && [ -n "$CURRENT" ]; then
echo "changed=true" >> "$GITHUB_OUTPUT"
echo "version=$CURRENT" >> "$GITHUB_OUTPUT"
echo "Version changed: $PREVIOUS -> $CURRENT"
else
echo "changed=false" >> "$GITHUB_OUTPUT"
echo "No version change detected"
fi
# ── Create release and trigger downstream workflows ──────────────────────
publish:
needs: detect-version-change
if: needs.detect-version-change.outputs.version_changed == 'true'
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write
actions: write
steps:
- uses: actions/checkout@v4
- name: Extract release notes from CHANGELOG
run: |
VER="${{ needs.detect-version-change.outputs.version }}"
awk "/^## \[${VER}\]/{found=1; next} /^## \[/{if(found) exit} found{print}" \
CHANGELOG.md > /tmp/release-notes.md
- name: Publish GitHub release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
if gh release view "v${{ needs.detect-version-change.outputs.version }}" &>/dev/null; then
echo "Release v${{ needs.detect-version-change.outputs.version }} already exists — skipping creation"
else
gh release create "v${{ needs.detect-version-change.outputs.version }}" \
--title "v${{ needs.detect-version-change.outputs.version }}" \
--notes-file /tmp/release-notes.md
fi
- name: Trigger Docker build
uses: actions/github-script@v7
with:
script: |
github.rest.actions.createWorkflowDispatch({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: 'docker.yml',
ref: 'release',
})
+14 -4
View File
@@ -5,15 +5,25 @@ 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-05
## [0.1.0] - 2026-06-06
### Added
- 🚀 **Initial release.** First public version of cptr: your computer, from anywhere. Code, manage, and control your machine from the web.
- 🖥️ **Terminal emulator.** Full PTY-backed terminal accessible from the browser with support for macOS and Linux.
- 💬 **AI chat interface.** Built-in chat panel with multi-provider LLM support (OpenAI, Anthropic, Ollama, and OpenAI-compatible endpoints), tool calling, and streaming responses.
- 🔧 **Tool system.** Extensible tool framework enabling AI agents to interact with the local filesystem, run commands, search the web, and read URLs.
- 📁 **File browser.** Web-based file explorer with directory navigation, file viewing, and management capabilities.
- 💬 **AI chat.** Built-in chat panel with multi-provider LLM support (OpenAI, Anthropic, Ollama, and OpenAI-compatible endpoints), model selector, tool calling, and streaming responses.
- 🔧 **Tool system.** Extensible tool framework enabling AI agents to interact with the local filesystem, run commands, search the web (Brave, DuckDuckGo, Exa, Tavily), and read URLs. Streaming JSON parser for improved tool-calling reliability.
- 📎 **File mentions.** Type `@` in the chat input to mention files with an inline suggestion popup, giving the AI context about your codebase.
- 🔄 **Queued messages.** Queue follow-up messages while the AI is responding — they'll be sent automatically when the current response completes.
- ✏️ **Output editing.** Review and edit AI-generated file changes before applying them.
- 📁 **File browser.** Web-based file explorer with directory navigation, file viewing, file icons by extension, and management capabilities.
- ⌨️ **Keyboard shortcuts.** Customizable keybinding system with a dedicated settings panel, including support for new-tab, quick-open, and other common actions.
- 📐 **Resizable sidebar.** Drag-to-resize sidebar with persistent width and smooth panel resize handles.
- 🔍 **Quick open.** Cmd+K modal with keyboard pill hints for fast file and command navigation.
- 🌐 **Proxy middleware.** Reverse-proxy system for forwarding local ports with automatic port detection and notification.
- 📁 **Workspace management.** Manage multiple project directories from a single instance.
- 📊 **Chat history.** Persistent chat list with automatic title generation, scrolling, and pagination.
- 🔐 **Authentication.** Username/password authentication with JWT-based session management.
- 🎨 **Admin settings.** Settings UI for managing AI connections and app configuration.
- 🐳 **Docker support.** Multi-stage Dockerfile and GitHub Actions workflow for building and publishing to GHCR.
- 📦 **PyPI packaging.** Hatchling-based build with frontend assets bundled into the wheel, published via trusted OIDC publishing.
+1 -1
View File
@@ -1 +1 @@
"""cptr - your computer, from anywhere."""
"""Your computer, from anywhere."""
+8 -1
View File
@@ -41,7 +41,7 @@ async def startup():
async def auth_middleware(request: Request, call_next):
path = request.url.path
# Skip auth for: auth endpoints, health, static assets, HTML pages
if path.startswith("/api/auth") or path == "/api/health" or path == "/api/config" or path == "/manifest.json":
if path.startswith("/api/auth") or path == "/api/health" or path == "/api/config" or path == "/api/changelog" or path == "/manifest.json":
return await call_next(request)
if path.startswith("/_app/") or not path.startswith("/api/"):
return await call_next(request)
@@ -175,6 +175,13 @@ async def health():
return {"status": "ok", "uptime_seconds": int(time.time() - START_TIME), "pid": os.getpid()}
@app.get("/api/changelog")
async def get_changelog():
"""Return parsed CHANGELOG.md as structured JSON (max 5 versions)."""
from cptr.utils.changelog import CHANGELOG
return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
# PWA manifest (backend-driven so each instance has its own identity)
@app.get("/manifest.json")
async def pwa_manifest():
+1 -1
View File
@@ -4,7 +4,7 @@ import uvicorn
@click.group()
def cli():
"""cptr - your computer, from anywhere."""
"""Your computer, from anywhere."""
pass
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "frontend",
"private": true,
"version": "0.0.1",
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite dev",
@@ -0,0 +1,145 @@
<script lang="ts">
import { fetchJSON } from '$lib/apis';
import Modal from './Modal.svelte';
import Icon from './Icon.svelte';
import { appVersion, lastSeenVersion, showChangelog } from '$lib/stores';
type ChangelogEntry = { title: string; content: string; raw: string };
type VersionData = { date: string; [section: string]: string | ChangelogEntry[] };
let changelog = $state<Record<string, VersionData> | null>(null);
let selectedVersion = $state<string | null>(null);
let error = $state(false);
const versions = $derived.by(() => (changelog ? Object.entries(changelog) : []));
const selectedData = $derived.by(() => {
if (!versions.length) return null;
const version = selectedVersion ?? versions[0][0];
return versions.find(([ver]) => ver === version) ?? versions[0];
});
$effect(() => {
if ($showChangelog && !changelog && !error) {
fetchJSON<Record<string, VersionData>>('/api/changelog')
.then((data) => {
changelog = data;
selectedVersion = Object.keys(data)[0] ?? null;
})
.catch(() => {
error = true;
});
}
});
function handleClose() {
if ($appVersion) {
lastSeenVersion.set($appVersion);
}
showChangelog.set(false);
}
function formatDate(dateStr: string): string {
if (!dateStr) return '';
const parts = dateStr.split('-');
if (parts.length !== 3) return dateStr;
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const year = parts[0];
const monthIdx = parseInt(parts[1], 10) - 1;
const day = parseInt(parts[2], 10);
return monthIdx >= 0 && monthIdx < 12 ? `${months[monthIdx]} ${day}, ${year}` : dateStr;
}
</script>
{#if $showChangelog}
<Modal onclose={handleClose} class="w-full max-w-3xl mx-4 md:mx-0 flex flex-col max-h-[52vh]">
<div class="flex items-center gap-3 px-4 pt-4 pb-2 shrink-0">
<div class="min-w-0 flex-1">
<h2 class="text-sm font-medium text-gray-900 dark:text-white">What's New</h2>
{#if selectedData}
{@const [ver, data] = selectedData}
<p class="mt-0.5 text-[11px] text-gray-400 dark:text-gray-600">v{ver} · {formatDate(data.date)}</p>
{/if}
</div>
<button
class="flex h-7 w-7 items-center justify-center rounded-lg text-gray-400 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-600 dark:hover:bg-white/6 dark:hover:text-gray-300 transition-colors duration-75"
onclick={handleClose}
aria-label="Close"
>
<Icon name="xmark" size={14} />
</button>
</div>
{#if versions.length > 1}
<div class="flex gap-1 overflow-x-auto px-3 pb-2 shrink-0 scrollbar-hidden">
{#each versions as [ver], i (ver)}
<button
class="h-7 shrink-0 rounded-lg px-2 text-[11px] transition-colors duration-75
{(selectedVersion ?? versions[0][0]) === ver
? 'bg-gray-100 text-gray-900 dark:bg-white/6 dark:text-white'
: 'text-gray-400 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300'}"
onclick={() => (selectedVersion = ver)}
>
v{ver}{#if i === 0}<span class="ml-1 font-sans text-[9px] text-gray-300 dark:text-gray-700">latest</span>{/if}
</button>
{/each}
</div>
{/if}
<div class="flex-1 min-h-0 overflow-y-auto px-4 py-3">
{#if selectedData}
{@const [_ver, data] = selectedData}
<div class="space-y-6">
{#each Object.entries(data).filter(([key]) => key !== 'date') as [section, items]}
{#if Array.isArray(items) && items.length > 0}
<section>
<h3 class="mb-2 text-[10px] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600">{section}</h3>
<ul class="space-y-2.5">
{#each items as entry}
<li class="flex gap-2.5 text-xs leading-relaxed">
<span class="mt-[0.45em] h-1 w-1 shrink-0 rounded-full bg-gray-300 dark:bg-gray-700"></span>
<div class="min-w-0">
{#if entry.title}
<span class="font-medium text-gray-900 dark:text-white">{entry.title}</span>
{#if entry.content}
<span class="ml-1 text-gray-500 dark:text-gray-400">{entry.content}</span>
{/if}
{:else}
<span class="text-gray-600 dark:text-gray-400">{entry.content || entry.raw}</span>
{/if}
</div>
</li>
{/each}
</ul>
</section>
{/if}
{/each}
</div>
{:else if error}
<div class="flex flex-col items-center justify-center py-16 gap-2 text-center">
<p class="text-xs text-gray-500 dark:text-gray-400">Couldn't load release notes.</p>
<button
class="rounded-lg bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-600 hover:text-gray-900 dark:bg-white/6 dark:text-gray-400 dark:hover:text-white transition-colors duration-75"
onclick={() => (error = false)}
>
Retry
</button>
</div>
{:else}
<div class="flex flex-col items-center justify-center py-16 gap-3">
<div class="h-4 w-4 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400"></div>
<span class="text-[11px] text-gray-400 dark:text-gray-600">Loading release notes...</span>
</div>
{/if}
</div>
<div class="flex items-center justify-end px-4 pt-1 pb-4 shrink-0">
<button
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100"
onclick={handleClose}
>
Done
</button>
</div>
</Modal>
{/if}
@@ -1,17 +1,6 @@
<script lang="ts">
import { onMount } from "svelte";
import { getWelcome } from "$lib/apis/state";
import { t } from "$lib/i18n";
let appVersion = $state("");
onMount(() => {
getWelcome()
.then((d) => {
appVersion = d.version || "";
})
.catch(() => {});
});
import { appVersion, showChangelog } from "$lib/stores";
</script>
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">
@@ -20,12 +9,18 @@
<div>
<div class="flex items-baseline gap-2">
<span class="text-xs font-semibold text-gray-900 dark:text-white"
>cptr</span
<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"
>cptr</a
>
{#if appVersion}
<span class="text-[11px] text-gray-400 dark:text-gray-600 font-mono"
>v{appVersion}</span
{#if $appVersion}
<button
onclick={() => showChangelog.set(true)}
class="text-[11px] text-gray-400 dark:text-gray-600 hover:text-gray-500 dark:hover:text-gray-400 font-mono hover:underline cursor-pointer"
>v{$appVersion}</button
>
{/if}
</div>
@@ -8,6 +8,8 @@
reorderWorkspaces,
sidebarOpen,
sidebarWidth,
appVersion,
showChangelog,
} from '$lib/stores';
import Sortable from 'sortablejs';
import Icon from './Icon.svelte';
@@ -29,7 +31,7 @@
let showAdmin = $state(false);
let wsMenuPath = $state<string | null>(null);
let wsMenuAnchor = $state<HTMLElement | null>(null);
let appVersion = $state('');
let menuButtonEl: HTMLButtonElement | undefined = $state();
let wsListEl: HTMLDivElement | undefined = $state();
let sortable: Sortable | null = null;
@@ -118,9 +120,6 @@
}
onMount(() => {
getWelcome()
.then(d => { appVersion = d.version || ''; })
.catch(() => {});
// Enable drag-reorder on non-touch devices
if (wsListEl && !isTouchDevice()) {
@@ -218,7 +217,7 @@
{/if}
</div>
<!-- Settings - pinned bottom -->
<!-- Settings and profile footer pinned to the bottom -->
<div class="relative px-1 pb-0.5 shrink-0">
<button
@@ -232,8 +231,13 @@
class="w-5 h-5 rounded-full object-cover shrink-0"
/>
<span class="truncate">{$session?.display_name || $session?.username || $t('sidebar.settings')}</span>
{#if appVersion}
<span class="ml-auto text-[10px] text-gray-400 dark:text-gray-600 font-mono">v{appVersion}</span>
{#if $appVersion}
<button
onclick={(e) => { e.stopPropagation(); showChangelog.set(true); }}
class="ml-auto text-[10px] text-gray-400 dark:text-gray-600 hover:text-gray-500 dark:hover:text-gray-400 font-mono hover:underline cursor-pointer"
>
v{$appVersion}
</button>
{/if}
</button>
</div>
@@ -54,7 +54,7 @@
type="button"
class="flex items-center justify-center rounded-full p-1 transition-colors duration-100
{recording
? 'text-red-500 dark:text-red-400 bg-red-50 dark:bg-red-500/10'
? 'text-gray-400 dark:text-gray-500 bg-gray-50 dark:bg-white/5'
: 'text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5'}"
onclick={toggle}
>
+7
View File
@@ -73,6 +73,7 @@ export interface UserPreferences {
locale: string;
workspaceOrder?: string[]; // ordered paths for sidebar drag-reorder
keybindings?: Record<string, string>; // user-customised keyboard shortcuts
version?: string; // last seen app version for changelog
}
export type Theme = 'dark' | 'light' | 'system';
@@ -120,6 +121,9 @@ export const sidebarOpen = writable(typeof window !== 'undefined' ? window.inner
export const sidebarWidth = writable(220);
export const theme = writable<Theme>('dark');
export const toolApprovalMode = writable<ToolApprovalMode>('auto');
export const appVersion = writable('');
export const lastSeenVersion = writable('');
export const showChangelog = writable(false);
/** @deprecated Use toolApprovalMode */
export const autoApproveTools = {
subscribe: toolApprovalMode.subscribe,
@@ -264,6 +268,7 @@ function persistPreferences(): void {
locale: i18next.language,
workspaceOrder: get(workspaceOrder),
keybindings: get(keybindings),
version: get(lastSeenVersion),
};
savePreferences(prefs as unknown as Record<string, unknown>).catch(() => {});
}, 300);
@@ -280,6 +285,7 @@ function subscribeForPersistence() {
toolApprovalMode.subscribe(() => { if (get(stateLoaded)) persistPreferences(); });
workspaceOrder.subscribe(() => { if (get(stateLoaded)) persistPreferences(); });
keybindings.subscribe(() => { if (get(stateLoaded)) persistPreferences(); });
lastSeenVersion.subscribe(() => { if (get(stateLoaded)) persistPreferences(); });
i18next.on('languageChanged', () => { if (get(stateLoaded)) persistPreferences(); });
}
@@ -301,6 +307,7 @@ export async function loadPreferences(): Promise<void> {
if (prefs.locale) changeLocale(prefs.locale as string);
if (Array.isArray(prefs.workspaceOrder)) workspaceOrder.set(prefs.workspaceOrder as string[]);
if (prefs.keybindings) loadKeybindings(prefs.keybindings as Record<string, string>);
if (prefs.version) lastSeenVersion.set(prefs.version as string);
} catch {
// First run, no preferences yet
}
+26 -2
View File
@@ -10,12 +10,13 @@
import QuickOpen from '$lib/components/QuickOpen.svelte';
import SettingsModal from '$lib/components/SettingsModal.svelte';
import AuthScreen from '$lib/components/AuthScreen.svelte';
import ChangelogModal from '$lib/components/ChangelogModal.svelte';
import { Toaster } from 'svelte-sonner';
import { activeTab, currentWorkspace, stateLoaded, initState, gitReviewOpen, isGitRepo, splitActive, splitCurrentTab, closeGroup } from '$lib/stores';
import { activeTab, currentWorkspace, stateLoaded, initState, gitReviewOpen, isGitRepo, splitActive, splitCurrentTab, closeGroup, appVersion, lastSeenVersion, showChangelog } from '$lib/stores';
import { matchKeybinding, executeAction } from '$lib/stores/keybindings';
import { systemEvents } from '$lib/stores/systemEvents.svelte';
import { socketStore } from '$lib/stores/socket.svelte';
import { setSession } from '$lib/session';
import { setSession, clearSession } from '$lib/session';
import { getSession, getConfig } from '$lib/apis/auth';
import { getGitStatus } from '$lib/apis/git';
import { t } from '$lib/i18n';
@@ -73,6 +74,23 @@
let startupToken = $state('');
$effect(() => {
if ($stateLoaded && $appVersion) {
const currentVer = $appVersion;
const lastSeen = $lastSeenVersion;
if (lastSeen !== currentVer) {
if (!lastSeen) {
// First-time load: initialize the last seen version to the current version so we don't pop up immediately
lastSeenVersion.set(currentVer);
} else {
// Update: record this version as seen before showing the changelog so it doesn't reopen repeatedly.
lastSeenVersion.set(currentVer);
showChangelog.set(true);
}
}
}
});
async function checkAuth() {
try {
const params = new URLSearchParams(window.location.search);
@@ -87,6 +105,10 @@
const auth = await getSession();
getConfig().then(cfg => {
appVersion.set(cfg.version);
}).catch(() => {});
if (auth.authenticated) {
setSession({
user_id: auth.user_id!,
@@ -107,6 +129,7 @@
} catch {
authState = 'authenticated';
initState();
refreshChatState();
}
}
@@ -231,6 +254,7 @@
{#if showSettings}
<SettingsModal onclose={() => showSettings = false} />
{/if}
<ChangelogModal />
{:else}
<div class="flex items-center justify-center h-dvh bg-white dark:bg-black">
<div class="w-5 h-5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
+8 -3
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { currentWorkspace, activeTab, workspaceList, addWorkspace, loadWorkspace, gitReviewOpen, setActiveGroup, setSplitRatio, moveTabToGroup, openInSplit, openTabInSplit, setSplitDirection } from '$lib/stores';
import { currentWorkspace, activeTab, workspaceList, addWorkspace, loadWorkspace, gitReviewOpen, setActiveGroup, setSplitRatio, moveTabToGroup, openInSplit, openTabInSplit, setSplitDirection, appVersion, showChangelog } from '$lib/stores';
import { splitActive } from '$lib/stores';
import type { Tab, EditorGroup, WorkspaceState } from '$lib/stores';
import { t } from '$lib/i18n';
@@ -247,8 +247,13 @@
<div class="mb-4">
<div class="flex items-baseline gap-2">
<h1 class="text-lg font-semibold tracking-tight text-gray-900 dark:text-white">cptr</h1>
{#if welcomeData?.version}
<span class="text-[11px] text-gray-400 dark:text-gray-600 font-mono">v{welcomeData.version}</span>
{#if $appVersion}
<button
onclick={() => showChangelog.set(true)}
class="text-[11px] text-gray-400 dark:text-gray-600 hover:text-gray-500 dark:hover:text-gray-400 font-mono hover:underline cursor-pointer"
>
v{$appVersion}
</button>
{/if}
</div>
{#if welcomeData?.hostname}
+119 -34
View File
@@ -12,12 +12,14 @@ import os
import platform
import subprocess
import sys
import threading
from pathlib import Path
from typing import Optional
from typing import Optional, NamedTuple
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, FileSystemEvent
from watchdog.observers.polling import PollingObserver
from cptr.utils.terminal import manager
from cptr.utils.config import check_access
@@ -29,16 +31,24 @@ router = APIRouter(prefix="/api/events", tags=["events"])
# ── Filesystem watcher ────────────────────────────────────────────
def _create_observer():
if platform.system() == "Darwin":
return PollingObserver()
return Observer()
class _ChangeCollector(FileSystemEventHandler):
"""Collects fs events into a set for debounced delivery."""
def __init__(self) -> None:
self._changes: set[str] = set()
self._lock = threading.Lock()
def _record(self, event: FileSystemEvent) -> None:
path = event.src_path
self._changes.add(str(Path(path).parent))
self._changes.add(path)
with self._lock:
self._changes.add(str(Path(path).parent))
self._changes.add(path)
def on_created(self, event: FileSystemEvent) -> None:
self._record(event)
@@ -52,64 +62,139 @@ class _ChangeCollector(FileSystemEventHandler):
def on_moved(self, event: FileSystemEvent) -> None:
self._record(event)
if hasattr(event, "dest_path"):
self._changes.add(str(Path(event.dest_path).parent))
self._changes.add(event.dest_path)
with self._lock:
self._changes.add(str(Path(event.dest_path).parent))
self._changes.add(event.dest_path)
def drain(self) -> list[str]:
paths = list(self._changes)
self._changes.clear()
with self._lock:
paths = list(self._changes)
self._changes.clear()
return paths
class _WatchEntry(NamedTuple):
observer: Observer
handler: _ChangeCollector
watch: object
subscribers: set[asyncio.Queue[list[str]]]
_watch_registry: dict[str, _WatchEntry] = {}
_watch_registry_lock = asyncio.Lock()
async def _subscribe_to_path(path: str) -> tuple[str, asyncio.Queue[list[str]]]:
"""Subscribe this connection to a shared filesystem watch."""
resolved = str(Path(path).resolve())
queue: asyncio.Queue[list[str]] = asyncio.Queue(maxsize=32)
async with _watch_registry_lock:
entry = _watch_registry.get(resolved)
if entry is None:
observer = _create_observer()
observer.daemon = True
handler = _ChangeCollector()
watch = observer.schedule(handler, resolved, recursive=True)
observer.start()
entry = _WatchEntry(observer, handler, watch, set())
_watch_registry[resolved] = entry
entry.subscribers.add(queue)
return resolved, queue
async def _unsubscribe_from_path(path: str, queue: asyncio.Queue[list[str]]) -> None:
"""Remove a filesystem watch subscription and stop idle observers."""
async with _watch_registry_lock:
entry = _watch_registry.get(path)
if entry is None:
return
entry.subscribers.discard(queue)
if entry.subscribers:
return
_watch_registry.pop(path, None)
try:
entry.observer.unschedule(entry.watch)
except Exception:
pass
try:
entry.observer.stop()
entry.observer.join(timeout=2)
except Exception:
pass
async def _dispatch_fs_changes() -> None:
"""Fan out debounced filesystem changes from shared watchers."""
while True:
await asyncio.sleep(1.0)
async with _watch_registry_lock:
entries = list(_watch_registry.items())
for path, entry in entries:
paths = entry.handler.drain()
if not paths:
continue
if sys.platform == "win32":
paths = [p.replace("\\", "/") for p in paths]
for queue in list(entry.subscribers):
try:
queue.put_nowait(paths)
except asyncio.QueueFull:
logger.debug("Dropped fs_change event for slow subscriber on %s", path)
_fs_dispatch_task: Optional[asyncio.Task] = None
async def _ensure_fs_dispatcher() -> None:
global _fs_dispatch_task
if _fs_dispatch_task is None or _fs_dispatch_task.done():
_fs_dispatch_task = asyncio.create_task(_dispatch_fs_changes())
async def _fs_watcher_loop(ws: WebSocket, initial_path: str, path_holder: dict) -> None:
"""Watch filesystem and push fs_change events."""
observer = Observer()
observer.daemon = True
observer.start()
handler = _ChangeCollector()
target = str(Path(initial_path).resolve())
path_holder["current"] = target
try:
watch = observer.schedule(handler, target, recursive=True)
await _ensure_fs_dispatcher()
current_path, queue = await _subscribe_to_path(target)
except Exception as e:
logger.warning(f"Failed to watch {target}: {e}")
return
try:
while True:
await asyncio.sleep(1.0)
# Check if path changed (from receive loop)
new_path = path_holder.get("pending")
if new_path:
del path_holder["pending"]
resolved = str(Path(new_path).resolve())
if resolved != path_holder["current"] and Path(resolved).is_dir():
try:
observer.unschedule(watch)
except Exception:
pass
handler = _ChangeCollector()
watch = observer.schedule(handler, resolved, recursive=True)
await _unsubscribe_from_path(current_path, queue)
current_path, queue = await _subscribe_to_path(resolved)
path_holder["current"] = resolved
logger.info(f"FS watch path changed to {resolved}")
paths = handler.drain()
if paths:
# Normalize to forward slashes so the frontend can compare with /
if sys.platform == "win32":
paths = [p.replace("\\", "/") for p in paths]
try:
await ws.send_json({"type": "fs_change", "paths": paths})
except Exception:
break
try:
paths = await asyncio.wait_for(queue.get(), timeout=1.0)
except asyncio.TimeoutError:
continue
try:
await ws.send_json({"type": "fs_change", "paths": paths})
except Exception:
break
finally:
try:
observer.stop()
except Exception:
pass
await _unsubscribe_from_path(current_path, queue)
# ── Port scanning ─────────────────────────────────────────────────
+1 -1
View File
@@ -1,4 +1,4 @@
"""Terminal API - WebSocket and REST endpoints for PTY sessions."""
"""Endpoints for spawning, managing, and interacting with terminal PTY sessions."""
from __future__ import annotations
+1 -1
View File
@@ -1,4 +1,4 @@
"""File browser API - directory listing endpoint."""
"""Endpoints for browsing directories and managing files within the workspace."""
from __future__ import annotations
+170 -106
View File
@@ -9,6 +9,7 @@ chat_completion() provides a simple non-streaming call for lightweight tasks
from __future__ import annotations
import asyncio
import json
import logging
from collections.abc import AsyncIterator
@@ -19,6 +20,15 @@ from pydantic import BaseModel
logger = logging.getLogger(__name__)
_STREAM_RETRY_ATTEMPTS = 3
_STREAM_RETRY_ERRORS = (
httpx.ConnectError,
httpx.ConnectTimeout,
httpx.ReadError,
httpx.ReadTimeout,
httpx.RemoteProtocolError,
)
class ChatCompletionForm(BaseModel):
"""Mirrors OpenAI Responses API request shape."""
@@ -171,51 +181,69 @@ async def stream_anthropic(
body = {k: v for k, v in body.items() if v is not None}
headers = {"x-api-key": key, "anthropic-version": "2023-06-01"}
async with httpx.AsyncClient(timeout=httpx.Timeout(30, read=300)) as client:
logger.info("[stream] anthropic POST %s/messages model=%s", url, form_data.model)
async with client.stream(
"POST", f"{url}/messages", json=body, headers=headers
) as resp:
logger.info("[stream] anthropic status=%s", resp.status_code)
resp.raise_for_status()
current_block: dict = {}
async for line in resp.aiter_lines():
if not line.startswith("data: "):
continue
event = json.loads(line[6:])
etype = event.get("type")
emitted = False
for attempt in range(_STREAM_RETRY_ATTEMPTS):
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(30, read=300)) as client:
logger.info("[stream] anthropic POST %s/messages model=%s", url, form_data.model)
async with client.stream(
"POST", f"{url}/messages", json=body, headers=headers
) as resp:
logger.info("[stream] anthropic status=%s", resp.status_code)
resp.raise_for_status()
current_block: dict = {}
async for line in resp.aiter_lines():
if not line.startswith("data: "):
continue
event = json.loads(line[6:])
etype = event.get("type")
if etype == "content_block_start":
block = event["content_block"]
current_block = {"type": block["type"], "index": event["index"]}
if block["type"] == "tool_use":
current_block["id"] = block["id"]
current_block["name"] = block["name"]
current_block["input_json"] = ""
if etype == "content_block_start":
block = event["content_block"]
current_block = {"type": block["type"], "index": event["index"]}
if block["type"] == "tool_use":
current_block["id"] = block["id"]
current_block["name"] = block["name"]
current_block["input_json"] = ""
elif etype == "content_block_delta":
delta = event["delta"]
if delta["type"] == "text_delta":
yield {"type": "text_delta", "content": delta["text"]}
elif delta["type"] == "input_json_delta":
current_block["input_json"] += delta["partial_json"]
elif etype == "content_block_delta":
delta = event["delta"]
if delta["type"] == "text_delta":
emitted = True
yield {"type": "text_delta", "content": delta["text"]}
elif delta["type"] == "input_json_delta":
current_block["input_json"] += delta["partial_json"]
elif etype == "content_block_stop":
if current_block.get("type") == "tool_use":
yield {
"type": "tool_call",
"call_id": current_block["id"],
"name": current_block["name"],
"arguments": json.loads(current_block["input_json"]),
}
elif etype == "content_block_stop":
if current_block.get("type") == "tool_use":
emitted = True
yield {
"type": "tool_call",
"call_id": current_block["id"],
"name": current_block["name"],
"arguments": json.loads(current_block["input_json"]),
}
elif etype == "message_delta":
usage = event.get("usage", {})
if usage:
yield {"type": "usage", **usage}
elif etype == "message_delta":
usage = event.get("usage", {})
if usage:
emitted = True
yield {"type": "usage", **usage}
elif etype == "message_stop":
yield {"type": "done"}
elif etype == "message_stop":
emitted = True
yield {"type": "done"}
return
except _STREAM_RETRY_ERRORS:
if emitted or attempt == _STREAM_RETRY_ATTEMPTS - 1:
raise
logger.warning(
"[stream] anthropic transient read failure before first event; retrying (%s/%s)",
attempt + 1,
_STREAM_RETRY_ATTEMPTS,
exc_info=True,
)
await asyncio.sleep(0.5 * (attempt + 1))
# ── OpenAI Chat Completions ──────────────────────────────────
@@ -258,49 +286,67 @@ async def stream_openai_completions(
body["tools"] = tools
headers = {"Authorization": f"Bearer {key}"}
async with httpx.AsyncClient(timeout=httpx.Timeout(30, read=300)) as client:
logger.info("[stream] openai completions POST %s/chat/completions model=%s", url, form_data.model)
async with client.stream(
"POST", f"{url}/chat/completions", json=body, headers=headers
) as resp:
logger.info("[stream] openai completions status=%s", resp.status_code)
resp.raise_for_status()
tool_calls: dict[int, dict] = {}
async for line in resp.aiter_lines():
if not line.startswith("data: ") or line == "data: [DONE]":
continue
chunk = json.loads(line[6:])
choices = chunk.get("choices", [])
delta = choices[0].get("delta", {}) if choices else {}
emitted = False
for attempt in range(_STREAM_RETRY_ATTEMPTS):
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(30, read=300)) as client:
logger.info("[stream] openai completions POST %s/chat/completions model=%s", url, form_data.model)
async with client.stream(
"POST", f"{url}/chat/completions", json=body, headers=headers
) as resp:
logger.info("[stream] openai completions status=%s", resp.status_code)
resp.raise_for_status()
tool_calls: dict[int, dict] = {}
async for line in resp.aiter_lines():
if not line.startswith("data: ") or line == "data: [DONE]":
continue
chunk = json.loads(line[6:])
choices = chunk.get("choices", [])
delta = choices[0].get("delta", {}) if choices else {}
if delta.get("content"):
yield {"type": "text_delta", "content": delta["content"]}
if delta.get("content"):
emitted = True
yield {"type": "text_delta", "content": delta["content"]}
for tc in delta.get("tool_calls", []):
idx = tc["index"]
if idx not in tool_calls:
tool_calls[idx] = {
"id": tc["id"],
"name": tc["function"]["name"],
"arguments_json": "",
}
tool_calls[idx]["arguments_json"] += tc["function"].get(
"arguments", ""
)
for tc in delta.get("tool_calls", []):
idx = tc["index"]
if idx not in tool_calls:
tool_calls[idx] = {
"id": tc["id"],
"name": tc["function"]["name"],
"arguments_json": "",
}
tool_calls[idx]["arguments_json"] += tc["function"].get(
"arguments", ""
)
if choices and choices[0].get("finish_reason") == "tool_calls":
for tc in tool_calls.values():
yield {
"type": "tool_call",
"call_id": tc["id"],
"name": tc["name"],
"arguments": json.loads(tc["arguments_json"]),
}
if choices and choices[0].get("finish_reason") == "tool_calls":
for tc in tool_calls.values():
emitted = True
yield {
"type": "tool_call",
"call_id": tc["id"],
"name": tc["name"],
"arguments": json.loads(tc["arguments_json"]),
}
if chunk.get("usage"):
yield {"type": "usage", **chunk["usage"]}
if chunk.get("usage"):
emitted = True
yield {"type": "usage", **chunk["usage"]}
yield {"type": "done"}
emitted = True
yield {"type": "done"}
return
except _STREAM_RETRY_ERRORS:
if emitted or attempt == _STREAM_RETRY_ATTEMPTS - 1:
raise
logger.warning(
"[stream] openai completions transient read failure before first event; retrying (%s/%s)",
attempt + 1,
_STREAM_RETRY_ATTEMPTS,
exc_info=True,
)
await asyncio.sleep(0.5 * (attempt + 1))
# ── OpenAI Responses API ─────────────────────────────────────
@@ -357,34 +403,52 @@ async def stream_openai_responses(
body["tools"] = tools
headers = {"Authorization": f"Bearer {key}"}
async with httpx.AsyncClient(timeout=httpx.Timeout(30, read=300)) as client:
logger.info("[stream] openai responses POST %s/responses model=%s", url, form_data.model)
async with client.stream(
"POST", f"{url}/responses", json=body, headers=headers
) as resp:
logger.info("[stream] openai responses status=%s", resp.status_code)
resp.raise_for_status()
async for line in resp.aiter_lines():
if not line.startswith("data: "):
continue
event = json.loads(line[6:])
etype = event.get("type")
emitted = False
for attempt in range(_STREAM_RETRY_ATTEMPTS):
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(30, read=300)) as client:
logger.info("[stream] openai responses POST %s/responses model=%s", url, form_data.model)
async with client.stream(
"POST", f"{url}/responses", json=body, headers=headers
) as resp:
logger.info("[stream] openai responses status=%s", resp.status_code)
resp.raise_for_status()
async for line in resp.aiter_lines():
if not line.startswith("data: "):
continue
event = json.loads(line[6:])
etype = event.get("type")
if etype == "response.output_text.delta":
yield {"type": "text_delta", "content": event["delta"]}
if etype == "response.output_text.delta":
emitted = True
yield {"type": "text_delta", "content": event["delta"]}
elif etype == "response.output_item.done":
item = event["item"]
if item["type"] == "function_call":
yield {
"type": "tool_call",
"call_id": item["call_id"],
"name": item["name"],
"arguments": json.loads(item["arguments"]),
}
elif etype == "response.output_item.done":
item = event["item"]
if item["type"] == "function_call":
emitted = True
yield {
"type": "tool_call",
"call_id": item["call_id"],
"name": item["name"],
"arguments": json.loads(item["arguments"]),
}
elif etype == "response.completed":
usage = event.get("response", {}).get("usage", {})
if usage:
yield {"type": "usage", **usage}
yield {"type": "done"}
elif etype == "response.completed":
usage = event.get("response", {}).get("usage", {})
if usage:
emitted = True
yield {"type": "usage", **usage}
emitted = True
yield {"type": "done"}
return
except _STREAM_RETRY_ERRORS:
if emitted or attempt == _STREAM_RETRY_ATTEMPTS - 1:
raise
logger.warning(
"[stream] openai responses transient read failure before first event; retrying (%s/%s)",
attempt + 1,
_STREAM_RETRY_ATTEMPTS,
exc_info=True,
)
await asyncio.sleep(0.5 * (attempt + 1))
+81
View File
@@ -0,0 +1,81 @@
"""Parse CHANGELOG.md into a structured dict for the /api/changelog endpoint.
Parses the Keep a Changelog format without requiring any external dependencies
(no markdown or beautifulsoup). The result is a dict keyed by version number,
each containing a 'date' and section lists (added, changed, fixed, etc.).
"""
from __future__ import annotations
import re
from pathlib import Path
def parse_changelog(path: Path | None = None) -> dict:
"""Parse CHANGELOG.md and return structured JSON.
Returns:
{
"0.1.0": {
"date": "2026-06-06",
"added": [
{"title": "Initial release.", "content": "First public version ...", "raw": "🚀 **Initial release.** First public ..."}
],
...
}
}
"""
if path is None:
# Look relative to project root (two levels up from this file)
path = Path(__file__).resolve().parent.parent.parent / "CHANGELOG.md"
try:
content = path.read_text(encoding="utf-8")
except FileNotFoundError:
return {}
changelog: dict = {}
current_version: str | None = None
current_section: str | None = None
current_date: str | None = None
for line in content.splitlines():
# Match version header: ## [0.1.0] - 2026-06-06
version_match = re.match(r"^## \[(.+?)\]\s*-\s*(.+)$", line.strip())
if version_match:
current_version = version_match.group(1)
current_date = version_match.group(2).strip()
changelog[current_version] = {"date": current_date}
current_section = None
continue
# Match section header: ### Added, ### Changed, ### Fixed, etc.
section_match = re.match(r"^### (.+)$", line.strip())
if section_match and current_version:
current_section = section_match.group(1).strip().lower()
changelog[current_version][current_section] = []
continue
# Match list item: - 🚀 **Title.** Description here.
item_match = re.match(r"^- (.+)$", line.strip())
if item_match and current_version and current_section:
raw = item_match.group(1).strip()
# Try to extract title from **Title.** pattern
title_match = re.match(r".*?\*\*(.+?)\*\*\s*(.*)", raw)
if title_match:
title = title_match.group(1).strip().rstrip(".")
content_text = title_match.group(2).strip()
else:
title = ""
content_text = raw
changelog[current_version][current_section].append(
{"title": title, "content": content_text, "raw": raw}
)
return changelog
# Parse once at import time (like Open WebUI does)
CHANGELOG = parse_changelog()
+2 -2
View File
@@ -1,7 +1,7 @@
[project]
name = "cptr"
version = "0.0.1"
description = "Your computer, from anywhere - code, manage, and control your machine from the web."
version = "0.1.0"
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
license = {file = "LICENSE"}
readme = "README.md"
requires-python = ">=3.9"