The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(desktop): add desktop control feature with i18n and UI integration
Steven Enamakelf62d8891240e
diff --git a/.gitmodules b/.gitmodulesindex 3c8b009bd2..a55599337e 100644--- a/.gitmodules+++ b/.gitmodules@@ -54,3 +54,6 @@[submodule "vendor/tinyskills"]path = vendor/tinyskillsurl = https://github.com/tinyhumansai/tinyskills+[submodule "vendor/tinydesktop"]+ path = vendor/tinydesktop+ url = [email protected]:tinyhumansai/tinydesktop.gitdiff --git a/Cargo.lock b/Cargo.lockindex ce1a7b9034..dd4dc8c709 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4101,6 +4101,7 @@ dependencies = ["tinychannels","tinychannels-bus","tinyconnectors-bus",+ "tinydesktop-bus","tinydocs-bus","tinyflows","tinyflows-catalog",@@ -6485,7 +6486,7 @@ dependencies = [[[package]]name = "tinybus"-version = "0.1.1"+version = "0.1.2"dependencies = ["async-trait","flate2",@@ -6504,7 +6505,7 @@ dependencies = [[[package]]name = "tinybus-macros"-version = "0.1.1"+version = "0.1.2"dependencies = ["proc-macro2","quote",@@ -6597,6 +6598,14 @@ dependencies = ["serde_json",]+[[package]]+name = "tinydesktop-bus"+version = "0.2.1"+dependencies = [+ "serde",+ "serde_json",+]+[[package]]name = "tinydocs-bus"version = "0.1.16"diff --git a/app/src/components/desktop/DesktopConnectionPage.test.tsx b/app/src/components/desktop/DesktopConnectionPage.test.tsxnew file mode 100644index 0000000000..d6f99ac60e--- /dev/null+++ b/app/src/components/desktop/DesktopConnectionPage.test.tsx@@ -0,0 +1,142 @@+// @vitest-environment jsdom+import '@testing-library/jest-dom/vitest';+import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { callCoreRpc, isLocalDesktopHost } from '../../services/coreRpcClient';+import { renderWithProviders } from '../../test/test-utils';+import { openUrl } from '../../utils/openUrl';+import DesktopConnectionPage, { type DesktopStatus } from './DesktopConnectionPage';++vi.mock('../../services/coreRpcClient', () => ({+ callCoreRpc: vi.fn(),+ isLocalDesktopHost: vi.fn(async () => true),+}));+vi.mock('../../utils/openUrl', () => ({ openUrl: vi.fn().mockResolvedValue(undefined) }));++const enabled: DesktopStatus = {+ supported: true,+ enabled: true,+ platform: 'macos',+ module_state: 'ready',+ accessibility: 'granted',+ screen_recording: 'denied',+ jev_ready: true,+};++describe('Desktop connection', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(isLocalDesktopHost).mockResolvedValue(true);+ });+ afterEach(() => cleanup());++ it('shows the core permission state and performs a read-only probe', async () => {+ vi.mocked(callCoreRpc).mockImplementation(async ({ method }) => {+ if (method === 'openhuman.desktop_status') return enabled as never;+ if (method === 'openhuman.desktop_pending') return [] as never;+ if (method === 'openhuman.desktop_probe') return { ok: true, app_count: 2 } as never;+ throw new Error(`Unexpected method: ${method}`);+ });+ renderWithProviders(<DesktopConnectionPage />);++ expect(await screen.findByText('Screen Recording')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Open settings' }));+ expect(openUrl).toHaveBeenCalledWith(+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture'+ );+ fireEvent.click(screen.getByRole('button', { name: 'Test desktop access' }));+ expect(await screen.findByText('Desktop access works.')).toBeInTheDocument();+ expect(callCoreRpc).toHaveBeenCalledWith({ method: 'openhuman.desktop_probe' });+ });++ it('keeps the switch off on a failed write and surfaces the failure', async () => {+ vi.mocked(callCoreRpc).mockImplementation(async ({ method }) => {+ if (method === 'openhuman.desktop_status') return { ...enabled, enabled: false } as never;+ throw new Error('could not save setting');+ });+ renderWithProviders(<DesktopConnectionPage />);++ fireEvent.click(await screen.findByRole('button', { name: 'Enable' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('could not save setting');+ expect(screen.getByRole('button', { name: 'Enable' })).toBeInTheDocument();+ expect(callCoreRpc).toHaveBeenCalledWith({+ method: 'openhuman.desktop_set_enabled',+ params: { enabled: true },+ });+ });++ it('does not offer enablement on unsupported runtimes', async () => {+ vi.mocked(callCoreRpc).mockResolvedValue({ ...enabled, supported: false, enabled: false });+ renderWithProviders(<DesktopConnectionPage />);+ await waitFor(() =>+ expect(+ screen.getByText('Desktop control is unavailable in this runtime.')+ ).toBeInTheDocument()+ );+ expect(screen.queryByRole('button', { name: 'Enable' })).not.toBeInTheDocument();+ });++ it('does not offer a remote or browser client control over its core host', async () => {+ vi.mocked(isLocalDesktopHost).mockResolvedValue(false);+ renderWithProviders(<DesktopConnectionPage />);+ expect(+ await screen.findByText('Desktop control is unavailable in this runtime.')+ ).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Enable' })).not.toBeInTheDocument();+ expect(callCoreRpc).not.toHaveBeenCalled();+ });++ it('sends a pending action approval through the trusted core RPC', async () => {+ let approved = false;+ vi.mocked(callCoreRpc).mockImplementation(async ({ method, params }) => {+ if (method === 'openhuman.desktop_status') return enabled as never;+ if (method === 'openhuman.desktop_pending') {+ return (+ approved+ ? []+ : [+ {+ confirmation_id: 'pending-1',+ app: 'TextEdit',+ goal: 'Delete a scratch note',+ operation: 'Click',+ target_name: 'Delete',+ action_summary: "Click button 'Delete' in TextEdit",+ reason: 'This action removes the note.',+ expires_at: '2030-01-01T00:00:00Z',+ approved: false,+ },+ ]+ ) as never;+ }+ if (method === 'openhuman.desktop_confirm') {+ expect(params).toEqual({ confirmation_id: 'pending-1', approve: true });+ approved = true;+ return { confirmation_id: 'pending-1', approve: true } as never;+ }+ throw new Error(`Unexpected method: ${method}`);+ });+ renderWithProviders(<DesktopConnectionPage />);++ expect(await screen.findByText('This action removes the note.')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Approve' }));+ await waitFor(() => expect(screen.queryByText('This action removes the note.')).toBeNull());+ expect(callCoreRpc).toHaveBeenCalledWith({+ method: 'openhuman.desktop_confirm',+ params: { confirmation_id: 'pending-1', approve: true },+ });+ });++ it('surfaces a pending approval read failure instead of silently hiding it', async () => {+ vi.mocked(callCoreRpc).mockImplementation(async ({ method }) => {+ if (method === 'openhuman.desktop_status') return enabled as never;+ if (method === 'openhuman.desktop_pending') throw new Error('unavailable');+ throw new Error(`Unexpected method: ${method}`);+ });+ renderWithProviders(<DesktopConnectionPage />);+ expect(+ await screen.findByText('Could not load pending desktop approvals. Refresh to try again.')+ ).toBeInTheDocument();+ });+});diff --git a/app/src/components/desktop/DesktopConnectionPage.tsx b/app/src/components/desktop/DesktopConnectionPage.tsxnew file mode 100644index 0000000000..8a594999d9--- /dev/null+++ b/app/src/components/desktop/DesktopConnectionPage.tsx@@ -0,0 +1,317 @@+/** Local desktop automation setup in Connections. Permission truth comes from the core. */+import { useCallback, useEffect, useState } from 'react';++import { useT } from '../../lib/i18n/I18nContext';+import { callCoreRpc, isLocalDesktopHost } from '../../services/coreRpcClient';+import { openUrl } from '../../utils/openUrl';+import SettingsTabbedPage from '../settings/layout/SettingsTabbedPage';+import Button from '../ui/Button';+import Card from '../ui/Card';++export interface DesktopStatus {+ supported: boolean;+ enabled: boolean;+ platform: string;+ module_state: string;+ accessibility: string;+ screen_recording: string;+ jev_ready: boolean;+ reason?: string;+}++interface DesktopProbe {+ ok: boolean;+ app_count?: number;+ reason?: string;+}++interface DesktopPending {+ confirmation_id: string;+ app: string;+ operation: string;+ target_name: string | null;+ action_summary: string;+ reason: string;+ expires_at: string;+ approved: boolean;+}++type PermissionKind = 'accessibility' | 'screen_recording';++function permissionSettingsUrl(kind: PermissionKind, platform: string): string | null {+ if (platform === 'macos') {+ return `x-apple.systempreferences:com.apple.preference.security?Privacy_${kind === 'accessibility' ? 'Accessibility' : 'ScreenCapture'}`;+ }+ if (platform === 'windows') {+ return 'ms-settings:privacy';+ }+ return null;+}++export default function DesktopConnectionPage() {+ const { t } = useT();+ const [localHost, setLocalHost] = useState<boolean | null>(null);+ const [status, setStatus] = useState<DesktopStatus | null>(null);+ const [loading, setLoading] = useState(true);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [pendingError, setPendingError] = useState<string | null>(null);+ const [probe, setProbe] = useState<DesktopProbe | null>(null);+ const [pending, setPending] = useState<DesktopPending[]>([]);++ useEffect(() => {+ let active = true;+ void isLocalDesktopHost().then(local => {+ if (active) setLocalHost(local);+ });+ return () => {+ active = false;+ };+ }, []);++ const refreshPending = useCallback(async () => {+ try {+ const entries = await callCoreRpc<DesktopPending[]>({ method: 'openhuman.desktop_pending' });+ setPending(entries.filter(entry => !entry.approved));+ setPendingError(null);+ } catch {+ setPendingError(t('desktop.pendingUnavailable'));+ }+ }, [t]);++ const refresh = useCallback(async () => {+ if (localHost === null) return;+ setLoading(true);+ setError(null);+ try {+ setStatus(+ localHost+ ? await callCoreRpc<DesktopStatus>({ method: 'openhuman.desktop_status' })+ : {+ supported: false,+ enabled: false,+ platform: 'remote',+ module_state: 'unavailable',+ accessibility: 'not_required',+ screen_recording: 'not_required',+ jev_ready: false,+ }+ );+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setLoading(false);+ }+ }, [localHost]);++ useEffect(() => {+ void Promise.resolve().then(refresh);+ }, [refresh]);++ useEffect(() => {+ if (!status?.enabled) return;+ void Promise.resolve().then(refreshPending);+ const timer = window.setInterval(() => void refreshPending(), 5000);+ return () => window.clearInterval(timer);+ }, [status?.enabled, refreshPending]);++ const setEnabled = async () => {+ if (!localHost || !status || busy) return;+ setBusy(true);+ setError(null);+ setProbe(null);+ try {+ const next = await callCoreRpc<DesktopStatus>({+ method: 'openhuman.desktop_set_enabled',+ params: { enabled: !status.enabled },+ });+ setStatus(next);+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setBusy(false);+ }+ };++ const runProbe = async () => {+ setBusy(true);+ setError(null);+ setProbe(null);+ try {+ setProbe(await callCoreRpc<DesktopProbe>({ method: 'openhuman.desktop_probe' }));+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setBusy(false);+ }+ };++ const decide = async (confirmationId: string, approve: boolean) => {+ setBusy(true);+ setError(null);+ try {+ await callCoreRpc({+ method: 'openhuman.desktop_confirm',+ params: { confirmation_id: confirmationId, approve },+ });+ await refreshPending();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setBusy(false);+ }+ };++ const openSettings = async (kind: PermissionKind) => {+ if (!status) return;+ const url = permissionSettingsUrl(kind, status.platform);+ if (!url) return;+ try {+ await openUrl(url);+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ }+ };++ const permissionRow = (kind: PermissionKind, value: string) => {+ const label = t(`desktop.permission.${kind}`);+ const url = status && permissionSettingsUrl(kind, status.platform);+ const stateLabel =+ value === 'granted'+ ? t('common.success')+ : value === 'denied'+ ? t('common.error')+ : t('common.notAvailable');+ return (+ <div key={kind} className="flex flex-wrap items-center justify-between gap-3 py-3">+ <div>+ <p className="text-sm font-medium text-content">{label}</p>+ <p className="text-xs text-content-muted">{stateLabel}</p>+ </div>+ {value !== 'granted' && value !== 'not_required' && url && (+ <Button variant="secondary" size="sm" onClick={() => void openSettings(kind)}>+ {t('desktop.openSettings')}+ </Button>+ )}+ </div>+ );+ };++ return (+ <SettingsTabbedPage+ title={t('desktop.title')}+ description={t('desktop.description')}+ headerAction={+ <Button+ variant="secondary"+ size="sm"+ onClick={() => {+ void refresh();+ if (status?.enabled) void refreshPending();+ }}+ disabled={loading}>+ {t('common.refresh')}+ </Button>+ }>+ <div className="max-w-2xl space-y-4" data-testid="desktop-connection-page">+ <Card title={t('desktop.title')} padded divided={false}>+ {loading && <p className="text-sm text-content-muted">{t('common.loading')}</p>}+ {!loading && status && (+ <div className="space-y-4">+ <p className="text-sm text-content-secondary">+ {!status.supported+ ? t('desktop.unsupported')+ : !status.enabled+ ? t('common.disabled')+ : status.module_state === 'failed'+ ? t('desktop.moduleUnavailable')+ : status.module_state === 'ready' &&+ status.accessibility === 'granted' &&+ status.jev_ready+ ? t('channels.status.connected')+ : t('desktop.enabledPending')}+ </p>+ {status.reason && <p className="text-sm text-content-muted">{status.reason}</p>}+ <p className="text-xs text-content-muted">{t('desktop.localOnly')}</p>+ {status.supported && (+ <Button onClick={() => void setEnabled()} disabled={busy}>+ {status.enabled ? t('common.disable') : t('common.enable')}+ </Button>+ )}+ </div>+ )}+ </Card>++ {status?.supported && (+ <Card title={t('desktop.permissions')} padded>+ {permissionRow('accessibility', status.accessibility)}+ {permissionRow('screen_recording', status.screen_recording)}+ <p className="py-3 text-xs text-content-muted">{t('desktop.captureNote')}</p>+ </Card>+ )}++ {status?.supported && status.enabled && (+ <>+ {pending.length > 0 && (+ <Card title={t('chat.approval.title')} padded>+ {pending.map(entry => (+ <div key={entry.confirmation_id} className="space-y-2 py-3">+ <p className="text-sm font-medium text-content">+ {entry.target_name+ ? t('desktop.approvalSummary')+ .replace(+ '{operation}',+ t(`desktop.action.${entry.operation.toLowerCase()}`, entry.operation)+ )+ .replace('{target}', entry.target_name)+ .replace('{app}', entry.app)+ : t('common.notAvailable')}+ </p>+ <p className="text-sm text-content-muted">{entry.reason}</p>+ <div className="flex gap-2">+ <Button+ size="sm"+ disabled={busy || !entry.action_summary || !entry.target_name}+ onClick={() => void decide(entry.confirmation_id, true)}>+ {t('chat.approval.approve')}+ </Button>+ <Button+ size="sm"+ variant="secondary"+ disabled={busy}+ onClick={() => void decide(entry.confirmation_id, false)}>+ {t('chat.approval.deny')}+ </Button>+ </div>+ </div>+ ))}+ </Card>+ )}+ <Card title={t('desktop.testButton')} padded divided={false}>+ <p className="mb-3 text-sm text-content-muted">{t('desktop.testDescription')}</p>+ <Button variant="secondary" onClick={() => void runProbe()} disabled={busy}>+ {t('desktop.testButton')}+ </Button>+ {probe && (+ <p className="mt-3 text-sm" role="status">+ {probe.ok ? t('desktop.testPassed') : (probe.reason ?? t('desktop.testFailed'))}+ </p>+ )}+ </Card>+ </>+ )}++ {error && (+ <p className="text-sm text-coral-600 dark:text-coral-400" role="alert">+ {error}+ </p>+ )}+ {pendingError && (+ <p className="text-sm text-coral-600 dark:text-coral-400" role="alert">+ {pendingError}+ </p>+ )}+ </div>+ </SettingsTabbedPage>+ );+}diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.tsindex 9b71b5e4dc..f749d5a4d3 100644--- a/app/src/lib/i18n/ar.ts+++ b/app/src/lib/i18n/ar.ts@@ -816,6 +816,32 @@ const messages: TranslationMap = {'connections.tabs.meetings': 'الاجتماعات','connections.groups.integrations': 'التكاملات','connections.groups.desktop': 'سطح المكتب',+ 'desktop.approvalSummary': '{operation} «{target}» في {app}',+ 'desktop.action.click': 'انقر على',+ 'desktop.action.type_text': 'أدخل نصًا في',+ 'desktop.action.check': 'فعّل',+ 'desktop.action.uncheck': 'ألغِ التفعيل',+ 'desktop.action.expand': 'وسّع',+ 'desktop.action.collapse': 'اطوِ',+ 'desktop.action.scroll': 'مرّر',+ 'desktop.title': 'التحكم بسطح المكتب',+ 'desktop.description': 'دع وكيلك يعمل في التطبيقات على هذا الكمبيوتر.',+ 'desktop.enabledPending': 'تم التمكين. أكمل الإعداد أدناه قبل استخدام أدوات سطح المكتب.',+ 'desktop.moduleUnavailable': 'وحدة سطح المكتب غير متاحة. تحقق من حالتها وحاول مجددًا.',+ 'desktop.pendingUnavailable':+ 'تعذر تحميل موافقات سطح المكتب المعلقة. حدّث الصفحة للمحاولة مجددًا.',+ 'desktop.unsupported': 'التحكم بسطح المكتب غير متاح في بيئة التشغيل هذه.',+ 'desktop.localOnly': 'ينطبق هذا الإعداد على هذا الكمبيوتر فقط.',+ 'desktop.permissions': 'أذونات النظام',+ 'desktop.permission.accessibility': 'إمكانية الوصول',+ 'desktop.permission.screen_recording': 'تسجيل الشاشة',+ 'desktop.openSettings': 'فتح الإعدادات',+ 'desktop.captureNote':+ 'يلزم تسجيل الشاشة للقطات الشاشة فقط. وتلزم إمكانية الوصول لفحص التطبيقات والتحكم بها.',+ 'desktop.testDescription': 'تحقق من قدرة النواة على رؤية التطبيقات العاملة على هذا الكمبيوتر.',+ 'desktop.testButton': 'اختبار الوصول لسطح المكتب',+ 'desktop.testPassed': 'يعمل الوصول لسطح المكتب.',+ 'desktop.testFailed': 'تعذر التحقق من الوصول لسطح المكتب.','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'مفاتيح API',diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.tsindex 4c953f9a2e..26ab2c6a21 100644--- a/app/src/lib/i18n/bn.ts+++ b/app/src/lib/i18n/bn.ts@@ -838,6 +838,32 @@ const messages: TranslationMap = {'connections.tabs.meetings': 'মিটিং','connections.groups.integrations': 'ইন্টিগ্রেশন','connections.groups.desktop': 'ডেস্কটপ',+ 'desktop.approvalSummary': '{app}-এ “{target}” {operation}',+ 'desktop.action.click': 'ক্লিক করুন',+ 'desktop.action.type_text': 'লেখা লিখুন',+ 'desktop.action.check': 'চালু করুন',+ 'desktop.action.uncheck': 'বন্ধ করুন',+ 'desktop.action.expand': 'প্রসারিত করুন',+ 'desktop.action.collapse': 'সংকুচিত করুন',+ 'desktop.action.scroll': 'স্ক্রল করুন',+ 'desktop.title': 'ডেস্কটপ নিয়ন্ত্রণ',+ 'desktop.description': 'আপনার এজেন্টকে এই কম্পিউটারের অ্যাপে কাজ করতে দিন।',+ 'desktop.enabledPending': 'চালু আছে। ডেস্কটপ টুল ব্যবহারের আগে নিচের সেটআপ শেষ করুন।',+ 'desktop.moduleUnavailable': 'ডেস্কটপ মডিউল উপলব্ধ নয়। এর অবস্থা দেখে আবার চেষ্টা করুন।',+ 'desktop.pendingUnavailable':+ 'অপেক্ষমাণ ডেস্কটপ অনুমোদন লোড করা যায়নি। আবার চেষ্টা করতে রিফ্রেশ করুন।',+ 'desktop.unsupported': 'এই পরিবেশে ডেস্কটপ নিয়ন্ত্রণ উপলব্ধ নয়।',+ 'desktop.localOnly': 'এই সেটিং শুধু এই কম্পিউটারে প্রযোজ্য।',+ 'desktop.permissions': 'সিস্টেম অনুমতি',+ 'desktop.permission.accessibility': 'অ্যাক্সেসিবিলিটি',+ 'desktop.permission.screen_recording': 'স্ক্রিন রেকর্ডিং',+ 'desktop.openSettings': 'সেটিংস খুলুন',+ 'desktop.captureNote':+ 'শুধু স্ক্রিনশটের জন্য স্ক্রিন রেকর্ডিং লাগে। অ্যাপ দেখা ও নিয়ন্ত্রণে অ্যাক্সেসিবিলিটি লাগে।',+ 'desktop.testDescription': 'কোর এই কম্পিউটারে চলা অ্যাপ দেখতে পাচ্ছে কি না পরীক্ষা করুন।',+ 'desktop.testButton': 'ডেস্কটপ অ্যাক্সেস পরীক্ষা',+ 'desktop.testPassed': 'ডেস্কটপ অ্যাক্সেস কাজ করছে।',+ 'desktop.testFailed': 'ডেস্কটপ অ্যাক্সেস যাচাই করা যায়নি।','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'API কী',diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.tsindex 89cb783bf4..b45c4ef527 100644--- a/app/src/lib/i18n/de.ts+++ b/app/src/lib/i18n/de.ts@@ -871,6 +871,35 @@ const messages: TranslationMap = {'connections.tabs.meetings': 'Meetings','connections.groups.integrations': 'Integrationen','connections.groups.desktop': 'Desktop',+ 'desktop.approvalSummary': '{operation} „{target}“ in {app}',+ 'desktop.action.click': 'Klicke auf',+ 'desktop.action.type_text': 'Gib Text ein in',+ 'desktop.action.check': 'Aktiviere',+ 'desktop.action.uncheck': 'Deaktiviere',+ 'desktop.action.expand': 'Erweitere',+ 'desktop.action.collapse': 'Klappe ein',+ 'desktop.action.scroll': 'Scrolle',+ 'desktop.title': 'Desktopsteuerung',+ 'desktop.description': 'Lass deinen Agenten in Apps auf diesem Computer arbeiten.',+ 'desktop.enabledPending':+ 'Aktiviert. Schließe die Einrichtung unten ab, bevor du Desktopwerkzeuge verwendest.',+ 'desktop.moduleUnavailable':+ 'Das Desktopmodul ist nicht verfügbar. Prüfe seinen Status und versuche es erneut.',+ 'desktop.pendingUnavailable':+ 'Ausstehende Desktopfreigaben konnten nicht geladen werden. Aktualisiere die Seite und versuche es erneut.',+ 'desktop.unsupported': 'Die Desktopsteuerung ist in dieser Laufzeit nicht verfügbar.',+ 'desktop.localOnly': 'Diese Einstellung gilt nur für diesen Computer.',+ 'desktop.permissions': 'Systemberechtigungen',+ 'desktop.permission.accessibility': 'Bedienungshilfen',+ 'desktop.permission.screen_recording': 'Bildschirmaufnahme',+ 'desktop.openSettings': 'Einstellungen öffnen',+ 'desktop.captureNote':+ 'Die Bildschirmaufnahme wird nur für Screenshots benötigt. Bedienungshilfen sind zum Prüfen und Steuern von Apps erforderlich.',+ 'desktop.testDescription':+ 'Prüfe, ob der Core die laufenden Apps auf diesem Computer sehen kann.',+ 'desktop.testButton': 'Desktopzugriff testen',+ 'desktop.testPassed': 'Der Desktopzugriff funktioniert.',+ 'desktop.testFailed': 'Der Desktopzugriff konnte nicht überprüft werden.','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'API-Schlüssel',diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.tsindex 6a72ff30f0..432c6027ff 100644--- a/app/src/lib/i18n/en.ts+++ b/app/src/lib/i18n/en.ts@@ -681,6 +681,31 @@ const en: TranslationMap = {'connections.tabs.meetings': 'Meetings','connections.groups.integrations': 'Integrations','connections.groups.desktop': 'Desktop',+ 'desktop.approvalSummary': '{operation} “{target}” in {app}',+ 'desktop.action.click': 'Click',+ 'desktop.action.type_text': 'Enter text in',+ 'desktop.action.check': 'Check',+ 'desktop.action.uncheck': 'Uncheck',+ 'desktop.action.expand': 'Expand',+ 'desktop.action.collapse': 'Collapse',+ 'desktop.action.scroll': 'Scroll',+ 'desktop.title': 'Desktop control',+ 'desktop.description': 'Let your agent work in apps on this computer.',+ 'desktop.enabledPending': 'Enabled. Finish setup below before using desktop tools.',+ 'desktop.moduleUnavailable': 'The desktop module is unavailable. Check its status and try again.',+ 'desktop.pendingUnavailable': 'Could not load pending desktop approvals. Refresh to try again.',+ 'desktop.unsupported': 'Desktop control is unavailable in this runtime.',+ 'desktop.localOnly': 'This setting applies only to this computer.',+ 'desktop.permissions': 'System permissions',+ 'desktop.permission.accessibility': 'Accessibility',+ 'desktop.permission.screen_recording': 'Screen Recording',+ 'desktop.openSettings': 'Open settings',+ 'desktop.captureNote':+ 'Screen Recording is needed only for screenshots. Accessibility is needed to inspect and control apps.',+ 'desktop.testDescription': 'Check that the core can see the apps running on this computer.',+ 'desktop.testButton': 'Test desktop access',+ 'desktop.testPassed': 'Desktop access works.',+ 'desktop.testFailed': 'Desktop access could not be verified.','connections.groups.intelligence': 'Intelligence',// Per-tab text headers (title reuses connections.tabs.*)'connections.header.composio': 'Connect the apps your agent can act in.',diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.tsindex f2096ece18..8e332e3284 100644--- a/app/src/lib/i18n/es.ts+++ b/app/src/lib/i18n/es.ts@@ -860,6 +860,35 @@ const messages: TranslationMap = {'connections.tabs.meetings': 'Reuniones','connections.groups.integrations': 'Integraciones','connections.groups.desktop': 'Escritorio',+ 'desktop.approvalSummary': '{operation} «{target}» en {app}',+ 'desktop.action.click': 'Haz clic en',+ 'desktop.action.type_text': 'Escribe en',+ 'desktop.action.check': 'Marca',+ 'desktop.action.uncheck': 'Desmarca',+ 'desktop.action.expand': 'Expande',+ 'desktop.action.collapse': 'Contrae',+ 'desktop.action.scroll': 'Desplázate por',+ 'desktop.title': 'Control del escritorio',+ 'desktop.description': 'Permite que tu agente trabaje en las aplicaciones de este equipo.',+ 'desktop.enabledPending':+ 'Activado. Completa la configuración siguiente antes de usar las herramientas de escritorio.',+ 'desktop.moduleUnavailable':+ 'El módulo de escritorio no está disponible. Revisa su estado y vuelve a intentarlo.',+ 'desktop.pendingUnavailable':+ 'No se pudieron cargar las aprobaciones pendientes del escritorio. Actualiza para reintentarlo.',+ 'desktop.unsupported': 'El control del escritorio no está disponible en este entorno.',+ 'desktop.localOnly': 'Este ajuste solo se aplica a este equipo.',+ 'desktop.permissions': 'Permisos del sistema',+ 'desktop.permission.accessibility': 'Accesibilidad',+ 'desktop.permission.screen_recording': 'Grabación de pantalla',+ 'desktop.openSettings': 'Abrir ajustes',+ 'desktop.captureNote':+ 'La grabación de pantalla solo se necesita para las capturas. La accesibilidad permite inspeccionar y controlar aplicaciones.',+ 'desktop.testDescription':+ 'Comprueba que el núcleo pueda ver las aplicaciones abiertas en este equipo.',+ 'desktop.testButton': 'Probar acceso al escritorio',+ 'desktop.testPassed': 'El acceso al escritorio funciona.',+ 'desktop.testFailed': 'No se pudo verificar el acceso al escritorio.','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'Claves de API',diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.tsindex 24e12108be..3a38eb2a21 100644--- a/app/src/lib/i18n/fr.ts+++ b/app/src/lib/i18n/fr.ts@@ -870,6 +870,35 @@ const messages: TranslationMap = {'connections.tabs.meetings': 'Réunions','connections.groups.integrations': 'Intégrations','connections.groups.desktop': 'Bureau',+ 'desktop.approvalSummary': '{operation} « {target} » dans {app}',+ 'desktop.action.click': 'Cliquez sur',+ 'desktop.action.type_text': 'Saisissez du texte dans',+ 'desktop.action.check': 'Cochez',+ 'desktop.action.uncheck': 'Décochez',+ 'desktop.action.expand': 'Développez',+ 'desktop.action.collapse': 'Réduisez',+ 'desktop.action.scroll': 'Faites défiler',+ 'desktop.title': 'Contrôle du bureau',+ 'desktop.description': 'Laissez votre agent travailler dans les applications de cet ordinateur.',+ 'desktop.enabledPending':+ 'Activé. Terminez la configuration ci-dessous avant d’utiliser les outils du bureau.',+ 'desktop.moduleUnavailable':+ 'Le module du bureau est indisponible. Vérifiez son état et réessayez.',+ 'desktop.pendingUnavailable':+ 'Impossible de charger les approbations du bureau en attente. Actualisez pour réessayer.',+ 'desktop.unsupported': 'Le contrôle du bureau n’est pas disponible dans cet environnement.',+ 'desktop.localOnly': 'Ce réglage ne s’applique qu’à cet ordinateur.',+ 'desktop.permissions': 'Autorisations système',+ 'desktop.permission.accessibility': 'Accessibilité',+ 'desktop.permission.screen_recording': 'Enregistrement de l’écran',+ 'desktop.openSettings': 'Ouvrir les réglages',+ 'desktop.captureNote':+ 'L’enregistrement de l’écran ne sert qu’aux captures. L’accessibilité permet d’inspecter et de contrôler les applications.',+ 'desktop.testDescription':+ 'Vérifiez que le cœur peut voir les applications ouvertes sur cet ordinateur.',+ 'desktop.testButton': 'Tester l’accès au bureau',+ 'desktop.testPassed': 'L’accès au bureau fonctionne.',+ 'desktop.testFailed': 'Impossible de vérifier l’accès au bureau.','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'Clés API',diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.tsindex ed123947a0..eab3684797 100644--- a/app/src/lib/i18n/hi.ts+++ b/app/src/lib/i18n/hi.ts@@ -838,6 +838,33 @@ const messages: TranslationMap = {'connections.tabs.meetings': 'मीटिंग','connections.groups.integrations': 'इंटीग्रेशन','connections.groups.desktop': 'डेस्कटॉप',+ 'desktop.approvalSummary': '{app} में “{target}” पर {operation}',+ 'desktop.action.click': 'क्लिक करें',+ 'desktop.action.type_text': 'लिखें',+ 'desktop.action.check': 'चुनें',+ 'desktop.action.uncheck': 'चयन हटाएँ',+ 'desktop.action.expand': 'फैलाएँ',+ 'desktop.action.collapse': 'समेटें',+ 'desktop.action.scroll': 'स्क्रॉल करें',+ 'desktop.title': 'डेस्कटॉप नियंत्रण',+ 'desktop.description': 'अपने एजेंट को इस कंप्यूटर के ऐप्स में काम करने दें।',+ 'desktop.enabledPending': 'चालू है। डेस्कटॉप टूल इस्तेमाल करने से पहले नीचे का सेटअप पूरा करें।',+ 'desktop.moduleUnavailable':+ 'डेस्कटॉप मॉड्यूल उपलब्ध नहीं है। इसकी स्थिति जाँचकर फिर कोशिश करें।',+ 'desktop.pendingUnavailable':+ 'लंबित डेस्कटॉप अनुमोदन लोड नहीं हो सके। फिर कोशिश करने के लिए रीफ़्रेश करें।',+ 'desktop.unsupported': 'इस रनटाइम में डेस्कटॉप नियंत्रण उपलब्ध नहीं है।',+ 'desktop.localOnly': 'यह सेटिंग केवल इस कंप्यूटर पर लागू होती है।',+ 'desktop.permissions': 'सिस्टम अनुमतियाँ',+ 'desktop.permission.accessibility': 'एक्सेसिबिलिटी',+ 'desktop.permission.screen_recording': 'स्क्रीन रिकॉर्डिंग',+ 'desktop.openSettings': 'सेटिंग्स खोलें',+ 'desktop.captureNote':+ 'स्क्रीन रिकॉर्डिंग केवल स्क्रीनशॉट के लिए चाहिए। ऐप्स देखने और नियंत्रित करने के लिए एक्सेसिबिलिटी चाहिए।',+ 'desktop.testDescription': 'जाँचें कि कोर इस कंप्यूटर पर चल रहे ऐप्स देख सकता है।',+ 'desktop.testButton': 'डेस्कटॉप एक्सेस जाँचें',+ 'desktop.testPassed': 'डेस्कटॉप एक्सेस काम कर रहा है।',+ 'desktop.testFailed': 'डेस्कटॉप एक्सेस सत्यापित नहीं हो सका।','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'API कुंजियाँ',diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.tsindex 2dd781baac..3714494f71 100644--- a/app/src/lib/i18n/id.ts+++ b/app/src/lib/i18n/id.ts@@ -849,6 +849,34 @@ const messages: TranslationMap = {'connections.tabs.meetings': 'Rapat','connections.groups.integrations': 'Integrasi','connections.groups.desktop': 'Desktop',+ 'desktop.approvalSummary': '{operation} “{target}” di {app}',+ 'desktop.action.click': 'Klik',+ 'desktop.action.type_text': 'Masukkan teks ke',+ 'desktop.action.check': 'Centang',+ 'desktop.action.uncheck': 'Hapus centang',+ 'desktop.action.expand': 'Perluas',+ 'desktop.action.collapse': 'Ciutkan',+ 'desktop.action.scroll': 'Gulir',+ 'desktop.title': 'Kontrol desktop',+ 'desktop.description': 'Izinkan agen Anda bekerja di aplikasi pada komputer ini.',+ 'desktop.enabledPending':+ 'Diaktifkan. Selesaikan penyiapan di bawah sebelum memakai alat desktop.',+ 'desktop.moduleUnavailable': 'Modul desktop tidak tersedia. Periksa statusnya dan coba lagi.',+ 'desktop.pendingUnavailable':+ 'Persetujuan desktop yang tertunda tidak dapat dimuat. Segarkan untuk mencoba lagi.',+ 'desktop.unsupported': 'Kontrol desktop tidak tersedia di lingkungan ini.',+ 'desktop.localOnly': 'Pengaturan ini hanya berlaku untuk komputer ini.',+ 'desktop.permissions': 'Izin sistem',+ 'desktop.permission.accessibility': 'Aksesibilitas',+ 'desktop.permission.screen_recording': 'Perekaman layar',+ 'desktop.openSettings': 'Buka pengaturan',+ 'desktop.captureNote':+ 'Perekaman layar hanya diperlukan untuk tangkapan layar. Aksesibilitas diperlukan untuk memeriksa dan mengendalikan aplikasi.',+ 'desktop.testDescription':+ 'Periksa apakah inti dapat melihat aplikasi yang berjalan di komputer ini.',+ 'desktop.testButton': 'Uji akses desktop',+ 'desktop.testPassed': 'Akses desktop berfungsi.',+ 'desktop.testFailed': 'Akses desktop tidak dapat diverifikasi.','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'Kunci API',diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.tsindex febb897a88..77f8d559f3 100644--- a/app/src/lib/i18n/it.ts+++ b/app/src/lib/i18n/it.ts@@ -860,6 +860,34 @@ const messages: TranslationMap = {'connections.tabs.meetings': 'Riunioni','connections.groups.integrations': 'Integrazioni','connections.groups.desktop': 'Desktop',+ 'desktop.approvalSummary': '{operation} “{target}” nell’app {app}',+ 'desktop.action.click': 'Fai clic su',+ 'desktop.action.type_text': 'Scrivi in',+ 'desktop.action.check': 'Seleziona',+ 'desktop.action.uncheck': 'Deseleziona',+ 'desktop.action.expand': 'Espandi',+ 'desktop.action.collapse': 'Comprimi',+ 'desktop.action.scroll': 'Scorri',+ 'desktop.title': 'Controllo desktop',+ 'desktop.description': 'Consenti al tuo agente di usare le app su questo computer.',+ 'desktop.enabledPending':+ 'Attivato. Completa la configurazione qui sotto prima di usare gli strumenti desktop.',+ 'desktop.moduleUnavailable': 'Il modulo desktop non è disponibile. Controlla lo stato e riprova.',+ 'desktop.pendingUnavailable':+ 'Impossibile caricare le approvazioni desktop in attesa. Aggiorna per riprovare.',+ 'desktop.unsupported': 'Il controllo desktop non è disponibile in questo ambiente.',+ 'desktop.localOnly': 'Questa impostazione vale solo per questo computer.',+ 'desktop.permissions': 'Autorizzazioni di sistema',+ 'desktop.permission.accessibility': 'Accessibilità',+ 'desktop.permission.screen_recording': 'Registrazione schermo',+ 'desktop.openSettings': 'Apri impostazioni',+ 'desktop.captureNote':+ 'La registrazione schermo serve solo per gli screenshot. L’accessibilità serve per esaminare e controllare le app.',+ 'desktop.testDescription':+ 'Verifica che il core possa vedere le app in esecuzione su questo computer.',+ 'desktop.testButton': 'Verifica accesso desktop',+ 'desktop.testPassed': 'L’accesso desktop funziona.',+ 'desktop.testFailed': 'Impossibile verificare l’accesso desktop.','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'Chiavi API',diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.tsindex ae853c5b56..24039d018c 100644--- a/app/src/lib/i18n/ko.ts+++ b/app/src/lib/i18n/ko.ts@@ -830,6 +830,34 @@ const messages: TranslationMap = {'connections.tabs.meetings': '미팅','connections.groups.integrations': '통합','connections.groups.desktop': '데스크톱',+ 'desktop.approvalSummary': '{app}에서 “{target}” {operation}',+ 'desktop.action.click': '클릭',+ 'desktop.action.type_text': '텍스트 입력',+ 'desktop.action.check': '선택',+ 'desktop.action.uncheck': '선택 해제',+ 'desktop.action.expand': '펼치기',+ 'desktop.action.collapse': '접기',+ 'desktop.action.scroll': '스크롤',+ 'desktop.title': '데스크톱 제어',+ 'desktop.description': '에이전트가 이 컴퓨터의 앱에서 작업하도록 허용합니다.',+ 'desktop.enabledPending':+ '활성화되었습니다. 데스크톱 도구를 사용하기 전에 아래 설정을 완료하세요.',+ 'desktop.moduleUnavailable':+ '데스크톱 모듈을 사용할 수 없습니다. 상태를 확인하고 다시 시도하세요.',+ 'desktop.pendingUnavailable':+ '대기 중인 데스크톱 승인을 불러올 수 없습니다. 새로고침 후 다시 시도하세요.',+ 'desktop.unsupported': '이 실행 환경에서는 데스크톱 제어를 사용할 수 없습니다.',+ 'desktop.localOnly': '이 설정은 이 컴퓨터에만 적용됩니다.',+ 'desktop.permissions': '시스템 권한',+ 'desktop.permission.accessibility': '손쉬운 사용',+ 'desktop.permission.screen_recording': '화면 기록',+ 'desktop.openSettings': '설정 열기',+ 'desktop.captureNote':+ '화면 기록은 스크린샷에만 필요합니다. 앱을 살펴보고 제어하려면 손쉬운 사용 권한이 필요합니다.',+ 'desktop.testDescription': '코어가 이 컴퓨터에서 실행 중인 앱을 볼 수 있는지 확인합니다.',+ 'desktop.testButton': '데스크톱 접근 테스트',+ 'desktop.testPassed': '데스크톱 접근이 작동합니다.',+ 'desktop.testFailed': '데스크톱 접근을 확인할 수 없습니다.','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'API 키',diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.tsindex a3bc743371..2a2201f871 100644--- a/app/src/lib/i18n/pl.ts+++ b/app/src/lib/i18n/pl.ts@@ -854,6 +854,34 @@ const messages: TranslationMap = {'connections.tabs.meetings': 'Spotkania','connections.groups.integrations': 'Integracje','connections.groups.desktop': 'Pulpit',+ 'desktop.approvalSummary': '{operation} „{target}” w {app}',+ 'desktop.action.click': 'Kliknij',+ 'desktop.action.type_text': 'Wpisz tekst w',+ 'desktop.action.check': 'Zaznacz',+ 'desktop.action.uncheck': 'Odznacz',+ 'desktop.action.expand': 'Rozwiń',+ 'desktop.action.collapse': 'Zwiń',+ 'desktop.action.scroll': 'Przewiń',+ 'desktop.title': 'Sterowanie pulpitem',+ 'desktop.description': 'Pozwól agentowi pracować w aplikacjach na tym komputerze.',+ 'desktop.enabledPending':+ 'Włączono. Dokończ konfigurację poniżej przed użyciem narzędzi pulpitu.',+ 'desktop.moduleUnavailable':+ 'Moduł pulpitu jest niedostępny. Sprawdź jego stan i spróbuj ponownie.',+ 'desktop.pendingUnavailable':+ 'Nie udało się wczytać oczekujących zgód na dostęp do pulpitu. Odśwież, aby spróbować ponownie.',+ 'desktop.unsupported': 'Sterowanie pulpitem jest niedostępne w tym środowisku.',+ 'desktop.localOnly': 'To ustawienie dotyczy tylko tego komputera.',+ 'desktop.permissions': 'Uprawnienia systemowe',+ 'desktop.permission.accessibility': 'Dostępność',+ 'desktop.permission.screen_recording': 'Nagrywanie ekranu',+ 'desktop.openSettings': 'Otwórz ustawienia',+ 'desktop.captureNote':+ 'Nagrywanie ekranu jest potrzebne tylko do zrzutów. Dostępność pozwala sprawdzać i obsługiwać aplikacje.',+ 'desktop.testDescription': 'Sprawdź, czy rdzeń widzi aplikacje uruchomione na tym komputerze.',+ 'desktop.testButton': 'Sprawdź dostęp do pulpitu',+ 'desktop.testPassed': 'Dostęp do pulpitu działa.',+ 'desktop.testFailed': 'Nie udało się potwierdzić dostępu do pulpitu.','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'Klucze API',diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.tsindex f893154c0b..5af8809045 100644--- a/app/src/lib/i18n/pt.ts+++ b/app/src/lib/i18n/pt.ts@@ -858,6 +858,35 @@ const messages: TranslationMap = {'connections.tabs.meetings': 'Reuniões','connections.groups.integrations': 'Integrações','connections.groups.desktop': 'Área de trabalho',+ 'desktop.approvalSummary': '{operation} “{target}” em {app}',+ 'desktop.action.click': 'Clique em',+ 'desktop.action.type_text': 'Digite texto em',+ 'desktop.action.check': 'Marque',+ 'desktop.action.uncheck': 'Desmarque',+ 'desktop.action.expand': 'Expanda',+ 'desktop.action.collapse': 'Recolha',+ 'desktop.action.scroll': 'Role',+ 'desktop.title': 'Controle do computador',+ 'desktop.description': 'Permita que seu agente trabalhe nos aplicativos deste computador.',+ 'desktop.enabledPending':+ 'Ativado. Conclua a configuração abaixo antes de usar as ferramentas do computador.',+ 'desktop.moduleUnavailable':+ 'O módulo de desktop está indisponível. Verifique o estado e tente novamente.',+ 'desktop.pendingUnavailable':+ 'Não foi possível carregar as aprovações de desktop pendentes. Atualize para tentar novamente.',+ 'desktop.unsupported': 'O controle do computador não está disponível neste ambiente.',+ 'desktop.localOnly': 'Esta configuração vale apenas para este computador.',+ 'desktop.permissions': 'Permissões do sistema',+ 'desktop.permission.accessibility': 'Acessibilidade',+ 'desktop.permission.screen_recording': 'Gravação de tela',+ 'desktop.openSettings': 'Abrir configurações',+ 'desktop.captureNote':+ 'A gravação de tela só é necessária para capturas. A acessibilidade é necessária para inspecionar e controlar aplicativos.',+ 'desktop.testDescription':+ 'Verifique se o núcleo consegue ver os aplicativos em execução neste computador.',+ 'desktop.testButton': 'Testar acesso ao computador',+ 'desktop.testPassed': 'O acesso ao computador funciona.',+ 'desktop.testFailed': 'Não foi possível verificar o acesso ao computador.','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'Chaves de API',diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex 74369b3d03..6f0fda8026 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -849,6 +849,34 @@ const messages: TranslationMap = {'connections.tabs.meetings': 'Встречи','connections.groups.integrations': 'Интеграции','connections.groups.desktop': 'Рабочий стол',+ 'desktop.approvalSummary': '{operation} «{target}» в {app}',+ 'desktop.action.click': 'Нажать',+ 'desktop.action.type_text': 'Ввести текст в',+ 'desktop.action.check': 'Отметить',+ 'desktop.action.uncheck': 'Снять отметку',+ 'desktop.action.expand': 'Развернуть',+ 'desktop.action.collapse': 'Свернуть',+ 'desktop.action.scroll': 'Прокрутить',+ 'desktop.title': 'Управление рабочим столом',+ 'desktop.description': 'Разрешите агенту работать с приложениями на этом компьютере.',+ 'desktop.enabledPending':+ 'Включено. Завершите настройку ниже перед использованием инструментов рабочего стола.',+ 'desktop.moduleUnavailable':+ 'Модуль рабочего стола недоступен. Проверьте его состояние и повторите попытку.',+ 'desktop.pendingUnavailable':+ 'Не удалось загрузить ожидающие подтверждения действий на рабочем столе. Обновите страницу и повторите попытку.',+ 'desktop.unsupported': 'Управление рабочим столом недоступно в этой среде.',+ 'desktop.localOnly': 'Эта настройка действует только на этом компьютере.',+ 'desktop.permissions': 'Системные разрешения',+ 'desktop.permission.accessibility': 'Универсальный доступ',+ 'desktop.permission.screen_recording': 'Запись экрана',+ 'desktop.openSettings': 'Открыть настройки',+ 'desktop.captureNote':+ 'Запись экрана нужна только для снимков. Универсальный доступ нужен для просмотра приложений и управления ими.',+ 'desktop.testDescription': 'Проверьте, видит ли ядро приложения, запущенные на этом компьютере.',+ 'desktop.testButton': 'Проверить доступ к рабочему столу',+ 'desktop.testPassed': 'Доступ к рабочему столу работает.',+ 'desktop.testFailed': 'Не удалось проверить доступ к рабочему столу.','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'API-ключи',diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.tsindex 57bf07de4e..bb37c34426 100644--- a/app/src/lib/i18n/zh-CN.ts+++ b/app/src/lib/i18n/zh-CN.ts@@ -780,6 +780,30 @@ const messages: TranslationMap = {'connections.tabs.meetings': '会议','connections.groups.integrations': '集成','connections.groups.desktop': '桌面',+ 'desktop.approvalSummary': '在 {app} 中{operation}“{target}”',+ 'desktop.action.click': '点击',+ 'desktop.action.type_text': '输入文字到',+ 'desktop.action.check': '勾选',+ 'desktop.action.uncheck': '取消勾选',+ 'desktop.action.expand': '展开',+ 'desktop.action.collapse': '折叠',+ 'desktop.action.scroll': '滚动',+ 'desktop.title': '桌面控制',+ 'desktop.description': '让智能体操作这台电脑上的应用。',+ 'desktop.enabledPending': '已启用。使用桌面工具前,请完成下方设置。',+ 'desktop.moduleUnavailable': '桌面模块不可用。请检查其状态并重试。',+ 'desktop.pendingUnavailable': '无法加载待处理的桌面操作审批。请刷新后重试。',+ 'desktop.unsupported': '此运行环境不支持桌面控制。',+ 'desktop.localOnly': '此设置仅适用于这台电脑。',+ 'desktop.permissions': '系统权限',+ 'desktop.permission.accessibility': '辅助功能',+ 'desktop.permission.screen_recording': '屏幕录制',+ 'desktop.openSettings': '打开设置',+ 'desktop.captureNote': '仅截图需要屏幕录制权限。查看和控制应用需要辅助功能权限。',+ 'desktop.testDescription': '检查核心能否看到这台电脑上运行的应用。',+ 'desktop.testButton': '测试桌面访问',+ 'desktop.testPassed': '桌面访问正常。',+ 'desktop.testFailed': '无法验证桌面访问。','connections.tabs.oauth': 'OAuth','connections.tabs.composioKey': 'Composio','connections.groups.apiKeys': 'API 密钥',diff --git a/app/src/pages/Skills.tsx b/app/src/pages/Skills.tsxindex 5cfdfb53e3..d35d533d57 100644--- a/app/src/pages/Skills.tsx+++ b/app/src/pages/Skills.tsx@@ -9,6 +9,7 @@ import {type ComposioToolkitMeta,KNOWN_COMPOSIO_TOOLKITS,} from '../components/composio/toolkitMeta';+import DesktopConnectionPage from '../components/desktop/DesktopConnectionPage';import EmptyStateCard from '../components/EmptyStateCard';import { ToastContainer } from '../components/intelligence/Toast';import PageSectionHeader from '../components/layout/PageSectionHeader';@@ -451,7 +452,8 @@ type ConnectionsTab =| 'search'| 'usage'| 'composio-key'- | 'wallet';+ | 'wallet'+ | 'desktop';/*** Tabs that render a relocated settings panel inside the shared card surface.@@ -492,6 +494,7 @@ const SELF_HEADER_TABS: ReadonlySet<ConnectionsTab> = new Set<ConnectionsTab>(['composio-key','usage','wallet',+ 'desktop',]);const INTELLIGENCE_TABS: ReadonlySet<ConnectionsTab> = new Set<ConnectionsTab>([@@ -502,6 +505,7 @@ const INTELLIGENCE_TABS: ReadonlySet<ConnectionsTab> = new Set<ConnectionsTab>(['usage','composio-key','wallet',+ 'desktop',]);export default function Skills() {@@ -529,7 +533,8 @@ export default function Skills() {raw === 'search' ||raw === 'usage' ||raw === 'composio-key' ||- raw === 'wallet'+ raw === 'wallet' ||+ raw === 'desktop')return raw;// Legacy back-compat aliases@@ -1022,6 +1027,16 @@ export default function Skills() {},],},+ {+ label: t('connections.groups.desktop'),+ items: [+ {+ value: 'desktop',+ label: t('desktop.title'),+ icon: navIcon('M4 5h16v11H4zM8 20h8m-4-4v4'),+ },+ ],+ },]}/></div>@@ -1130,6 +1145,7 @@ export default function Skills() {</SettingsTabbedPage>)}{activeTab === 'wallet' && <WalletPanel />}+ {activeTab === 'desktop' && <DesktopConnectionPage />}</SettingsLayoutProvider>) : (<>diff --git a/app/src/pages/__tests__/Skills.tab-resolution.test.tsx b/app/src/pages/__tests__/Skills.tab-resolution.test.tsxindex 61e32710bd..46abea3981 100644--- a/app/src/pages/__tests__/Skills.tab-resolution.test.tsx+++ b/app/src/pages/__tests__/Skills.tab-resolution.test.tsx@@ -59,6 +59,9 @@ vi.mock('../../components/skills/SkillsExplorerTab', () => ({vi.mock('../../components/channels/mcp/McpServersPage', () => ({default: () => <div data-testid="tab-body-mcp-servers" />,}));+vi.mock('../../components/desktop/DesktopConnectionPage', () => ({+ default: () => <div data-testid="tab-body-desktop" />,+}));vi.mock('../../lib/skills/skillsApi', () => ({installSkill: vi.fn().mockResolvedValue(undefined),@@ -152,7 +155,7 @@ describe('Connections ?tab= resolution — legacy aliases', () => {});describe('Connections ?tab= resolution — canonical values', () => {- it.each([['composio'], ['channels'], ['mcp'], ['skills'], ['wallet']])(+ it.each([['composio'], ['channels'], ['mcp'], ['skills'], ['wallet'], ['desktop']])('?tab=%s passes through unchanged',async tab => {renderAt(`?tab=${tab}`);diff --git a/app/src/services/__tests__/coreRpcClient.test.ts b/app/src/services/__tests__/coreRpcClient.test.tsindex 7bc413d001..3f39f0ae83 100644--- a/app/src/services/__tests__/coreRpcClient.test.ts+++ b/app/src/services/__tests__/coreRpcClient.test.ts@@ -486,6 +486,26 @@ describe('coreRpcClient', () => {expect(headers.Authorization).toBe('Bearer test-local-token');});+ test('desktop setup follows the resolved shell endpoint, not the loopback build default', async () => {+ vi.resetModules();+ vi.mocked(isTauri).mockReturnValue(true);+ vi.stubGlobal('__TAURI_INTERNALS__', { invoke: vi.fn() });+ vi.mocked(invoke).mockImplementation(async (cmd: string) => {+ if (cmd === 'core_rpc_endpoint') {+ return { url: 'https://remote.example/rpc', token: 'test-remote-token' };+ }+ throw new Error(`unexpected command: ${cmd}`);+ });+ const { isLocalDesktopHost: checkLocalHost } = await import('../coreRpcClient');+ try {+ expect(await checkLocalHost()).toBe(false);+ expect(invoke).toHaveBeenCalledWith('core_rpc_endpoint');+ } finally {+ vi.mocked(isTauri).mockReturnValue(false);+ vi.unstubAllGlobals();+ }+ });+test('fails closed in Tauri mode when core rpc token is unavailable', async () => {vi.resetModules();vi.mocked(isTauri).mockReturnValue(true);diff --git a/app/src/services/coreRpcClient.ts b/app/src/services/coreRpcClient.tsindex 7c6942735a..a5aeef68d0 100644--- a/app/src/services/coreRpcClient.ts+++ b/app/src/services/coreRpcClient.ts@@ -1,4 +1,4 @@-import { invoke } from '@tauri-apps/api/core';+import { invoke, isTauri as isTauriRuntime } from '@tauri-apps/api/core';import debug from 'debug';import { dispatchLocalAiMethod } from '../lib/ai/localCoreAiMemory';@@ -96,6 +96,17 @@ let resolvingShellEndpoint: Promise<{ url: string; token: string } | null> | nul/** Active transport set by TransportManager for non-local profiles. */let _activeTransport: CoreTransport | null = null;+/** Desktop controls in the UI target only the native app's resolved local core. */+export async function isLocalDesktopHost(): Promise<boolean> {+ if (!isTauriRuntime() || _activeTransport !== null) return false;+ try {+ const host = new URL(await getCoreRpcUrl()).hostname;+ return host === '127.0.0.1' || host === 'localhost' || host === '[::1]';+ } catch {+ return false;+ }+}+/*** Override the active transport used by `callCoreRpc`.* Set to null to revert to the default local HTTP path.diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lockindex 7fbad240b1..6fabc18d9e 100644--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@ -4301,6 +4301,7 @@ dependencies = ["tinychannels","tinychannels-bus","tinyconnectors-bus",+ "tinydesktop-bus","tinydocs-bus","tinyflows","tinyflows-catalog",@@ -7193,7 +7194,7 @@ dependencies = [[[package]]name = "tinybus"-version = "0.1.1"+version = "0.1.2"dependencies = ["async-trait","flate2",@@ -7212,7 +7213,7 @@ dependencies = [[[package]]name = "tinybus-macros"-version = "0.1.1"+version = "0.1.2"dependencies = ["proc-macro2","quote",@@ -7301,6 +7302,14 @@ dependencies = ["serde_json",]+[[package]]+name = "tinydesktop-bus"+version = "0.2.1"+dependencies = [+ "serde",+ "serde_json",+]+[[package]]name = "tinydocs-bus"version = "0.1.16"diff --git a/crates/openhuman-app/capabilities/default.json b/crates/openhuman-app/capabilities/default.jsonindex e540b87f4e..488539bf5d 100644--- a/crates/openhuman-app/capabilities/default.json+++ b/crates/openhuman-app/capabilities/default.json@@ -25,7 +25,10 @@"identifier": "opener:allow-open-url","allow": [{ "url": "obsidian://open*" },- { "url": "https://ollama.com/*" }+ { "url": "https://ollama.com/*" },+ { "url": "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" },+ { "url": "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture" },+ { "url": "ms-settings:privacy" }]},"updater:default",diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex 9686077d7b..188a6a2795 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -332,6 +332,7 @@ tinychannels = { version = "0.1", features = ["relay-websocket"], optional = tru# --features flows` would carry `ureq` and the archive stack for a host that# never loads a module. The kernel-floor ratchet catches exactly that, and did.tinybus = { path = "../../vendor/tinybus/crates/tinybus", default-features = false, features = ["macros", "uds"] }+tinydesktop-bus = { path = "../../vendor/tinydesktop/crates/tinydesktop-bus" }# Portable skill metadata, parsing, discovery, and filesystem hardening.tinyskills = { path = "../../vendor/tinyskills/crates/tinyskills" }serde = { version = "1", features = ["derive"] }diff --git a/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.md b/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.mdindex b0c54326ea..857ddb8b16 100644--- a/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.md+++ b/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.md@@ -4,6 +4,7 @@ Take the first branch that applies:1. **Answerable without tools**: reply. Small talk, simple Q&A, general knowledge.1b. **Needs a capability you do not see listed**: `tool_search` with the intent in plain words before delegating or declining; if nothing comes back, say so.+Desktop control, when enabled, is available through `tool_search`.2. **Needs a connected service's own data or actions** (inbox, messages, calendar, docs, tickets, "send/check X"): `tool_search` for the action ("send an email", "list calendar events"), then call what it returns. No sub-agent runs it for you, and an announced search never runs: emit it. Use the live service even when memory could plausibly answer. A service being connected is not a reason to touch it: general knowledge, web/news lookups, headlines, date/time, math, and anything public on the web (a public repository, a product page, docs) never go to a service; those are `web_fetch` / `web_search_tool` / `research` work. Reach for a toolkit only for the user's own account data or actions on it. Not connected? Raise a connect card with `composio_connect`: the list shows what is connected, not what is connectable, so never refuse from it or send the user to settings, and never paste OAuth URLs. If the connect call reports the toolkit unavailable, relay its message; that is the only honest refusal.3. **Solvable with a direct tool**: do it yourself. `web_search_tool` and `web_fetch` for a fact or a page, `memory_recall` and `memory_store` for the user's own facts, `shell` plus `apply_patch` for repository work. Keep code work end-to-end: edit and verify in the same turn; never delegate merely because a task touches a repository.4. **Needs a specialist**: the specialists you can call are in your tool list with their own descriptions. **Capabilities not in your tool list** names the ones a skill holds; reach those through `use_skill`. Workers return only their result; carry out any `## Handoff Plan` they return yourself, under the approval gate.diff --git a/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs b/crates/openhuman-core/src/agent/tinyagents/host/bundle.rsindex 0924545c24..8d59d19a66 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs@@ -150,10 +150,21 @@ impl OpenHumanHostBundleFactory {.map(|tool| tool.name().to_string()).collect(),);+ let session_deferred_tools = Arc::new(+ inputs+ .tool_sets+ .iter()+ .flat_map(|set| set.iter())+ .filter(|tool| tool.exposure() == tinytools::ToolExposure::Deferred)+ .map(|tool| tool.name().to_owned())+ .collect(),+ );let mut definitions_adapter = OpenHumanDefinitionRegistry::new(inputs.definitions).with_config(Arc::clone(&inputs.config)).with_registered_tools(registered_tools).with_session_delegation_tools(session_delegation_tools);+ definitions_adapter =+ definitions_adapter.with_session_deferred_tools(session_deferred_tools);if let Some(definition) = inputs.session_definition {definitions_adapter = definitions_adapter.with_session_definition(definition);}diff --git a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rsindex 52a529dc17..0b512dc412 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs@@ -143,6 +143,9 @@ pub struct OpenHumanDefinitionRegistry {/// tool registry. They must augment a named root scope so the hosted loop/// authorizes the same hand-off routes it advertises.session_delegation_tools: Option<Arc<Vec<String>>>,+ /// Deferred tools admitted through a named `tool_search` belt. The hosted+ /// invocation's own allowlist must retain them for the intrinsic bridge.+ session_deferred_tools: Option<Arc<Vec<String>>>,/// The session's own caller-supplied definition, when it has one.////// A library host builds its agent from a definition it owns and passes by@@ -184,6 +187,7 @@ impl OpenHumanDefinitionRegistry {config: None,registered_tools: None,session_delegation_tools: None,+ session_deferred_tools: None,session_definition: None,}}@@ -200,6 +204,7 @@ impl OpenHumanDefinitionRegistry {config: None,registered_tools: None,session_delegation_tools: None,+ session_deferred_tools: None,session_definition: None,})}@@ -233,6 +238,11 @@ impl OpenHumanDefinitionRegistry {self}+ pub fn with_session_deferred_tools(mut self, tools: Arc<Vec<String>>) -> Self {+ self.session_deferred_tools = Some(tools);+ self+ }+/// Attaches the session's own definition, which outranks the registry.////// See [`Self::session_definition`] — without this a caller-supplied@@ -325,6 +335,11 @@ impl OpenHumanDefinitionRegistry {match &def.tools {ToolScope::Named(named) => {let mut names = named.clone();+ if named.iter().any(|name| name == "tool_search") {+ if let Some(deferred) = self.session_deferred_tools.as_deref() {+ names.extend(deferred.iter().cloned());+ }+ }if let Some(delegation_tools) = self.session_delegation_tools.as_deref() {names.extend(delegation_tools.iter().cloned());}diff --git a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry_tests.rsindex 57871683cc..30f028dd36 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry_tests.rs@@ -244,6 +244,26 @@ fn an_undenied_wildcard_scope_projects_registered_tools() {);}+#[test]+fn named_tool_search_grants_deferred_tools_to_hosted_run() {+ let mut with_search = synthetic("searcher", AgentTier::Chat, &[]);+ with_search.tools = ToolScope::Named(vec!["tool_search".to_owned()]);+ let registry =+ registry_of(vec![with_search.clone()]).with_session_deferred_tools(Arc::new(vec![+ "desktop_list_apps".to_owned(),+ "desktop_goal".to_owned(),+ ]));+ let tools = registry.project(&with_search).tools;+ assert!(tools.iter().any(|name| name == "tool_search"));+ assert!(tools.iter().any(|name| name == "desktop_list_apps"));+ assert!(tools.iter().any(|name| name == "desktop_goal"));++ let mut without_search = synthetic("no-search", AgentTier::Chat, &[]);+ without_search.tools = ToolScope::Named(vec!["file_read".to_owned()]);+ let tools = registry.project(&without_search).tools;+ assert!(!tools.iter().any(|name| name.starts_with("desktop_")));+}+/// A wildcard scope carrying a denylist must be materialised against the/// registered tool list, not projected as the unrestricted marker — which/// would hand every denied tool straight back.diff --git a/crates/openhuman-core/src/core/all.rs b/crates/openhuman-core/src/core/all.rsindex 565ed7be38..3abc8b8b6c 100644--- a/crates/openhuman-core/src/core/all.rs+++ b/crates/openhuman-core/src/core/all.rs@@ -1132,6 +1132,11 @@ fn build_registered_controllers() -> Vec<GroupedController> {/// (e.g. the desktop shell) that should not appear in agent tool listings.fn build_internal_only_controllers() -> Vec<GroupedController> {let mut controllers = Vec::new();+ push(+ &mut controllers,+ DomainGroup::Desktop,+ crate::desktop::control::all_registered_controllers(),+ );// MCP write audit list: internal-only so the desktop UI/CLI can inspect// local write history without exposing cross-client history as an MCP tool.push(diff --git a/crates/openhuman-core/src/core/runtime/builder.rs b/crates/openhuman-core/src/core/runtime/builder.rsindex bdbb2b6559..7ca064b574 100644--- a/crates/openhuman-core/src/core/runtime/builder.rs+++ b/crates/openhuman-core/src/core/runtime/builder.rs@@ -905,6 +905,9 @@ impl CoreRuntime {let listen_port = pick.port;let bind_addr = format!("{host}:{listen_port}");let listener = pick.listener;+ crate::desktop::control::set_listener_is_loopback(+ listener.local_addr().is_ok_and(|address| address.ip().is_loopback()),+ );// Synchronize OPENHUMAN_CORE_RPC_URL with the actual bound port so// connectivity::rpc::resolve_listen_port() reports the live listenerdiff --git a/crates/openhuman-core/src/desktop/control/WORKFLOW.md b/crates/openhuman-core/src/desktop/control/WORKFLOW.mdnew file mode 100644index 0000000000..63f3eb4940--- /dev/null+++ b/crates/openhuman-core/src/desktop/control/WORKFLOW.md@@ -0,0 +1,10 @@+---+name: desktop-control+description: Inspect and control native desktop apps when Desktop is enabled in Connections.+---++# Desktop control++Use `tool_search` to discover `desktop_*` tools. Begin with `desktop_list_apps` and `desktop_snapshot` (skeleton first); use `desktop_find` or a deeper snapshot to select a snapshot-qualified element ref. After an action, observe the app again and verify the visible result.++If a ref is stale, take a fresh snapshot. If Accessibility is denied, ask the user to grant it to the process running OpenHuman. Desktop goals have small action and model-call limits. A confirmation stop names the proposed operation and target; wait for the user to approve it in Connections before continuing with the `confirmation_id`. Never claim an action succeeded from a timeout or a model decision alone.diff --git a/crates/openhuman-core/src/desktop/control/confirmation.rs b/crates/openhuman-core/src/desktop/control/confirmation.rsnew file mode 100644index 0000000000..75dfabcac2--- /dev/null+++ b/crates/openhuman-core/src/desktop/control/confirmation.rs@@ -0,0 +1,263 @@+//! One-use user decisions for Jev goal stops, separate from autonomy auto-approval.++use std::collections::HashMap;+use std::sync::{Mutex, OnceLock};+use std::time::{Duration, Instant};++use serde::Serialize;+use serde_json::{json, Value};+use tinydesktop_bus::names;++use crate::agent::turn_origin::{self, AgentTurnOrigin};+use crate::config::Config;++const TTL: Duration = Duration::from_secs(10 * 60);++#[derive(Clone)]+struct Pending {+ app: String,+ goal: String,+ origin: String,+ operation: String,+ target: Option<String>,+ target_name: Option<String>,+ target_role: String,+ action_summary: String,+ reason: String,+ expires_at: String,+ created: Instant,+ approved: bool,+}++#[derive(Serialize)]+pub struct PendingDesktopConfirmation {+ pub confirmation_id: String,+ pub app: String,+ pub operation: String,+ pub target: Option<String>,+ pub target_name: Option<String>,+ pub target_role: String,+ pub action_summary: String,+ pub reason: String,+ pub expires_at: String,+ pub approved: bool,+}++fn table() -> &'static Mutex<HashMap<String, Pending>> {+ static TABLE: OnceLock<Mutex<HashMap<String, Pending>>> = OnceLock::new();+ TABLE.get_or_init(|| Mutex::new(HashMap::new()))+}++fn origin_key() -> String {+ match turn_origin::current() {+ Some(AgentTurnOrigin::WebChat { thread_id, .. }) => format!("web:{thread_id}"),+ Some(AgentTurnOrigin::DirectChat) => "direct-chat".to_owned(),+ Some(AgentTurnOrigin::Cli) => "cli".to_owned(),+ _ => "untrusted".to_owned(),+ }+}++/// Capture only the operation and target named by a module confirmation stop.+pub(super) fn record(app: &str, goal: &str, data: &Value) {+ if data.get("stop").and_then(Value::as_str) != Some("confirmation_required") {+ return;+ }+ let Some(id) = data.get("confirmation_id").and_then(Value::as_str) else {+ return;+ };+ let Some(operation) = data+ .get("pending")+ .and_then(|value| value.get("operation"))+ .and_then(Value::as_str)+ else {+ return;+ };+ let target = data+ .get("pending")+ .and_then(|value| value.get("target"))+ .and_then(|value| value.get("ref_id"))+ .and_then(Value::as_str)+ .map(str::to_owned);+ let target_name = data+ .get("pending")+ .and_then(|value| value.get("target"))+ .and_then(|value| value.get("name"))+ .and_then(Value::as_str)+ .and_then(|name| {+ (!name.trim().is_empty()).then(|| name.trim().chars().take(100).collect::<String>())+ });+ let target_role = data+ .get("pending")+ .and_then(|value| value.get("target"))+ .and_then(|value| value.get("role"))+ .and_then(Value::as_str)+ .and_then(|role| {+ (!role.trim().is_empty()).then(|| role.trim().chars().take(60).collect::<String>())+ });+ // The raw ref cannot tell a person which control will be activated.+ let (Some(target_name), Some(target_role)) = (target_name, target_role) else {+ return;+ };+ let action_summary = format!("{operation} {target_role} '{target_name}' in {app}");+ let reason = data+ .get("pending")+ .and_then(|value| value.get("reason"))+ .and_then(Value::as_str)+ .unwrap_or("This desktop action needs confirmation.")+ .to_owned();+ let expires_at = (chrono::Utc::now() + chrono::Duration::minutes(10)).to_rfc3339();+ table()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .insert(+ id.to_owned(),+ Pending {+ app: app.to_owned(),+ goal: goal.to_owned(),+ origin: origin_key(),+ operation: operation.to_owned(),+ target,+ target_name: Some(target_name),+ target_role,+ action_summary,+ reason,+ expires_at,+ created: Instant::now(),+ approved: false,+ },+ );+}++pub fn pending() -> Vec<PendingDesktopConfirmation> {+ if !super::ops::listener_is_loopback() {+ return Vec::new();+ }+ let mut guard = table()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ guard.retain(|_, value| value.created.elapsed() < TTL);+ guard+ .iter()+ .map(|(id, value)| PendingDesktopConfirmation {+ confirmation_id: id.clone(),+ app: value.app.clone(),+ operation: value.operation.clone(),+ target: value.target.clone(),+ approved: value.approved,+ target_name: value.target_name.clone(),+ target_role: value.target_role.clone(),+ action_summary: value.action_summary.clone(),+ reason: value.reason.clone(),+ expires_at: value.expires_at.clone(),+ })+ .collect()+}++/// Called only by a trusted RPC client carrying the core launch bearer.+pub async fn confirm(config: &Config, id: &str, approve: bool) -> Result<Value, String> {+ if !super::ops::listener_is_loopback() {+ return Err("desktop confirmation requires a loopback core listener".to_owned());+ }+ let entry = {+ let mut guard = table()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ guard.retain(|_, value| value.created.elapsed() < TTL);+ let item = guard+ .get_mut(id)+ .ok_or("desktop confirmation is missing or expired")?;+ if approve {+ item.approved = true;+ return Ok(json!({"confirmation_id":id,"approve":true}));+ }+ guard.remove(id).expect("checked above")+ };+ let reply = crate::modules::desktop::call(+ config,+ names::methods::RUN_GOAL,+ json!({"app":entry.app,"goal":entry.goal,+ "continuation":{"id":id,"approve":false}}),+ )+ .await?;+ if !reply.ok {+ return Err(reply.error.map_or_else(+ || "desktop cancellation failed".to_owned(),+ |error| error.message,+ ));+ }+ Ok(json!({"confirmation_id":id,"approve":false}))+}++/// Consume an approved decision before making one continuation call.+pub(super) fn take_approved(id: &str) -> Result<(String, String), String> {+ let mut guard = table()+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let item = guard+ .get(id)+ .ok_or("desktop confirmation is missing or expired")?;+ if item.created.elapsed() >= TTL {+ guard.remove(id);+ return Err("desktop confirmation expired".to_owned());+ }+ if !item.approved {+ return Err("desktop action needs the user's explicit confirmation".to_owned());+ }+ if item.origin != origin_key() {+ return Err("desktop confirmation does not match this thread".to_owned());+ }+ let item = guard.remove(id).expect("checked above");+ Ok((item.app, item.goal))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn confirmation_requires_trusted_one_use_decision_for_same_goal() {+ super::super::ops::set_listener_is_loopback(true);+ let id = uuid::Uuid::new_v4().to_string();+ record(+ "TextEdit",+ "make a note",+ &json!({+ "stop":"confirmation_required", "confirmation_id":id,+ "pending":{"operation":"CLICK", "reason":"May save a file",+ "target":{"ref_id":"@s1:e2", "name":"Save", "role":"button"}}+ }),+ );+ assert!(take_approved(&id).is_err());+ let listed = pending();+ let item = listed+ .iter()+ .find(|item| item.confirmation_id == id)+ .unwrap();+ assert_eq!(item.operation, "CLICK");+ assert_eq!(item.target_name.as_deref(), Some("Save"));+ assert_eq!(item.action_summary, "CLICK button 'Save' in TextEdit");+ let config = Config::default();+ let approved = confirm(&config, &id, true).await.unwrap();+ assert_eq!(approved["approve"], true);+ assert_eq!(+ take_approved(&id).unwrap(),+ ("TextEdit".to_owned(), "make a note".to_owned())+ );+ assert!(take_approved(&id).is_err());+ }++ #[test]+ fn unnamed_target_cannot_be_approved() {+ super::super::ops::set_listener_is_loopback(true);+ let id = uuid::Uuid::new_v4().to_string();+ record(+ "TextEdit",+ "test",+ &json!({+ "stop":"confirmation_required", "confirmation_id":id,+ "pending":{"operation":"CLICK", "target":{"ref_id":"@s1:e2", "role":"button"}}+ }),+ );+ assert!(!pending().iter().any(|item| item.confirmation_id == id));+ }+}diff --git a/crates/openhuman-core/src/desktop/control/mod.rs b/crates/openhuman-core/src/desktop/control/mod.rsnew file mode 100644index 0000000000..a11c163c07--- /dev/null+++ b/crates/openhuman-core/src/desktop/control/mod.rs@@ -0,0 +1,12 @@+//! Local opt-in desktop automation connection and agent tools.++mod confirmation;+mod ops;+mod schemas;+pub mod tools;++pub use confirmation::{confirm, pending};+pub use ops::listener_is_loopback;+pub(crate) use ops::set_listener_is_loopback;+pub use ops::{enabled, probe, set_enabled, status, DesktopProbe, DesktopStatus};+pub use schemas::all_registered_controllers;diff --git a/crates/openhuman-core/src/desktop/control/ops.rs b/crates/openhuman-core/src/desktop/control/ops.rsnew file mode 100644index 0000000000..a0efa2037f--- /dev/null+++ b/crates/openhuman-core/src/desktop/control/ops.rs@@ -0,0 +1,267 @@+//! Local desktop enablement and permission-aware status.++use std::fs;+use std::io::Write;+use std::sync::{+ atomic::{AtomicBool, Ordering},+ Mutex,+};++use serde::{Deserialize, Serialize};+use tinydesktop_bus::{names, ListAppsRequest, SnapshotRequest};++use crate::config::Config;++static STATE_LOCK: Mutex<()> = Mutex::new(());+static LOOPBACK_LISTENER: AtomicBool = AtomicBool::new(false);++/// The HTTP host reports its actual bound address before serving requests.+pub(crate) fn set_listener_is_loopback(value: bool) {+ LOOPBACK_LISTENER.store(value, Ordering::Release);+}++pub fn listener_is_loopback() -> bool {+ LOOPBACK_LISTENER.load(Ordering::Acquire)+}++#[derive(Debug, Clone, Serialize)]+pub struct DesktopStatus {+ pub supported: bool,+ pub enabled: bool,+ pub platform: &'static str,+ pub module_state: String,+ pub accessibility: String,+ pub screen_recording: String,+ pub jev_ready: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+pub struct DesktopProbe {+ pub ok: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub app_count: Option<usize>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,+}++#[derive(Serialize, Deserialize)]+struct LocalState {+ enabled: bool,+}++fn state_path(config: &Config) -> std::path::PathBuf {+ config+ .workspace_dir+ .join("state")+ .join("desktop-control.json")+}++/// Corrupt or unreadable local state fails closed, never enabling desktop access.+pub fn enabled(config: &Config) -> bool {+ let _lock = STATE_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ fs::read_to_string(state_path(config))+ .ok()+ .and_then(|raw| serde_json::from_str::<LocalState>(&raw).ok())+ .is_some_and(|state| state.enabled)+}++fn save(config: &Config, value: bool) -> Result<(), String> {+ let _lock = STATE_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let path = state_path(config);+ let parent = path.parent().ok_or("desktop state path has no parent")?;+ fs::create_dir_all(parent).map_err(|error| format!("desktop state directory: {error}"))?;+ let mut temporary = tempfile::NamedTempFile::new_in(parent)+ .map_err(|error| format!("desktop state temporary file: {error}"))?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ temporary+ .as_file()+ .set_permissions(fs::Permissions::from_mode(0o600))+ .map_err(|error| format!("desktop state permissions: {error}"))?;+ }+ serde_json::to_writer(&mut temporary, &LocalState { enabled: value })+ .map_err(|error| format!("desktop state serialization: {error}"))?;+ temporary+ .flush()+ .map_err(|error| format!("desktop state flush: {error}"))?;+ temporary+ .as_file()+ .sync_all()+ .map_err(|error| format!("desktop state sync: {error}"))?;+ temporary+ .persist(path)+ .map_err(|error| format!("desktop state persist: {error}"))?;+ Ok(())+}++pub async fn set_enabled(config: &Config, value: bool) -> Result<DesktopStatus, String> {+ if value && !supported() {+ return Err(+ "desktop control requires macOS or Windows and a loopback core listener".to_owned(),+ );+ }+ save(config, value)?;+ tracing::info!(enabled = value, "[desktop] local enablement changed");+ Ok(status(config).await)+}++fn supported() -> bool {+ cfg!(any(target_os = "macos", target_os = "windows")) && listener_is_loopback()+}++fn permission(data: &serde_json::Value, field: &str) -> String {+ let raw = data+ .get(field)+ .and_then(|value| value.get("state"))+ .and_then(serde_json::Value::as_str)+ .unwrap_or("unknown");+ match raw {+ "granted" | "denied" | "not_required" => raw.to_owned(),+ _ => "unknown".to_owned(),+ }+}++pub async fn status(config: &Config) -> DesktopStatus {+ let local_enabled = enabled(config);+ let (module_state, mut reason) = crate::modules::desktop::state(config);+ let mut result = DesktopStatus {+ supported: supported(),+ enabled: local_enabled,+ platform: std::env::consts::OS,+ module_state,+ accessibility: "unknown".to_owned(),+ screen_recording: "unknown".to_owned(),+ jev_ready: crate::modules::desktop::jev_ready(config),+ reason: None,+ };+ if !result.supported {+ reason = Some(+ "desktop control requires macOS or Windows and a loopback core listener".to_owned(),+ );+ } else if local_enabled {+ match crate::modules::desktop::permissions(config).await {+ Ok(response) if response.ok => {+ if let Some(data) = response.data.as_ref() {+ result.accessibility = permission(data, "accessibility");+ result.screen_recording = permission(data, "screen_recording");+ }+ result.module_state = "ready".to_owned();+ }+ Ok(response) => reason = response.error.map(|error| error.message),+ Err(error) => reason = Some(error),+ }+ result.module_state = crate::modules::desktop::state(config).0;+ }+ result.reason = reason;+ result+}++pub async fn probe(config: &Config) -> DesktopProbe {+ if !supported() || !enabled(config) {+ return DesktopProbe {+ ok: false,+ app_count: None,+ reason: Some("desktop control is unavailable or disabled".to_owned()),+ };+ }+ let permissions = match crate::modules::desktop::permissions(config).await {+ Ok(reply) if reply.ok => reply,+ Ok(reply) => {+ return DesktopProbe {+ ok: false,+ app_count: None,+ reason: reply.error.map(|error| error.message),+ }+ }+ Err(error) => {+ return DesktopProbe {+ ok: false,+ app_count: None,+ reason: Some(error),+ }+ }+ };+ if permissions+ .data+ .as_ref()+ .map(|data| permission(data, "accessibility"))+ .as_deref()+ != Some("granted")+ {+ return DesktopProbe {+ ok: false,+ app_count: None,+ reason: Some("Accessibility permission is not granted to the core process".to_owned()),+ };+ }+ let snapshot = crate::modules::desktop::call(+ config,+ names::methods::SNAPSHOT,+ SnapshotRequest {+ skeleton: true,+ ..SnapshotRequest::default()+ },+ )+ .await;+ match snapshot {+ Ok(response) if response.ok => {+ let apps = crate::modules::desktop::call(+ config,+ names::methods::LIST_APPS,+ ListAppsRequest::default(),+ )+ .await;+ DesktopProbe {+ ok: true,+ app_count: apps.ok().and_then(|reply| reply.data).and_then(|data| {+ data.get("apps")+ .and_then(serde_json::Value::as_array)+ .map(Vec::len)+ }),+ reason: None,+ }+ }+ Ok(response) => DesktopProbe {+ ok: false,+ app_count: None,+ reason: response.error.map(|error| error.message),+ },+ Err(error) => DesktopProbe {+ ok: false,+ app_count: None,+ reason: Some(error),+ },+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn disabled_by_default_and_persists() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.workspace_dir = dir.path().to_path_buf();+ assert!(!enabled(&config));+ save(&config, true).unwrap();+ assert!(enabled(&config));+ save(&config, false).unwrap();+ assert!(!enabled(&config));+ }++ #[test]+ fn permission_states_are_normalized() {+ let data = serde_json::json!({"accessibility":{"state":"granted"},+ "screen_recording":{"state":"weird"}});+ assert_eq!(permission(&data, "accessibility"), "granted");+ assert_eq!(permission(&data, "screen_recording"), "unknown");+ }+}diff --git a/crates/openhuman-core/src/desktop/control/schemas.rs b/crates/openhuman-core/src/desktop/control/schemas.rsnew file mode 100644index 0000000000..0d880f2a19--- /dev/null+++ b/crates/openhuman-core/src/desktop/control/schemas.rs@@ -0,0 +1,132 @@+//! RPC controllers for the local desktop connection.++use serde_json::{Map, Value};++use crate::core::all::{ControllerFuture, RegisteredController};+use crate::core::{ControllerSchema, FieldSchema, TypeSchema};++pub fn all_registered_controllers() -> Vec<RegisteredController> {+ vec![+ RegisteredController {+ schema: schema("status"),+ handler: status,+ },+ RegisteredController {+ schema: schema("set_enabled"),+ handler: set_enabled,+ },+ RegisteredController {+ schema: schema("probe"),+ handler: probe,+ },+ RegisteredController {+ schema: schema("pending"),+ handler: pending,+ },+ RegisteredController {+ schema: schema("confirm"),+ handler: confirm,+ },+ ]+}++fn schema(function: &'static str) -> ControllerSchema {+ ControllerSchema {+ namespace: "desktop",+ function,+ description: match function {+ "status" => "Local desktop connection, module, Jev, and OS permission status.",+ "set_enabled" => "Enable or disable local desktop control on this computer.",+ "pending" => "List desktop actions awaiting a user decision on this computer.",+ "confirm" => "Approve or deny one pending desktop action from a trusted client.",+ _ => "Read-only desktop connection test by listing running apps.",+ },+ inputs: if function == "set_enabled" {+ vec![FieldSchema {+ name: "enabled",+ ty: TypeSchema::Bool,+ comment: "Whether this computer allows desktop control.",+ required: true,+ }]+ } else if function == "confirm" {+ vec![+ FieldSchema {+ name: "confirmation_id",+ ty: TypeSchema::String,+ comment: "One-use confirmation handle returned by a desktop goal.",+ required: true,+ },+ FieldSchema {+ name: "approve",+ ty: TypeSchema::Bool,+ comment: "True to approve, false to cancel the pending action.",+ required: true,+ },+ ]+ } else {+ vec![]+ },+ outputs: vec![FieldSchema {+ name: "result",+ ty: TypeSchema::Json,+ comment: "Desktop connection status or probe result.",+ required: true,+ }],+ }+}++fn status(_: Map<String, Value>) -> ControllerFuture {+ Box::pin(async {+ let config = crate::config::rpc::load_config_with_timeout()+ .await+ .map_err(|error| format!("config unavailable: {error}"))?;+ serde_json::to_value(super::ops::status(&config).await).map_err(|error| error.to_string())+ })+}++fn set_enabled(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let value = params+ .get("enabled")+ .and_then(Value::as_bool)+ .ok_or_else(|| "enabled must be a boolean".to_owned())?;+ let config = crate::config::rpc::load_config_with_timeout()+ .await+ .map_err(|error| format!("config unavailable: {error}"))?;+ let result = super::ops::set_enabled(&config, value).await?;+ serde_json::to_value(result).map_err(|error| error.to_string())+ })+}++fn probe(_: Map<String, Value>) -> ControllerFuture {+ Box::pin(async {+ let config = crate::config::rpc::load_config_with_timeout()+ .await+ .map_err(|error| format!("config unavailable: {error}"))?;+ serde_json::to_value(super::ops::probe(&config).await).map_err(|error| error.to_string())+ })+}++fn pending(_: Map<String, Value>) -> ControllerFuture {+ Box::pin(async {+ serde_json::to_value(super::confirmation::pending()).map_err(|error| error.to_string())+ })+}++fn confirm(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let id = params+ .get("confirmation_id")+ .and_then(Value::as_str)+ .filter(|value| !value.is_empty())+ .ok_or_else(|| "confirmation_id is required".to_owned())?;+ let approve = params+ .get("approve")+ .and_then(Value::as_bool)+ .ok_or_else(|| "approve must be a boolean".to_owned())?;+ let config = crate::config::rpc::load_config_with_timeout()+ .await+ .map_err(|error| format!("config unavailable: {error}"))?;+ super::confirmation::confirm(&config, id, approve).await+ })+}diff --git a/crates/openhuman-core/src/desktop/control/tools.rs b/crates/openhuman-core/src/desktop/control/tools.rsnew file mode 100644index 0000000000..c7558da549--- /dev/null+++ b/crates/openhuman-core/src/desktop/control/tools.rs@@ -0,0 +1,270 @@+//! Deferred desktop tools. Only their names and descriptions enter discovery.++use std::sync::Arc;++use async_trait::async_trait;+use serde_json::{json, Value};+use tinydesktop_bus::{+ names, FindRequest, ListAppsRequest, ListWindowsRequest, RefRequest, SnapshotRequest,+ TypeRequest,+};+use tinytools::{PermissionLevel, Tool, ToolExposure, ToolResult};++use crate::config::Config;++#[derive(Clone, Copy)]+pub enum DesktopToolKind {+ Apps,+ Windows,+ Snapshot,+ Find,+ Act,+ Goal,+}++pub struct DesktopTool {+ config: Arc<Config>,+ kind: DesktopToolKind,+}++impl DesktopTool {+ pub fn new(config: Arc<Config>, kind: DesktopToolKind) -> Self {+ Self { config, kind }+ }+}++fn required(args: &Value, key: &str) -> anyhow::Result<String> {+ args.get(key)+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(str::to_owned)+ .ok_or_else(|| anyhow::anyhow!("missing required parameter: {key}"))+}++#[async_trait]+impl Tool for DesktopTool {+ fn name(&self) -> &str {+ match self.kind {+ DesktopToolKind::Apps => "desktop_list_apps",+ DesktopToolKind::Windows => "desktop_list_windows",+ DesktopToolKind::Snapshot => "desktop_snapshot",+ DesktopToolKind::Find => "desktop_find",+ DesktopToolKind::Act => "desktop_act",+ DesktopToolKind::Goal => "desktop_goal",+ }+ }++ fn description(&self) -> &str {+ match self.kind {+ DesktopToolKind::Apps => "List running desktop applications on this computer.",+ DesktopToolKind::Windows => "List native windows for a running desktop app.",+ DesktopToolKind::Snapshot => "Inspect an app's accessibility tree and obtain snapshot-qualified element refs.",+ DesktopToolKind::Find => "Find a desktop accessibility element by role and name, returning a ref.",+ DesktopToolKind::Act => "Act on a desktop element ref: click, focus, type, check, uncheck, expand, or collapse.",+ DesktopToolKind::Goal => "Run a bounded Jev-guided desktop goal. Search for desktop tools before use; consequential actions require confirmation.",+ }+ }++ fn exposure(&self) -> ToolExposure {+ ToolExposure::Deferred+ }++ fn permission_level(&self) -> PermissionLevel {+ match self.kind {+ DesktopToolKind::Act | DesktopToolKind::Goal => PermissionLevel::Write,+ _ => PermissionLevel::ReadOnly,+ }+ }++ fn external_effect(&self) -> bool {+ matches!(self.kind, DesktopToolKind::Act | DesktopToolKind::Goal)+ }++ fn parameters_schema(&self) -> Value {+ match self.kind {+ DesktopToolKind::Apps => json!({"type":"object","properties":{}}),+ DesktopToolKind::Windows => json!({"type":"object","properties":{+ "app":{"type":"string","description":"Optional application name"}}}),+ DesktopToolKind::Snapshot => json!({"type":"object","properties":{+ "app":{"type":"string"}, "skeleton":{"type":"boolean"},+ "root_ref":{"type":"string"}, "max_depth":{"type":"integer","minimum":1,"maximum":12}}}),+ DesktopToolKind::Find => json!({"type":"object","properties":{+ "app":{"type":"string"},"role":{"type":"string"},"name":{"type":"string"},+ "root":{"type":"string"},"limit":{"type":"integer","minimum":1,"maximum":20}}}),+ DesktopToolKind::Act => json!({"type":"object","properties":{+ "operation":{"type":"string","enum":["click","focus","type","check","uncheck","expand","collapse"]},+ "ref_id":{"type":"string","description":"Snapshot-qualified ref from desktop_snapshot or desktop_find"},+ "text":{"type":"string","description":"Required for type"}},+ "required":["operation","ref_id"]}),+ DesktopToolKind::Goal => json!({"type":"object","properties":{+ "app":{"type":"string"},"goal":{"type":"string"},+ "text":{"type":"array","items":{"type":"string"}},+ "max_steps":{"type":"integer","minimum":1,"maximum":8},+ "max_model_calls":{"type":"integer","minimum":1,"maximum":16},+ "confirmation_id":{"type":"string","description":"Continue only after the user approved this pending action in the desktop confirmation UI"}}}),+ }+ }++ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {+ if !super::ops::listener_is_loopback() || !super::ops::enabled(&self.config) {+ return Ok(ToolResult::error(+ "Desktop control is disabled in Connections.",+ ));+ }+ let permission = crate::modules::desktop::permissions(&self.config).await;+ let permission = match permission {+ Ok(value) if value.ok => value,+ Ok(value) => {+ return Ok(ToolResult::error(format!(+ "Desktop permission check failed: {}",+ value+ .error+ .map_or_else(|| "unknown error".to_owned(), |error| error.message)+ )))+ }+ Err(error) => return Ok(ToolResult::error(error)),+ };+ let accessibility = permission+ .data+ .as_ref()+ .and_then(|data| data.get("accessibility"))+ .and_then(|value| value.get("state"))+ .and_then(Value::as_str)+ .unwrap_or("unknown");+ if accessibility != "granted"+ && !matches!(self.kind, DesktopToolKind::Apps | DesktopToolKind::Windows)+ {+ return Ok(ToolResult::error("Desktop Accessibility permission is not granted. Enable it in system settings and retry."));+ }+ let mut goal_identity = None;+ let (member, request) = match self.kind {+ DesktopToolKind::Apps => (+ names::methods::LIST_APPS,+ serde_json::to_value(ListAppsRequest::default())?,+ ),+ DesktopToolKind::Windows => (+ names::methods::LIST_WINDOWS,+ serde_json::to_value(ListWindowsRequest {+ app: args.get("app").and_then(Value::as_str).map(str::to_owned),+ })?,+ ),+ DesktopToolKind::Snapshot => {+ let request = SnapshotRequest {+ app: args.get("app").and_then(Value::as_str).map(str::to_owned),+ skeleton: args+ .get("skeleton")+ .and_then(Value::as_bool)+ .unwrap_or(true),+ root_ref: args+ .get("root_ref")+ .and_then(Value::as_str)+ .map(str::to_owned),+ max_depth: args+ .get("max_depth")+ .and_then(Value::as_u64)+ .map(|n| n.clamp(1, 12) as u8),+ ..SnapshotRequest::default()+ };+ (names::methods::SNAPSHOT, serde_json::to_value(request)?)+ }+ DesktopToolKind::Find => {+ let request = FindRequest {+ app: args.get("app").and_then(Value::as_str).map(str::to_owned),+ role: args.get("role").and_then(Value::as_str).map(str::to_owned),+ name: args.get("name").and_then(Value::as_str).map(str::to_owned),+ root: args.get("root").and_then(Value::as_str).map(str::to_owned),+ limit: Some(+ args.get("limit")+ .and_then(Value::as_u64)+ .unwrap_or(10)+ .clamp(1, 20) as usize,+ ),+ ..FindRequest::default()+ };+ (names::methods::FIND, serde_json::to_value(request)?)+ }+ DesktopToolKind::Act => {+ let reference = required(&args, "ref_id")?;+ let operation = required(&args, "operation")?;+ if operation == "type" {+ let text = required(&args, "text")?;+ (+ names::methods::TYPE,+ serde_json::to_value(TypeRequest {+ ref_id: reference,+ text,+ ..TypeRequest::default()+ })?,+ )+ } else {+ let member = match operation.as_str() {+ "click" => names::methods::CLICK,+ "focus" => names::methods::FOCUS,+ "check" => names::methods::CHECK,+ "uncheck" => names::methods::UNCHECK,+ "expand" => names::methods::EXPAND,+ "collapse" => names::methods::COLLAPSE,+ _ => return Ok(ToolResult::error("Unsupported desktop operation")),+ };+ (member, serde_json::to_value(RefRequest::new(reference))?)+ }+ }+ DesktopToolKind::Goal => {+ let (app, goal, continuation) =+ if let Some(id) = args.get("confirmation_id").and_then(Value::as_str) {+ let (app, goal) =+ super::confirmation::take_approved(id).map_err(anyhow::Error::msg)?;+ (app, goal, Some(json!({"id":id,"approve":true})))+ } else {+ (required(&args, "app")?, required(&args, "goal")?, None)+ };+ goal_identity = Some((app.clone(), goal.clone()));+ let mut request = json!({"app":app,"goal":goal,+ "text":args.get("text").cloned().unwrap_or_else(|| json!([])),+ "include_values":false,+ "max_steps":args.get("max_steps").and_then(Value::as_u64).unwrap_or(6).clamp(1,8),+ "max_model_calls":args.get("max_model_calls").and_then(Value::as_u64).unwrap_or(12).clamp(1,16)});+ if let Some(continuation) = continuation {+ request["continuation"] = continuation;+ }+ (names::methods::RUN_GOAL, request)+ }+ };+ let reply = crate::modules::desktop::call(&self.config, member, request).await;+ match reply {+ Ok(response) if response.ok => {+ let data = response.data.unwrap_or(Value::Null);+ if let Some((app, goal)) = goal_identity {+ super::confirmation::record(&app, &goal, &data);+ }+ let rendered = serde_json::to_string(&data)?;+ // A bounded model result; full screenshots are not exposed through this tool.+ Ok(ToolResult::success(+ rendered.chars().take(24_000).collect::<String>(),+ ))+ }+ Ok(response) => Ok(ToolResult::error(response.error.map_or_else(+ || "Desktop command failed without an error".to_owned(),+ |error| format!("{}: {}", error.code, error.message),+ ))),+ Err(error) => Ok(ToolResult::error(error)),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn deferred_tool_is_discoverable_but_fails_closed_when_disabled() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.workspace_dir = dir.path().to_path_buf();+ let tool = DesktopTool::new(Arc::new(config), DesktopToolKind::Apps);+ assert_eq!(tool.exposure(), ToolExposure::Deferred);+ let result = tool.execute(json!({})).await.unwrap();+ assert!(result.output().contains("disabled in Connections"));+ }+}diff --git a/crates/openhuman-core/src/desktop/mod.rs b/crates/openhuman-core/src/desktop/mod.rsindex 448472e257..1a732f177d 100644--- a/crates/openhuman-core/src/desktop/mod.rs+++ b/crates/openhuman-core/src/desktop/mod.rs@@ -19,6 +19,7 @@pub mod accessibility;pub mod app_state;pub mod dashboard;+pub mod control;pub mod notifications;pub mod overlay;pub mod provider_surfaces;diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rsindex cf8c913418..ddc6fbf255 100644--- a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs@@ -68,6 +68,19 @@ pub enum FetchConnectedIntegrationsStatus {pub async fn fetch_connected_integrations_status(config: &Config,) -> FetchConnectedIntegrationsStatus {+ // The offline local token is a core identity, never a TinyHumans backend+ // credential. Asking the hosted integrations endpoint with it yields 401,+ // can race the scheduler gate into signed-out state, and cannot discover a+ // real connection. An authoritative empty set keeps this session local.+ if crate::security::credentials::session_support::get_session_token(config)+ .ok()+ .flatten()+ .is_some_and(|token| {+ crate::security::credentials::session_support::is_local_session_token(&token)+ })+ {+ return FetchConnectedIntegrationsStatus::Authoritative(Vec::new());+ }let key = cache_key(config);// Fast path: return cached result if fresh. Stale entries falldiff --git a/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs b/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rsindex 6887cdbf63..470180ab72 100644--- a/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs@@ -1,5 +1,30 @@use super::*;+#[tokio::test]+async fn offline_local_session_never_fetches_hosted_integrations() {+ let _guard = cache_guard();+ let tmp = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.workspace_dir = tmp.path().join("workspace");+ config.config_path = tmp.path().join("config.toml");+ config.api_url = Some("http://127.0.0.1:1".to_owned());+ crate::security::credentials::AuthService::from_config(&config)+ .store_provider_token(+ crate::security::credentials::APP_SESSION_PROVIDER,+ crate::security::credentials::DEFAULT_AUTH_PROFILE_NAME,+ "desktop.test.local",+ std::collections::HashMap::new(),+ true,+ )+ .unwrap();+ match fetch_connected_integrations_status(&config).await {+ FetchConnectedIntegrationsStatus::Authoritative(items) => assert!(items.is_empty()),+ FetchConnectedIntegrationsStatus::Unavailable => {+ panic!("offline local mode must not fetch backend")+ }+ }+}+#[tokio::test]async fn fetch_connected_integrations_via_mock_aggregates_tools() {let _guard = cache_guard();diff --git a/crates/openhuman-core/src/modules/desktop.rs b/crates/openhuman-core/src/modules/desktop.rsnew file mode 100644index 0000000000..eed32d4c08--- /dev/null+++ b/crates/openhuman-core/src/modules/desktop.rs@@ -0,0 +1,144 @@+//! Host calls to the attested tinydesktop module.++use std::hash::{Hash, Hasher};+use std::sync::OnceLock;++use serde::Serialize;+use tinybus::Proxy;+use tinydesktop_bus::{names, DesktopResponse, PermissionsRequest};++use crate::config::Config;++pub const MODULE_ID: &str = "tinydesktop";++/// This confidential payload is sent only to the module lifecycle callback.+/// Missing or expired host credentials remove the old Jev client on refresh.+pub fn module_config(config: &Config) -> serde_json::Value {+ let credential =+ crate::security::credentials::session_support::resolve_backend_credential(config)+ .ok()+ .map(crate::security::credentials::session_support::BackendCredential::into_secret)+ .filter(|token| {+ !crate::security::credentials::session_support::is_local_session_token(token)+ });+ match credential {+ Some(api_key) => serde_json::json!({+ "jev": {+ "api_key": api_key,+ "provider": "tiny_humans_open_router",+ "sdk_name": crate::api::product_identity().as_str()+ }+ }),+ None => {+ // A headless or BYOK host may have no TinyHumans session. Direct+ // OpenRouter Jev remains usable with its own scoped credential.+ let direct =+ crate::inference::provider::factory::lookup_key_for_slug("openrouter", config)+ .ok()+ .filter(|key| !key.trim().is_empty())+ .or_else(|| {+ std::env::var("OPENROUTER_API_KEY")+ .ok()+ .filter(|key| !key.trim().is_empty())+ });+ direct.map_or_else(+ || serde_json::json!({}),+ |api_key| {+ serde_json::json!({+ "jev": { "api_key": api_key, "provider": "open_router" }+ })+ },+ )+ }+ }+}++pub fn jev_ready(config: &Config) -> bool {+ module_config(config)["jev"].is_object()+}++fn last_config() -> &'static tokio::sync::Mutex<Option<u64>> {+ static LAST: OnceLock<tokio::sync::Mutex<Option<u64>>> = OnceLock::new();+ LAST.get_or_init(|| tokio::sync::Mutex::new(None))+}++fn fingerprint(value: &serde_json::Value) -> u64 {+ let mut hasher = std::collections::hash_map::DefaultHasher::new();+ value.to_string().hash(&mut hasher);+ hasher.finish()+}++async fn proxy(config: &Config) -> Result<Proxy, String> {+ crate::modules::ops::ensure_loaded_within(+ config,+ MODULE_ID,+ Some(std::time::Duration::from_secs(8)),+ )+ .await+ .map_err(crate::modules::ops::LoadError::into_message)?;+ let runtime = crate::modules::host::runtime()+ .await+ .map_err(|error| format!("desktop module bus unavailable: {error}"))?;+ crate::modules::registry::find(MODULE_ID)+ .ok_or_else(|| "desktop module is not in the compiled registry".to_owned())?;++ // Reinitialization is private and retains no plaintext secret in this host.+ // The lock makes credential rotation atomic across concurrent tool calls.+ let configuration = module_config(config);+ let current = fingerprint(&configuration);+ let mut previous = last_config().lock().await;+ if *previous != Some(current) {+ runtime+ .connection()+ .reinitialize_module(MODULE_ID, configuration)+ .await+ .map_err(|error| format!("desktop module credential refresh failed: {error}"))?;+ }+ *previous = Some(current);+ drop(previous);+ runtime+ .proxy(names::INTERFACE, names::OBJECT_PATH)+ .map_err(|error| format!("desktop module proxy unavailable: {error}"))+}++/// Call one contract member, preserving the structured error envelope.+pub async fn call<Request: Serialize + Send>(+ config: &Config,+ member: &str,+ request: Request,+) -> Result<DesktopResponse, String> {+ let proxy = proxy(config).await?;+ let response = if member == names::methods::RUN_GOAL || member == names::methods::RESOLVE_INTENT+ {+ proxy+ .call_confidential::<DesktopResponse>(member, (request,))+ .await+ } else {+ proxy.call::<DesktopResponse>(member, (request,)).await+ };+ response.map_err(|error| format!("desktop {member} failed: {error}"))+}++pub async fn permissions(config: &Config) -> Result<DesktopResponse, String> {+ call(+ config,+ names::methods::PERMISSIONS,+ PermissionsRequest::default(),+ )+ .await+}++pub fn state(config: &Config) -> (String, Option<String>) {+ crate::modules::ops::list(config)+ .into_iter()+ .find(|item| item.id == MODULE_ID)+ .map_or_else(+ || {+ (+ "failed".to_owned(),+ Some("desktop module is not registered".to_owned()),+ )+ },+ |item| (format!("{:?}", item.state).to_lowercase(), item.detail),+ )+}diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rsindex daf10b932b..c244c46410 100644--- a/crates/openhuman-core/src/modules/mod.rs+++ b/crates/openhuman-core/src/modules/mod.rs@@ -40,6 +40,7 @@pub mod boot;pub mod connectors;+pub mod desktop;#[cfg(feature = "documents")]pub mod documents;pub mod host;diff --git a/crates/openhuman-core/src/modules/ops.rs b/crates/openhuman-core/src/modules/ops.rsindex 5a68bfeb9f..ec23335913 100644--- a/crates/openhuman-core/src/modules/ops.rs+++ b/crates/openhuman-core/src/modules/ops.rs@@ -458,6 +458,9 @@ pub(super) fn load_local(/// Credentials are intentionally absent. TinyMemory calls back into the host/// for embedding and chat compute; the other modules need no host config.fn module_config(config: &Config, id: &str) -> serde_json::Value {+ if id == super::desktop::MODULE_ID {+ return super::desktop::module_config(config);+ }if id == super::connectors::MODULE_ID {// The connector module takes its route and credential from here and// reads one from nowhere else. A configuration that cannot be built —diff --git a/crates/openhuman-core/src/modules/registry.rs b/crates/openhuman-core/src/modules/registry.rsindex 7ab91b522a..a134771436 100644--- a/crates/openhuman-core/src/modules/registry.rs+++ b/crates/openhuman-core/src/modules/registry.rs@@ -35,6 +35,7 @@mod tests;mod records_docs_wallet;+mod records_desktop;mod records_extra;mod records_mcp_connectors;mod records_memory_juice;@@ -43,6 +44,7 @@ mod records_voice;use crate::modules::types::ModuleRecord;use records_docs_wallet::{TINYDOCS, TINYWALLET};+use records_desktop::TINYDESKTOP;use records_extra::{TINYBOX, TINYCHANNELS, TINYHOSTS};use records_mcp_connectors::{TINYCONNECTORS, TINYMCP};use records_memory_juice::{TINYJUICE, TINYMEMORY};@@ -51,6 +53,7 @@ use records_voice::TINYVOICE;/// Every module this build can load.pub const ALL: &[ModuleRecord] = &[+ TINYDESKTOP,TINYDOCS,TINYWALLET,TINYMEMORY,diff --git a/crates/openhuman-core/src/modules/registry/records_desktop.rs b/crates/openhuman-core/src/modules/registry/records_desktop.rsnew file mode 100644index 0000000000..80d0eca357--- /dev/null+++ b/crates/openhuman-core/src/modules/registry/records_desktop.rs@@ -0,0 +1,17 @@+//! Native desktop module. Published digests are added only from its release manifest.++use crate::modules::types::{LoadPolicy, ModuleRecord};+use tinydesktop_bus::names;++pub(crate) const TINYDESKTOP: ModuleRecord = ModuleRecord {+ id: "tinydesktop",+ description: "Permission-aware native desktop observation and control",+ bus_name: names::INTERFACE,+ object_path: names::OBJECT_PATH,+ version: "0.3.0",+ release_url: "https://github.com/tinyhumansai/tinydesktop/releases/tag/v0.3.0",+ // The local override may be tested before publication. Do not derive a+ // release pin from that debug build: use the published checksum.toml.+ assets: &[],+ load: LoadPolicy::Lazy,+};diff --git a/crates/openhuman-core/src/platform/about_app/catalog_data.rs b/crates/openhuman-core/src/platform/about_app/catalog_data.rsindex a58ca2e935..c4553efb86 100644--- a/crates/openhuman-core/src/platform/about_app/catalog_data.rs+++ b/crates/openhuman-core/src/platform/about_app/catalog_data.rs@@ -8,6 +8,15 @@ const LOCAL_RAW: Option<CapabilityPrivacy> = Some(CapabilityPrivacy {destinations: &[],});+const DESKTOP_TO_JEV: Option<CapabilityPrivacy> = Some(CapabilityPrivacy {+ leaves_device: true,+ data_kind: PrivacyDataKind::Raw,+ destinations: &[+ "Configured OpenHuman inference provider",+ "TinyHumans OpenRouter Jev proxy",+ ],+});+const DERIVED_TO_BACKEND: Option<CapabilityPrivacy> = Some(CapabilityPrivacy {leaves_device: true,data_kind: PrivacyDataKind::Derived,diff --git a/crates/openhuman-core/src/platform/about_app/catalog_localai_settings_mobile.rs b/crates/openhuman-core/src/platform/about_app/catalog_localai_settings_mobile.rsindex 546f439c22..84c5a653eb 100644--- a/crates/openhuman-core/src/platform/about_app/catalog_localai_settings_mobile.rs+++ b/crates/openhuman-core/src/platform/about_app/catalog_localai_settings_mobile.rs@@ -121,6 +121,16 @@ Capability {status: CapabilityStatus::Stable,privacy: None,},+Capability {+ id: "settings.desktop_control",+ name: "Desktop Control",+ domain: "desktop",+ category: CapabilityCategory::Settings,+ description: "Let agents inspect and control native desktop apps through a local, permission-aware connection. Desktop actions are discovered on demand.",+ how_to: "Connections → Desktop; enable access and grant operating system permissions when requested",+ status: CapabilityStatus::Beta,+ privacy: DESKTOP_TO_JEV,+ },Capability {id: "settings.persona_pack",name: "Choose Assistant Mascot",diff --git a/crates/openhuman-core/src/security/credentials/ops/user_scope.rs b/crates/openhuman-core/src/security/credentials/ops/user_scope.rsindex 045dfd0663..5a98310ddb 100644--- a/crates/openhuman-core/src/security/credentials/ops/user_scope.rs+++ b/crates/openhuman-core/src/security/credentials/ops/user_scope.rs@@ -23,9 +23,28 @@ const LOG_PREFIX: &str = "[credentials][user-scope]";/// and must never change which user the operator's real install believes is/// active purely by virtue of running a library call.pub(super) fn operator_user_activation_allowed() -> bool {- !is_embedder_host()+ if is_embedder_host() {+ return false;+ }+ let Some(workspace) = std::env::var_os("OPENHUMAN_WORKSPACE").filter(|value| !value.is_empty())+ else {+ return true;+ };+ let Ok(root) = default_root_openhuman_dir() else {+ return false;+ };+ let workspace = std::path::PathBuf::from(workspace);+ let workspace = workspace.canonicalize().unwrap_or(workspace);+ let root = root.canonicalize().unwrap_or(root);+ // An explicit scratch workspace must never switch the operator's real+ // ~/.openhuman active user. Its credential still lives at its own config_path.+ workspace.starts_with(root)}+#[cfg(test)]+#[path = "user_scope_tests.rs"]+mod tests;+/// Activate `~/.openhuman/users/<user_id>/` as the current user directory.////// On the very first activation (no previous `active_user.toml`) thediff --git a/crates/openhuman-core/src/security/credentials/ops/user_scope_tests.rs b/crates/openhuman-core/src/security/credentials/ops/user_scope_tests.rsnew file mode 100644index 0000000000..6198ddccc4--- /dev/null+++ b/crates/openhuman-core/src/security/credentials/ops/user_scope_tests.rs@@ -0,0 +1,16 @@+use super::*;++#[test]+fn explicit_scratch_workspace_cannot_activate_operator_user() {+ let _guard = crate::config::TEST_ENV_LOCK.lock().unwrap();+ let previous = std::env::var_os("OPENHUMAN_WORKSPACE");+ let scratch = tempfile::tempdir().unwrap();+ unsafe {+ std::env::set_var("OPENHUMAN_WORKSPACE", scratch.path());+ }+ assert!(!operator_user_activation_allowed());+ match previous {+ Some(value) => unsafe { std::env::set_var("OPENHUMAN_WORKSPACE", value) },+ None => unsafe { std::env::remove_var("OPENHUMAN_WORKSPACE") },+ }+}diff --git a/crates/openhuman-core/src/security/credentials/session_support.rs b/crates/openhuman-core/src/security/credentials/session_support.rsindex a0e3fff983..df7365d2b9 100644--- a/crates/openhuman-core/src/security/credentials/session_support.rs+++ b/crates/openhuman-core/src/security/credentials/session_support.rs@@ -352,6 +352,9 @@ pub fn resolve_backend_credential(config: &Config) -> Result<BackendCredential,}let profile = load_app_session_profile(config)?;match classify_session_token(profile.as_ref(), chrono::Utc::now()) {+ SessionTokenCheck::Live(token) if is_local_session_token(&token) => {+ Err("backend unavailable for offline local session".to_owned())+ }SessionTokenCheck::Live(token) => Ok(BackendCredential::Session(token)),SessionTokenCheck::Absent => {Err("no backend session token; run auth_store_session first".to_string())diff --git a/crates/openhuman-core/src/security/credentials/session_support_tests.rs b/crates/openhuman-core/src/security/credentials/session_support_tests.rsindex ff04600507..9c55686bf1 100644--- a/crates/openhuman-core/src/security/credentials/session_support_tests.rs+++ b/crates/openhuman-core/src/security/credentials/session_support_tests.rs@@ -256,6 +256,23 @@ fn get_session_token_returns_stored_token_when_present() {assert!(state.profile_id.is_some());}+#[test]+fn offline_local_token_is_never_a_backend_bearer() {+ let tmp = TempDir::new().unwrap();+ let config = test_config(&tmp);+ AuthService::from_config(&config)+ .store_provider_token(+ APP_SESSION_PROVIDER,+ DEFAULT_AUTH_PROFILE_NAME,+ "desktop.test.local",+ std::collections::HashMap::new(),+ true,+ )+ .unwrap();+ let error = resolve_backend_credential(&config).unwrap_err();+ assert_eq!(error, "backend unavailable for offline local session");+}+/// Regression: when both an app-session profile and a stored API key are/// present, `auth.get_state` must report `credential: "api-key"`, matching/// `resolve_backend_credential`'s precedence — every backend request thediff --git a/crates/openhuman-core/src/skills/bundled/mod.rs b/crates/openhuman-core/src/skills/bundled/mod.rsindex 282e41adb9..bafbf56eb7 100644--- a/crates/openhuman-core/src/skills/bundled/mod.rs+++ b/crates/openhuman-core/src/skills/bundled/mod.rs@@ -10,6 +10,13 @@ mod mod_tests;/// Skills compiled into this product build.pub const BUNDLED: &[BundledSkill] = &[+ BundledSkill {+ dir_name: "desktop-control",+ files: &[BundledFile {+ path: "WORKFLOW.md",+ contents: include_str!("../../desktop/control/WORKFLOW.md"),+ }],+ },#[cfg(feature = "flows")]crate::flows::skills::FLOW_AUTHORING,];diff --git a/crates/openhuman-core/src/tools/mod.rs b/crates/openhuman-core/src/tools/mod.rsindex 649734da3e..3f9558b6ae 100644--- a/crates/openhuman-core/src/tools/mod.rs+++ b/crates/openhuman-core/src/tools/mod.rs@@ -24,6 +24,7 @@ pub use crate::config::tools::*;pub use crate::config::workspace::tools::*;pub use crate::cron::tools::*;pub use crate::desktop::dashboard::tools::*;+pub use crate::desktop::control::tools::*;#[cfg(feature = "flows")]pub use crate::flows::builder_tools::*;#[cfg(feature = "flows")]diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rsindex 438bfabdaa..88985298de 100644--- a/crates/openhuman-core/src/tools/ops.rs+++ b/crates/openhuman-core/src/tools/ops.rs@@ -559,6 +559,11 @@ pub fn all_tools_with_runtime(Box::new(CostDailyHistoryTool::new(config.clone())),Box::new(CostSummaryTool::new(config.clone())),Box::new(DashboardModelHealthTool::new(config.clone())),+ Box::new(DesktopTool::new(config.clone(), DesktopToolKind::Apps)),+ Box::new(DesktopTool::new(config.clone(), DesktopToolKind::Windows)),+ Box::new(DesktopTool::new(config.clone(), DesktopToolKind::Snapshot)),+ Box::new(DesktopTool::new(config.clone(), DesktopToolKind::Find)),+ Box::new(DesktopTool::new(config.clone(), DesktopToolKind::Goal)),Box::new(SecurityPolicyInfoTool::new(config.clone())),Box::new(ServiceStatusTool::new(config.clone())),Box::new(DaemonHostPrefsGetTool::new(config.clone())),@@ -1303,7 +1308,7 @@ fn tool_group(name: &str) -> crate::core::all::DomainGroup {return DomainGroup::Hosted;}// Desktop: shell-facing surfaces.- if name.starts_with("dashboard_") {+ if name.starts_with("dashboard_") || name.starts_with("desktop_") {return DomainGroup::Desktop;}// Runtimes: the managed Node/Python execution tools. These live underdiff --git a/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs b/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rsindex c85e898bda..f8e464c2c4 100644--- a/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs+++ b/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs@@ -573,6 +573,10 @@ fn desktop_tools_are_registered() {let tmp = TempDir::new().unwrap();let names = tool_names(&expansion_tools_for(&tmp));assert_contains_all(&names, DESKTOP_TOOLS);+ assert!(names.iter().any(|name| name == "desktop_goal"));+ assert!(names.iter().any(|name| name == "desktop_snapshot"));+ assert!(!names.iter().any(|name| name == "desktop_act"),+ "raw ref actions must not enter the agent/tool_search registry");}#[test]diff --git a/scripts/debug/desktop-live.mjs b/scripts/debug/desktop-live.mjsnew file mode 100644index 0000000000..a767862a86--- /dev/null+++ b/scripts/debug/desktop-live.mjs@@ -0,0 +1,206 @@+#!/usr/bin/env node+/**+ * Opt-in core-only desktop smoke test against an already-running local core.+ *+ * Prepare an empty, unsaved TextEdit document first. Set+ * `[agent] tool_dispatcher = "native"` in the isolated config for an OpenRouter+ * model that supports structured tool calls. Start the core with an+ * isolated OPENHUMAN_WORKSPACE, an operator-supplied OPENHUMAN_CORE_TOKEN (so it+ * writes no core.token file), and OPENROUTER_API_KEY when no TinyHumans session+ * is present. Then run:+ *+ * node scripts/debug/desktop-live.mjs --live --workspace "$OPENHUMAN_WORKSPACE" \+ * --model 'openai/gpt-4.1-mini' --rpc-url http://127.0.0.1:7788/rpc+ *+ * The script prints only method names and counts. It never prints a prompt,+ * transcript body, credential, accessibility value, or the random test marker.+ * It makes three bounded orchestrator turns: discover/list apps, type into the+ * unsaved document through Jev, and read the value back through accessibility.+ * Clean up by closing the unsaved document without saving after the run.+ */++import { createHash, randomUUID } from 'node:crypto';+import { copyFile, mkdir, readFile, readdir, realpath, writeFile } from 'node:fs/promises';+import path from 'node:path';++function option(name, fallback) {+ const index = process.argv.indexOf(name);+ return index < 0 ? fallback : process.argv[index + 1];+}++function fail(message) {+ throw new Error(message);+}++const workspace = option('--workspace', process.env.OPENHUMAN_WORKSPACE);+const localModule = option('--prepare-local-module', null);+if (localModule) {+ if (!workspace) fail('Pass --workspace to prepare a local module.');+ const directory = path.join(workspace, 'desktop-live-module');+ const destination = path.join(directory, path.basename(localModule));+ await mkdir(directory, { recursive: true, mode: 0o700 });+ await copyFile(localModule, destination);+ const digest = createHash('sha256').update(await readFile(destination)).digest('hex');+ await writeFile(path.join(directory, 'modules.toml'),+ `${JSON.stringify(path.basename(destination))} = ${JSON.stringify(digest)}\n`,+ { mode: 0o600 });+ console.log('Local debug module copied and operator allowlist written.');+ const canonical = await realpath(destination);+ console.log(`Add [[modules.overrides]] with id = "tinydesktop" and path = ${JSON.stringify(canonical)} to the isolated core config, then restart the core.`);+ process.exit(0);+}+if (!process.argv.includes('--live')) fail('Pass --live to run real desktop actions.');+const rpcUrl = option('--rpc-url', 'http://127.0.0.1:7788/rpc');+const model = option('--model', process.env.OPENHUMAN_DESKTOP_TEST_MODEL);+const token = process.env.OPENHUMAN_CORE_TOKEN;+const openRouterKey = process.env.OPENROUTER_API_KEY;+const approveDisposable = process.argv.includes('--approve-disposable');+const localOfflineSession = process.argv.includes('--local-offline-session');+if (!workspace || !model || !token) {+ fail('Set --workspace, --model, and OPENHUMAN_CORE_TOKEN.');+}+if (!rpcUrl.startsWith('http://127.0.0.1:') && !rpcUrl.startsWith('http://localhost:')) {+ fail('The live driver accepts only a loopback core RPC URL.');+}++let sequence = 0;+async function rpc(method, params = {}) {+ const response = await fetch(rpcUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },+ body: JSON.stringify({ jsonrpc: '2.0', id: ++sequence, method, params }),+ signal: AbortSignal.timeout(240_000),+ });+ if (!response.ok) fail(`${method}: HTTP ${response.status}`);+ const body = await response.json();+ if (body.error) fail(`${method}: JSON-RPC error ${body.error.code ?? 'unknown'}`);+ return body.result;+}++async function transcriptFiles(directory) {+ const files = [];+ async function visit(dir) {+ for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {+ const file = path.join(dir, entry.name);+ if (entry.isDirectory()) await visit(file);+ else if (entry.isFile() && file.endsWith('.jsonl')) files.push(file);+ }+ }+ await visit(directory);+ return files;+}++async function readThread(threadId) {+ const files = await transcriptFiles(path.join(workspace, 'session_raw'));+ const messages = [];+ for (const file of files) {+ const lines = (await readFile(file, 'utf8')).split(/\r?\n/).filter(Boolean);+ if (lines.length === 0) continue;+ let meta;+ try { meta = JSON.parse(lines[0])._meta; } catch { continue; }+ if (meta?.thread_id !== threadId || meta?.agent !== 'orchestrator') continue;+ for (const line of lines.slice(1)) {+ try { messages.push(JSON.parse(line)); } catch { /* partial append */ }+ }+ }+ return messages;+}++function calls(messages) {+ const names = [];+ for (const message of messages) {+ for (const call of message.tool_calls ?? []) {+ const name = call.function?.name ?? call.name;+ if (typeof name === 'string') names.push(name);+ if (name === 'tool_call') {+ let argumentsValue = call.function?.arguments ?? call.arguments;+ if (typeof argumentsValue === 'string') {+ try { argumentsValue = JSON.parse(argumentsValue); } catch { argumentsValue = {}; }+ }+ if (typeof argumentsValue?.name === 'string') names.push(argumentsValue.name);+ }+ }+ }+ return names;+}++const threadId = `desktop-live-${randomUUID()}`;+const marker = `OH desktop live ${randomUUID()}`;+const route = openRouterKey ? {+ inference_url: 'https://openrouter.ai/api/v1', api_key: openRouterKey,+} : {};++async function turn(label, message) {+ const before = (await readThread(threadId)).length;+ await rpc('openhuman.inference_agent_chat', {+ message, thread_id: threadId, model_override: model, ...route,+ });+ const transcript = await readThread(threadId);+ if (transcript.length <= before) fail(`${label}: no orchestrator transcript appeared`);+ console.log(`${label}: ${transcript.length - before} new transcript records`);+ return transcript;+}++if (localOfflineSession) {+ await rpc('openhuman.auth_set_credential', {+ token: `desktop-live.${randomUUID().replaceAll('-', '')}.local`,+ kind: 'local',+ user: { id: 'desktop-live', name: 'Desktop live test' },+ });+ console.log('auth: isolated offline local session installed');+}+const status = await rpc('openhuman.desktop_set_enabled', { enabled: true });+if (!status.supported) fail('Desktop control is unsupported on this host.');+if (status.module_state === 'failed') fail('Desktop module failed to load; inspect local core logs.');+if (status.accessibility !== 'granted') fail('Grant Accessibility to the core process, then retry.');+console.log(`desktop: module=${status.module_state}, accessibility=${status.accessibility}, jev_ready=${status.jev_ready}`);+if (!status.jev_ready) fail('No Jev credential is available to the core.');++let transcript = await turn('discover',+ 'List the running desktop applications on this computer. Discover desktop tools with tool_search first, then call the matching desktop tool. Report only whether TextEdit is running.');+let names = calls(transcript);+if (!names.includes('tool_search') || !names.includes('desktop_list_apps')) {+ fail(`discover: expected tool_search then desktop_list_apps; saw ${names.join(', ')}`);+}+console.log('discover: tool_search -> desktop_list_apps observed');++transcript = await turn('windows',+ 'Use the desktop window listing tool to list windows belonging to TextEdit. Do not change any app.');+names = calls(transcript);+if (!names.includes('desktop_list_windows')) fail(`windows: desktop_list_windows was not called; saw ${names.join(', ')}`);+console.log('windows: desktop_list_windows observed');++transcript = await turn('type',+ `In the already open, empty, unsaved TextEdit document, type this exact marker: ${marker}. ` ++ 'Use tool_search to find desktop_goal and run the bounded goal with max_steps 4 and max_model_calls 8. Do not save or close the document.');+names = calls(transcript);+if (!names.includes('desktop_goal')) fail(`type: desktop_goal was not called; saw ${names.join(', ')}`);++const pending = await rpc('openhuman.desktop_pending');+if (Array.isArray(pending) && pending.length > 0) {+ console.log(`type: ${pending.length} action(s) paused for user confirmation`);+ if (!approveDisposable) {+ fail('Inspect the pending action in Connections. Rerun with --approve-disposable only for a disposable TextEdit document.');+ }+ if (pending.length !== 1 || pending[0].app !== 'TextEdit') {+ fail('Approval refused: pending action is not the single TextEdit test action.');+ }+ await rpc('openhuman.desktop_confirm', {+ confirmation_id: pending[0].confirmation_id, approve: true,+ });+ transcript = await turn('continue',+ `Continue the previously paused TextEdit desktop goal using confirmation_id ${pending[0].confirmation_id}. ` ++ 'The user approved the action in the trusted connection UI. Call desktop_goal with only that confirmation_id; the core restores the original goal.');+ if (!calls(transcript).includes('desktop_goal')) fail('continue: desktop_goal was not called');+ console.log('continue: trusted confirmation consumed by agent desktop_goal call');+}++transcript = await turn('verify',+ 'Read the full accessibility snapshot of the current TextEdit document using desktop_snapshot with skeleton false. Do not change the document.');+names = calls(transcript);+if (!names.includes('desktop_snapshot')) fail(`verify: desktop_snapshot was not called; saw ${names.join(', ')}`);+const observed = transcript.some((message) => message.role === 'tool' &&+ JSON.stringify(message.content ?? '').includes(marker));+if (!observed) fail('verify: marker was not observed in a desktop tool result');+console.log('verify: marker observed in desktop_snapshot tool result');+console.log('PASS: direct-core orchestrator discovered and used desktop tools; close the unsaved TextEdit document without saving.');diff --git a/vendor/tinybus b/vendor/tinybusindex 3aba4abe85..6ee8258c03 160000--- a/vendor/tinybus+++ b/vendor/tinybus@@ -1 +1 @@-Subproject commit 3aba4abe8564fa803f3054bd5538f46daf43629b+Subproject commit 6ee8258c03eb442aca8225d328d3c8e7c5489af6diff --git a/vendor/tinydesktop b/vendor/tinydesktopnew file mode 160000index 0000000000..cab323a2bf--- /dev/null+++ b/vendor/tinydesktop@@ -0,0 +1 @@+Subproject commit cab323a2bf92da0a52d1a77665076ef7ada89ee4