Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat: guide computer access and keep roster order per device
leepokaie75fadd8c9e1
diff --git a/apps/desktop/src/main/screen.ts b/apps/desktop/src/main/screen.tsindex daf8af7a..8a23f771 100644--- a/apps/desktop/src/main/screen.ts+++ b/apps/desktop/src/main/screen.ts@@ -1,8 +1,9 @@-import { statSync } from 'node:fs'+import { existsSync, statSync } from 'node:fs'import { join } from 'node:path'import { app, ipcMain } from 'electron'import { prefs } from './host-controller'import { identity } from './environment'+import { shouldSyncScreenAgent } from '../shared/computer-access'// Codync Screen (capture + input for Remote screen): on macOS a launchd agent inside the app// bundle (apps/screen-macos, registered through SMAppService), which owns the Screen Recording@@ -31,6 +32,7 @@ export function setScreenAgent(on: boolean): { needsApproval: boolean } {if (!isMac || !app.isPackaged) return { needsApproval: false }app.setLoginItemSettings({ type: 'agentService', serviceName, openAtLogin: on })prefs.set('screenHelperStamp', on ? helperStamp() : null)+ prefs.set('screenHelperResumeAfterUpdate', false)return { needsApproval: status() === 'requires-approval' }}@@ -40,6 +42,10 @@ export function setScreenAgent(on: boolean): { needsApproval: boolean } {*/export function syncScreenAgent(enabled: boolean): { needsApproval: boolean } {if (!isMac || !app.isPackaged || !enabled) return { needsApproval: false }+ // A first registration belongs to explicit setup, never application startup.+ if (!shouldSyncScreenAgent(enabled, status(), prefs.get('screenHelperResumeAfterUpdate') === true)) {+ return { needsApproval: status() === 'requires-approval' }+ }const stale = prefs.get('screenHelperStamp') !== helperStamp()if (!stale && status() === 'enabled') return { needsApproval: false }if (stale && status() === 'enabled') app.setLoginItemSettings({ type: 'agentService', serviceName, openAtLogin: false })@@ -49,11 +55,17 @@ export function syncScreenAgent(enabled: boolean): { needsApproval: boolean } {/** Before the app is replaced: the old helper stops along with its job. */export function unregisterScreenAgent() {if (!isMac || !app.isPackaged || status() !== 'enabled') return+ prefs.set('screenHelperResumeAfterUpdate', true)app.setLoginItemSettings({ type: 'agentService', serviceName, openAtLogin: false })prefs.set('screenHelperStamp', null)}export function registerScreenIPC() {+ ipcMain.handle('screen:state', () => ({+ available: !isMac || (app.isPackaged && existsSync(join(process.resourcesPath, '..', `Library/LoginItems/${identity.screenName}.app/Contents/MacOS/${identity.screenName}`))),+ needsApproval: status() === 'requires-approval',+ registered: status() === 'enabled',+ }))ipcMain.handle('screen:setAgent', (_e, on: boolean) => setScreenAgent(on))ipcMain.handle('screen:syncAgent', (_e, enabled: boolean) => syncScreenAgent(enabled))}diff --git a/apps/desktop/src/main/tray.ts b/apps/desktop/src/main/tray.tsindex 252bc15d..25d16cfd 100644--- a/apps/desktop/src/main/tray.ts+++ b/apps/desktop/src/main/tray.ts@@ -147,14 +147,7 @@ export class Tray {},{ label: screen.subtitle, enabled: false },]- if (screen.enabled) {- if (screen.needsLoginItem) {- items.push({ label: `Allow ${app.getName()} Screen in Login Items…`, click: () => void shell.openExternal('x-apple.systempreferences:com.apple.LoginItems-Settings.extension') })- } else {- if (screen.needsCapture) items.push({ label: 'Allow Screen Recording…', click: () => void shell.openExternal('x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture') })- if (screen.needsInput) items.push({ label: 'Allow Accessibility…', click: () => void shell.openExternal('x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility') })- }- }+ items.push({ label: 'Set up computer access…', click: () => this.deps.send({ kind: 'computerAccess' }, true) })if (screen.error) items.push({ label: screen.error, enabled: false })return items}diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex 00515898..1e55d69d 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -92,6 +92,7 @@ const bridge: CodyncBridge = {launchAtLogin: () => ipcRenderer.invoke('app:launchAtLogin'),openSettings: (url) => ipcRenderer.send('app:openSettings', url),authenticate: (url, scheme) => ipcRenderer.invoke('app:authenticate', url, scheme),+ screenAgentState: () => ipcRenderer.invoke('screen:state'),setScreenAgent: (on) => ipcRenderer.invoke('screen:setAgent', on),syncScreenAgent: (enabled) => ipcRenderer.invoke('screen:syncAgent', enabled),},diff --git a/apps/desktop/src/renderer/demo/bridge.ts b/apps/desktop/src/renderer/demo/bridge.tsindex 0778627f..c02811e8 100644--- a/apps/desktop/src/renderer/demo/bridge.ts+++ b/apps/desktop/src/renderer/demo/bridge.ts@@ -88,6 +88,7 @@ const bridge: CodyncBridge = {launchAtLogin: async () => false,openSettings() {},authenticate: unavailable,+ screenAgentState: async () => ({ available: false, needsApproval: false, registered: false }),setScreenAgent: unavailable,syncScreenAgent: async () => ({ needsApproval: false }),},@@ -98,6 +99,7 @@ const bridge: CodyncBridge = {try {for (const key of Object.keys(localStorage)) if (key.startsWith('codync-')) localStorage.removeItem(key)localStorage.setItem('macAccountOnboardingCompleted', 'true')+ localStorage.setItem('computerAccessSetup', JSON.stringify('later'))localStorage.setItem('githubStarAsk', JSON.stringify({ kind: 'done' }))} catch {}diff --git a/apps/desktop/src/renderer/demo/fake-host.ts b/apps/desktop/src/renderer/demo/fake-host.tsindex cf4e49b9..c6b0bf9a 100644--- a/apps/desktop/src/renderer/demo/fake-host.ts+++ b/apps/desktop/src/renderer/demo/fake-host.ts@@ -249,7 +249,7 @@ export class FakeHost {case 'listDirs':return { path: '/Users/demo/code', parent: '/Users/demo', isGit: false, dirs: [{ name: 'pace', path: story.cwd, isGit: true }] }case 'memory':- return { location: '', facts: [] }+ return { location: '', facts: [], total: 0, nextOffset: null }case 'routines':return { routines: [], runs: [] }case 'skills':diff --git a/apps/desktop/src/renderer/lib/computer-access.test.ts b/apps/desktop/src/renderer/lib/computer-access.test.tsnew file mode 100644index 00000000..1fdc1bcd--- /dev/null+++ b/apps/desktop/src/renderer/lib/computer-access.test.ts@@ -0,0 +1,52 @@+import assert from 'node:assert/strict'+import { existsSync } from 'node:fs'+import { registerHooks } from 'node:module'+import { test } from 'node:test'+import type { AppModel } from '../store/app-model'++registerHooks({ resolve(specifier, context, nextResolve) {+ if (specifier.startsWith('@shared/')) return nextResolve(new URL(`../../shared/${specifier.slice(8)}.ts`, import.meta.url).href, context)+ if (specifier.startsWith('.') && context.parentURL && !/\.[a-z]+$/.test(specifier)) {+ const url = new URL(`${specifier}.ts`, context.parentURL)+ if (existsSync(url)) return nextResolve(url.href, context)+ }+ return nextResolve(specifier, context)+} })++test('repeated checks never request permissions; explicit actions and failures stay reviewable', async () => {+ const calls: string[] = []+ let fail = false+ let capture = false+ let settings = ''+ Object.assign(globalThis, { window: { codync: { platform: 'darwin', app: {+ screenAgentState: async () => ({ available: true, needsApproval: false, registered: true }),+ openSettings: (url: string) => { settings = url },+ } } } })+ const app = { local: { connection: { kind: 'online' }, client: { call: async (method: string) => {+ calls.push(method)+ if (method === 'requestScreenPermission' && fail) throw new Error('Permission denied')+ return { enabled: true, connected: true, capture, input: false, permissionApp: 'CodyncDevScreen' }+ } } }, setRemoteScreen: async () => { calls.push('enable') }, screenError: null } as unknown as AppModel+ const { ComputerAccess } = await import('../store/computer-access.ts')+ const access = new ComputerAccess(app)+ await access.refresh()+ await access.refresh()+ assert.deepEqual(calls, ['screenStatus', 'screenStatus'])+ assert.equal(access.helperName, 'CodyncDevScreen')+ assert.equal(access.step, 'capture')+ access.openSettings('input')+ assert.match(settings, /Privacy_Accessibility/)+ assert.equal(access.step, 'capture')+ fail = true+ await access.request('capture')+ assert.equal(access.busy, null)+ assert.equal(access.error, 'Permission denied')+ assert.equal(access.requested.has('capture'), true)+ fail = false+ capture = true+ await access.request('capture')+ assert.equal(access.error, null)+ assert.equal(access.step, 'input')+ await access.enable()+ assert.ok(calls.includes('enable'))+})diff --git a/apps/desktop/src/renderer/lib/computer-order.test.ts b/apps/desktop/src/renderer/lib/computer-order.test.tsnew file mode 100644index 00000000..5652acb0--- /dev/null+++ b/apps/desktop/src/renderer/lib/computer-order.test.ts@@ -0,0 +1,72 @@+import assert from 'node:assert/strict'+import { existsSync } from 'node:fs'+import { registerHooks } from 'node:module'+import { test } from 'node:test'++// Run the actual renderer store with a browser's local storage and account events.+registerHooks({+ resolve(specifier, context, nextResolve) {+ if (specifier.startsWith('.') && context.parentURL && !/\.[a-z]+$/.test(specifier)) {+ const url = new URL(`${specifier}.ts`, context.parentURL)+ if (existsSync(url)) return nextResolve(url.href, context)+ }+ return nextResolve(specifier, context)+ },+})++test('computer ordering stays on each device, survives restart, and isolates accounts', async () => {+ let disk = new Map<string, string>()+ const desktopDisk = disk+ const listeners = new Map<string, ((event: unknown) => void)[]>()+ const user = { userId: 'same-account', email: null, avatarURL: null }+ let session = { user: user as typeof user | null, cloudURL: 'https://cloud.test', ready: true, configured: true, busy: false, error: null }+ const network = () => assert.fail('Ordering must not send network requests')+ Object.assign(globalThis, {+ localStorage: { getItem: (key: string) => disk.get(key) ?? null, setItem: (key: string, value: string) => disk.set(key, value) },+ window: {+ addEventListener: (type: string, callback: (event: unknown) => void) => listeners.set(type, [...listeners.get(type) ?? [], callback]),+ setInterval: () => assert.fail('Ordering must not poll'),+ codync: { cloud: { request: network }, account: { state: async () => session, onChange() {} } },+ },+ fetch: network,+ })+ const { account } = await import('../store/account.ts')+ const { DeviceComputerOrder } = await import('../store/computer-order.ts')+ const selectAccount = async (id: string | null, cloudURL = 'https://cloud.test') => {+ session = { ...session, user: id ? { ...user, userId: id } : null, cloudURL }+ await account.start()+ await new Promise((resolve) => setImmediate(resolve))+ }+ await selectAccount('same-account')+ const key = 'computerOrder.https://cloud.test/same-account'+ desktopDisk.set(key, JSON.stringify({ ids: ['a', 'hidden', 'b'], pending: true }))+ const desktop = new DeviceComputerOrder()+ assert.deepEqual(desktop.ids, ['a', 'hidden', 'b'])+ desktop.move('b', 'a', ['a', 'b', 'new'])+ assert.deepEqual(JSON.parse(desktopDisk.get(key)!), { ids: ['b', 'a', 'hidden', 'new'] })+ assert.deepEqual(new DeviceComputerOrder().ids, desktop.ids)++ // A second installation uses the same account but has a separate localStorage.+ disk = new Map()+ const laptop = new DeviceComputerOrder()+ assert.deepEqual(laptop.ids, [])+ laptop.move('a', 'b', ['a', 'b'])+ assert.deepEqual(laptop.ids, ['b', 'a'])+ assert.deepEqual(desktop.ids, ['b', 'a', 'hidden', 'new'])+ assert.deepEqual(new DeviceComputerOrder().ids, ['b', 'a'])+ assert.deepEqual(JSON.parse(desktopDisk.get(key)!).ids, desktop.ids)++ disk = desktopDisk+ await selectAccount('another-account')+ assert.deepEqual(desktop.ids, [])+ desktop.move('x', 'y', ['x', 'y'])+ await selectAccount('same-account')+ assert.deepEqual(desktop.ids, ['b', 'a', 'hidden', 'new'])+ await selectAccount('same-account', 'https://another-cloud.test')+ assert.deepEqual(desktop.ids, [])+ await selectAccount(null)+ desktop.move('local', 'ssh', ['local', 'ssh'])+ assert.deepEqual(JSON.parse(desktopDisk.get('computerOrder')!), ['ssh', 'local'])+ assert.equal(listeners.has('focus'), false)+ assert.equal(listeners.has('online'), false)+})diff --git a/apps/desktop/src/renderer/lib/computer-roster.test.ts b/apps/desktop/src/renderer/lib/computer-roster.test.tsnew file mode 100644index 00000000..62e7f7e7--- /dev/null+++ b/apps/desktop/src/renderer/lib/computer-roster.test.ts@@ -0,0 +1,31 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { computerSections, moveComputer, orderedComputers } from './computer-roster.ts'++test('saved computer order survives reconnect order and appends new computers', () => {+ const computers = [{ id: 'new' }, { id: 'a' }, { id: 'b' }]+ assert.deepEqual(orderedComputers(computers, ['gone', 'b', 'a']).map((c) => c.id), ['b', 'a', 'new'])+ assert.equal(computers[0]?.id, 'new')+})++test('moving a section works in either direction without losing hidden computers', () => {+ const order = ['a', 'hidden', 'b', 'c']+ assert.deepEqual(moveComputer(order, 'a', 'b'), ['hidden', 'b', 'a', 'c'])+ assert.deepEqual(moveComputer(order, 'c', 'a'), ['c', 'a', 'hidden', 'b'])+ assert.deepEqual(moveComputer(order, 'a', 'a'), order)+ assert.deepEqual(moveComputer(order, 'missing', 'b'), order)+ assert.deepEqual(moveComputer(order, 'a', 'missing'), order)+ assert.deepEqual(order, ['a', 'hidden', 'b', 'c'])+})++test('each computer keeps its own bots in activity order, including duplicate bot ids', () => {+ const roster = [+ { id: 'same', ref: { computerId: 'b' } },+ { id: 'same', ref: { computerId: 'a' } },+ { id: 'hidden', ref: { computerId: 'hidden' } },+ { id: 'older', ref: { computerId: 'b' } },+ ]+ const sections = computerSections([{ id: 'a' }, { id: 'b' }, { id: 'empty' }], roster)+ assert.deepEqual(sections.map((s) => s.items.map((i) => i.id)), [['same'], ['same', 'older'], []])+ assert.equal(sections[0]?.items[0]?.ref.computerId, 'a')+})diff --git a/apps/desktop/src/renderer/lib/computer-roster.ts b/apps/desktop/src/renderer/lib/computer-roster.tsnew file mode 100644index 00000000..7ae5bf64--- /dev/null+++ b/apps/desktop/src/renderer/lib/computer-roster.ts@@ -0,0 +1,24 @@+/** Saved computers retain their order; newly connected computers follow them. */+export function orderedComputers<T extends { id: string }>(computers: T[], order: string[]): T[] {+ const ranks = new Map(order.map((id, index) => [id, index]))+ return [...computers].sort((a, b) => (ranks.get(a.id) ?? order.length) - (ranks.get(b.id) ?? order.length))+}++/** Insert at the target's position, preserving hidden computers and unrelated ordering. */+export function moveComputer(order: string[], id: string, target: string): string[] {+ const from = order.indexOf(id)+ const to = order.indexOf(target)+ if (from < 0 || to < 0 || from === to) return order+ const next = [...order]+ next.splice(from, 1)+ next.splice(to, 0, id)+ return next+}++/** Group without changing pinned/activity order inside each computer. Include empty computers. */+export function computerSections<C extends { id: string }, T extends { ref: { computerId: string } }>(computers: C[], roster: T[]) {+ const sections = computers.map((computer) => ({ computer, items: [] as T[] }))+ const byID = new Map(sections.map((section) => [section.computer.id, section]))+ for (const item of roster) byID.get(item.ref.computerId)?.items.push(item)+ return sections+}diff --git a/apps/desktop/src/renderer/lib/prefs.ts b/apps/desktop/src/renderer/lib/prefs.tsindex fe48de4c..d983cd97 100644--- a/apps/desktop/src/renderer/lib/prefs.ts+++ b/apps/desktop/src/renderer/lib/prefs.ts@@ -57,8 +57,11 @@ export const prefs = {sidebarCompact: pref('sidebarCompact', false),sidebarWidth: pref('desktopSidebarWidth', 266),hiddenComputers: pref('hiddenComputers', ''),+ computerOrder: pref<string[]>('computerOrder', []),+ collapsedComputers: pref<string[]>('collapsedComputerSections', []),usageIconStyle: pref<'character' | 'original'>('usageIconStyle', 'character'),onboardingDone: pref('macAccountOnboardingCompleted', false),+ computerAccessSetup: pref<'ready' | 'later' | null>('computerAccessSetup', null),starAsk: pref<StarAsk>('githubStarAsk', { kind: 'never' }),}diff --git a/apps/desktop/src/renderer/store/app-model.ts b/apps/desktop/src/renderer/store/app-model.tsindex 21cd511b..cd374fcf 100644--- a/apps/desktop/src/renderer/store/app-model.ts+++ b/apps/desktop/src/renderer/store/app-model.ts@@ -5,6 +5,8 @@ import { Observable } from '../lib/observable'import { account } from './account'import { BotStore } from './bot-store'import { CloudModel } from './cloud'+import { DeviceComputerOrder } from './computer-order'+import { ComputerAccess } from './computer-access'/** A bot on a computer: bot ids are only unique per computer. */export interface BotRef {@@ -56,10 +58,14 @@ export class AppModel extends Observable {private storeSubscriptions = new Map<string, () => void>()/** The signed-in account's side of this computer (claims, cloud default, account computers). */+ readonly computerAccess: ComputerAccess+ readonly computerOrder: DeviceComputerOrderreadonly cloud: CloudModelconstructor(private mirrors = true) {super()+ this.computerAccess = new ComputerAccess(this)+ this.computerOrder = new DeviceComputerOrder()this.cloud = new CloudModel(this)account.subscribe(() => this.noteAccount())}@@ -222,6 +228,9 @@ export class AppModel extends Observable {void window.codync.app.syncScreenAgent(store.screen.enabled).then((r) => {this.screenNeedsApproval = r.needsApprovalthis.changed()+ }).catch((error: unknown) => {+ this.screenError = error instanceof Error ? error.message : String(error)+ this.changed()})}diff --git a/apps/desktop/src/renderer/store/computer-access.ts b/apps/desktop/src/renderer/store/computer-access.tsnew file mode 100644index 00000000..5cb22f2f--- /dev/null+++ b/apps/desktop/src/renderer/store/computer-access.ts@@ -0,0 +1,88 @@+import { computerAccessStep, computerPermissionSettings, type ComputerPermission, type ScreenAgentState } from '@shared/computer-access'+import { normalizeScreen, type ScreenState } from '@shared/models'+import { Observable } from '../lib/observable'+import type { AppModel } from './app-model'++/** Read-only checks are safe on launch. Requests happen only after an explicit setup action. */+export class ComputerAccess extends Observable {+ screen: ScreenState | null = null+ agent: ScreenAgentState | null = null+ busy: ComputerPermission | 'enable' | null = null+ private checkError: string | null = null+ private actionError: string | null = null+ private lastRequest: ComputerPermission | null = null+ requested = new Set<ComputerPermission>()+ private refreshing = false+ private app: AppModel++ constructor(app: AppModel) { super(); this.app = app }++ get step() {+ return computerAccessStep(window.codync.platform, this.app.local?.connection.kind === 'online', this.screen, this.agent)+ }++ get helperName() { return this.screen?.permissionApp || 'Codync Screen' }+ get error() { return this.checkError ?? this.actionError }++ async refresh() {+ if (this.refreshing) return+ this.refreshing = true+ try {+ const local = this.app.local+ this.agent = await window.codync.app.screenAgentState()+ if (local?.client && local.connection.kind === 'online') {+ this.screen = normalizeScreen(await local.client.call<ScreenState>('screenStatus', {}))+ } else this.screen = null+ this.checkError = null+ const granted = this.lastRequest === 'portal'+ ? this.screen?.capture && this.screen.input+ : this.lastRequest && this.screen?.[this.lastRequest]+ if (granted || this.step === 'ready') this.actionError = null+ } catch (error) {+ this.screen = null+ this.checkError = message(error)+ } finally {+ this.refreshing = false+ this.changed()+ }+ }++ async enable() {+ if (this.busy) return+ this.busy = 'enable'+ this.actionError = null+ this.changed()+ try {+ await this.app.setRemoteScreen(true)+ if (this.app.screenError) throw new Error(this.app.screenError)+ await this.refresh()+ } catch (error) { this.actionError = message(error) }+ finally { this.busy = null; this.changed() }+ }++ async request(permission: ComputerPermission) {+ const client = this.app.local?.client+ if (!client || this.busy) return+ this.busy = permission+ this.actionError = null+ this.lastRequest = permission+ this.requested.add(permission)+ this.changed()+ try {+ await client.call('requestScreenPermission', { permission }, 125_000)+ await this.refresh()+ } catch (error) {+ this.actionError = message(error)+ } finally { this.busy = null; this.changed() }+ }++ openSettings(permission: keyof typeof computerPermissionSettings) {+ window.codync.app.openSettings(computerPermissionSettings[permission])+ }+}++function message(error: unknown): string {+ if (error instanceof Error) return error.message+ if (error && typeof error === 'object' && 'message' in error) return String(error.message)+ return String(error)+}diff --git a/apps/desktop/src/renderer/store/computer-order.ts b/apps/desktop/src/renderer/store/computer-order.tsnew file mode 100644index 00000000..fbba9139--- /dev/null+++ b/apps/desktop/src/renderer/store/computer-order.ts@@ -0,0 +1,45 @@+import { Observable } from '../lib/observable'+import { pref, prefs, type Pref } from '../lib/prefs'+import { moveComputer } from '../lib/computer-roster'+import { account } from './account'++/** This device's order, kept separately for each account and cloud environment. */+export class DeviceComputerOrder extends Observable {+ private scope: string | null = null+ private saved: Pref<{ ids: string[] }> | null = null+ private accounts = new Map<string, Pref<{ ids: string[] }>>()+ private unsubscribe: (() => void) | undefined++ constructor() {+ super()+ account.subscribe(() => this.updateAccount())+ prefs.computerOrder.subscribe(() => { if (!this.saved) this.changed() })+ this.updateAccount()+ }++ get ids() { return this.saved?.get().ids ?? prefs.computerOrder.get() }++ move(id: string, target: string, computers: string[]) {+ const current = [...new Set([...this.ids, ...computers])]+ const next = moveComputer(current, id, target)+ if (next === current) return+ if (this.saved) this.saved.set({ ids: next })+ else prefs.computerOrder.set(next)+ }++ private updateAccount() {+ const user = account.user?.userId+ const scope = user ? `${account.cloudURL}/${user}` : null+ if (scope === this.scope) return+ this.unsubscribe?.()+ this.scope = scope+ this.saved = null+ if (scope) {+ const saved = this.accounts.get(scope) ?? pref<{ ids: string[] }>(`computerOrder.${scope}`, { ids: [] })+ this.accounts.set(scope, saved)+ this.saved = saved+ this.unsubscribe = saved.subscribe(() => this.changed())+ }+ this.changed()+ }+}diff --git a/apps/desktop/src/renderer/store/computer-roster.ts b/apps/desktop/src/renderer/store/computer-roster.tsnew file mode 100644index 00000000..4b6d7412--- /dev/null+++ b/apps/desktop/src/renderer/store/computer-roster.ts@@ -0,0 +1,29 @@+import { computerSections, orderedComputers } from '../lib/computer-roster'+import { prefs, usePref } from '../lib/prefs'+import { useModel } from '../lib/observable'+import type { BotStore } from './bot-store'+import type { AppModel } from './app-model'++/** Device-local section ordering and folding, matching the iPhone roster. */+export function useComputerRoster(app: AppModel, shown: Set<string>) {+ const order = useModel(app.computerOrder).ids+ const [collapsed, setCollapsed] = usePref(prefs.collapsedComputers)+ const computers = orderedComputers(app.computers, order)+ const sections = computerSections(computers.filter((c) => shown.has(c.id)), app.roster)+ .map((section) => ({ ...section, store: app.store(section.computer.id) }))+ .filter((section): section is typeof section & { store: BotStore } => section.store !== null)+ const grouped = sections.length > 1+ return {+ sections,+ grouped,+ collapsed,+ items: sections.flatMap((section) => section.items),+ navigable: sections.flatMap((section) => grouped && collapsed.includes(section.computer.id) ? [] : section.items),+ toggle(id: string) {+ setCollapsed(collapsed.includes(id) ? collapsed.filter((value) => value !== id) : [...collapsed, id])+ },+ move(id: string, target: string) {+ app.computerOrder.move(id, target, computers.map((c) => c.id))+ },+ }+}diff --git a/apps/desktop/src/renderer/views/BotRoster.tsx b/apps/desktop/src/renderer/views/BotRoster.tsxnew file mode 100644index 00000000..72f3d661--- /dev/null+++ b/apps/desktop/src/renderer/views/BotRoster.tsx@@ -0,0 +1,62 @@+import { useState } from 'react'+import { isGroup, type Bot } from '@shared/models'+import { sameRef, refKey, type RosterItem } from '../store/app-model'+import type { BotStore } from '../store/bot-store'+import type { useComputerRoster } from '../store/computer-roster'+import { StoreContext, useApp } from '../store/context'+import { BotRow } from './BotRow'+import { ComputerRosterSection } from './ComputerRosterSection'+import { UpdateNeededCard } from './UpdateNeededCard'++export function BotRoster({ roster, compact, onContext }: {+ roster: ReturnType<typeof useComputerRoster>+ compact: boolean+ onContext: (bot: Bot, store: BotStore, x: number, y: number) => void+}) {+ const app = useApp()+ const selected = app.selection+ const [hovered, setHovered] = useState<string | null>(null)+ const [dragged, setDragged] = useState<string | null>(null)+ const row = (item: RosterItem) => {+ const key = refKey(item.ref)+ const isSelected = sameRef(item.ref, selected)+ return (+ <button+ key={key}+ className="roster-row"+ style={{+ padding: compact ? 0 : '0 8px',+ background: isSelected ? 'var(--roster-selected)' : hovered === key ? 'var(--bubble-agent)' : 'transparent',+ }}+ aria-label={roster.sections.length > 1 ? `${item.bot.name}, on ${item.store.hostName}` : item.bot.name}+ aria-selected={isSelected}+ title={roster.sections.length > 1 ? `${item.bot.name} · ${item.store.hostName}` : item.bot.name}+ onMouseEnter={() => setHovered(key)}+ onMouseLeave={() => setHovered((h) => (h === key ? null : h))}+ onClick={() => app.select(item.ref)}+ onContextMenu={(e) => {+ e.preventDefault()+ onContext(item.bot, item.store, e.clientX, e.clientY)+ }}+ >+ <BotRow bot={item.bot} store={item.store} compact={compact} usingComputer={item.store.screen?.agentBot === item.bot.id} members={isGroup(item.bot) ? item.store.members(item.bot) : noMembers} />+ </button>+ )+ }++ return roster.sections.map(({ computer, store, items }, index) => {+ const notice = store.mismatch && !compact ? <StoreContext.Provider value={store}><UpdateNeededCard /></StoreContext.Provider> : null+ if (!roster.grouped) return <div key={computer.id}>{notice}{items.map(row)}</div>+ return (+ <ComputerRosterSection key={computer.id} store={store} compact={compact}+ collapsed={roster.collapsed.includes(computer.id)} toggle={() => roster.toggle(computer.id)}+ previous={roster.sections[index - 1]?.computer.id} next={roster.sections[index + 1]?.computer.id}+ dragged={dragged} setDragged={setDragged} move={roster.move} notice={notice}>+ {items.map(row)}+ {!items.length && !store.mismatch && !compact ? <div className="computer-roster-empty">{store.shownConnection.kind === 'online' ? 'No bots yet' : store.connectionLabel}</div> : null}+ </ComputerRosterSection>+ )+ })+}++const noMembers: Bot[] = []diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsxindex 55e92b0f..8fdadd1a 100644--- a/apps/desktop/src/renderer/views/ChatWindow.tsx+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx@@ -1,17 +1,18 @@import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'import type { WindowCommand } from '@shared/ipc'import { isSSHConnecting, showsChat as shouldShowChat } from '@shared/ssh-startup'-import { draftOf, isGroup, type Bot, type BotDraft } from '@shared/models'+import { draftOf, type Bot, type BotDraft } from '@shared/models'import { CharacterAvatar } from '../components/Avatar'import { Button, ChoicePicker, IconButton } from '../components/Controls'-import { AnchoredMenu, Dialog, Sheet, type MenuItem } from '../components/Overlay'+import { AnchoredMenu, Dialog, ModalHeader, Sheet, type MenuItem } from '../components/Overlay'import { font } from '../lib/fonts'import { useModels } from '../lib/observable'import { prefs, stepTextSize, usePref, DEFAULT_TEXT_SIZE } from '../lib/prefs'import { useApp, StoreContext } from '../store/context'import { refKey, sameRef, parseRef, type BotRef } from '../store/app-model'import type { BotStore } from '../store/bot-store'-import { BotRow } from './BotRow'+import { useComputerRoster } from '../store/computer-roster'+import { BotRoster } from './BotRoster'import { SidebarFooter } from './SidebarFooter'import { ComputerFilterHeader, computerSelection } from './ComputerFilterHeader'import { ThreadView } from './thread/ThreadView'@@ -20,9 +21,9 @@ import { BotEditorView } from './bots/BotEditorView'import { MarketplaceView } from './marketplace/MarketplaceView'import { SettingsView, type SettingsPage } from './settings/SettingsView'import { ApprovalSheet } from './settings/ApprovalSheet'-import { UpdateNeededCard } from './UpdateNeededCard'import { SearchPalette } from './SearchPalette'import { AccountWelcomeView } from './AccountWelcomeView'+import { ComputerAccessView } from './computer-access/ComputerAccessView'import { HostStateView } from './HostStateView'import { StartupRecovery } from './StartupRecovery'export { EmptyState } from './HostStateView'@@ -41,6 +42,8 @@ const isMac = window.codync.platform === 'darwin'export function ChatWindow() {const app = useApp()const [onboarded, setOnboarded] = usePref(prefs.onboardingDone)+ const [accessSetup, setAccessSetup] = usePref(prefs.computerAccessSetup)+ const [showAccess, setShowAccess] = useState(false)const [confirmReset, setConfirmReset] = useState(false)useTraySummary(app)useSSHAttachments(app)@@ -51,6 +54,8 @@ export function ChatWindow() {() =>window.codync.app.onCommand((c: WindowCommand) => {switch (c.kind) {+ case 'computerAccess':+ return setShowAccess(true)case 'confirmReset':return setConfirmReset(true)case 'reviewApprovals':@@ -83,7 +88,9 @@ export function ChatWindow() {return (<div className="chat-window">{onboarded ? (- showsChat ? (+ accessSetup === null ? (+ <ComputerAccessView onContinue={(ready) => setAccessSetup(ready ? 'ready' : 'later')} />+ ) : showsChat ? (<ChatSplitView />) : (<HostStateView />@@ -91,8 +98,11 @@ export function ChatWindow() {) : (<AccountWelcomeView onContinue={() => setOnboarded(true)} />)}- <AnalyticsPrompt />- <StarPrompt />+ {onboarded && accessSetup !== null ? <><AnalyticsPrompt /><StarPrompt /></> : null}+ <Sheet open={showAccess} onClose={() => setShowAccess(false)} width={660} height={Math.min(820, window.innerHeight - 80)}>+ <ModalHeader title="Computer access" />+ <ComputerAccessView onContinue={(ready) => { setAccessSetup(ready ? 'ready' : 'later'); setShowAccess(false) }} />+ </Sheet><Dialogopen={confirmReset}title="Reset all data?"@@ -133,7 +143,6 @@ function ChatSplitView() {const previousSelection = useRef<BotRef | null>(null)const [newMenu, setNewMenu] = useState(false)const [railNewMenu, setRailNewMenu] = useState(false)- const [hovered, setHovered] = useState<string | null>(null)const [contextBot, setContextBot] = useState<{ target: BotTarget; x: number; y: number } | null>(null)const [editing, setEditing] = useState<EditTarget | null>(null)const [confirmDelete, setConfirmDelete] = useState<BotTarget | null>(null)@@ -163,7 +172,8 @@ function ChatSplitView() {const onlineStores = stores.filter((s) => shown.has(s.computer.id) && s.connection.kind === 'online' && !s.mismatch)const selectedStore = app.selectedStoreconst composeStore = composeComputer ? app.store(composeComputer) : null- const visibleRoster = app.roster.filter((item) => shown.has(item.ref.computerId))+ const roster = useComputerRoster(app, shown)+ const visibleRoster = roster.itemsconst compose = (group = false) => {setComposingGroup(group)@@ -233,7 +243,8 @@ function ChatSplitView() {// ↑/↓ in the roster move the selection.const onListKey = (e: React.KeyboardEvent) => {if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return- const refs = visibleRoster.map((i) => i.ref)+ if (e.target instanceof HTMLElement && e.target.closest('.computer-roster-heading')) return+ const refs = roster.navigable.map((i) => i.ref)if (!refs.length) returne.preventDefault()const current = refs.findIndex((r) => sameRef(r, app.selection))@@ -324,42 +335,8 @@ function ChatSplitView() {</div>) : null}<div className="roster" ref={listRef} tabIndex={0} onKeyDown={onListKey}>- {!compact- ? mismatchStores.map((s) => (- <div key={s.computer.id} style={{ paddingBottom: 8 }}>- <StoreContext.Provider value={s}>- <UpdateNeededCard />- </StoreContext.Provider>- </div>- ))- : null}- {visibleRoster.map((item) => {- const key = refKey(item.ref)- const isSelected = sameRef(item.ref, selected)- return (- <button- key={key}- className="roster-row"- style={{- padding: compact ? 0 : '0 8px',- background: isSelected ? 'var(--roster-selected)' : hovered === key ? 'var(--bubble-agent)' : 'transparent',- }}- aria-label={stores.length > 1 ? `${item.bot.name}, on ${item.store.hostName}` : item.bot.name}- aria-selected={isSelected}- title={stores.length > 1 ? `${item.bot.name} · ${item.store.hostName}` : item.bot.name}- onMouseEnter={() => setHovered(key)}- onMouseLeave={() => setHovered((h) => (h === key ? null : h))}- onClick={() => app.select(item.ref)}- onContextMenu={(e) => {- e.preventDefault()- setContextBot({ target: { bot: item.bot, store: item.store }, x: e.clientX, y: e.clientY })- }}- >- <BotRow bot={item.bot} store={item.store} compact={compact} usingComputer={item.store.screen?.agentBot === item.bot.id} members={isGroup(item.bot) ? item.store.members(item.bot) : noMembers} />- </button>- )- })}- {visibleRoster.length === 0 && !compact && mismatchStores.length === 0 ? (+ <BotRoster roster={roster} compact={compact} onContext={(bot, store, x, y) => setContextBot({ target: { bot, store }, x, y })} />+ {visibleRoster.length === 0 && !roster.grouped && !compact && mismatchStores.length === 0 ? (<div className="roster-empty"><div style={font(13, 'medium')}>{onlineStores.length ? 'No bots yet' : 'Waiting for a computer'}</div>{onlineStores.length ? <div style={{ ...font(12), color: 'var(--secondary)' }}>Use + to start a new chat.</div> : null}@@ -448,8 +425,6 @@ function ChatSplitView() {)}-const noMembers: Bot[] = []-/** Which computer a new chat goes to, when more than one is online. */function ComputerPicker({ stores, value, onChange }: { stores: BotStore[]; value: string; onChange: (id: string) => void }) {const options = useMemo(() => stores.map((s) => ({ id: s.computer.id, label: s.hostName })), [stores])diff --git a/apps/desktop/src/renderer/views/ComputerFilterHeader.tsx b/apps/desktop/src/renderer/views/ComputerFilterHeader.tsxindex 301f2182..274a563a 100644--- a/apps/desktop/src/renderer/views/ComputerFilterHeader.tsx+++ b/apps/desktop/src/renderer/views/ComputerFilterHeader.tsx@@ -41,7 +41,7 @@ function summary(connections: Connection[]) {return `${connections.length} offline`}-/** The roster's only connection surface: a quiet summary, with details and filters on demand. */+/** The roster's connection summary, with details and filters on demand. */export function ComputerFilterHeader({ hidden, setHidden, manage, compact = false }: { hidden: string; setHidden: (v: string) => void; manage: () => void; compact?: boolean }) {const app = useApp()const ssh = useSSH()diff --git a/apps/desktop/src/renderer/views/ComputerRosterSection.tsx b/apps/desktop/src/renderer/views/ComputerRosterSection.tsxnew file mode 100644index 00000000..d652054c--- /dev/null+++ b/apps/desktop/src/renderer/views/ComputerRosterSection.tsx@@ -0,0 +1,76 @@+import { useLayoutEffect, useRef, type ReactNode } from 'react'+import { Icon } from '../components/Icon'+import { reduceMotion } from '../lib/theme'+import type { BotStore } from '../store/bot-store'+import { ComputerBadge } from './ComputerBadge'+import './computer-roster.css'++interface Props {+ store: BotStore+ compact: boolean+ collapsed: boolean+ previous?: string+ next?: string+ dragged: string | null+ setDragged: (id: string | null) => void+ toggle: () => void+ move: (id: string, target: string) => void+ notice: ReactNode+ children: ReactNode+}++export function ComputerRosterSection({ store, compact, collapsed, previous, next, dragged, setDragged, toggle, move, notice, children }: Props) {+ const section = useRef<HTMLElement>(null)+ const lastTop = useRef<number | null>(null)+ const id = store.computer.id+ useLayoutEffect(() => {+ const element = section.current+ if (!element) return+ const top = element.offsetTop+ if (lastTop.current !== null && top !== lastTop.current && !reduceMotion()) {+ element.animate([{ transform: `translateY(${lastTop.current - top}px)` }, { transform: 'translateY(0)' }], { duration: 300, easing: 'ease-out' })+ }+ lastTop.current = top+ })+ return (+ <section ref={section} className={`computer-roster-section ${dragged === id ? 'dragging' : ''}`} aria-label={store.hostName}+ onDragOver={(event) => {+ if (!dragged || dragged === id) return+ event.preventDefault()+ event.dataTransfer.dropEffect = 'move'+ }}+ onDrop={(event) => {+ if (!dragged) return+ event.preventDefault()+ move(dragged, id)+ setDragged(null)+ }}>+ <div className="computer-roster-heading">+ <button className="computer-roster-toggle" draggable aria-expanded={!collapsed}+ aria-label={`${store.hostName}, ${store.connectionLabel}`} title={`${store.hostName} · ${store.connectionLabel}. Drag to reorder.`}+ onClick={toggle}+ onDragStart={(event) => {+ event.dataTransfer.effectAllowed = 'move'+ event.dataTransfer.setData('text/plain', id)+ setDragged(id)+ }}+ onDragEnd={() => setDragged(null)}+ onKeyDown={(event) => {+ if (!event.altKey || !['ArrowUp', 'ArrowDown'].includes(event.key)) return+ event.preventDefault()+ event.stopPropagation()+ const target = event.key === 'ArrowUp' ? previous : next+ if (target) move(id, target)+ }}>+ <ComputerBadge computer={store.computer} size={20} />+ {!compact ? <span className="computer-roster-label"><strong>{store.hostName}</strong><span className={store.shownConnection.kind === 'online' ? '' : 'warning'}>{store.connectionLabel}</span></span> : null}+ <span className={`computer-roster-chevron ${collapsed ? 'collapsed' : ''}`}><Icon name="chevron.down" size={9} /></span>+ </button>+ </div>+ {notice}+ <div className={`computer-roster-content ${collapsed ? 'collapsed' : ''}`} inert={collapsed} aria-hidden={collapsed}>+ <div>{children}</div>+ </div>+ </section>+ )+}diff --git a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx b/apps/desktop/src/renderer/views/bots/BotEditorView.tsxindex 1c4d23c4..764f64c0 100644--- a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx+++ b/apps/desktop/src/renderer/views/bots/BotEditorView.tsx@@ -202,11 +202,13 @@ function BotSettingsForm({ draft, onChange, error, plugins }: {<SwitchRowtitle="Use the computer"detail={- store.screen.enabled+ store.screen.platform !== 'windows' && !(store.screen.enabled && store.screen.connected && store.screen.capture && store.screen.input)+ ? 'Let this bot use apps. On that computer, open Codync → Settings → Computer access to set up permissions first.'+ : store.screen.enabled? 'Let this bot see the screen and use the mouse and keyboard. You can watch and take over from your phone.': store.screen.computerUse? 'Let this bot see the screen and use the mouse and keyboard.'- : "Let this bot see the screen and use the mouse and keyboard. Turn on Remote screen in Codync's menu on the computer first."+ : "Let this bot see the screen and use the mouse and keyboard. On that computer, open Codync → Settings → Computer access to set up permissions first."}on={draft.computer ?? false}onChange={(on) => set('computer', on)}diff --git a/apps/desktop/src/renderer/views/computer-access/ComputerAccessView.tsx b/apps/desktop/src/renderer/views/computer-access/ComputerAccessView.tsxnew file mode 100644index 00000000..4c765f72--- /dev/null+++ b/apps/desktop/src/renderer/views/computer-access/ComputerAccessView.tsx@@ -0,0 +1,100 @@+import type { ReactNode } from 'react'+import { Button, Spinner } from '../../components/Controls'+import { Icon } from '../../components/Icon'+import { useComputerAccess } from './use-computer-access'+import appIcon from '../../../../resources/icon.png'+import './computer-access.css'++/** Shared by onboarding and Settings. Permission requests remain explicit and local. */+export function ComputerAccessView({ onContinue }: { onContinue?: (ready: boolean) => void }) {+ const access = useComputerAccess()+ const { screen, step, busy } = access+ const mac = window.codync.platform === 'darwin'+ const windows = window.codync.platform === 'win32'+ const ready = step === 'ready'+ const canRequest = ['capture', 'input', 'portal', 'ready'].includes(step)+ const helperReady = screen?.enabled === true && screen.connected && step !== 'background'+ const completed = windows ? Number(ready) : Number(helperReady) + (mac+ ? Number(screen?.capture === true) + Number(screen?.input === true)+ : Number(screen?.capture === true && screen.input))+ const request = (permission: 'capture' | 'input' | 'portal', title: string) => (+ <Button kind={step === permission ? 'primary' : 'secondary'} disabled={!canRequest || busy !== null} onClick={() => void access.request(permission)}>+ {busy === permission ? <><Spinner /> Waiting for permission…</> : title}+ </Button>+ )+ return (+ <section className={`computer-access ${onContinue ? 'onboarding' : ''}`} aria-label="Computer access setup">+ <div className="computer-access-content">+ <header className="computer-access-header">+ <div className="computer-access-identity">+ <img src={appIcon} width={40} height={40} alt="Codync" />+ <div><span>This computer</span><strong>{window.codync.computerName || 'Your computer'}</strong></div>+ </div>+ <h1>{ready ? 'Your computer is ready' : 'Computer access'}</h1>+ <p>{windows ? 'Let a bot work in your apps. You choose which bots can use this computer.' : 'Work in your apps with a bot, or access your screen from your phone. You choose which bots can use this computer.'}</p>+ </header>+ {step === 'host' ? <AccessNotice title="Waiting for your computer" icon="desktopcomputer">+ Start or restart the host from Codync’s menu to continue. We’ll check again automatically.+ </AccessNotice> : null}+ {step === 'unavailable' ? <AccessNotice title="Codync Screen is missing" icon="desktopcomputer.trianglebadge.exclamationmark">+ Install the full Codync desktop app to finish setup.+ </AccessNotice> : null}+ {access.error ? <AccessNotice title="Couldn’t finish setup" icon="exclamationmark.circle" error>{access.error}</AccessNotice> : null}+ <div className="computer-access-section-label"><span>{windows ? 'Availability' : 'Permissions'}</span><span>{ready ? 'All set' : `${completed} of ${mac ? 3 : windows ? 1 : 2} ready`}</span></div>+ <div className="computer-access-steps">+ {windows ? <AccessRow title="Computer control" icon="cursorarrow.motionlines" detail="Bots can use apps on this computer. Remote screen viewing from your phone isn’t available on Windows yet." done={ready} /> : <>+ <AccessRow title="Codync Screen" icon="desktopcomputer" detail="Runs in the background to share your screen and connect your controls." done={helperReady} active={['enable', 'helper', 'background'].includes(step)} status={step === 'background' ? 'Needs approval' : undefined}>+ {['enable', 'helper'].includes(step) ? <Button disabled={busy !== null} onClick={() => void access.enable()}>{busy === 'enable' ? <><Spinner /> Starting…</> : step === 'helper' ? 'Start again' : 'Enable Codync Screen'}</Button> : null}+ {step === 'background' ? <><p className="computer-access-inline-note">Allow Codync to run in the background in Login Items.</p><Button onClick={() => access.openSettings('background')}>Open Login Items <Icon name="arrow.up.right.square" size={10} /></Button></> : null}+ </AccessRow>+ {mac ? <>+ <AccessRow title="Screen recording" icon="record.circle" detail="Lets Codync see your screen, including anything visible in your apps." done={screen?.capture === true} active={step === 'capture'}>+ {canRequest ? request('capture', 'Allow screen recording') : null}+ {access.requested.has('capture') ? <SettingsLink action={() => access.openSettings('capture')} /> : null}+ </AccessRow>+ <AccessRow title="Control apps" icon="cursorarrow.motionlines" detail="Lets Codync click, type and interact with apps on your behalf." done={screen?.input === true} active={step === 'input'}>+ {canRequest ? request('input', 'Allow computer control') : null}+ {access.requested.has('input') ? <SettingsLink action={() => access.openSettings('input')} /> : null}+ </AccessRow>+ </> : <AccessRow title="Screen sharing & control" icon="cursorarrow.motionlines" detail="Choose a screen and allow mouse and keyboard access. You can stop sharing at any time." done={screen?.capture === true && screen.input} active={step === 'portal'}>+ {canRequest ? request('portal', 'Choose screen and allow control') : null}+ </AccessRow>}+ </>}+ </div>+ {mac && !ready ? <div className="computer-access-help">+ <Icon name="info.circle" size={13} />+ <p>In System Settings, look for <strong>{access.helperName}</strong>. Computer control may be called <strong>Device Control and Data Access</strong> or <strong>Accessibility</strong>. Return here after granting access; if asked, allow the helper to restart.</p>+ </div> : null}+ <div className="computer-access-reassurance"><Icon name="lock.shield" size={13} /><p>Permissions stay on this computer. {onContinue ? 'You can change them later in Settings → Computer access.' : 'Your other computers keep their own permissions.'}</p></div>+ <footer className="computer-access-footer">+ <Button kind="secondary" onClick={() => void access.refresh()}><Icon name="arrow.clockwise" size={12} /> Check again</Button>+ {onContinue ? <Button kind={ready ? 'primary' : 'secondary'} onClick={() => onContinue(ready)}>{ready ? 'Continue' : 'Set up later'}{ready ? <Icon name="arrow.right" size={12} /> : null}</Button> : null}+ </footer>+ <p className="computer-access-phone-note">On iPhone, connect with a QR code or Ask Access. No SSH setup needed.</p>+ </div>+ </section>+ )+}++function AccessRow({ title, icon, detail, done, active = false, status, children }: {+ title: string; icon: string; detail: string; done: boolean; active?: boolean; status?: string; children?: ReactNode+}) {+ return <div className={`computer-access-row ${done ? 'granted' : active ? 'current' : 'waiting'}`}>+ <span className="computer-access-row-icon"><Icon name={icon} size={17} /></span>+ <div className="computer-access-row-body">+ <div className="computer-access-row-heading"><h2>{title}</h2><span className="computer-access-status">{done ? <><Icon name="checkmark" size={10} weight="semibold" /> Ready</> : status ?? (active ? 'Needs access' : 'Waiting')}</span></div>+ <p>{detail}</p>+ {!done ? <div className="computer-access-actions">{children}</div> : null}+ </div>+ </div>+}++function AccessNotice({ title, icon, error = false, children }: { title: string; icon: string; error?: boolean; children: ReactNode }) {+ return <div className={`computer-access-notice ${error ? 'error' : ''}`} role={error ? 'alert' : 'status'}>+ <Icon name={icon} size={16} /><div><strong>{title}</strong><p>{children}</p></div>+ </div>+}++function SettingsLink({ action }: { action: () => void }) {+ return <Button kind="secondary" onClick={action}>Open System Settings <Icon name="arrow.up.right.square" size={10} /></Button>+}diff --git a/apps/desktop/src/renderer/views/computer-access/computer-access.css b/apps/desktop/src/renderer/views/computer-access/computer-access.cssnew file mode 100644index 00000000..3921bf9b--- /dev/null+++ b/apps/desktop/src/renderer/views/computer-access/computer-access.css@@ -0,0 +1,56 @@+.computer-access { overflow: auto; width: 100%; animation: computer-access-appear 180ms ease-out; }+@keyframes computer-access-appear { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }+.computer-access.onboarding { height: 100%; padding: clamp(24px, 6vh, 56px) 24px 24px; }+.settings-page > .computer-access { height: 100%; padding-bottom: 24px; }+.modal-content > .computer-access { flex: 1; min-height: 0; height: auto; padding-top: 20px; }+.computer-access-content { width: 100%; max-width: 520px; margin: 0 auto; }+.computer-access-header { margin-bottom: 24px; }+.computer-access-identity { display: flex; align-items: center; gap: 10px; margin-bottom: 24px; }+.computer-access-identity img { flex: none; }+.computer-access-identity div { display: grid; gap: 3px; min-width: 0; }+.computer-access-identity span { color: var(--secondary); font-size: 11px; }+.computer-access-identity strong { font-size: 12px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.computer-access h1 { font-size: 26px; letter-spacing: -.65px; line-height: 1.2; font-weight: 600; margin: 0 0 10px; text-wrap: balance; }+.computer-access p { color: var(--secondary); font-size: 12px; line-height: 1.6; margin: 5px 0 0; text-wrap: pretty; }+.computer-access-header > p { font-size: 13px; max-width: 480px; }+.computer-access-section-label { display: flex; justify-content: space-between; gap: 12px; margin-bottom: 10px; font-size: 11px; color: var(--secondary); }+.computer-access-section-label > :first-child { color: var(--text); font-weight: 500; }+/* The requested outline matches the desktop toolbar/composer treatment. */+.computer-access-steps { border: 1px solid var(--composer-stroke); border-radius: 16px; overflow: hidden; background: var(--surface); }+.computer-access-row { display: flex; align-items: flex-start; gap: 12px; padding: 18px; transition: background var(--fade); }+.computer-access-row + .computer-access-row { border-top: 1px solid var(--border); }+.computer-access-row.current { background: var(--chrome-fill); }+.computer-access-row-icon { display: flex; align-items: center; justify-content: center; width: 30px; height: 30px; flex: none; color: var(--secondary); }+.computer-access-row.current .computer-access-row-icon, .computer-access-row.granted .computer-access-row-icon { color: var(--text); }+.computer-access-row-body { flex: 1; min-width: 0; }+.computer-access-row-heading { display: flex; align-items: baseline; gap: 10px; justify-content: space-between; flex-wrap: wrap; }+.computer-access h2 { font-size: 13px; line-height: 1.5; font-weight: 600; margin: 0; }+.computer-access-status { display: inline-flex; align-items: center; gap: 5px; color: var(--secondary); font-size: 10px; line-height: 1.5; white-space: nowrap; }+.computer-access-row.current .computer-access-status, .computer-access-row.granted .computer-access-status { color: var(--text); }+.computer-access-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }+.computer-access-actions:not(:empty) { margin-top: 12px; }+.computer-access .styled-button { min-height: 30px; font-size: 11px; padding: 6px 12px; }+.computer-access .styled-button.secondary { background: transparent; border: 1px solid var(--composer-stroke); }+.computer-access .styled-button.secondary:hover:not(:disabled) { background: var(--chrome-fill); }+.computer-access .styled-button:focus-visible { outline: 2px solid var(--text); outline-offset: 3px; }+.computer-access .computer-access-inline-note { flex-basis: 100%; margin: 0; }+.computer-access-help, .computer-access-reassurance { display: flex; align-items: flex-start; gap: 8px; margin-top: 16px; color: var(--secondary); }+.computer-access-help > :first-child, .computer-access-reassurance > :first-child { margin-top: 3px; }+.computer-access-help p, .computer-access-reassurance p { margin: 0; font-size: 11px; }+.computer-access-help strong { font-weight: 500; color: var(--text); }+.computer-access-reassurance { margin-top: 20px; }+.computer-access-footer { display: flex; justify-content: space-between; gap: 12px; margin-top: 22px; padding-top: 18px; border-top: 1px solid var(--border); }+.computer-access .computer-access-phone-note { font-size: 10px; margin-top: 16px; }+.computer-access-notice { display: flex; align-items: flex-start; gap: 10px; border: 1px solid var(--composer-stroke); border-radius: 12px; padding: 12px 14px; margin-bottom: 20px; }+.computer-access-notice > :first-child { margin-top: 2px; color: var(--secondary); }+.computer-access-notice strong { font-size: 12px; font-weight: 500; }+.computer-access-notice p { font-size: 11px; margin-top: 3px; }+.computer-access-notice.error { border-color: var(--danger); }+.computer-access-notice.error strong, .computer-access-notice.error > :first-child { color: var(--danger); }+@media (max-width: 440px) {+ .computer-access.onboarding { padding: 24px 16px; }+ .computer-access-row { padding: 14px 12px; gap: 8px; }+ .computer-access-row-heading { gap: 4px 8px; }+ .computer-access h1 { font-size: 24px; }+}+@media (prefers-reduced-motion: reduce) { .computer-access { animation: none; } }diff --git a/apps/desktop/src/renderer/views/computer-access/use-computer-access.ts b/apps/desktop/src/renderer/views/computer-access/use-computer-access.tsnew file mode 100644index 00000000..9c0e2486--- /dev/null+++ b/apps/desktop/src/renderer/views/computer-access/use-computer-access.ts@@ -0,0 +1,19 @@+import { useEffect } from 'react'+import { useModel } from '../../lib/observable'+import { useApp } from '../../store/context'++/** Returning from System Settings only checks state; it never requests a grant. */+export function useComputerAccess() {+ const access = useModel(useApp().computerAccess)+ useEffect(() => {+ const refresh = () => void access.refresh()+ refresh()+ const timer = window.setInterval(refresh, 2_000)+ window.addEventListener('focus', refresh)+ return () => {+ window.clearInterval(timer)+ window.removeEventListener('focus', refresh)+ }+ }, [access])+ return access+}diff --git a/apps/desktop/src/renderer/views/computer-roster.css b/apps/desktop/src/renderer/views/computer-roster.cssnew file mode 100644index 00000000..14974443--- /dev/null+++ b/apps/desktop/src/renderer/views/computer-roster.css@@ -0,0 +1,97 @@+.computer-roster-section {+ flex: none;+ min-width: 0;+ transition: opacity var(--layout);+}++.computer-roster-section.dragging {+ opacity: 0.45;+}++.computer-roster-heading {+ display: flex;+ align-items: center;+ gap: 2px;+ padding: 12px 2px 4px;+}++.computer-roster-toggle {+ display: flex;+ align-items: center;+ gap: 5px;+ flex: 1;+ min-width: 0;+ padding: 5px 4px;+ color: var(--secondary);+ border-radius: 8px;+ cursor: grab;+}++.computer-roster-toggle:hover {+ background: var(--bubble-agent);+}++.computer-roster-label {+ display: flex;+ flex: 1;+ min-width: 0;+ align-items: baseline;+ gap: 6px;+ font-size: calc(11px * var(--scale));+ text-align: left;+}++.computer-roster-label strong {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.computer-roster-label > span {+ color: var(--tertiary);+ font-size: calc(10px * var(--scale));+ white-space: nowrap;+}++.computer-roster-label > .warning {+ color: var(--warning);+}++.computer-roster-chevron {+ flex: none;+ display: flex;+ transition: transform var(--layout);+}++.computer-roster-chevron.collapsed {+ transform: rotate(-90deg);+}++.computer-roster-content {+ display: grid;+ grid-template-rows: 1fr;+ opacity: 1;+ transition: grid-template-rows var(--layout), opacity var(--layout);+}++.computer-roster-content.collapsed {+ grid-template-rows: 0fr;+ opacity: 0;+}++.computer-roster-content > div {+ min-height: 0;+ overflow: hidden;+}++.computer-roster-empty {+ padding: 8px 10px 12px;+ color: var(--tertiary);+ font-size: calc(11px * var(--scale));+}++.sidebar.compact .computer-roster-toggle {+ justify-content: center;+ padding: 4px 0;+ gap: 2px;+}diff --git a/apps/desktop/src/renderer/views/settings/SettingsView.tsx b/apps/desktop/src/renderer/views/settings/SettingsView.tsxindex 2bd5b930..803bbee2 100644--- a/apps/desktop/src/renderer/views/settings/SettingsView.tsx+++ b/apps/desktop/src/renderer/views/settings/SettingsView.tsx@@ -13,14 +13,16 @@ import { ComputersView } from './ComputersView'import { errorText, isMac, thisMac } from './parts'import { UsageLimits } from './UsageLimits'import { VoiceChatSettingsView } from './VoiceChatSettingsView'+import { ComputerAccessView } from '../computer-access/ComputerAccessView'/** The chat window's Settings: pages in a sidebar, ChatGPT's settings layout. */-export type SettingsPage = 'general' | 'computers' | 'voice' | 'usage' | 'updates'+export type SettingsPage = 'general' | 'computers' | 'access' | 'voice' | 'usage' | 'updates'const thisComputer = isMac ? 'This Mac' : 'This computer'const pages: { id: SettingsPage; title: string; label?: string; group: string; icon: string }[] = [{ id: 'general', title: 'General', group: 'Personal', icon: 'gearshape' },{ id: 'computers', title: 'Computers & devices', label: 'Computers', group: thisComputer, icon: 'desktopcomputer' },+ { id: 'access', title: 'Computer access', group: thisComputer, icon: 'hand.raised' },{ id: 'voice', title: 'Voice chat', group: 'Personal', icon: 'waveform' },{ id: 'usage', title: 'Usage', group: 'Personal', icon: 'gauge.with.dots.needle.33percent' },{ id: 'updates', title: 'Updates', group: thisComputer, icon: 'arrow.down.circle' },@@ -69,6 +71,8 @@ export function SettingsView({ page: initial }: { page: SettingsPage }) {function PageContent({ page }: { page: SettingsPage }) {const app = useApp()switch (page) {+ case 'access':+ return <ComputerAccessView />case 'general':return <GeneralSettings />case 'computers':diff --git a/apps/desktop/src/shared/computer-access.test.ts b/apps/desktop/src/shared/computer-access.test.tsnew file mode 100644index 00000000..cb6e12de--- /dev/null+++ b/apps/desktop/src/shared/computer-access.test.ts@@ -0,0 +1,36 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { computerAccessStep, shouldSyncScreenAgent } from './computer-access.ts'+import type { ScreenState } from './models.ts'++const screen: ScreenState = { enabled: true, connected: true, capture: false, input: false, platform: 'macos', displays: [], userControl: false, agentBot: null, computerUse: true, viewers: 0 }+const agent = { available: true, needsApproval: false, registered: true }++test('startup never registers a fresh helper, but an app update restores an existing choice', () => {+ assert.equal(shouldSyncScreenAgent(true, 'not-registered', false), false)+ assert.equal(shouldSyncScreenAgent(true, 'not-registered', true), true)+ assert.equal(shouldSyncScreenAgent(true, 'enabled', false), true)+ assert.equal(shouldSyncScreenAgent(false, 'enabled', true), false)+ assert.equal(shouldSyncScreenAgent(true, 'requires-approval', true), false)+})++test('macOS setup advances only with observed permissions, and recovers after revocation', () => {+ assert.equal(computerAccessStep('darwin', false, screen, agent), 'host')+ assert.equal(computerAccessStep('darwin', true, null, agent), 'host')+ assert.equal(computerAccessStep('darwin', true, screen, { ...agent, available: false }), 'unavailable')+ assert.equal(computerAccessStep('darwin', true, { ...screen, enabled: false }, agent), 'enable')+ assert.equal(computerAccessStep('darwin', true, screen, { ...agent, registered: false }), 'enable')+ assert.equal(computerAccessStep('darwin', true, screen, { ...agent, registered: false, needsApproval: true }), 'background')+ assert.equal(computerAccessStep('darwin', true, { ...screen, connected: false }, agent), 'helper')+ assert.equal(computerAccessStep('darwin', true, screen, agent), 'capture')+ assert.equal(computerAccessStep('darwin', true, { ...screen, capture: true }, agent), 'input')+ assert.equal(computerAccessStep('darwin', true, { ...screen, capture: true, input: true }, agent), 'ready')+ assert.equal(computerAccessStep('darwin', true, { ...screen, input: true }, agent), 'capture')+})++test('Linux requests a portal session and Windows never asks for macOS grants', () => {+ assert.equal(computerAccessStep('linux', true, screen, null), 'portal')+ assert.equal(computerAccessStep('linux', true, { ...screen, capture: true }, null), 'portal')+ assert.equal(computerAccessStep('linux', true, { ...screen, capture: true, input: true }, null), 'ready')+ assert.equal(computerAccessStep('win32', true, { ...screen, connected: false, enabled: false }, null), 'ready')+})diff --git a/apps/desktop/src/shared/computer-access.ts b/apps/desktop/src/shared/computer-access.tsnew file mode 100644index 00000000..796f0712--- /dev/null+++ b/apps/desktop/src/shared/computer-access.ts@@ -0,0 +1,36 @@+import type { ScreenState } from './models'++export interface ScreenAgentState {+ available: boolean+ needsApproval: boolean+ registered: boolean+}++export type ComputerPermission = 'capture' | 'input' | 'portal'+export type ComputerAccessStep = 'host' | 'unavailable' | 'enable' | 'background' | 'helper' | ComputerPermission | 'ready'++/** First registration is explicit; only a previously enabled helper resumes after an app update. */+export function shouldSyncScreenAgent(enabled: boolean, status: string, resumeAfterUpdate: boolean): boolean {+ return enabled && (status === 'enabled' || (status === 'not-registered' && resumeAfterUpdate))+}++/** OS-specific requirements, based only on observed state; opening Settings never grants access. */+export function computerAccessStep(platform: string, online: boolean, screen: ScreenState | null, agent: ScreenAgentState | null): ComputerAccessStep {+ if (!online || !screen) return 'host'+ if (platform === 'win32') return screen.computerUse ? 'ready' : 'host'+ if (platform === 'darwin' && agent?.available === false) return 'unavailable'+ if (!screen.enabled) return 'enable'+ if (platform === 'darwin' && agent?.needsApproval) return 'background'+ if (platform === 'darwin' && agent?.registered === false) return 'enable'+ if (!screen.connected) return 'helper'+ if (platform === 'linux') return screen.capture && screen.input ? 'ready' : 'portal'+ if (!screen.capture) return 'capture'+ if (!screen.input) return 'input'+ return 'ready'+}++export const computerPermissionSettings = {+ capture: 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture',+ input: 'x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility',+ background: 'x-apple.systempreferences:com.apple.LoginItems-Settings.extension',+} as constdiff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.tsindex ff90f7d9..07f78305 100644--- a/apps/desktop/src/shared/ipc.ts+++ b/apps/desktop/src/shared/ipc.ts@@ -1,4 +1,5 @@import type { SSHBridge } from './ssh'+import type { ScreenAgentState } from './computer-access'// The bridge between the main process (host lifecycle, loopback HTTP, tray, windows)// and the renderer (stores and UI). Exposed as `window.codync` by the preload script.@@ -61,6 +62,7 @@ export type WindowCommand =| { kind: 'stepTextSize'; up: boolean | null }| { kind: 'setUsageIconStyle'; style: 'character' | 'original' }| { kind: 'setRemoteScreen'; on: boolean }+ | { kind: 'computerAccess' }| { kind: 'newChat' }| { kind: 'search' }| { kind: 'toggleSidebar' }@@ -175,6 +177,7 @@ export interface CodyncBridge {*/authenticate(url: string, scheme: string): Promise<string>/** macOS: registers or removes the Codync Screen agent (SMAppService). */+ screenAgentState(): Promise<ScreenAgentState>setScreenAgent(on: boolean): Promise<{ needsApproval: boolean }>syncScreenAgent(enabled: boolean): Promise<{ needsApproval: boolean }>}diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex 63f1c31e..c1a9c9c1 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -229,6 +229,8 @@ export interface ScreenDisplay {}export interface ScreenState {+ /** The helper's display name in operating-system permission settings. */+ permissionApp?: stringenabled: booleanconnected: booleanplatform: string@@ -248,6 +250,7 @@ export function normalizeScreen(raw: Partial<ScreenState> | undefined | null): Senabled: raw.enabled ?? false,connected: raw.connected ?? false,platform: raw.platform ?? '',+ permissionApp: raw.permissionApp,capture: raw.capture ?? false,input: raw.input ?? false,displays: raw.displays ?? [],diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swiftindex 88ae16c2..0580aa39 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift@@ -32,7 +32,7 @@ public enum SharedStore {self.suite = suite}- private static let names = ["computers", "bots", "usage", "lastComputerId", "composerDrafts"]+ private static let names = ["computers", "bots", "usage", "lastComputerId", "composerDrafts", "computerOrder"]private func key(_ name: String) -> String { accountID == nil ? name : "account.\(id).\(name)" }public static func digest(_ value: String) -> String {SHA256.hash(data: Data(value.utf8)).map { String(format: "%02x", $0) }.joined()@@ -49,6 +49,11 @@ public enum SharedStore {get { read([Computer].self, "computers") ?? [] }nonmutating set { write(newValue, "computers") }}+ /// Device-local ordering, isolated by account.+ public var computerOrder: ComputerOrder? {+ get { read(ComputerOrder.self, "computerOrder") }+ nonmutating set { write(newValue, "computerOrder") }+ }/// The widgets' snapshot of every computer's bots.public var bots: [BotSnapshot] {get { read([BotSnapshot].self, "bots") ?? [] }diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/ComputerOrder.swift b/apps/ios/Kit/Sources/CodyncKit/Models/ComputerOrder.swiftnew file mode 100644index 00000000..fa0e540e--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/ComputerOrder.swift@@ -0,0 +1,24 @@+import Foundation++/// Device-local order, including computers temporarily unavailable in this account.+public struct ComputerOrder: Codable, Equatable, Sendable {+ public var ids: [ComputerID]++ public init(ids: [ComputerID] = []) {+ self.ids = ids+ }++ public func orderedIDs(_ available: [ComputerID]) -> [ComputerID] {+ let known = Set(available)+ var seen: Set<ComputerID> = []+ return (ids + available).filter { known.contains($0) && seen.insert($0).inserted }+ }++ public func moving(_ id: ComputerID, to target: ComputerID, available: [ComputerID]) -> [ComputerID]? {+ var seen: Set<ComputerID> = []+ var next = (ids + available).filter { seen.insert($0).inserted }+ guard id != target, let from = next.firstIndex(of: id), let to = next.firstIndex(of: target) else { return nil }+ next.insert(next.remove(at: from), at: to)+ return next+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swiftindex e1443755..5e84f95b 100644--- a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift@@ -168,11 +168,13 @@ struct BotSettingsForm: View {SwitchRow("Notifications", detail: "Get notified when this bot finishes or needs you",isOn: Binding(get: { draft.notify ?? true }, set: { draft.notify = $0 }))if model.screen != nil {- SwitchRow("Use the computer", detail: model.screen?.enabled == true+ SwitchRow("Use the computer", detail: model.screen?.controlReady != true+ ? "Let this bot use apps. On that computer, open Codync → Settings → Computer access to set up permissions first."+ : model.screen?.enabled == true? "Let this bot see the screen and use the mouse and keyboard. You can watch and take over from your phone.": model.screen?.computerUse == true? "Let this bot see the screen and use the mouse and keyboard."- : "Let this bot see the screen and use the mouse and keyboard. Turn on Remote screen in Codync's menu on the computer first.",+ : "Let this bot see the screen and use the mouse and keyboard. On that computer, open Codync → Settings → Computer access to set up permissions first.",isOn: Binding(get: { draft.computer ?? false }, set: { draft.computer = $0 }))}}diff --git a/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenView.swift b/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenView.swiftindex 4d9ac83e..e2cf4020 100644--- a/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenView.swift@@ -69,6 +69,9 @@ public struct ScreenView: View {.onChange(of: screen?.available) { _, available inif available == true, session == nil { start() }}+ .onChange(of: screen?.input) { _, input in+ if input != true { setInteractive(false) }+ }}// MARK: lifecycle@@ -92,12 +95,13 @@ public struct ScreenView: View {}private func setInteractive(_ on: Bool) {- interactive = on- if on != tookOver {- tookOver = on- model.screenTakeover(on)+ let allowed = on && screen?.input == true+ interactive = allowed+ if allowed != tookOver {+ tookOver = allowed+ model.screenTakeover(allowed)}- if !on { keyboard = false }+ if !allowed { keyboard = false }}// MARK: chrome@@ -142,6 +146,7 @@ public struct ScreenView: View {OverlayButton(interactive ? "Hand back to bots" : "Take over", interactive ? "hand.raised.slash" : "hand.raised") {animate { setInteractive(!interactive) }}+ .disabled(screen?.input != true)}}.animation(Motion.reduced(Motion.fade, reduceMotion), value: zoomed)@@ -184,7 +189,12 @@ public struct ScreenView: View {Task { await session.start() }}case .live, .closed:- if let error = session.lastError {+ if screen?.input != true {+ Text("View only. To allow control, open Codync → Settings → Computer access on the computer.")+ .font(.caption).padding(12)+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 12))+ .frame(maxHeight: .infinity, alignment: .bottom).padding(.bottom, 24)+ } else if let error = session.lastError {Text(error).font(.caption).padding(8)@@ -200,9 +210,7 @@ public struct ScreenView: View {let (icon, text): (String, String) =if model.connection != .online { ("wifi.slash", "This computer is offline.") }else if s == nil { ("arrow.down.circle", "Update Codync on your computer to use its screen from here.") }- else if s?.enabled != true { ("lock.display", "Remote screen is off. Turn it on in Codync's menu on the computer.") }- else if s?.connected != true { ("display.trianglebadge.exclamationmark", "Codync Screen isn't running on the computer. Turn Remote screen off and on again in Codync's menu there.") }- else { ("record.circle", "Allow Codync Screen to record the screen: System Settings → Privacy & Security → Screen & System Audio Recording, on the computer.") }+ else { ("lock.display", s?.accessGuidance ?? "Set up Computer access in Codync on the computer.") }Overlay(icon: icon, text: text)}}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swiftindex 5e16b64d..de639ec3 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift@@ -47,6 +47,7 @@ public final class AccountStore {private let clientKind: Stringprivate let cloud: CloudClient?+ private let computerOrder: ComputerOrderStoreprivate let makeStore: @MainActor (Computer) -> BotStore/// Persisted in the context (channel route).private var saved: [Computer]@@ -67,9 +68,11 @@ public final class AccountStore {self.storage = storageself.clientKind = clientKindself.cloud = cloud+ computerOrder = ComputerOrderStore(storage: storage)self.makeStore = makeStoresaved = storage.computers.filter(\.isConsistent)for computer in saved { open(computer) }+ computerOrder.onChanged = { [weak self] in self?.refreshList() }refreshList()}@@ -135,14 +138,9 @@ public final class AccountStore {refreshList()}- /// Moves a computer (and its bots in the roster) to `target`'s place; saved on this device.- /// Attached computers (the Mac's own host, SSH tunnels) stay first.+ /// Moves a computer section on this device only.public func move(_ id: ComputerID, to target: ComputerID) {- guard id != target, let from = saved.firstIndex(where: { $0.id == id }),- let to = saved.firstIndex(where: { $0.id == target }) else { return }- saved.insert(saved.remove(at: from), at: to)- persist()- refreshList()+ computerOrder.move(id, to: target, available: computers.map(\.id))}// MARK: account (§4.2 B)@@ -292,6 +290,7 @@ public final class AccountStore {/// Account switched or signed out: nothing from here writes into storage or calls back anymore.public func retire() {retired = true+ computerOrder.retire()for store in stores.values { store.retire() }for poll in accessPolls.values { poll.cancel() }accessPolls = [:]@@ -352,7 +351,13 @@ public final class AccountStore {}private func refreshList() {- if saved != computers { Motion.animate { computers = saved } }+ let byID = Dictionary(saved.map { ($0.id, $0) }, uniquingKeysWith: { _, newest in newest })+ let ordered = computerOrder.state.orderedIDs(saved.map(\.id)).compactMap { byID[$0] }+ if saved != ordered {+ saved = ordered+ persist()+ }+ if ordered != computers { Motion.animate { computers = ordered } }rosterChanged()}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/ComputerOrderStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/ComputerOrderStore.swiftnew file mode 100644index 00000000..a0bdfc92--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Store/ComputerOrderStore.swift@@ -0,0 +1,29 @@+import CodyncKit++/// Saves ordering on this device only, within the current account's local context.+@MainActor+final class ComputerOrderStore {+ private(set) var state: ComputerOrder+ var onChanged: (() -> Void)?+ private let storage: SharedStore.Context+ private var retired = false++ init(storage: SharedStore.Context) {+ self.storage = storage+ state = storage.computerOrder ?? ComputerOrder(ids: storage.computers.map(\.id))+ }++ func move(_ id: ComputerID, to target: ComputerID, available: [ComputerID]) {+ guard !retired, let ids = state.moving(id, to: target, available: available) else { return }+ let next = ComputerOrder(ids: ids)+ guard state != next else { return }+ state = next+ storage.computerOrder = next+ onChanged?()+ }++ func retire() {+ retired = true+ onChanged = nil+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/UpdateNeededCard.swift b/apps/ios/Kit/Sources/CodyncUI/UpdateNeededCard.swiftindex f9eafe1e..3636a698 100644--- a/apps/ios/Kit/Sources/CodyncUI/UpdateNeededCard.swift+++ b/apps/ios/Kit/Sources/CodyncUI/UpdateNeededCard.swift@@ -159,9 +159,10 @@ public struct UpdateReminderCard: View {public var body: some View {HStack(alignment: .top, spacing: 12) {- Image(systemName: "sparkles")- .font(.title3)- .foregroundStyle(Palette.secondary)+ Image(systemName: "arrow.down.circle.fill")+ .font(.title3.weight(.medium))+ .symbolRenderingMode(.hierarchical)+ .foregroundStyle(Palette.text).accessibilityHidden(true)VStack(alignment: .leading, spacing: 6) {Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text)diff --git a/apps/ios/Kit/Tests/CodyncKitTests/ComputerOrderTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ComputerOrderTests.swiftnew file mode 100644index 00000000..dee900b1--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncKitTests/ComputerOrderTests.swift@@ -0,0 +1,22 @@+import Foundation+import Testing+@testable import CodyncKit++@Test func computerOrderKeepsUnavailableComputersAndAppendsNewOnes() {+ let order = ComputerOrder(ids: ["offline", "b", "a"])+ #expect(order.orderedIDs(["a", "new", "b"]) == ["b", "a", "new"])+ #expect(order.moving("a", to: "b", available: ["a", "b", "new"]) == ["offline", "a", "b", "new"])+ #expect(order.moving("missing", to: "a", available: ["a", "b"]) == nil)+ #expect(order.orderedIDs(["a", "a", "b"]) == ["b", "a"])+}++@Test func computerOrderPersistenceIsIsolatedByAccount() {+ let suite = "computer-order-\(UUID().uuidString)"+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let a = SharedStore.Context(accountID: "a", suite: suite)+ let b = SharedStore.Context(accountID: "b", suite: suite)+ a.computerOrder = ComputerOrder(ids: ["mini", "laptop"])+ #expect(SharedStore.Context(accountID: "a", suite: suite).computerOrder?.ids == ["mini", "laptop"])+ #expect(b.computerOrder == nil)+ #expect(SharedStore.Context(accountID: nil, suite: suite).computerOrder == nil)+}diff --git a/apps/ios/Kit/Tests/CodyncKitTests/ScreenAccessTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ScreenAccessTests.swiftnew file mode 100644index 00000000..7c82ba14--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncKitTests/ScreenAccessTests.swift@@ -0,0 +1,30 @@+import Foundation+import Testing+@testable import CodyncKit++struct ScreenAccessTests {+ @Test func oldHostScreenStatusStillDecodes() throws {+ let state = try JSONDecoder().decode(ScreenState.self, from: Data("{\"enabled\":true}".utf8))+ #expect(state.permissionApp == nil)+ #expect(!state.available)+ #expect(state.accessGuidance.contains("Settings → Computer access"))+ }++ @Test func guidanceUsesTheActualPermissionAppAndPlatform() {+ var state = ScreenState()+ state.enabled = true+ state.connected = true+ state.permissionApp = "CodyncDevScreen"+ #expect(state.accessGuidance.contains("CodyncDevScreen"))+ state.capture = true+ #expect(state.available)+ #expect(!state.controlReady)+ #expect(state.accessGuidance.contains("Device Control and Data Access"))+ state.platform = "linux"+ #expect(state.accessGuidance.contains("system sharing dialog"))+ state.platform = "windows"+ #expect(state.accessGuidance.contains("not available on Windows"))+ state.computerUse = true+ #expect(state.controlReady)+ }+}diff --git a/apps/ios/Kit/Tests/CodyncUITests/ComputerAccessIsolationTests.swift b/apps/ios/Kit/Tests/CodyncUITests/ComputerAccessIsolationTests.swiftnew file mode 100644index 00000000..4ebb2d10--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncUITests/ComputerAccessIsolationTests.swift@@ -0,0 +1,63 @@+import Foundation+import Testing+@testable import CodyncKit+@testable import CodyncUI++private func isolationComputer(_ name: String, keyByte: UInt8) -> Computer {+ let key = Data(repeating: keyByte, count: 32)+ let encoded = key.base64EncodedString()+ .replacingOccurrences(of: "+", with: "-")+ .replacingOccurrences(of: "/", with: "_")+ .replacingOccurrences(of: "=", with: "")+ return Computer(id: RelayCrypto.computerId(signKey: key), name: name, signKey: encoded)+}++@MainActor @Test(arguments: [false, true])+func phoneRosterUsesItsOwnPairingsNotUnavailableOrderEntries(hasIndependentAccessToB: Bool) throws {+ let suite = "ComputerAccessIsolation.\(UUID().uuidString)"+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let storage = SharedStore.Context(accountID: "same-account", suite: suite)+ let a = isolationComputer("A", keyByte: 1)+ let b = isolationComputer("B via desktop SSH", keyByte: 2)+ storage.computers = hasIndependentAccessToB ? [a, b] : [a]+ // A previously saved position must not grant access to an unavailable computer.+ storage.computerOrder = ComputerOrder(ids: [b.id, a.id])+ var opened: [ComputerID] = []+ let bot = try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"same-bot-id","name":"Local bot","rev":1}"#.utf8))+ let accounts = AccountStore(storage: storage, clientKind: "ios", cloud: nil) { computer in+ opened.append(computer.id)+ let store = BotStore(computer: computer, clientKind: "ios", storage: storage) { FakeRemote(.connecting) }+ store.bots[bot.id] = bot+ return store+ }+ defer { accounts.retire() }+ accounts.setActive(false)++ let expected = hasIndependentAccessToB ? [b.id, a.id] : [a.id]+ #expect(accounts.computers.map(\.id) == expected)+ #expect(Set(opened) == Set(expected))+ #expect(Set(accounts.roster.map(\.ref.computerId)) == Set(expected))+ #expect(accounts.roster.count == expected.count)+ #expect((accounts.store(for: b.id) != nil) == hasIndependentAccessToB)+ #expect(Set(storage.computers.map(\.id)) == Set(expected))+}++@MainActor @Test func forgottenComputerDoesNotReturnFromAccountOrder() {+ let suite = "ComputerAccessIsolation.\(UUID().uuidString)"+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let storage = SharedStore.Context(accountID: "same-account", suite: suite)+ let a = isolationComputer("A", keyByte: 1)+ let b = isolationComputer("B", keyByte: 2)+ storage.computers = [a, b]+ storage.computerOrder = ComputerOrder(ids: [b.id, a.id])+ let accounts = AccountStore(storage: storage, clientKind: "ios", cloud: nil) { computer in+ BotStore(computer: computer, clientKind: "ios", storage: storage) { FakeRemote(.connecting) }+ }+ defer { accounts.retire() }+ accounts.setActive(false)+ accounts.forget(b.id)+ #expect(accounts.computers.map(\.id) == [a.id])+ #expect(accounts.store(for: b.id) == nil)+ #expect(storage.computers.map(\.id) == [a.id])+ #expect(storage.computerOrder?.ids.contains(b.id) == true)+}diff --git a/apps/ios/Kit/Tests/CodyncUITests/ComputerOrderStoreTests.swift b/apps/ios/Kit/Tests/CodyncUITests/ComputerOrderStoreTests.swiftnew file mode 100644index 00000000..c6dbf1ec--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncUITests/ComputerOrderStoreTests.swift@@ -0,0 +1,58 @@+import CodyncKit+import Foundation+import Testing+@testable import CodyncUI++@MainActor @Test func computerOrderSavesImmediatelyAndSurvivesRestart() {+ let suite = "order-\(UUID().uuidString)"+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let storage = SharedStore.Context(accountID: "a", suite: suite)+ storage.computerOrder = ComputerOrder(ids: ["a", "hidden", "b"])+ let store = ComputerOrderStore(storage: storage)+ var changes = 0+ store.onChanged = { changes += 1 }+ store.move("b", to: "a", available: ["a", "b", "new"])+ #expect(storage.computerOrder?.ids == ["b", "a", "hidden", "new"])+ #expect(ComputerOrderStore(storage: storage).state == store.state)+ #expect(changes == 1)+}++@MainActor @Test func sameAccountOnDifferentDevicesKeepsIndependentOrders() {+ let phoneSuite = "phone-order-\(UUID().uuidString)"+ let desktopSuite = "desktop-order-\(UUID().uuidString)"+ defer {+ UserDefaults(suiteName: phoneSuite)?.removePersistentDomain(forName: phoneSuite)+ UserDefaults(suiteName: desktopSuite)?.removePersistentDomain(forName: desktopSuite)+ }+ let phoneStorage = SharedStore.Context(accountID: "same-account", suite: phoneSuite)+ let desktopStorage = SharedStore.Context(accountID: "same-account", suite: desktopSuite)+ phoneStorage.computerOrder = ComputerOrder(ids: ["a", "b", "c"])+ desktopStorage.computerOrder = ComputerOrder(ids: ["c", "b", "a"])+ let phone = ComputerOrderStore(storage: phoneStorage)+ let desktop = ComputerOrderStore(storage: desktopStorage)+ phone.move("b", to: "a", available: ["a", "b", "c"])+ #expect(desktop.state.ids == ["c", "b", "a"])+ desktop.move("a", to: "c", available: ["a", "b", "c"])+ #expect(phone.state.ids == ["b", "a", "c"])+ #expect(ComputerOrderStore(storage: phoneStorage).state.ids == ["b", "a", "c"])+ #expect(ComputerOrderStore(storage: desktopStorage).state.ids == ["a", "c", "b"])+}++@MainActor @Test func retiredComputerOrderCannotChangeLocalStorage() {+ let suite = "order-\(UUID().uuidString)"+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let storage = SharedStore.Context(accountID: "a", suite: suite)+ storage.computerOrder = ComputerOrder(ids: ["a", "b"])+ let store = ComputerOrderStore(storage: storage)+ store.retire()+ store.move("b", to: "a", available: ["a", "b"])+ #expect(storage.computerOrder?.ids == ["a", "b"])+}++@Test func previouslyCachedOrderDecodesWithoutUploadState() throws {+ let cached = Data(#"{"ids":["b","a"],"pending":true}"#.utf8)+ let order = try JSONDecoder().decode(ComputerOrder.self, from: cached)+ #expect(order.ids == ["b", "a"])+ let encoded = try JSONSerialization.jsonObject(with: JSONEncoder().encode(order)) as? [String: Any]+ #expect(encoded?["pending"] == nil)+}diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swiftindex e5a72bb7..6cef47ec 100644--- a/apps/ios/Views/BotListView.swift+++ b/apps/ios/Views/BotListView.swift@@ -83,7 +83,7 @@ struct BotListView: View {// Not synced while it needs an update: "No bots yet" wouldn't be true.ComputerSection(store: store, empty: store.mismatch == nil && !roster.contains { $0.ref.computerId == id },collapsed: collapsed, toggle: { toggleCollapsed(id) }, move: move)- .gesture(SectionLongPress { state, y in dragSection(id, state, y) })+ .modifier(ComputerSectionGesture(tap: { toggleCollapsed(id) }) { state, y in dragSection(id, state, y) })updateCard(store)if !collapsed {ForEach(roster.filter { $0.ref.computerId == id }) { row($0, store: store) }@@ -205,15 +205,22 @@ struct BotListView: View {drag = SectionDrag(id: id, startY: y, y: y)case .changed:drag?.y = y- default:- guard let drag else { return }+ case .ended:+ guard var drag, drag.id == id else { return }+ drag.y = ylet ids = shownStores.map(\.computer.id)let to = landingIndex(ids, drag)// The order changes as the offsets drop, so everything settles where it's shown.withAnimation(Motion.reduced(Motion.layout, reduceMotion)) {- if ids[to] != id { accounts.move(id, to: ids[to]) }+ if ids.contains(id), ids.indices.contains(to), ids[to] != id {+ accounts.move(id, to: ids[to])+ }self.drag = nil}+ case .cancelled, .failed:+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { drag = nil }+ default:+ break}}@@ -275,8 +282,9 @@ private struct ComputerSection: View {var body: some View {VStack(alignment: .leading, spacing: 6) {- Button(action: toggle) { heading }- .buttonStyle(.plain)+ // The parent's tap/hold gesture owns touch input, so a release+ // after dragging cannot also trigger a nested button's collapse action.+ headingif empty && !collapsed {Text("No bots yet").font(.footnote)@@ -290,9 +298,12 @@ private struct ComputerSection: View {.padding(.bottom, 2).padding(.horizontal, -8).accessibilityElement(children: .combine)- .accessibilityAddTraits(.isHeader)+ .accessibilityAddTraits([.isHeader, .isButton])+ .accessibilityLabel("\(store.hostName), \(store.statusText)").accessibilityValue(collapsed ? "Collapsed" : "Expanded")+ .accessibilityHint("Double-tap to fold or expand. Touch and hold, then drag to reorder on this device.").accessibilityAction(named: collapsed ? "Expand" : "Collapse", toggle)+ .accessibilityAction(.default) { toggle() }.accessibilityActions {Button("Move up") { move(store.computer.id, -1) }Button("Move down") { move(store.computer.id, 1) }@@ -334,22 +345,6 @@ private struct SectionDrag {var translation: CGFloat { y - startY }}-/// UIKit's long press: it waits for the hold, then reports the finger, and leaves the scroll-/// view alone until then (a SwiftUI long-press-then-drag steals the scroll).-private struct SectionLongPress: UIGestureRecognizerRepresentable {- let update: (UIGestureRecognizer.State, CGFloat) -> Void-- func makeUIGestureRecognizer(context: Context) -> UILongPressGestureRecognizer {- let recognizer = UILongPressGestureRecognizer()- recognizer.minimumPressDuration = 0.35- return recognizer- }-- func handleUIGestureRecognizerAction(_ recognizer: UILongPressGestureRecognizer, context: Context) {- update(recognizer.state, recognizer.location(in: nil).y)- }-}-private struct GroupTarget: Identifiable {let id = UUID()let computerId: ComputerIDdiff --git a/apps/ios/Views/ComputerSectionGesture.swift b/apps/ios/Views/ComputerSectionGesture.swiftnew file mode 100644index 00000000..0d7c5654--- /dev/null+++ b/apps/ios/Views/ComputerSectionGesture.swift@@ -0,0 +1,46 @@+import SwiftUI+import UIKit++/// A shared hit area keeps short taps, scrolling and long-press reordering distinct.+struct ComputerSectionGesture: ViewModifier {+ let tap: () -> Void+ let drag: (UIGestureRecognizer.State, CGFloat) -> Void+ @GestureState private var holding = false+ @State private var dragging = false++ func body(content: Content) -> some View {+ content+ .contentShape(Rectangle())+ .highPriorityGesture(hold.simultaneously(with: TapGesture().onEnded {+ if !dragging { tap() }+ }))+ .onChange(of: holding) { _, held in+ if !held && dragging {+ dragging = false+ drag(.cancelled, 0)+ }+ }+ }++ private var hold: some Gesture {+ LongPressGesture(minimumDuration: 0.35)+ .sequenced(before: DragGesture(minimumDistance: 0, coordinateSpace: .global))+ .updating($holding) { value, held, _ in+ if case .second(true, _) = value { held = true }+ }+ .onChanged { value in+ guard case let .second(true, movement?) = value else { return }+ if !dragging {+ dragging = true+ drag(.began, movement.startLocation.y)+ }+ drag(.changed, movement.location.y)+ }+ .onEnded { value in+ dragging = false+ if case let .second(true, movement?) = value {+ drag(.ended, movement.location.y)+ } else { drag(.cancelled, 0) }+ }+ }+}diff --git a/apps/screen-linux/Cargo.lock b/apps/screen-linux/Cargo.lockindex ca31fddf..59b417fa 100644--- a/apps/screen-linux/Cargo.lock+++ b/apps/screen-linux/Cargo.lock@@ -294,6 +294,7 @@ dependencies = ["atspi","base64","dirs",+ "futures-util","gstreamer","gstreamer-app","gstreamer-sdp",diff --git a/apps/screen-linux/Cargo.toml b/apps/screen-linux/Cargo.tomlindex d68e5c17..d948fcea 100644--- a/apps/screen-linux/Cargo.toml+++ b/apps/screen-linux/Cargo.toml@@ -11,6 +11,7 @@ ashpd = { version = "0.13", default-features = false, features = ["tokio", "remoatspi = { version = "0.30", default-features = false, features = ["proxies", "connection", "tokio"] }base64 = "0.22"dirs = "7"+futures-util = "0.3"gst = { package = "gstreamer", version = "0.25" }gst-app = { package = "gstreamer-app", version = "0.25" }gst-sdp = { package = "gstreamer-sdp", version = "0.25" }diff --git a/apps/screen-linux/src/main.rs b/apps/screen-linux/src/main.rsindex f8c4db17..0aeec297 100644--- a/apps/screen-linux/src/main.rs+++ b/apps/screen-linux/src/main.rs@@ -31,7 +31,8 @@ fn data_dir() -> PathBuf {pub type Outbox = mpsc::UnboundedSender<Value>;pub struct Helper {- portal: portal::Portal,+ portal: Arc<Mutex<Option<portal::Portal>>>,+ last_status: Mutex<Option<Value>>,sessions: Mutex<HashMap<String, stream::Session>>,out: Outbox,}@@ -45,9 +46,8 @@ async fn main() -> Result<()> {).init();gst::init().context("starting GStreamer")?;- // One portal session for the life of the process: the approval dialog appears once,- // and later runs restore it silently from the saved token.- let portal = portal::Portal::start(&data_dir()).await?;+ // Starting the helper must not display a system dialog. Setup explicitly opens a session.+ let portal = Arc::new(Mutex::new(None));loop {match UnixStream::connect(data_dir().join("screen.sock")).await {Ok(sock) => {@@ -62,7 +62,7 @@ async fn main() -> Result<()> {}}-async fn serve(sock: UnixStream, portal: &portal::Portal) -> Result<()> {+async fn serve(sock: UnixStream, portal: &Arc<Mutex<Option<portal::Portal>>>) -> Result<()> {let (rd, mut wr) = sock.into_split();let (out, mut outbox) = mpsc::unbounded_channel::<Value>();let writer = tokio::spawn(async move {@@ -76,13 +76,25 @@ async fn serve(sock: UnixStream, portal: &portal::Portal) -> Result<()> {});let helper = Arc::new(Helper {portal: portal.clone(),+ last_status: Mutex::new(None),sessions: Mutex::default(),out: out.clone(),});- let _ =- out.send(json!({"jsonrpc": "2.0", "method": "status", "params": helper.portal.status()}));+ helper.send_status().await;+ let watched = helper.clone();+ let status_task = tokio::spawn(async move {+ loop {+ tokio::time::sleep(Duration::from_secs(3)).await;+ watched.send_status().await;+ }+ });let mut lines = BufReader::new(rd).lines();- while let Some(line) = lines.next_line().await? {+ let result = loop {+ let line = match lines.next_line().await {+ Ok(Some(line)) => line,+ Ok(None) => break Ok(()),+ Err(error) => break Err(error.into()),+ };let Ok(msg) = serde_json::from_str::<Value>(&line) else {continue;};@@ -102,16 +114,55 @@ async fn serve(sock: UnixStream, portal: &portal::Portal) -> Result<()> {};let _ = helper.out.send(reply);});- }+ };writer.abort();+ status_task.abort();for (_, s) in helper.sessions.lock().await.drain() {s.close();}- Ok(())+ result}async fn handle(h: &Arc<Helper>, method: &str, p: &Value) -> Result<Value> {- let display = || h.portal.display(p["display"].as_u64());+ if method == "requestPermission" {+ if p["permission"] != "portal" {+ return Err(anyhow!("Linux uses the screen sharing portal"));+ }+ let mut portal = h.portal.lock().await;+ if portal.as_ref().is_none_or(|p| !p.has_input()) {+ let restore = portal.as_ref().is_none_or(|p| !p.is_active());+ let next = portal::Portal::start(&data_dir(), restore).await?;+ if let Some(previous) = portal.as_ref() {+ if previous.is_active() {+ previous.session().close().await?;+ }+ for (_, session) in h.sessions.lock().await.drain() {+ session.close();+ }+ }+ *portal = Some(next);+ }+ drop(portal);+ h.send_status().await;+ return Ok(json!({}));+ }+ // Close requests remain valid before setup; all other methods require a granted session.+ if method == "closeAll" {+ for (_, s) in h.sessions.lock().await.drain() {+ s.close();+ }+ return Ok(json!({}));+ }+ if method == "close" {+ if let Some(id) = p["session"].as_str()+ && let Some(s) = h.sessions.lock().await.remove(id)+ {+ s.close();+ }+ return Ok(json!({}));+ }+ let portal = h.portal().await?;+ let display = || portal.display(p["display"].as_u64());Ok(match method {"answer" => {let id = p["session"]@@ -125,40 +176,25 @@ async fn handle(h: &Arc<Helper>, method: &str, p: &Value) -> Result<Value> {return Ok(json!({"sdp": s.answer(sdp).await?}));}let d = display()?;- let fd = h.portal.pipewire_fd().await?;+ let fd = portal.pipewire_fd().await?;let session = stream::Session::new(id.clone(), &d, fd, h.clone(), p)?;let answer = session.answer(sdp).await?;h.sessions.lock().await.insert(id, session);json!({"sdp": answer})}- "close" => {- if let Some(s) = p["session"]- .as_str()- .and_then(|id| h.sessions.try_lock().ok()?.remove(id))- {- s.close();- }- json!({})- }- "closeAll" => {- for (_, s) in h.sessions.lock().await.drain() {- s.close();- }- json!({})- }"screenshot" => {let (w, h2) = (p["width"].as_u64().unwrap_or(1280),p["height"].as_u64().unwrap_or(800),);let d = display()?;- let fd = h.portal.pipewire_fd().await?;+ let fd = portal.pipewire_fd().await?;let jpeg = stream::screenshot(fd, &d, u32::try_from(w)?, u32::try_from(h2)?).await?;json!({"data": jpeg})}"input" => {let d = display()?;- input::perform(&h.portal, &d, &p["event"]).await?;+ input::perform(&portal, &d, &p["event"]).await?;json!({})}"uiTree" => a11y::frontmost(&display()?).await?,@@ -177,6 +213,30 @@ async fn handle(h: &Arc<Helper>, method: &str, p: &Value) -> Result<Value> {}impl Helper {+ async fn portal(&self) -> Result<portal::Portal> {+ self.portal+ .lock()+ .await+ .clone()+ .filter(portal::Portal::is_active)+ .ok_or_else(|| anyhow!("Set up Computer access in Codync on this computer first."))+ }++ async fn send_status(&self) {+ let status = self.portal.lock().await.as_ref().map_or_else(+ || json!({"platform": "linux", "permissionApp": "Codync Screen", "capture": false, "input": false, "displays": []}),+ portal::Portal::status,+ );+ let mut last = self.last_status.lock().await;+ if last.as_ref() == Some(&status) {+ return;+ }+ *last = Some(status.clone());+ let _ = self+ .out+ .send(json!({"jsonrpc": "2.0", "method": "status", "params": status}));+ }+/// A session's WebRTC connection ended on its own.pub fn ended(self: &Arc<Self>, id: &str) {let this = self.clone();diff --git a/apps/screen-linux/src/portal.rs b/apps/screen-linux/src/portal.rsindex e81135c8..931ef4a4 100644--- a/apps/screen-linux/src/portal.rs+++ b/apps/screen-linux/src/portal.rs@@ -7,10 +7,12 @@ use ashpd::desktop::PersistMode;use ashpd::desktop::Session;use ashpd::desktop::remote_desktop::{DeviceType, RemoteDesktop, SelectDevicesOptions};use ashpd::desktop::screencast::{CursorMode, Screencast, SelectSourcesOptions, SourceType};+use futures_util::StreamExt;use serde_json::{Value, json};use std::os::fd::OwnedFd;use std::path::{Path, PathBuf};use std::sync::Arc;+use std::sync::atomic::{AtomicBool, Ordering};/// A monitor as the portal streams it. `width`/`height` are logical pixels: the/// coordinate space of input events and of the host's `Display` points.@@ -33,12 +35,17 @@ struct Inner {session: Session<RemoteDesktop>,displays: Vec<Display>,input: bool,+ active: AtomicBool,}impl Portal {- pub async fn start(data: &Path) -> Result<Self> {+ pub async fn start(data: &Path, restore: bool) -> Result<Self> {let token_file = data.join("screen-restore-token");- let token = std::fs::read_to_string(&token_file).ok();+ let token = if restore {+ std::fs::read_to_string(&token_file).ok()+ } else {+ None+ };let remote = RemoteDesktop::new().await.context("the RemoteDesktop portal isn't available")?;@@ -92,22 +99,46 @@ impl Portal {if displays.is_empty() {return Err(anyhow!("the portal shared no screen"));}- let input = started.devices().contains(DeviceType::Pointer);- Ok(Self(Arc::new(Inner {+ let input = started+ .devices()+ .contains(DeviceType::Pointer | DeviceType::Keyboard);+ let portal = Self(Arc::new(Inner {remote,screencast,session,displays,input,- })))+ active: AtomicBool::new(true),+ }));+ // Ending sharing in the system UI must make setup available again.+ let watched = portal.clone();+ tokio::spawn(async move {+ match watched.session().receive_closed().await {+ Ok(mut closed) => {+ let _ = closed.next().await;+ }+ Err(error) => tracing::warn!(%error, "could not watch the screen sharing session"),+ }+ watched.0.active.store(false, Ordering::Relaxed);+ });+ Ok(portal)+ }++ pub fn is_active(&self) -> bool {+ self.0.active.load(Ordering::Relaxed)+ }++ pub fn has_input(&self) -> bool {+ self.is_active() && self.0.input}pub fn status(&self) -> Value {json!({"platform": "linux",+ "permissionApp": "Codync Screen","version": env!("CARGO_PKG_VERSION"),- "capture": true,- "input": self.0.input,+ "capture": self.is_active(),+ "input": self.has_input(),"displays": self.0.displays.iter().map(|d| json!({"id": d.id,"name": format!("Display {}", d.id + 1),diff --git a/apps/screen-linux/src/stream.rs b/apps/screen-linux/src/stream.rsindex 74457386..0701cd57 100644--- a/apps/screen-linux/src/stream.rs+++ b/apps/screen-linux/src/stream.rs@@ -128,11 +128,14 @@ impl Session {.as_ref().map(error_msg)}- _ => input::perform(&helper.portal, &display, &msg)- .await- .err()- .as_ref()- .map(error_msg),+ _ => match helper.portal().await {+ Ok(portal) => input::perform(&portal, &display, &msg)+ .await+ .err()+ .as_ref()+ .map(error_msg),+ Err(error) => Some(error_msg(&error)),+ },};if let Some(reply) = reply {send(&channels, &reply);diff --git a/apps/screen-macos/Permissions.swift b/apps/screen-macos/Permissions.swiftnew file mode 100644index 00000000..b6ceb384--- /dev/null+++ b/apps/screen-macos/Permissions.swift@@ -0,0 +1,21 @@+import AppKit+import ApplicationServices+import CoreGraphics++/// System prompts are explicit onboarding actions, never a side effect of launching the helper.+@MainActor+enum ScreenPermissions {+ static func request(_ permission: String) throws {+ switch permission {+ case "capture":+ if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() }+ case "input":+ if !AXIsProcessTrusted() {+ // The C global for this option is not available under Swift 6 concurrency.+ _ = AXIsProcessTrustedWithOptions(["AXTrustedCheckOptionPrompt": true] as CFDictionary)+ }+ default:+ throw HelperError("Unknown computer access permission.")+ }+ }+}diff --git a/apps/screen-macos/ScreenHelper.swift b/apps/screen-macos/ScreenHelper.swiftindex c891062a..ab9ab09a 100644--- a/apps/screen-macos/ScreenHelper.swift+++ b/apps/screen-macos/ScreenHelper.swift@@ -26,9 +26,6 @@ final class ScreenHelper {func start() {let captureAtLaunch = CGPreflightScreenCaptureAccess()- if !captureAtLaunch { CGRequestScreenCaptureAccess() }- // `kAXTrustedCheckOptionPrompt` is a C global Swift 6 won't read; its value is this string.- _ = AXIsProcessTrustedWithOptions(["AXTrustedCheckOptionPrompt": true] as CFDictionary)link.start()NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ inMainActor.assumeIsolated { self?.sendStatus() }@@ -51,6 +48,11 @@ final class ScreenHelper {private func handle(_ method: String, _ p: [String: Any]) async throws -> Any {switch method {+ case "requestPermission":+ guard let permission = p["permission"] as? String else { throw HelperError("permission is required") }+ try ScreenPermissions.request(permission)+ sendStatus()+ return [String: Any]()case "answer":guard let id = p["session"] as? String, let sdp = p["sdp"] as? String else { throw HelperError("session and sdp are required") }if let s = sessions[id] { return ["sdp": try await s.answer(offer: sdp)] }@@ -83,6 +85,9 @@ final class ScreenHelper {case "focusedField":return try AXTree.focusedField(pid: (p["pid"] as? NSNumber).map { pid_t($0.int32Value) })case "driver":+ guard CGPreflightScreenCaptureAccess(), AXIsProcessTrusted() else {+ throw HelperError("Set up Computer access in Codync → Settings on this computer first.")+ }return ["socket": try await driver.socket()]default:throw HelperError("unknown method \(method)")@@ -135,6 +140,7 @@ final class ScreenHelper {}let status: [String: AnyHashable] = ["platform": "macos",+ "permissionApp": Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? "Codync Screen","version": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "","displays": displays,"capture": CGPreflightScreenCaptureAccess(),diff --git a/cloud/migrations/0004_computer_order.sql b/cloud/migrations/0004_computer_order.sqlnew file mode 100644index 00000000..596ed64e--- /dev/null+++ b/cloud/migrations/0004_computer_order.sql@@ -0,0 +1,2 @@+-- Historical migration, already deployed. Ordering is now device-local; this column is unused.+ALTER TABLE accounts ADD COLUMN computer_order TEXT;diff --git a/cloud/test/computer-order.test.ts b/cloud/test/computer-order.test.tsnew file mode 100644index 00000000..826f676f--- /dev/null+++ b/cloud/test/computer-order.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from "vitest";+import { call, clerkToken } from "./helpers";++describe("device-local computer order", () => {+ it("does not expose account-wide ordering endpoints", async () => {+ const id = `user_${crypto.randomUUID()}`;+ const token = await clerkToken(id);+ const path = `/v1/accounts/${id}/computer-order`;+ expect((await call("GET", path, { token })).status).toBe(404);+ expect((await call("PUT", path, { token, body: { computerIds: ["mini", "ssh"] } })).status).toBe(404);+ });+});diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.mdindex 16d78e81..4b78640a 100644--- a/docs/architecture/desktop-app.md+++ b/docs/architecture/desktop-app.md@@ -36,6 +36,18 @@ app restores the exact text. Submitting clears only that conversation's draft. Dcleared when the host identity changes or the bot is deleted. iOS and the TUI keep drafts thesame way; the shared desktop behavior covers macOS and Linux.+When several computers are selected, the sidebar groups bots by computer, with connection+status and update notices in each section. Drag a heading or press Alt+Up/Down on the+heading to reorder sections. Click a heading to fold its bots.+Order and folded sections stay on this device; the iPhone and other computers keep+independent orders even when signed in to the same account. Filtering a computer out+does not discard its position. One selected computer keeps a flat roster. Bot pin/activity+ordering stays within each section, and arrow-key navigation skips folded sections.+Search still includes their bots. The compact sidebar uses computer badges for the same+section controls. Ordering is saved locally immediately and survives restart, with separate+preferences per account and cloud environment. See [computer ordering](../features/computer-order.md).+The TUI connects to one host at a time, so it keeps its single roster.+## Platform notes- **SSH startup** in the shared desktop UI keeps the workspace open whenever saved profilesdiff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex bd07ca97..9e2fcf6f 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -16,6 +16,12 @@ Sources: `apps/ios/Views/BotListView.swift`, `AccountSwitcherView.swift`, `apps/## Desktop menu bar (tray)+The iPhone App Store update reminder uses a hierarchical `arrow.down.circle.fill`+symbol in the primary text color, keeping the download arrow clear against its+softer circle in both appearances. Desktop updates live in Settings and the native+tray menu; the TUI uses a text action and status message. Neither has this App Store+reminder card, so its decorative icon treatment is iPhone-only.+Release update controls live in the tray's Settings → Updates submenu; the chatwindow's Settings has the same controls on its Updates page (**Check for updates**,which becomes **Update to <version>** once a release is found). The TUI action list@@ -200,3 +206,5 @@ The desktop sidebar computer filter shares the toolbar's subtle outline and 32pxheight, with a capsule enclosing both the computer glyph and its chevron. Thisapplies in expanded and compact sidebars. iOS retains native toolbar treatment;terminal computer selection has no corresponding icon button.++Dialog scrims cover the entire presentation surface, including the iPhone status-bar and home-indicator safe areas, throughout opening and closing. The shared iPhone overlay fades a full-screen canvas without scaling its backdrop; root in-place dialogs also extend the canvas beyond container safe areas. Desktop dialogs keep their viewport-sized backdrop fixed and scale only the card. Terminal dialogs already dim the complete terminal buffer.diff --git a/docs/features/computer-order.md b/docs/features/computer-order.mdnew file mode 100644index 00000000..c9d0260a--- /dev/null+++ b/docs/features/computer-order.md@@ -0,0 +1,39 @@+# Computer identity and list ordering++A computer's identity is its host signing key's `computerId`, not its display name,+address, Apple login or transport. Pairing and account discovery of the same host+reuse that ID; iOS keeps one store per ID. Different computers may have the same+name without being merged. Resetting the host's data/keys makes a new identity:+its old offline entry may need removing. Signing in with Apple and Google shares+this state only when both reach the same Codync account.++Desktop and iOS show one section per selected computer, or a flat list when only+one is selected. Drag a section heading to reorder it. Desktop also supports+Alt+Up/Down on the heading; iOS exposes Move up/down accessibility actions.+Filtering, folding and ordering are device-local preferences. The iPhone and each+desktop installation keep their own order, even when signed in to the same account.++## Local persistence++Desktop saves the order in localStorage, separately for each account and cloud+environment. Signed-out ordering has its own local preference. iOS saves the order+in its App Group UserDefaults, scoped to the local account context. Existing cached+positions remain in place; there are no uploads, downloads, pending writes or polls.+Reordering works offline and survives restarting the app.++Devices show their available computers in their own saved order and append newly+available computers. Missing/filtered computers retain their position for when+they return. Computer names and bots never become ordering keys, and an ordering+entry never grants access to a computer or imports another device's SSH connection.++On iOS, touch and hold a computer heading, then drag up or down and release to save+the order. Cancelling a drag leaves the saved order unchanged. A tap folds or expands+the section; Move up/down accessibility actions are also available. The desktop+app supports heading drags and Alt+Up/Down on macOS, Linux and Windows.+The terminal UI connects to one host, so it has no cross-computer ordering.++The account computer-order API has been removed. Migration+`0004_computer_order.sql` remains as already-deployed schema history; its column is+unused. Updating clients stops them from reading or writing remote order immediately,+without requiring a cloud deployment. Removing the endpoint from an existing Worker+requires deploying the updated cloud code separately.diff --git a/docs/features/computer-use.md b/docs/features/computer-use.mdindex 6d8b76e4..e7d8cc2a 100644--- a/docs/features/computer-use.md+++ b/docs/features/computer-use.md@@ -6,6 +6,21 @@ Bots with **Use the computer** on get the built-in `computer` MCP server (`codyn- `type_login` types a saved login only into its own site or app, and a password only into a password field. The agent never sees the value.- The harness's own approval rules still apply to each call.+## Computer access setup++Desktop onboarding includes **Computer access**, also available from **Settings → Computer access** and the tray's **Set up computer access…** action. Users can choose **Set up later** and keep using chat. Setup choices stay on this installation.++The desktop setup uses a compact device header and one outlined permission group, matching the toolbar and composer outlines. Rows distinguish ready, current and waiting steps; host and setup errors appear before the checklist. This requested outline is an exception to the default borderless filled-card rule. The shared Electron layout applies to macOS, Linux and Windows. iOS and terminal retain their existing status and setup guidance: neither runs this local graphical permission onboarding, so their layout is unaffected.++- macOS: explicitly enable the background helper, then request Screen Recording and computer control. Depending on macOS, control is listed as **Device Control and Data Access** or **Accessibility**. Setup identifies the exact helper name. Codync Screen includes the Codync icon for system permission lists. A fresh installation registers the helper only when enabled; existing registrations are maintained across updates.+- Opening setup, starting the macOS helper and returning from System Settings only check grants. Native prompts require an explicit setup action through local-only `requestScreenPermission`. The helper refuses to start the embedded driver until both grants are present. Newly granted screen recording triggers the existing helper restart mechanism.+- Linux: setup opens the system screen-sharing portal for a display, mouse and keyboard. Helper startup never opens a chooser. The session survives host reconnections; after the helper itself restarts, reopen setup to restore sharing explicitly. Denied or partial grants can be retried.+- Windows: computer-use bots need no macOS-style grants. Setup explains that phone screen viewing is not yet supported.+- iPhone: pair through QR / Ask Access, with no SSH configuration. The viewer explains missing permissions and points to setup on the computer. Capture-only access allows viewing; takeover remains disabled until input is allowed, and revoking input exits takeover.+- Terminal UI: the bot editor shows current helper/permission status and points to **Computer access**. System Settings, background-service registration and portal choosers require the graphical desktop, so the terminal does not issue those prompts. Status follows host events.++Desktop setup polls read-only status while open and checks again on focus. Opening Settings never counts as a grant. Failures retain retry and Settings actions; completion requires actual platform-specific status. Skipping grants no permissions. Older clients ignore the additive `permissionApp` status field.+## The driverThe tools come from [cua-driver](https://github.com/trycua/cua) (MIT), which works on apps in the background: by accessibility element where it can (`element_token` from `get_window_state`), by pixels posted to the app otherwise, and in the foreground only when a call asks for `delivery_mode: "foreground"`. The user's cursor and front app stay theirs.diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.mdindex 9e615426..96f9caae 100644--- a/docs/reference/compatibility.md+++ b/docs/reference/compatibility.md@@ -138,6 +138,7 @@ Update this table in the release that changes a floor, with the reason.| Release | Host `minApp` | Client `minHost` | Why ||---|---|---|---|+| 2.12.0 | 2.3.0 | 2.12.0 | The clients require Engram memory management fields and methods. Older clients can still list and forget memories on the new host. || 2.4.0 | 2.3.0 | 2.3.0 | First release with the check. Since 2.3.0 the wire only gained `minApp` and lost the unused `protocol`; 2.3.0 is the oldest pairing verified to work, and a higher floor would lock out hosts that never auto-update. |## Trying it on a simulatordiff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.mdindex b033ed28..4016fc5c 100644--- a/docs/reference/remote-relay.md+++ b/docs/reference/remote-relay.md@@ -303,6 +303,7 @@ blob = epk(32) ‖ sig(64) ‖ ct- `id`:device 端遞增 u32,連線內唯一。- 每條 channel 最多 32 個進行中的 request、4 個訂閱;超過回 `err 429`。- `events` 訂閱的語意與 SSE 完全相同(先 subscribe、再 catch-up、`hello` 在最前、落後時送 `{"type":"resync"}`);`client == "ios"` 時計入 `hub.ios_clients`(推播抑制)。+- Bot 刪除標記會保留在 host 資料庫;增量同步與 `since = 0` 的全量同步都傳送它們。手機及桌面在版本更新或解碼重試時會保留快取並重設同步游標,必須收到刪除標記才能移除舊 Bot、對話與草稿;終端使用相同的事件串流。- 串流沒有額外的 keep-alive;存活由 WebSocket ping(§7.6)負責。### 6.6 方法權限(host 以 `Caller` 判斷)diff --git a/host/src/api/devices.rs b/host/src/api/devices.rsindex 62812281..a1985d05 100644--- a/host/src/api/devices.rs+++ b/host/src/api/devices.rs@@ -35,6 +35,7 @@ const LOCAL_ONLY: &[&str] = &["installHostUpdate","setHostAutomaticUpdates","setScreenEnabled",+ "requestScreenPermission",// Analytics is the computer owner's choice; phones decide only for themselves."setAnalytics","track",@@ -46,6 +47,7 @@ const LOCAL_ONLY: &[&str] = &["chatCall","teamCall","memoryCall",+ "memoryTools","routineCall","composioCall","connectorTarget",diff --git a/host/src/api/host.rs b/host/src/api/host.rsindex e1100428..72c98559 100644--- a/host/src/api/host.rs+++ b/host/src/api/host.rs@@ -133,6 +133,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Valuejson!({})}"screenStatus" => hub.screen.state(),+ "requestScreenPermission" => hub.screen.request_permission(&b).await?,"screenPrepare" => {if !hub.screen.enabled() {bail!("Remote screen is turned off on this computer.");diff --git a/host/src/screen/helper.rs b/host/src/screen/helper.rsindex 7e343e0d..0f07d61d 100644--- a/host/src/screen/helper.rs+++ b/host/src/screen/helper.rs@@ -10,7 +10,6 @@ use serde_json::{Value, json};use std::collections::HashMap;use std::sync::atomic::{AtomicI64, Ordering};use std::sync::{Arc, Mutex};-#[cfg(unix)]use std::time::Duration;#[cfg(unix)]use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};@@ -39,7 +38,9 @@ impl Link {self.pending.locked().remove(&id);bail!("the screen helper disconnected");}- match tokio::time::timeout(HELPER_TIMEOUT, rx).await {+ // Permission dialogs wait for a person; normal helper calls should still fail quickly.+ let timeout = if method == "requestPermission" { Duration::from_secs(120) } else { HELPER_TIMEOUT };+ match tokio::time::timeout(timeout, rx).await {Ok(Ok(Ok(v))) => Ok(v),Ok(Ok(Err(message))) => Err(anyhow!(message)),Ok(Err(_)) => bail!("the screen helper disconnected"),diff --git a/host/src/screen/mod.rs b/host/src/screen/mod.rsindex 6447ac76..dbb61d0e 100644--- a/host/src/screen/mod.rs+++ b/host/src/screen/mod.rs@@ -35,6 +35,7 @@ mod cua;mod helper;#[cfg(target_os = "linux")]mod helper_tools;+mod permissions;mod protocol;mod viewer;@@ -137,6 +138,7 @@ impl Screen {"enabled": self.enabled(),"connected": connected,"platform": st.platform,+ "permissionApp": st.permission_app,"capture": st.capture,"input": st.input,"displays": st.displays,diff --git a/host/src/screen/permissions.rs b/host/src/screen/permissions.rsnew file mode 100644index 00000000..7bd7c404--- /dev/null+++ b/host/src/screen/permissions.rs@@ -0,0 +1,50 @@+//! Explicit, local-only permission requests from the computer access setup flow.++use super::Screen;+use anyhow::{Context, Result, bail};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};++#[derive(Clone, Copy, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+enum Permission {+ Capture,+ Input,+ Portal,+}++impl Screen {+ pub(crate) async fn request_permission(&self, body: &Value) -> Result<Value> {+ let permission: Permission = serde_json::from_value(body["permission"].clone())+ .context("permission must be capture, input or portal")?;+ if cfg!(windows) {+ bail!("Windows does not require these computer access permissions");+ }+ let is_portal = matches!(permission, Permission::Portal);+ if is_portal != cfg!(target_os = "linux") {+ bail!("this permission is not supported on this platform");+ }+ self.link()?.request("requestPermission", json!({"permission": permission})).await?;+ Ok(self.state())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn invalid_permission_never_reaches_a_helper() {+ let screen = Screen::new(Some(true), tokio::sync::broadcast::channel(1).0);+ let error = screen.request_permission(&json!({"permission": "all"})).await.unwrap_err();+ assert!(error.to_string().contains("permission must be"));+ }++ #[test]+ fn remote_devices_cannot_request_system_permissions() {+ use crate::api::devices::{Caller, permit};+ assert!(permit(&Caller::Local, "requestScreenPermission").is_ok());+ let device = Caller::Pairing { key: "test".into() };+ assert!(permit(&device, "requestScreenPermission").is_err());+ }+}diff --git a/host/src/screen/protocol.rs b/host/src/screen/protocol.rsindex 55b56771..e287ebb2 100644--- a/host/src/screen/protocol.rs+++ b/host/src/screen/protocol.rs@@ -23,6 +23,9 @@ pub struct HelperStatus {pub platform: String,#[serde(default)]pub version: String,+ /// Name to look for in the operating system's permission settings.+ #[serde(default)]+ pub permission_app: String,#[serde(default)]pub displays: Vec<Display>,/// Screen capture is permitted.diff --git a/host/src/tui/app/events.rs b/host/src/tui/app/events.rsindex cfba8297..c34140b5 100644--- a/host/src/tui/app/events.rs+++ b/host/src/tui/app/events.rs@@ -38,6 +38,7 @@ impl App {match v["type"].as_str() {Some("hello") if !v["usage"].is_null() => self.usage = v["usage"].clone(),Some("usage") => self.usage = v["usage"].clone(),+ Some("screen") => self.screen = v["screen"].clone(),Some("bot") => self.upsert_bot(&v["bot"]),Some("entry") => {if let Some((bot, e)) = Entry::parse(&v["entry"]) {@@ -149,6 +150,7 @@ impl App {v["home"].as_str().unwrap_or_default().clone_into(&mut self.home);self.backends = v["backends"].as_array().cloned().unwrap_or_default();self.analytics_hello(&v);+ self.screen = v["screen"].clone();}After::Analytics => self.analytics_set(&v),After::Backends => {diff --git a/host/src/tui/app/input.rs b/host/src/tui/app/input.rsindex e7981786..24939c21 100644--- a/host/src/tui/app/input.rs+++ b/host/src/tui/app/input.rs@@ -49,6 +49,7 @@ impl App {},Overlay::Market(m) => Some(&mut m.query),Overlay::Fields(f) => f.current().map(|i| &mut i.ed),+ Overlay::Memory(m) => m.editor(),Overlay::Routine(f) => Some(match f.field {super::super::manage::RoutineField::Name => &mut f.name,super::super::manage::RoutineField::Instruction => &mut f.instruction,diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rsindex c050318a..b7794f70 100644--- a/host/src/tui/app/mod.rs+++ b/host/src/tui/app/mod.rs@@ -48,6 +48,7 @@ pub struct App {pub bots: HashMap<String, Bot>,pub entries: HashMap<String, BTreeMap<i64, Entry>>,pub usage: Value,+ pub screen: Value,pub backends: Vec<Value>,pub selected: Option<String>,pub focus: Focus,@@ -112,6 +113,7 @@ impl App {bots: HashMap::new(),entries: HashMap::new(),usage: Value::Null,+ screen: Value::Null,backends: vec![],selected: None,focus: Focus::Roster,diff --git a/host/src/tui/view/computer_access.rs b/host/src/tui/view/computer_access.rsnew file mode 100644index 00000000..03c353a8--- /dev/null+++ b/host/src/tui/view/computer_access.rs@@ -0,0 +1,49 @@+//! Permission status in the bot editor. OS grants happen on the computer's desktop.+use serde_json::Value;++pub(super) fn status(screen: &Value, online: bool) -> &'static str {+ if !online {+ return "Computer offline";+ }+ if screen.is_null() {+ return "Checking computer access";+ }+ if screen["platform"] == "windows" {+ return "Control ready; remote viewing unavailable";+ }+ if screen["enabled"] != true {+ return "Computer access is off";+ }+ if screen["connected"] != true {+ return "Start Codync Screen";+ }+ if screen["platform"] == "linux" && (screen["capture"] != true || screen["input"] != true) {+ return "Allow screen sharing and control";+ }+ if screen["capture"] != true {+ return "Allow screen recording";+ }+ if screen["input"] != true {+ return "Allow computer control";+ }+ "Computer access ready"+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn permission_status_follows_grants_and_revocation() {+ let mut state = json!({"enabled":true,"connected":true,"capture":false,"input":false});+ assert_eq!(status(&state, false), "Computer offline");+ assert_eq!(status(&state, true), "Allow screen recording");+ state["capture"] = true.into();+ assert_eq!(status(&state, true), "Allow computer control");+ state["input"] = true.into();+ assert_eq!(status(&state, true), "Computer access ready");+ state["platform"] = "windows".into();+ assert_eq!(status(&state, true), "Control ready; remote viewing unavailable");+ }+}diff --git a/host/src/tui/view/mod.rs b/host/src/tui/view/mod.rsindex d909aec0..69355aa3 100644--- a/host/src/tui/view/mod.rs+++ b/host/src/tui/view/mod.rs@@ -8,6 +8,7 @@mod buffer;mod chat;+mod computer_access;mod consent;mod forms;mod goto;