Merge pull request #154 from open-webui/main

0.9.10
This commit is contained in:
Tim Baek
2026-07-18 02:22:25 -04:00
committed by GitHub
Unverified
25 changed files with 429 additions and 195 deletions
+17
View File
@@ -5,6 +5,23 @@ 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.9.10] - 2026-07-18
### Added
- 🎚️ **You can make borders easier to see.** Appearance settings now include a border contrast control, so people who found the softer 0.9.9 borders hard to follow can make workspace sections stand out again without changing themes.
### Changed
- 🤖 **Coding-agent chats continue more naturally.** Codex, Claude Code, Cursor, Cline, Grok, and OpenCode now send your latest request into the existing agent chat instead of replaying the whole conversation back at the agent.
### Fixed
- 💬 **Open WebUI messages save even when the model arrives as a list.** Computer now accepts Open WebUI's model format and keeps the chat turn instead of dropping it during save.
- 📁 **Dropping a file onto an open folder uploads it once.** File drops on expanded folders now go only to that folder, not both the folder and the current directory.
- 🎚️ **The border contrast slider is easier to use.** The slider track and handle are more visible in light and dark mode.
- 📦 **Fresh installs avoid a known package mismatch.** Computer now stays within the supported `cryptography` release range instead of picking a newer release that can break installs.
## [0.9.9] - 2026-07-16
### Changed
@@ -763,6 +763,7 @@
if (draggedItem && (targetDir === draggedItem || targetDir.startsWith(draggedItem + '/')))
return;
e.preventDefault();
e.stopPropagation();
if (e.dataTransfer) e.dataTransfer.dropEffect = 'move';
if (dragOverDir !== targetDir) {
@@ -821,6 +822,7 @@
// Resolve actual target directory (entry itself if dir, or parent expanded dir)
const targetDir = resolveDropTarget(entry) ?? (entry.type === 'directory' ? entry.path : null);
if (!targetDir) return; // root-level file drop — container handles it
e.stopPropagation();
// Handle file browser item drag (single or multi)
if (draggedItem) {
@@ -2,10 +2,20 @@
import { toast } from 'svelte-sonner';
import Icon from '../Icon.svelte';
import { t } from '$lib/i18n';
import { expandToolDetails, textScale, theme, themeConfig, widescreenMode } from '$lib/stores';
import {
borderContrast,
expandToolDetails,
textScale,
theme,
themeConfig,
widescreenMode
} from '$lib/stores';
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
import type { Theme, ThemeConfig } from '$lib/stores';
import {
DEFAULT_BORDER_CONTRAST,
MAX_BORDER_CONTRAST,
normalizeBorderContrast,
normalizeHexColor,
resolveThemeMode,
resolveThemeConfig,
@@ -14,16 +24,19 @@
const minTextScale = 1;
const maxTextScale = 1.5;
const borderContrastStep = 0.5;
let fileInput: HTMLInputElement;
let scaleEnabled = $state(false);
let scaleDraft = $state(1);
let borderContrastEnabled = $state(false);
let borderContrastDraft = $state(DEFAULT_BORDER_CONTRAST);
let colorDrafts = $state({ background: '', foreground: '' });
const resolvedTheme = $derived(resolveThemeMode($theme));
const resolvedConfig = $derived(resolveThemeConfig($theme, $themeConfig));
const hasCustomAppearance = $derived(
Boolean($themeConfig || $textScale !== null || $widescreenMode)
Boolean($themeConfig || $textScale !== null || $borderContrast !== null || $widescreenMode)
);
$effect(() => {
@@ -37,6 +50,12 @@
} else if (!scaleEnabled) {
scaleDraft = 1;
}
if ($borderContrast !== null) {
borderContrastEnabled = true;
borderContrastDraft = $borderContrast;
} else if (!borderContrastEnabled) {
borderContrastDraft = DEFAULT_BORDER_CONTRAST;
}
});
function setTheme(v: Theme) {
@@ -78,6 +97,17 @@
}
}
function toggleBorderContrast() {
if (borderContrastEnabled) {
borderContrastEnabled = false;
borderContrastDraft = DEFAULT_BORDER_CONTRAST;
borderContrast.set(null);
} else {
borderContrastEnabled = true;
borderContrastDraft = $borderContrast ?? DEFAULT_BORDER_CONTRAST;
}
}
function normalizeTextScale(scale: number | string) {
const value = Number(scale);
if (!Number.isFinite(value)) return minTextScale;
@@ -88,6 +118,11 @@
return `${scale.toFixed(scale % 1 === 0 ? 0 : 2)}x`;
}
function borderContrastLabel(contrast: number | null) {
if (contrast === null) return $t('general.default');
return `${contrast.toFixed(contrast % 1 === 0 ? 0 : 1)}%`;
}
function setTextScalePreference(scale: number | string) {
const next = normalizeTextScale(scale);
scaleDraft = next;
@@ -100,11 +135,26 @@
}
}
function setBorderContrastPreference(contrast: number | string) {
const next = normalizeBorderContrast(contrast) ?? DEFAULT_BORDER_CONTRAST;
borderContrastDraft = next;
if (next === DEFAULT_BORDER_CONTRAST) {
borderContrastEnabled = false;
borderContrast.set(null);
} else {
borderContrastEnabled = true;
borderContrast.set(next);
}
}
function resetAppearance() {
themeConfig.set(null);
scaleEnabled = false;
scaleDraft = 1;
textScale.set(null);
borderContrastEnabled = false;
borderContrastDraft = DEFAULT_BORDER_CONTRAST;
borderContrast.set(null);
widescreenMode.set(false);
}
@@ -113,6 +163,7 @@
theme: $theme,
themeConfig: sanitizeThemeConfig($themeConfig),
textScale: $textScale,
borderContrast: $borderContrast,
widescreenMode: $widescreenMode
};
@@ -162,11 +213,15 @@
: undefined;
const importedWidescreenMode =
typeof parsed?.widescreenMode === 'boolean' ? parsed.widescreenMode : undefined;
const importedBorderContrast =
normalizeBorderContrast(parsed?.borderContrast) ??
(parsed?.highContrastBorders === true ? 12 : undefined);
if (
!importedConfig &&
!importedTheme &&
importedScale === undefined &&
importedBorderContrast === undefined &&
importedWidescreenMode === undefined
) {
throw new Error('empty theme');
@@ -174,6 +229,10 @@
if (importedTheme) theme.set(importedTheme);
if (importedConfig) themeConfig.set(importedConfig);
if (importedScale !== undefined) textScale.set(importedScale === 1 ? null : importedScale);
if (importedBorderContrast !== undefined)
borderContrast.set(
importedBorderContrast === DEFAULT_BORDER_CONTRAST ? null : importedBorderContrast
);
if (importedWidescreenMode !== undefined) widescreenMode.set(importedWidescreenMode);
toast.success($t('appearance.imported'));
} catch {
@@ -275,6 +334,59 @@
/>
</label>
<div class="w-full mt-3">
<div class="flex items-center gap-2">
<span id="border-contrast-label" class="text-xs text-gray-600 dark:text-gray-400">
{$t('appearance.borderContrast')}
</span>
<button
type="button"
class="ml-auto h-6 px-2 rounded-lg text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/6 transition-colors"
aria-live="polite"
onclick={toggleBorderContrast}
>
{borderContrastEnabled ? borderContrastLabel(borderContrastDraft) : $t('general.default')}
</button>
</div>
{#if borderContrastEnabled}
<div class="flex items-center gap-1.5 pt-1.5">
<button
type="button"
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/6 transition-colors"
aria-labelledby="border-contrast-label"
aria-label={$t('appearance.decreaseBorderContrast')}
onclick={() => setBorderContrastPreference(borderContrastDraft - borderContrastStep)}
>
<Icon name="minus" size={12} />
</button>
<input
id="border-contrast-slider"
class="appearance-range flex-1 min-w-0"
type="range"
min={DEFAULT_BORDER_CONTRAST}
max={MAX_BORDER_CONTRAST}
step={borderContrastStep}
bind:value={borderContrastDraft}
aria-labelledby="border-contrast-label"
aria-valuemin={DEFAULT_BORDER_CONTRAST}
aria-valuemax={MAX_BORDER_CONTRAST}
aria-valuenow={borderContrastDraft}
aria-valuetext={borderContrastLabel(borderContrastDraft)}
oninput={() => setBorderContrastPreference(borderContrastDraft)}
/>
<button
type="button"
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/6 transition-colors"
aria-labelledby="border-contrast-label"
aria-label={$t('appearance.increaseBorderContrast')}
onclick={() => setBorderContrastPreference(borderContrastDraft + borderContrastStep)}
>
<Icon name="plus" size={12} />
</button>
</div>
{/if}
</div>
<label class="flex items-center justify-between gap-3 mt-3">
<span class="text-xs text-gray-600 dark:text-gray-400">{$t('appearance.widescreenMode')}</span
>
@@ -316,7 +428,7 @@
</button>
<input
id="ui-scale-slider"
class="ui-scale-range flex-1 min-w-0"
class="appearance-range flex-1 min-w-0"
type="range"
min={minTextScale}
max={maxTextScale}
@@ -354,41 +466,40 @@
padding: 0.125rem;
}
.ui-scale-range {
.appearance-range {
appearance: none;
height: 1rem;
background: transparent;
cursor: pointer;
}
.ui-scale-range::-webkit-slider-runnable-track {
height: 0.125rem;
.appearance-range::-webkit-slider-runnable-track {
height: 0.1875rem;
border-radius: 624.9375rem;
background: var(--app-divider);
background: color-mix(in oklab, var(--app-fg) 24%, transparent);
}
.ui-scale-range::-webkit-slider-thumb {
.appearance-range::-webkit-slider-thumb {
appearance: none;
width: 0.75rem;
height: 0.75rem;
margin-top: -0.3125rem;
border-radius: 624.9375rem;
border: 1px solid var(--app-border);
background: var(--app-bg);
border: 1px solid color-mix(in oklab, var(--app-bg) 70%, transparent);
background: color-mix(in oklab, var(--app-fg) 82%, var(--app-bg));
}
.ui-scale-range::-moz-range-track {
height: 0.125rem;
.appearance-range::-moz-range-track {
height: 0.1875rem;
border-radius: 624.9375rem;
background: var(--app-divider);
background: color-mix(in oklab, var(--app-fg) 24%, transparent);
}
.ui-scale-range::-moz-range-thumb {
.appearance-range::-moz-range-thumb {
width: 0.75rem;
height: 0.75rem;
border-radius: 624.9375rem;
border: 1px solid var(--app-border);
background: var(--app-bg);
border: 1px solid color-mix(in oklab, var(--app-bg) 70%, transparent);
background: color-mix(in oklab, var(--app-fg) 82%, var(--app-bg));
}
</style>
@@ -963,6 +963,9 @@
"appearance.background": "Hintergrund",
"appearance.foreground": "Vordergrund",
"appearance.uiFont": "Oberflächenschrift",
"appearance.borderContrast": "Rahmenkontrast",
"appearance.decreaseBorderContrast": "Rahmenkontrast verringern",
"appearance.increaseBorderContrast": "Rahmenkontrast erhöhen",
"appearance.widescreenMode": "Breitbildmodus",
"appearance.expandToolDetails": "Aktivitäten immer erweitern",
"appearance.exported": "Design exportiert",
@@ -995,6 +995,9 @@
"appearance.background": "Background",
"appearance.foreground": "Foreground",
"appearance.uiFont": "UI font",
"appearance.borderContrast": "Border contrast",
"appearance.decreaseBorderContrast": "Decrease border contrast",
"appearance.increaseBorderContrast": "Increase border contrast",
"appearance.widescreenMode": "Widescreen Mode",
"appearance.expandToolDetails": "Always Expand Activity",
"appearance.exported": "Theme exported",
@@ -963,6 +963,9 @@
"appearance.background": "Fondo",
"appearance.foreground": "Primer plano",
"appearance.uiFont": "Fuente de interfaz",
"appearance.borderContrast": "Contraste de bordes",
"appearance.decreaseBorderContrast": "Disminuir contraste de bordes",
"appearance.increaseBorderContrast": "Aumentar contraste de bordes",
"appearance.widescreenMode": "Modo panorámico",
"appearance.expandToolDetails": "Expandir siempre la actividad",
"appearance.exported": "Tema exportado",
@@ -963,6 +963,9 @@
"appearance.background": "Arrière-plan",
"appearance.foreground": "Premier plan",
"appearance.uiFont": "Police de l’interface",
"appearance.borderContrast": "Contraste des bordures",
"appearance.decreaseBorderContrast": "Réduire le contraste des bordures",
"appearance.increaseBorderContrast": "Augmenter le contraste des bordures",
"appearance.widescreenMode": "Mode grand écran",
"appearance.expandToolDetails": "Toujours développer l’activité",
"appearance.exported": "Thème exporté",
@@ -963,6 +963,9 @@
"appearance.background": "背景",
"appearance.foreground": "前景",
"appearance.uiFont": "UIフォント",
"appearance.borderContrast": "境界線のコントラスト",
"appearance.decreaseBorderContrast": "境界線のコントラストを下げる",
"appearance.increaseBorderContrast": "境界線のコントラストを上げる",
"appearance.widescreenMode": "ワイドスクリーンモード",
"appearance.expandToolDetails": "アクティビティを常に展開",
"appearance.exported": "テーマをエクスポートしました",
@@ -963,6 +963,9 @@
"appearance.background": "배경",
"appearance.foreground": "전경",
"appearance.uiFont": "UI 글꼴",
"appearance.borderContrast": "테두리 대비",
"appearance.decreaseBorderContrast": "테두리 대비 낮추기",
"appearance.increaseBorderContrast": "테두리 대비 높이기",
"appearance.widescreenMode": "와이드스크린 모드",
"appearance.expandToolDetails": "항상 활동 펼치기",
"appearance.exported": "테마를 내보냈습니다",
@@ -963,6 +963,9 @@
"appearance.background": "Plano de fundo",
"appearance.foreground": "Primeiro plano",
"appearance.uiFont": "Fonte da interface",
"appearance.borderContrast": "Contraste das bordas",
"appearance.decreaseBorderContrast": "Diminuir contraste das bordas",
"appearance.increaseBorderContrast": "Aumentar contraste das bordas",
"appearance.widescreenMode": "Modo tela ampla",
"appearance.expandToolDetails": "Sempre expandir a atividade",
"appearance.exported": "Tema exportado",
@@ -963,6 +963,9 @@
"appearance.background": "Фон",
"appearance.foreground": "Передний план",
"appearance.uiFont": "Шрифт интерфейса",
"appearance.borderContrast": "Контраст границ",
"appearance.decreaseBorderContrast": "Уменьшить контраст границ",
"appearance.increaseBorderContrast": "Увеличить контраст границ",
"appearance.widescreenMode": "Широкоэкранный режим",
"appearance.expandToolDetails": "Всегда разворачивать действия",
"appearance.exported": "Тема экспортирована",
@@ -963,6 +963,9 @@
"appearance.background": "背景",
"appearance.foreground": "前景",
"appearance.uiFont": "界面字体",
"appearance.borderContrast": "边框对比度",
"appearance.decreaseBorderContrast": "降低边框对比度",
"appearance.increaseBorderContrast": "提高边框对比度",
"appearance.widescreenMode": "宽屏模式",
"appearance.expandToolDetails": "始终展开活动",
"appearance.exported": "主题已导出",
@@ -963,6 +963,9 @@
"appearance.background": "背景",
"appearance.foreground": "前景",
"appearance.uiFont": "介面字體",
"appearance.borderContrast": "邊框對比度",
"appearance.decreaseBorderContrast": "降低邊框對比度",
"appearance.increaseBorderContrast": "提高邊框對比度",
"appearance.widescreenMode": "寬螢幕模式",
"appearance.expandToolDetails": "一律展開活動",
"appearance.exported": "主題已匯出",
+49 -5
View File
@@ -34,6 +34,7 @@ import { defaultPwaPreferences, type PwaPreferences } from '$lib/intents/types';
import { getPathDisplayName, isSupportedWorkspacePath } from '$lib/utils/paths';
import {
applyAppearance,
normalizeBorderContrast,
sanitizeThemeConfig,
type AppearancePreferences,
type Theme,
@@ -326,6 +327,7 @@ export const streamingBehavior = writable<StreamingBehavior>('queue');
export const pwaPreferences = writable<PwaPreferences>(defaultPwaPreferences);
export const themeConfig = writable<ThemeConfig | null>(null);
export const textScale = writable<number | null>(null);
export const borderContrast = writable<number | null>(null);
export const widescreenMode = writable(false);
export const expandToolDetails = writable(false);
@@ -422,7 +424,8 @@ function persistPreferences(): void {
appearance: {
theme: get(theme),
themeConfig: sanitizeThemeConfig(get(themeConfig)),
textScale: get(textScale)
textScale: get(textScale),
borderContrast: get(borderContrast)
},
sidebarOpen: get(sidebarOpen),
sidebarWidth: get(sidebarWidth),
@@ -485,6 +488,9 @@ function subscribeForPersistence() {
textScale.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
borderContrast.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
widescreenMode.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
@@ -530,6 +536,10 @@ export async function loadPreferences(): Promise<void> {
? (prefs.textScale as number)
: null
);
borderContrast.set(
normalizeBorderContrast(appearance.borderContrast) ??
(appearance.highContrastBorders === true ? 12 : null)
);
if (prefs.widescreenMode !== undefined) widescreenMode.set(prefs.widescreenMode as boolean);
if (prefs.expandToolDetails !== undefined)
expandToolDetails.set(prefs.expandToolDetails as boolean);
@@ -749,12 +759,13 @@ export const loadStateFromServer = initState;
// ── Appearance application ──────────────────────────────────────
function applyCurrentAppearance() {
applyAppearance(get(theme), get(themeConfig), get(textScale));
applyAppearance(get(theme), get(themeConfig), get(textScale), get(borderContrast));
}
theme.subscribe(applyCurrentAppearance);
themeConfig.subscribe(applyCurrentAppearance);
textScale.subscribe(applyCurrentAppearance);
borderContrast.subscribe(applyCurrentAppearance);
if (typeof window !== 'undefined') {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
@@ -781,6 +792,10 @@ if (typeof BroadcastChannel !== 'undefined') {
if (value.theme) theme.set(value.theme);
themeConfig.set(sanitizeThemeConfig(value.themeConfig));
textScale.set(typeof value.textScale === 'number' ? value.textScale : null);
borderContrast.set(
normalizeBorderContrast(value.borderContrast) ??
(value.highContrastBorders === true ? 12 : null)
);
} else if (type === 'locale' && value) {
changeLocale(value);
}
@@ -794,7 +809,12 @@ if (typeof BroadcastChannel !== 'undefined') {
channel.postMessage({ type: 'theme', value: t });
channel.postMessage({
type: 'appearance',
value: { theme: t, themeConfig: get(themeConfig), textScale: get(textScale) }
value: {
theme: t,
themeConfig: get(themeConfig),
textScale: get(textScale),
borderContrast: get(borderContrast)
}
});
}
});
@@ -803,7 +823,12 @@ if (typeof BroadcastChannel !== 'undefined') {
if (!_syncingFromBroadcast) {
channel.postMessage({
type: 'appearance',
value: { theme: get(theme), themeConfig: config, textScale: get(textScale) }
value: {
theme: get(theme),
themeConfig: config,
textScale: get(textScale),
borderContrast: get(borderContrast)
}
});
}
});
@@ -812,7 +837,26 @@ if (typeof BroadcastChannel !== 'undefined') {
if (!_syncingFromBroadcast) {
channel.postMessage({
type: 'appearance',
value: { theme: get(theme), themeConfig: get(themeConfig), textScale: scale }
value: {
theme: get(theme),
themeConfig: get(themeConfig),
textScale: scale,
borderContrast: get(borderContrast)
}
});
}
});
borderContrast.subscribe((contrast) => {
if (!_syncingFromBroadcast) {
channel.postMessage({
type: 'appearance',
value: {
theme: get(theme),
themeConfig: get(themeConfig),
textScale: get(textScale),
borderContrast: contrast
}
});
}
});
+24 -1
View File
@@ -17,12 +17,27 @@ export type AppearancePreferences = {
theme?: Theme;
themeConfig?: ThemeConfig | null;
textScale?: number | null;
borderContrast?: number | null;
highContrastBorders?: boolean;
};
type ResolvedTheme = 'dark' | 'light';
const DEFAULT_UI_FONT =
"'Inter', -apple-system, BlinkMacSystemFont, ui-sans-serif, system-ui, sans-serif";
export const DEFAULT_BORDER_CONTRAST = 1.5;
export const DEFAULT_DIVIDER_CONTRAST = 0.875;
export const MAX_BORDER_CONTRAST = 16;
export function normalizeBorderContrast(value: unknown): number | null {
if (value === null || value === undefined || value === '') return null;
const contrast = Number(value);
if (!Number.isFinite(contrast)) return null;
return Math.max(
DEFAULT_BORDER_CONTRAST,
Math.min(MAX_BORDER_CONTRAST, Number(contrast.toFixed(1)))
);
}
export function resolveThemeMode(theme: Theme): ResolvedTheme {
if (theme === 'system' && typeof window !== 'undefined') {
@@ -103,18 +118,26 @@ function setVar(name: string, value: string) {
export function applyAppearance(
theme: Theme,
config: ThemeConfig | null,
textScale: number | null
textScale: number | null,
borderContrast: number | null = null
) {
if (typeof document === 'undefined') return;
const resolved = resolveThemeMode(theme);
const merged = resolveThemeConfig(theme, config);
const borderMix = normalizeBorderContrast(borderContrast) ?? DEFAULT_BORDER_CONTRAST;
const dividerMix =
borderMix === DEFAULT_BORDER_CONTRAST
? DEFAULT_DIVIDER_CONTRAST
: Number(((borderMix * 2) / 3).toFixed(3));
document.documentElement.classList.toggle('dark', resolved === 'dark');
document.documentElement.style.colorScheme = resolved;
setVar('--app-bg', merged.background);
setVar('--app-fg', merged.foreground);
setVar('--app-border', `color-mix(in oklab, var(--app-fg) ${borderMix}%, transparent)`);
setVar('--app-divider', `color-mix(in oklab, var(--app-fg) ${dividerMix}%, transparent)`);
setVar('--app-ui-font', merged.uiFont);
setVar('--font-sans', merged.uiFont);
+6 -1
View File
@@ -581,13 +581,18 @@ class ChatMessage(Base):
role: str,
content: str,
parent_id: str | None = None,
model: str | None = None,
model: object = None,
done: bool = True,
output: dict | list | None = None,
usage: dict | None = None,
meta: dict | None = None,
created_at: int = 0,
) -> ChatMessage:
if isinstance(model, (list, tuple)):
model = next((item.strip() for item in model if isinstance(item, str) and item.strip()), None)
elif model is not None and not isinstance(model, str):
model = str(model)
async with await get_db() as db:
msg = ChatMessage(
chat_id=chat_id,
+9 -21
View File
@@ -17,22 +17,7 @@ from cptr.utils.agents.events import (
AgentTextDelta,
AgentToolUpdate,
)
def _prompt_from_messages(messages: list[dict[str, Any]]) -> str:
parts: list[str] = []
for message in messages:
role = message.get("role", "user")
content = message.get("content", "")
if isinstance(content, list):
text = "\n".join(
str(block.get("text", "")) for block in content if isinstance(block, dict)
)
else:
text = str(content or "")
if text:
parts.append(f"[{role}]\n{text}")
return "\n\n".join(parts)
from cptr.utils.agents.prompts import latest_user_text
def _claude_query_input(
@@ -124,7 +109,7 @@ async def run_claude_code_agent(
yield AgentError("Claude Code support requires the claude-agent-sdk Python package")
return
prompt = _prompt_from_messages(messages)
prompt = latest_user_text(messages)
env = os.environ.copy()
if profile.get("home"):
env["HOME"] = os.path.expanduser(str(profile["home"]))
@@ -134,6 +119,11 @@ async def run_claude_code_agent(
extra_args = shlex.split(launch_args) if launch_args else []
try:
session_id = None
if resume_state:
value = resume_state.get("session_id")
session_id = value if isinstance(value, str) and value else None
options_kwargs: dict[str, Any] = {
"system_prompt": system_prompt or None,
"permission_mode": permission_mode,
@@ -141,6 +131,8 @@ async def run_claude_code_agent(
"include_partial_messages": True,
"max_buffer_size": CLAUDE_CODE_MAX_BUFFER_SIZE,
}
if session_id:
options_kwargs["resume"] = session_id
if workspace:
options_kwargs["cwd"] = workspace
if extra_args:
@@ -153,10 +145,6 @@ async def run_claude_code_agent(
client = sdk.ClaudeSDKClient(options)
await client.connect()
session_id = None
if resume_state:
value = resume_state.get("session_id")
session_id = value if isinstance(value, str) and value else None
try:
query_input = _claude_query_input(prompt, attachments)
+2 -19
View File
@@ -21,22 +21,7 @@ from cptr.utils.agents.events import (
AgentTextDelta,
AgentToolUpdate,
)
def _prompt_from_messages(messages: list[dict[str, Any]]) -> str:
parts: list[str] = []
for message in messages:
role = message.get("role", "user")
content = message.get("content", "")
if isinstance(content, list):
text = "\n".join(
str(block.get("text", "")) for block in content if isinstance(block, dict)
)
else:
text = str(content or "")
if text:
parts.append(f"[{role}]\n{text}")
return "\n\n".join(parts)
from cptr.utils.agents.prompts import turn_prompt_text
def _auto_approve(chat_params: dict[str, Any]) -> bool:
@@ -78,9 +63,7 @@ async def run_cline_agent(
if model != "default":
await client.set_model(model)
prompt = _prompt_from_messages(messages)
if system_prompt:
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
prompt = turn_prompt_text(messages, system_prompt, resumed=bool(session_id))
images = [
{"data": image.base64, "mimeType": image.mime_type} for image in attachments.images
+31 -20
View File
@@ -21,6 +21,7 @@ from cptr.utils.agents.events import (
AgentToolOutputDelta,
AgentToolUpdate,
)
from cptr.utils.agents.prompts import latest_user_text
CODEX_STDOUT_CHUNK_SIZE = 64 * 1024
CODEX_MAX_WIRE_MESSAGE_CHARS = 16 * 1024 * 1024
@@ -209,22 +210,6 @@ class CodexAppServer:
return "Codex app-server exited."
def _messages_to_prompt(messages: list[dict[str, Any]]) -> str:
parts: list[str] = []
for message in messages:
role = message.get("role", "user")
content = message.get("content", "")
if isinstance(content, list):
text = "\n".join(
str(block.get("text", "")) for block in content if isinstance(block, dict)
)
else:
text = str(content or "")
if text:
parts.append(f"[{role}]\n{text}")
return "\n\n".join(parts)
def _approval_policy(value: str) -> str:
return {"ask": "on-request", "auto": "on-failure", "full": "never"}.get(value, "on-failure")
@@ -254,6 +239,34 @@ def _codex_turn_options(chat_params: dict[str, Any]) -> dict[str, str]:
return options
def _resume_thread_id(resume_state: dict[str, Any] | None) -> str | None:
if not resume_state:
return None
value = resume_state.get("thread_id")
return value if isinstance(value, str) and value.strip() else None
async def _open_thread(
client: CodexAppServer,
thread_params: dict[str, Any],
resume_state: dict[str, Any] | None,
) -> str | None:
thread_id = _resume_thread_id(resume_state)
if thread_id:
try:
response = await client.request(
"thread/resume", {"threadId": thread_id, **thread_params}
)
except RuntimeError:
response = await client.request("thread/start", thread_params)
else:
response = await client.request("thread/start", thread_params)
thread = response.get("result", {}).get("thread", {})
value = thread.get("id") if isinstance(thread, dict) else None
return value if isinstance(value, str) and value else None
def _tool_from_item_event(method: str, params: dict[str, Any]) -> AgentToolUpdate | None:
if method not in {"item/started", "item/completed"}:
return None
@@ -357,14 +370,12 @@ async def run_codex_agent(
if system_prompt:
thread_params["developerInstructions"] = system_prompt
response = await client.request("thread/start", thread_params)
thread = response.get("result", {}).get("thread", {})
thread_id = thread.get("id") if isinstance(thread, dict) else None
thread_id = await _open_thread(client, thread_params, resume_state)
if not thread_id:
yield AgentError("Codex did not return a thread id")
return
prompt = _messages_to_prompt(messages)
prompt = latest_user_text(messages)
turn_input: list[dict[str, Any]] = []
if prompt:
turn_input.append({"type": "text", "text": prompt})
+2 -19
View File
@@ -21,27 +21,12 @@ from cptr.utils.agents.events import (
AgentTextDelta,
AgentToolUpdate,
)
from cptr.utils.agents.prompts import turn_prompt_text
CURSOR_CAPABILITIES = {"_meta": {"parameterizedModelPicker": True}}
def _prompt_from_messages(messages: list[dict[str, Any]]) -> str:
parts: list[str] = []
for message in messages:
role = message.get("role", "user")
content = message.get("content", "")
if isinstance(content, list):
text = "\n".join(
str(block.get("text", "")) for block in content if isinstance(block, dict)
)
else:
text = str(content or "")
if text:
parts.append(f"[{role}]\n{text}")
return "\n\n".join(parts)
def _auto_approve(chat_params: dict[str, Any]) -> bool:
if chat_params.get("tool_approval_mode") == "full":
return True
@@ -88,9 +73,7 @@ async def run_cursor_agent(
if model != "default":
await client.set_model(model)
prompt = _prompt_from_messages(messages)
if system_prompt:
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
prompt = turn_prompt_text(messages, system_prompt, resumed=bool(session_id))
images = [
{"data": image.base64, "mimeType": image.mime_type} for image in attachments.images
+2 -19
View File
@@ -21,22 +21,7 @@ from cptr.utils.agents.events import (
AgentTextDelta,
AgentToolUpdate,
)
def _prompt_from_messages(messages: list[dict[str, Any]]) -> str:
parts: list[str] = []
for message in messages:
role = message.get("role", "user")
content = message.get("content", "")
if isinstance(content, list):
text = "\n".join(
str(block.get("text", "")) for block in content if isinstance(block, dict)
)
else:
text = str(content or "")
if text:
parts.append(f"[{role}]\n{text}")
return "\n\n".join(parts)
from cptr.utils.agents.prompts import turn_prompt_text
def _auth_method(env: dict[str, str]) -> str:
@@ -83,9 +68,7 @@ async def run_grok_agent(
if model != "default":
await client.set_model(model)
prompt = _prompt_from_messages(messages)
if system_prompt:
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
prompt = turn_prompt_text(messages, system_prompt, resumed=bool(session_id))
images = [
{"data": image.base64, "mimeType": image.mime_type} for image in attachments.images
+93 -69
View File
@@ -22,22 +22,7 @@ from cptr.utils.agents.events import (
AgentTextDelta,
AgentToolUpdate,
)
def _prompt_from_messages(messages: list[dict[str, Any]]) -> str:
parts: list[str] = []
for message in messages:
role = message.get("role", "user")
content = message.get("content", "")
if isinstance(content, list):
text = "\n".join(
str(block.get("text", "")) for block in content if isinstance(block, dict)
)
else:
text = str(content or "")
if text:
parts.append(f"[{role}]\n{text}")
return "\n\n".join(parts)
from cptr.utils.agents.prompts import turn_prompt_text
def _free_port() -> int:
@@ -161,6 +146,51 @@ def _opencode_parts(prompt: str, attachments: PreparedAgentAttachments) -> list[
return parts
def _resume_session_id(resume_state: dict[str, Any] | None) -> str | None:
if not resume_state:
return None
value = resume_state.get("session_id")
return value if isinstance(value, str) and value.strip() else None
async def _create_opencode_session(
client: httpx.AsyncClient,
headers: dict[str, str],
) -> str:
session_payload = await _request(
client,
"POST",
["session.create", "session/create", "session"],
headers=headers,
json_body={"title": "cptr", "permission": []},
)
session = _session_data(session_payload)
session_id = session.get("id")
if not isinstance(session_id, str) or not session_id:
raise RuntimeError("OpenCode did not return a session id")
return session_id
async def _start_opencode_prompt(
client: httpx.AsyncClient,
headers: dict[str, str],
session_id: str,
parsed_model: dict[str, str],
parts: list[dict[str, Any]],
) -> None:
await _request(
client,
"POST",
["session.promptAsync", "session/promptAsync", "session/prompt"],
headers=headers,
json_body={
"sessionID": session_id,
"model": parsed_model,
"parts": parts,
},
)
def _text_from_event(event: dict[str, Any], emitted: dict[str, str]) -> str | None:
event_type = event.get("type")
props = event.get("properties") if isinstance(event.get("properties"), dict) else {}
@@ -239,67 +269,61 @@ async def run_opencode_agent(
resume_state: dict[str, Any] | None,
attachments: PreparedAgentAttachments,
) -> AsyncIterator[AgentEvent]:
del chat_params, resume_state
del chat_params
try:
async with _opencode_server(profile, workspace) as (server_url, _proc):
headers = _headers(profile)
async with httpx.AsyncClient(base_url=server_url, timeout=None) as client:
session_id: str | None = None
session_payload = await _request(
client,
"POST",
["session.create", "session/create", "session"],
headers=headers,
json_body={"title": "cptr", "permission": []},
)
session = _session_data(session_payload)
session_id = session.get("id")
if not isinstance(session_id, str) or not session_id:
raise RuntimeError("OpenCode did not return a session id")
session_id = _resume_session_id(resume_state)
resumed = bool(session_id)
if session_id is None:
session_id = await _create_opencode_session(client, headers)
emitted: dict[str, str] = {}
event_queue: asyncio.Queue[AgentEvent | None] = asyncio.Queue()
event_task = asyncio.create_task(
_collect_opencode_events(client, headers, session_id, emitted, event_queue)
)
prompt = _prompt_from_messages(messages)
if system_prompt:
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
parsed_model = _parse_model(model)
parts = _opencode_parts(prompt, attachments)
try:
await _request(
client,
"POST",
["session.promptAsync", "session/promptAsync", "session/prompt"],
headers=headers,
json_body={
"sessionID": session_id,
"model": parsed_model,
"parts": parts,
},
while True:
emitted: dict[str, str] = {}
event_queue: asyncio.Queue[AgentEvent | None] = asyncio.Queue()
event_task = asyncio.create_task(
_collect_opencode_events(client, headers, session_id, emitted, event_queue)
)
while True:
item = await event_queue.get()
if item is None:
break
yield item
except asyncio.CancelledError:
with suppress(Exception):
await _request(
client,
"POST",
["session.abort", "session/abort"],
headers=headers,
json_body={"sessionID": session_id},
)
raise
finally:
event_task.cancel()
with suppress(asyncio.CancelledError):
await event_task
prompt = turn_prompt_text(messages, system_prompt, resumed=resumed)
parts = _opencode_parts(prompt, attachments)
try:
try:
await _start_opencode_prompt(
client, headers, session_id, parsed_model, parts
)
except Exception:
if not resumed:
raise
event_task.cancel()
with suppress(asyncio.CancelledError):
await event_task
session_id = await _create_opencode_session(client, headers)
resumed = False
continue
while True:
item = await event_queue.get()
if item is None:
break
yield item
except asyncio.CancelledError:
with suppress(Exception):
await _request(
client,
"POST",
["session.abort", "session/abort"],
headers=headers,
json_body={"sessionID": session_id},
)
raise
finally:
event_task.cancel()
with suppress(asyncio.CancelledError):
await event_task
break
yield AgentDone(
resume_state={
+30
View File
@@ -0,0 +1,30 @@
"""Prompt helpers shared by coding agent adapters."""
from __future__ import annotations
from typing import Any
def message_text(message: dict[str, Any]) -> str:
content = message.get("content", "")
if isinstance(content, list):
return "\n".join(
str(block.get("text", "")) for block in content if isinstance(block, dict)
)
return str(content or "")
def latest_user_text(messages: list[dict[str, Any]]) -> str:
"""Return only the current user turn for native-session agents."""
for message in reversed(messages):
if message.get("role") == "user":
return message_text(message).strip()
return ""
def turn_prompt_text(messages: list[dict[str, Any]], system_prompt: str, resumed: bool) -> str:
prompt = latest_user_text(messages)
if system_prompt and not resumed:
return f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
return prompt
+2 -2
View File
@@ -1,6 +1,6 @@
[project]
name = "cptr"
version = "0.9.9"
version = "0.9.10"
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
license = {file = "LICENSE"}
readme = "README.md"
@@ -15,7 +15,7 @@ dependencies = [
"aiosqlite>=0.20",
"alembic>=1.13",
"PyJWT>=2.8",
"cryptography>=42.0",
"cryptography>=42.0,<49.0.0",
"loguru>=0.7.3",
"python-socketio[asgi]>=5.11",
"python-dateutil>=2.8",
Generated
+2 -2
View File
@@ -284,7 +284,7 @@ wheels = [
[[package]]
name = "cptr"
version = "0.9.9"
version = "0.9.10"
source = { editable = "." }
dependencies = [
{ name = "aiosqlite" },
@@ -341,7 +341,7 @@ requires-dist = [
{ name = "claude-agent-sdk", marker = "extra == 'agents'", specifier = ">=0.1.62" },
{ name = "claude-agent-sdk", marker = "extra == 'all'", specifier = ">=0.1.62" },
{ name = "click", specifier = ">=8.1" },
{ name = "cryptography", specifier = ">=42.0" },
{ name = "cryptography", specifier = ">=42.0,<49.0.0" },
{ name = "fastapi", extras = ["standard"], specifier = ">=0.128.8" },
{ name = "httpx", specifier = ">=0.28.1" },
{ name = "loguru", specifier = ">=0.7.3" },