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
refactor(desktop): split bot store into modules
leepokaic680bbc967bb
diff --git a/apps/desktop/src/renderer/store/bot-mirror.ts b/apps/desktop/src/renderer/store/bot-mirror.tsnew file mode 100644index 00000000..45235af8--- /dev/null+++ b/apps/desktop/src/renderer/store/bot-mirror.ts@@ -0,0 +1,261 @@+import { checkVersions, isBelow, type VersionMismatch } from '@shared/compat'+import {+ type AccessRequest,+ type Bot,+ type CloudStatus,+ type Computer,+ type Entry,+ type Hello,+ type ScreenState,+ type Usage,+} from '@shared/models'+import type { HostClient, HostRoute, HostTransport } from '../client/host-client'+import { Observable } from '../lib/observable'+import { ComposerDrafts } from '@shared/composer-drafts'++export type Connection =+ | { kind: 'unpaired' }+ | { kind: 'connecting' }+ | { kind: 'online' }+ | { kind: 'computerOffline'; lastSeen: number | null }+ | { kind: 'offline'; message: string }+ | { kind: 'unauthorized'; message: string }++/**+ * The state half of `BotStore`: one computer's mirror (bots, transcripts), the selectors views+ * read, entry merging and the on-device cache.+ */+export class BotMirror extends Observable {+ computer: Computer+ connection: Connection = { kind: 'connecting' }+ hostRoute: HostRoute | null = null+ client: HostClient | null = null+ hello: Hello | null = null+ hostVersion: { version: string; minApp?: string | null } | null = null+ bots = new Map<string, Bot>()+ entries = new Map<string, Entry[]>()+ usage: Usage = { providers: [] }+ screen: ScreenState | null = null+ accessRequests: AccessRequest[] = []+ cloud: CloudStatus | null = null+ historyComplete = new Set<string>()+ routineDrafts = new Map<string, string>()+ readonly composerDrafts: ComposerDrafts+ lastError: string | null = null+ /** A kit view selected a bot on this store (new chat, editor); the account picks it up. */+ selection: string | null = null+ /** Permission cards whose answer is on its way, with the chosen option. */+ answering = new Map<string, string>()++ onRosterChanged: (() => void) | null = null+ onComputerChanged: ((c: Computer) => void) | null = null++ protected waiting = 0+ protected rev = 0+ protected hostId: string | null = null+ protected retired = false+ protected unreadable = false+ protected saveTimer: ReturnType<typeof setTimeout> | null = null+ protected cacheStamp: string | null = null++ constructor(+ computer: Computer,+ readonly isLoopback: boolean,+ protected makeTransport: () => HostTransport,+ protected clientKind = 'mac',+ protected appVersion = window.codync.appVersion,+ readonly contextId = 'local',+ ) {+ super()+ this.computer = computer+ this.composerDrafts = new ComposerDrafts(localStorage, `codync-drafts-v1-${JSON.stringify([contextId, computer.id])}`,+ () => this.setError("Couldn't save the draft on this device. Your text is still here; keep this window open until you send or copy it."))+ this.loadCache()+ }++ // MARK: derived++ get isOffline() {+ const k = this.connection.kind+ return k === 'computerOffline' || k === 'offline' || k === 'unauthorized'+ }++ /** Loopback has no relay mailbox. */+ get canQueue() {+ return false+ }++ /** What headers show: a reconnect the grace period keeps quiet reads "Connecting…" while an action waits. */+ get shownConnection(): Connection {+ return this.waiting > 0 && this.connection.kind === 'online' ? { kind: 'connecting' } : this.connection+ }++ get hostName() {+ return this.hello?.name ?? this.computer.name+ }++ get mismatch(): VersionMismatch | null {+ if (!this.hostVersion) return null+ const found = checkVersions(this.appVersion, this.hostVersion.version, this.hostVersion.minApp)+ if (found) return found+ if (this.unreadable && isBelow(this.appVersion, this.hostVersion.version)) return { kind: 'updateApp', minimum: this.hostVersion.version }+ return null+ }++ /** Roster order: pinned first, then most recent activity. */+ get roster(): Bot[] {+ return [...this.bots.values()].filter((b) => !b.hidden).sort((a, b) => (a.pinned !== b.pinned ? (a.pinned ? -1 : 1) : b.lastAt - a.lastAt))+ }++ get hiddenBots(): Bot[] {+ return [...this.bots.values()].filter((b) => b.hidden).sort((a, b) => a.name.localeCompare(b.name))+ }++ backendName(id: string) {+ return this.hello?.backends.find((b) => b.id === id)?.name ?? builtInBackendName(id)+ }++ /** A bot's or group's main chat (thread replies are left out). */+ chat(botId: string) {+ return (this.entries.get(botId) ?? []).filter((e) => !e.threadId)+ }++ allEntries(botId: string) {+ return this.entries.get(botId) ?? []+ }++ replies(botId: string, root: string) {+ return (this.entries.get(botId) ?? []).filter((e) => e.threadId === root)+ }++ members(group: Bot) {+ return group.members.map((id) => this.bots.get(id)).filter((b): b is Bot => !!b)+ }++ authorName(id: string | null | undefined) {+ return (id && this.bots.get(id)?.name) || 'A deleted bot'+ }++ /** The latest thinking of the turn running in a chat (`thread` null) or thread. */+ currentThinking(botId: string, thread: string | null) {+ const list = this.allEntries(botId)+ for (let i = list.length - 1; i >= 0; i--) {+ const e = list[i]!+ if ((e.threadId ?? null) !== thread) continue+ if (e.kind === 'user' || (e.kind === 'agent' && e.data.final === true)) return null+ if (e.kind === 'thought' && e.data.text) return e.data.text+ }+ return null+ }++ get connectionLabel() {+ switch (this.shownConnection.kind) {+ case 'online':+ return this.mismatch ? 'Needs update' : 'Connected'+ case 'connecting':+ return 'Connecting…'+ case 'computerOffline':+ case 'offline':+ return 'Offline'+ case 'unauthorized':+ return 'No access'+ case 'unpaired':+ return 'Not paired'+ }+ }++ updateComputer(change: (c: Computer) => Computer) {+ const next = change({ ...this.computer })+ if (JSON.stringify(next) === JSON.stringify(this.computer)) return+ this.computer = next+ this.onComputerChanged?.(next)+ this.changed()+ }++ protected upsert(e: Entry) {+ const list = [...(this.entries.get(e.botId) ?? [])]+ const i = list.findIndex((x) => x.id === e.id)+ if (i >= 0) {+ // A late API response mustn't undo a newer SSE update.+ if (e.rev < list[i]!.rev) return+ list[i] = e+ } else {+ // Replace the optimistic copy of a message we sent.+ const nonce = e.kind === 'user' ? e.data.clientNonce : undefined+ const filtered = nonce ? list.filter((x) => x.id !== `local-${nonce}`) : list+ const last = filtered[filtered.length - 1]+ if (last && last.seq > e.seq && e.seq > 0) {+ const at = filtered.findIndex((x) => x.seq > e.seq)+ filtered.splice(at < 0 ? filtered.length : at, 0, e)+ } else {+ filtered.push(e)+ }+ this.entries.set(e.botId, filtered)+ return+ }+ this.entries.set(e.botId, list)+ }++ setError(message: string | null) {+ this.lastError = message+ this.changed()+ }++ // MARK: cache (instant launch, offline reading)++ private get cacheKey() {+ return `codync-mirror-${this.contextId}-${this.computer.id}`+ }++ private loadCache() {+ try {+ const raw = localStorage.getItem(this.cacheKey)+ if (!raw) return+ const cache = JSON.parse(raw) as { stamp?: string; hostId?: string; rev: number; bots: Bot[]; entries: Entry[] }+ this.cacheStamp = cache.stamp ?? ''+ this.hostId = cache.hostId ?? null+ this.rev = cache.rev+ this.bots = new Map(cache.bots.map((b) => [b.id, b]))+ const grouped = new Map<string, Entry[]>()+ for (const e of cache.entries) grouped.set(e.botId, [...(grouped.get(e.botId) ?? []), e])+ this.entries = grouped+ } catch {}+ }++ protected scheduleSave() {+ if (this.retired) return+ if (this.saveTimer) clearTimeout(this.saveTimer)+ this.saveTimer = setTimeout(() => this.saveCache(), 2000)+ }++ saveCache() {+ if (this.retired) return+ // Keep the newest 200 entries per bot; older ones page in from the host.+ const kept: Entry[] = []+ for (const list of this.entries.values()) {+ kept.push(...list.filter((e) => !e.id.startsWith('local-')).slice(-200))+ kept.push(...list.filter((e) => e.id.startsWith('local-') && e.data.status === 'failed'))+ }+ const cache = { stamp: `${this.appVersion}/${this.hello?.version ?? ''}`, hostId: this.hostId, rev: this.rev, bots: [...this.bots.values()], entries: kept }+ try {+ localStorage.setItem(this.cacheKey, JSON.stringify(cache))+ } catch {}+ }+}++export function builtInBackendName(id: string) {+ switch (id) {+ case 'claude':+ return 'Claude Code'+ case 'codex':+ return 'Codex'+ case 'opencode':+ return 'OpenCode'+ case 'grok':+ return 'Grok Build'+ case 'gemini':+ return 'Gemini CLI'+ default:+ return 'Custom agent'+ }+}diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex d3c44d2f..c60b3013 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -1,13 +1,8 @@-import { checkVersions, isBelow, type VersionMismatch } from '@shared/compat'import {- isChat,isWorking,needsInput,- type AccessRequest,type Bot,type BotDraft,- type CloudStatus,- type Computer,type DirListing,type Entry,type GroupDraft,@@ -15,17 +10,9 @@ import {type ScreenState,type Usage,} from '@shared/models'-import { HostClient, HostError, type HostEvent, type HostRoute, type HostTransport } from '../client/host-client'-import { Observable } from '../lib/observable'-import { ComposerDrafts } from '@shared/composer-drafts'--export type Connection =- | { kind: 'unpaired' }- | { kind: 'connecting' }- | { kind: 'online' }- | { kind: 'computerOffline'; lastSeen: number | null }- | { kind: 'offline'; message: string }- | { kind: 'unauthorized'; message: string }+import { BotSync, sleep } from './bot-sync'++export { builtInBackendName, type Connection } from './bot-mirror'/** A file picked in the composer, sent with the next message. */export interface OutgoingFile {@@ -39,495 +26,12 @@ export const MAX_FILE_SIZE = 100 * 1024 * 1024export const QUICK_REACTIONS = ['👍', '❤️', '😂', '🎉', '👀', '✅']-const DROP_GRACE = 5000-const INITIAL_GRACE = 1000-const ACTION_PATIENCE = 20_000-const MISMATCH_RECHECK = 30_000--const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))-const same = (a: Connection, b: Connection) => a.kind === b.kind && JSON.stringify(a) === JSON.stringify(b)-/*** One computer's mirror (bots, transcripts), kept by one events stream (catch-up since* `rev`, then live). Port of kit's `BotStore`.*/-export class BotStore extends Observable {- computer: Computer- connection: Connection = { kind: 'connecting' }- hostRoute: HostRoute | null = null- client: HostClient | null = null- hello: Hello | null = null- hostVersion: { version: string; minApp?: string | null } | null = null- bots = new Map<string, Bot>()- entries = new Map<string, Entry[]>()- usage: Usage = { providers: [] }- screen: ScreenState | null = null- accessRequests: AccessRequest[] = []- cloud: CloudStatus | null = null- historyComplete = new Set<string>()- routineDrafts = new Map<string, string>()- readonly composerDrafts: ComposerDrafts- lastError: string | null = null- /** A kit view selected a bot on this store (new chat, editor); the account picks it up. */- selection: string | null = null- /** Permission cards whose answer is on its way, with the chosen option. */- answering = new Map<string, string>()-- onRosterChanged: (() => void) | null = null- onComputerChanged: ((c: Computer) => void) | null = null-- private heldDrop: Connection | null = null- private dropTimer: ReturnType<typeof setTimeout> | null = null- private waiting = 0- private rev = 0- private hostId: string | null = null- private retired = false- private closeEvents: (() => void) | null = null- private eventsLoop = 0- private rewound = false- private unreadable = false- private saveTimer: ReturnType<typeof setTimeout> | null = null+export class BotStore extends BotSync {private outgoingFiles = new Map<string, OutgoingFile[]>()- private readingViews = new Map<string, { botId: string; thread: string | null }>()- private cacheStamp: string | null = null-- constructor(- computer: Computer,- readonly isLoopback: boolean,- private makeTransport: () => HostTransport,- private clientKind = 'mac',- private appVersion = window.codync.appVersion,- readonly contextId = 'local',- ) {- super()- this.computer = computer- this.composerDrafts = new ComposerDrafts(localStorage, `codync-drafts-v1-${JSON.stringify([contextId, computer.id])}`,- () => this.setError("Couldn't save the draft on this device. Your text is still here; keep this window open until you send or copy it."))- this.loadCache()- }-- // MARK: derived-- get isOffline() {- const k = this.connection.kind- return k === 'computerOffline' || k === 'offline' || k === 'unauthorized'- }-- /** Loopback has no relay mailbox. */- get canQueue() {- return false- }-- /** What headers show: a reconnect the grace period keeps quiet reads "Connecting…" while an action waits. */- get shownConnection(): Connection {- return this.waiting > 0 && this.connection.kind === 'online' ? { kind: 'connecting' } : this.connection- }-- get hostName() {- return this.hello?.name ?? this.computer.name- }-- get mismatch(): VersionMismatch | null {- if (!this.hostVersion) return null- const found = checkVersions(this.appVersion, this.hostVersion.version, this.hostVersion.minApp)- if (found) return found- if (this.unreadable && isBelow(this.appVersion, this.hostVersion.version)) return { kind: 'updateApp', minimum: this.hostVersion.version }- return null- }-- /** Roster order: pinned first, then most recent activity. */- get roster(): Bot[] {- return [...this.bots.values()].filter((b) => !b.hidden).sort((a, b) => (a.pinned !== b.pinned ? (a.pinned ? -1 : 1) : b.lastAt - a.lastAt))- }-- get hiddenBots(): Bot[] {- return [...this.bots.values()].filter((b) => b.hidden).sort((a, b) => a.name.localeCompare(b.name))- }-- backendName(id: string) {- return this.hello?.backends.find((b) => b.id === id)?.name ?? builtInBackendName(id)- }-- /** A bot's or group's main chat (thread replies are left out). */- chat(botId: string) {- return (this.entries.get(botId) ?? []).filter((e) => !e.threadId)- }-- allEntries(botId: string) {- return this.entries.get(botId) ?? []- }-- replies(botId: string, root: string) {- return (this.entries.get(botId) ?? []).filter((e) => e.threadId === root)- }-- members(group: Bot) {- return group.members.map((id) => this.bots.get(id)).filter((b): b is Bot => !!b)- }-- authorName(id: string | null | undefined) {- return (id && this.bots.get(id)?.name) || 'A deleted bot'- }-- /** The latest thinking of the turn running in a chat (`thread` null) or thread. */- currentThinking(botId: string, thread: string | null) {- const list = this.allEntries(botId)- for (let i = list.length - 1; i >= 0; i--) {- const e = list[i]!- if ((e.threadId ?? null) !== thread) continue- if (e.kind === 'user' || (e.kind === 'agent' && e.data.final === true)) return null- if (e.kind === 'thought' && e.data.text) return e.data.text- }- return null- }-- get connectionLabel() {- switch (this.shownConnection.kind) {- case 'online':- return this.mismatch ? 'Needs update' : 'Connected'- case 'connecting':- return 'Connecting…'- case 'computerOffline':- case 'offline':- return 'Offline'- case 'unauthorized':- return 'No access'- case 'unpaired':- return 'Not paired'- }- }-- updateComputer(change: (c: Computer) => Computer) {- const next = change({ ...this.computer })- if (JSON.stringify(next) === JSON.stringify(this.computer)) return- this.computer = next- this.onComputerChanged?.(next)- this.changed()- }-- // MARK: lifecycle-- retire() {- this.retired = true- this.composerDrafts.retire()- this.stopTransport()- if (this.saveTimer) clearTimeout(this.saveTimer)- this.onRosterChanged = null- this.onComputerChanged = null- this.client = null- this.selection = null- }-- start() {- this.restartStream()- }-- restartStream() {- if (this.retired) return- this.stopTransport()- if (this.connection.kind !== 'online') this.setConnection({ kind: 'connecting' })- const transport = this.makeTransport()- this.client = new HostClient(transport)- this.hostRoute = this.isLoopback ? 'loopback' : null- this.runEvents(this.client)- }-- private stopTransport() {- this.eventsLoop++- this.closeEvents?.()- this.closeEvents = null- if (this.dropTimer) clearTimeout(this.dropTimer)- this.dropTimer = null- this.heldDrop = null- }-- /** Give initial connection failures a second to recover and online drops five seconds. */- private setConnection(next: Connection) {- const transient = next.kind === 'connecting' || next.kind === 'offline' || next.kind === 'computerOffline'- const recovering = next.kind === 'online' && (this.connection.kind !== 'online' || this.heldDrop !== null)- const initialFailure = this.connection.kind === 'connecting' && transient && next.kind !== 'connecting'- if (transient && (this.connection.kind === 'online' || initialFailure)) {- const grace = this.connection.kind === 'online' ? DROP_GRACE : INITIAL_GRACE- this.heldDrop = next- if (!this.dropTimer) {- this.dropTimer = setTimeout(() => {- this.dropTimer = null- const held = this.heldDrop- this.heldDrop = null- if (held && !this.retired) {- this.connection = held- this.changed()- }- }, grace)- }- return- }- if (this.dropTimer) clearTimeout(this.dropTimer)- this.dropTimer = null- this.heldDrop = null- if (!same(next, this.connection)) {- this.connection = next- this.changed()- }- if (recovering) for (const scope of this.readingViews.values()) this.markRead(scope.botId, scope.thread)- }-- /** Events (catch-up since `rev`, then live) for as long as the store lives. */- private runEvents(client: HostClient) {- const loop = ++this.eventsLoop- let backoff = 1000- const alive = () => loop === this.eventsLoop && !this.retired- const attempt = async () => {- if (!alive()) return- try {- await this.refreshHello(client)- if (!alive()) return- if (this.mismatch) {- this.setConnection({ kind: 'online' })- await sleep(MISMATCH_RECHECK)- return void attempt()- }- if (this.isLoopback) {- try {- this.accessRequests = (await client.call<{ requests: AccessRequest[] }>('accessRequests')).requests- } catch {}- try {- this.cloud = await client.call<CloudStatus>('cloudStatus')- } catch {}- this.changed()- }- if (!alive()) return- await new Promise<void>((resolve, reject) => {- this.closeEvents = client.events(- this.rev,- this.clientKind,- (event) => {- if (!alive()) return- this.setConnection({ kind: 'online' })- backoff = 1000- this.apply(event)- },- (error) => (error ? reject(error) : resolve()),- )- })- } catch (error) {- if (!alive()) return- const message = error instanceof Error ? error.message : String(error)- this.setConnection({ kind: 'offline', message })- if (error instanceof HostError && error.status === 401) return- }- if (!alive()) return- await sleep(backoff)- backoff = Math.min(backoff * 2, 20_000)- void attempt()- }- void attempt()- }-- /** Resubscribes from the current `rev` on the same link. */- private restartEvents() {- if (!this.client) return- this.closeEvents?.()- this.runEvents(this.client)- }-- private async refreshHello(client: HostClient) {- const h = await client.hello()- if (this.retired) return- this.hello = h- this.noteHostVersion({ version: h.version, minApp: h.minApp })- if (this.isLoopback) this.updateComputer((c) => ({ ...c, name: h.name, device: h.device ?? c.device }))- this.changed()- }-- private noteHostVersion(next: { version: string; minApp?: string | null }) {- const cached = this.cacheStamp !== null && this.cacheStamp !== `${this.appVersion}/${next.version}`- if (cached || (this.hostVersion && this.hostVersion.version !== next.version)) {- // A different host version or app build: data may carry new fields, so fetch it all again.- this.rev = 0- this.rewound = false- this.unreadable = false- }- this.cacheStamp = null- this.hostVersion = next- }-- private apply(event: HostEvent) {- switch (event.type) {- case 'hello':- if (this.hostId && this.hostId !== event.hostId) this.resetMirror()- this.hostId = event.hostId- this.usage = event.usage- this.screen = event.screen- if (event.rev < this.rev) this.rev = 0- break- case 'bot':- this.bots.set(event.bot.id, event.bot)- this.bump(event.bot.rev)- this.onRosterChanged?.()- if (event.bot.unread > 0) this.acknowledgeVisible(event.bot.id)- break- case 'botDeleted':- this.composerDrafts.removeBot(event.id)- this.bots.delete(event.id)- this.entries.delete(event.id)- this.bump(event.rev)- if (this.selection === event.id) this.selection = null- this.onRosterChanged?.()- break- case 'entry':- this.upsert(event.entry)- this.bump(event.entry.rev)- this.acknowledgeVisible(event.entry.botId, event.entry)- break- case 'usage':- this.usage = event.usage- break- case 'screen':- this.screen = event.screen- break- case 'accessRequests':- this.accessRequests = event.requests- break- case 'cloud':- this.cloud = event.cloud- break- case 'resync':- this.restartEvents()- break- case 'undecodable':- // Never skip past data we couldn't read: rewind once and fetch everything again.- if (!this.rewound) {- this.rewound = true- this.rev = 0- this.restartEvents()- } else if (!this.unreadable) {- this.unreadable = true- if (this.mismatch) this.restartEvents()- }- break- }- this.changed()- this.scheduleSave()- }-- private resetMirror() {- this.composerDrafts.clear()- this.bots = new Map()- const kept = new Map<string, Entry[]>()- for (const [id, list] of this.entries) {- const local = list.filter((e) => e.id.startsWith('local-'))- if (local.length) kept.set(id, local)- }- this.entries = kept- this.selection = null- this.onRosterChanged?.()- this.rev = 0- this.hostId = null- this.historyComplete = new Set()- this.screen = null- this.saveCache()- }-- private bump(r: number) {- this.rev = Math.max(this.rev, r)- }-- private upsert(e: Entry) {- const list = [...(this.entries.get(e.botId) ?? [])]- const i = list.findIndex((x) => x.id === e.id)- if (i >= 0) {- // A late API response mustn't undo a newer SSE update.- if (e.rev < list[i]!.rev) return- list[i] = e- } else {- // Replace the optimistic copy of a message we sent.- const nonce = e.kind === 'user' ? e.data.clientNonce : undefined- const filtered = nonce ? list.filter((x) => x.id !== `local-${nonce}`) : list- const last = filtered[filtered.length - 1]- if (last && last.seq > e.seq && e.seq > 0) {- const at = filtered.findIndex((x) => x.seq > e.seq)- filtered.splice(at < 0 ? filtered.length : at, 0, e)- } else {- filtered.push(e)- }- this.entries.set(e.botId, filtered)- return- }- this.entries.set(e.botId, list)- }-- // MARK: actions-- private get live(): HostClient | null {- return this.connection.kind === 'online' && !this.heldDrop && !this.retired ? this.client : null- }-- /** The client once the link is up. A reconnect in progress is waited out (headers show it). */- async ready(deadline = Date.now() + ACTION_PATIENCE): Promise<HostClient> {- let counted = false- let retried = false- try {- while (!this.retired) {- if (this.live) return this.live- switch (this.connection.kind) {- case 'online':- case 'connecting':- break- case 'offline':- if (!retried) {- retried = true- this.restartStream()- break- }- throw HostError.unreachable()- case 'unpaired':- throw HostError.unreachable()- case 'computerOffline':- throw new HostError(0, 'Your computer is offline.')- case 'unauthorized':- throw new HostError(401, this.connection.message)- }- if (Date.now() >= deadline) break- if (!counted) {- counted = true- this.waiting++- this.changed()- }- await sleep(100)- }- throw HostError.unreachable()- } finally {- if (counted) {- this.waiting--- this.changed()- }- }- }-- /** Runs `op` once the link is up; with `replay`, a call the link dropped under is tried again. */- private async withLink<T>(op: (c: HostClient) => Promise<T>, replay = false): Promise<T> {- const deadline = Date.now() + ACTION_PATIENCE- for (;;) {- const client = await this.ready(deadline)- try {- return await op(client)- } catch (error) {- if (replay && error instanceof HostError && error.isTransient && Date.now() < deadline) {- await sleep(500)- continue- }- throw error- }- }- }-- private perform(op: (c: HostClient) => Promise<unknown>, replay = false) {- void this.withLink(op, replay).catch((error: unknown) => {- this.lastError = error instanceof Error ? error.message : String(error)- this.changed()- })- }send(text: string, botId: string, thread: string | null = null, files: OutgoingFile[] = [], nonce: string = crypto.randomUUID()) {const trimmed = text.trim()@@ -676,42 +180,6 @@ export class BotStore extends Observable {})()}- /** Views register while visible. Multiple windows may read the same conversation. */- setReading(token: string, botId: string, thread: string | null, active: boolean) {- if (active) {- this.readingViews.set(token, { botId, thread })- if (this.connection.kind === 'online') this.markRead(botId, thread)- } else {- this.readingViews.delete(token)- }- }-- private acknowledgeVisible(botId: string, entry?: Entry) {- if (this.connection.kind !== 'online') return- const seen = new Set<string>()- for (const scope of this.readingViews.values()) {- if (scope.botId !== botId) continue- if (entry && (!isChat(entry) || (entry.threadId ?? null) !== scope.thread)) continue- const key = `${scope.botId}/${scope.thread}`- if (seen.has(key)) continue- seen.add(key)- this.markRead(botId, scope.thread)- }- }-- markRead(botId: string, thread: string | null = null) {- void (async () => {- if (!this.live) await sleep(INITIAL_GRACE)- const client = this.live- if (!client) return- try {- await client.call('markRead', { botId, threadId: thread, all: false })- } catch {- // The visible scope is acknowledged again when the link recovers.- }- })()- }-/** The roster's "Mark as read": the chat and all its threads. */markAllRead(botId: string) {const bot = this.bots.get(botId)@@ -813,11 +281,6 @@ export class BotStore extends Observable {} catch {}}- setError(message: string | null) {- this.lastError = message- this.changed()- }-setSelection(id: string | null) {this.selection = idthis.changed()@@ -836,47 +299,6 @@ export class BotStore extends Observable {this.routineDrafts.set(botId, text)this.changed()}-- // MARK: cache (instant launch, offline reading)-- private get cacheKey() {- return `codync-mirror-${this.contextId}-${this.computer.id}`- }-- private loadCache() {- try {- const raw = localStorage.getItem(this.cacheKey)- if (!raw) return- const cache = JSON.parse(raw) as { stamp?: string; hostId?: string; rev: number; bots: Bot[]; entries: Entry[] }- this.cacheStamp = cache.stamp ?? ''- this.hostId = cache.hostId ?? null- this.rev = cache.rev- this.bots = new Map(cache.bots.map((b) => [b.id, b]))- const grouped = new Map<string, Entry[]>()- for (const e of cache.entries) grouped.set(e.botId, [...(grouped.get(e.botId) ?? []), e])- this.entries = grouped- } catch {}- }-- private scheduleSave() {- if (this.retired) return- if (this.saveTimer) clearTimeout(this.saveTimer)- this.saveTimer = setTimeout(() => this.saveCache(), 2000)- }-- saveCache() {- if (this.retired) return- // Keep the newest 200 entries per bot; older ones page in from the host.- const kept: Entry[] = []- for (const list of this.entries.values()) {- kept.push(...list.filter((e) => !e.id.startsWith('local-')).slice(-200))- kept.push(...list.filter((e) => e.id.startsWith('local-') && e.data.status === 'failed'))- }- const cache = { stamp: `${this.appVersion}/${this.hello?.version ?? ''}`, hostId: this.hostId, rev: this.rev, bots: [...this.bots.values()], entries: kept }- try {- localStorage.setItem(this.cacheKey, JSON.stringify(cache))- } catch {}- }}/** A full editor update must explicitly clear a previous model override. */@@ -889,23 +311,6 @@ function updatePayload(bot: Bot): BotDraft {}}-export function builtInBackendName(id: string) {- switch (id) {- case 'claude':- return 'Claude Code'- case 'codex':- return 'Codex'- case 'opencode':- return 'OpenCode'- case 'grok':- return 'Grok Build'- case 'gemini':- return 'Gemini CLI'- default:- return 'Custom agent'- }-}-// ponytail: in-memory attachment cache; a disk cache (main process) if relaunches refetching hurts.const attachmentCache = new Map<string, Uint8Array>()function cacheAttachment(id: string, data: Uint8Array) {diff --git a/apps/desktop/src/renderer/store/bot-sync.ts b/apps/desktop/src/renderer/store/bot-sync.tsnew file mode 100644index 00000000..b2106076--- /dev/null+++ b/apps/desktop/src/renderer/store/bot-sync.ts@@ -0,0 +1,361 @@+import { isChat, type AccessRequest, type CloudStatus, type Entry } from '@shared/models'+import { HostClient, HostError, type HostEvent } from '../client/host-client'+import { BotMirror, type Connection } from './bot-mirror'++const DROP_GRACE = 5000+const INITIAL_GRACE = 1000+const ACTION_PATIENCE = 20_000+const MISMATCH_RECHECK = 30_000++export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))+const same = (a: Connection, b: Connection) => a.kind === b.kind && JSON.stringify(a) === JSON.stringify(b)++/**+ * The link half of `BotStore`: the events stream (catch-up since `rev`, then live), connection+ * graces, waiting for the link before an action, and read acknowledgements.+ */+export class BotSync extends BotMirror {+ private heldDrop: Connection | null = null+ private dropTimer: ReturnType<typeof setTimeout> | null = null+ private closeEvents: (() => void) | null = null+ private eventsLoop = 0+ private rewound = false+ private readingViews = new Map<string, { botId: string; thread: string | null }>()++ // MARK: lifecycle++ retire() {+ this.retired = true+ this.composerDrafts.retire()+ this.stopTransport()+ if (this.saveTimer) clearTimeout(this.saveTimer)+ this.onRosterChanged = null+ this.onComputerChanged = null+ this.client = null+ this.selection = null+ }++ start() {+ this.restartStream()+ }++ restartStream() {+ if (this.retired) return+ this.stopTransport()+ if (this.connection.kind !== 'online') this.setConnection({ kind: 'connecting' })+ const transport = this.makeTransport()+ this.client = new HostClient(transport)+ this.hostRoute = this.isLoopback ? 'loopback' : null+ this.runEvents(this.client)+ }++ private stopTransport() {+ this.eventsLoop+++ this.closeEvents?.()+ this.closeEvents = null+ if (this.dropTimer) clearTimeout(this.dropTimer)+ this.dropTimer = null+ this.heldDrop = null+ }++ /** Give initial connection failures a second to recover and online drops five seconds. */+ private setConnection(next: Connection) {+ const transient = next.kind === 'connecting' || next.kind === 'offline' || next.kind === 'computerOffline'+ const recovering = next.kind === 'online' && (this.connection.kind !== 'online' || this.heldDrop !== null)+ const initialFailure = this.connection.kind === 'connecting' && transient && next.kind !== 'connecting'+ if (transient && (this.connection.kind === 'online' || initialFailure)) {+ const grace = this.connection.kind === 'online' ? DROP_GRACE : INITIAL_GRACE+ this.heldDrop = next+ if (!this.dropTimer) {+ this.dropTimer = setTimeout(() => {+ this.dropTimer = null+ const held = this.heldDrop+ this.heldDrop = null+ if (held && !this.retired) {+ this.connection = held+ this.changed()+ }+ }, grace)+ }+ return+ }+ if (this.dropTimer) clearTimeout(this.dropTimer)+ this.dropTimer = null+ this.heldDrop = null+ if (!same(next, this.connection)) {+ this.connection = next+ this.changed()+ }+ if (recovering) for (const scope of this.readingViews.values()) this.markRead(scope.botId, scope.thread)+ }++ /** Events (catch-up since `rev`, then live) for as long as the store lives. */+ private runEvents(client: HostClient) {+ const loop = ++this.eventsLoop+ let backoff = 1000+ const alive = () => loop === this.eventsLoop && !this.retired+ const attempt = async () => {+ if (!alive()) return+ try {+ await this.refreshHello(client)+ if (!alive()) return+ if (this.mismatch) {+ this.setConnection({ kind: 'online' })+ await sleep(MISMATCH_RECHECK)+ return void attempt()+ }+ if (this.isLoopback) {+ try {+ this.accessRequests = (await client.call<{ requests: AccessRequest[] }>('accessRequests')).requests+ } catch {}+ try {+ this.cloud = await client.call<CloudStatus>('cloudStatus')+ } catch {}+ this.changed()+ }+ if (!alive()) return+ await new Promise<void>((resolve, reject) => {+ this.closeEvents = client.events(+ this.rev,+ this.clientKind,+ (event) => {+ if (!alive()) return+ this.setConnection({ kind: 'online' })+ backoff = 1000+ this.apply(event)+ },+ (error) => (error ? reject(error) : resolve()),+ )+ })+ } catch (error) {+ if (!alive()) return+ const message = error instanceof Error ? error.message : String(error)+ this.setConnection({ kind: 'offline', message })+ if (error instanceof HostError && error.status === 401) return+ }+ if (!alive()) return+ await sleep(backoff)+ backoff = Math.min(backoff * 2, 20_000)+ void attempt()+ }+ void attempt()+ }++ /** Resubscribes from the current `rev` on the same link. */+ private restartEvents() {+ if (!this.client) return+ this.closeEvents?.()+ this.runEvents(this.client)+ }++ private async refreshHello(client: HostClient) {+ const h = await client.hello()+ if (this.retired) return+ this.hello = h+ this.noteHostVersion({ version: h.version, minApp: h.minApp })+ if (this.isLoopback) this.updateComputer((c) => ({ ...c, name: h.name, device: h.device ?? c.device }))+ this.changed()+ }++ private noteHostVersion(next: { version: string; minApp?: string | null }) {+ const cached = this.cacheStamp !== null && this.cacheStamp !== `${this.appVersion}/${next.version}`+ if (cached || (this.hostVersion && this.hostVersion.version !== next.version)) {+ // A different host version or app build: data may carry new fields, so fetch it all again.+ this.rev = 0+ this.rewound = false+ this.unreadable = false+ }+ this.cacheStamp = null+ this.hostVersion = next+ }++ private apply(event: HostEvent) {+ switch (event.type) {+ case 'hello':+ if (this.hostId && this.hostId !== event.hostId) this.resetMirror()+ this.hostId = event.hostId+ this.usage = event.usage+ this.screen = event.screen+ if (event.rev < this.rev) this.rev = 0+ break+ case 'bot':+ this.bots.set(event.bot.id, event.bot)+ this.bump(event.bot.rev)+ this.onRosterChanged?.()+ if (event.bot.unread > 0) this.acknowledgeVisible(event.bot.id)+ break+ case 'botDeleted':+ this.composerDrafts.removeBot(event.id)+ this.bots.delete(event.id)+ this.entries.delete(event.id)+ this.bump(event.rev)+ if (this.selection === event.id) this.selection = null+ this.onRosterChanged?.()+ break+ case 'entry':+ this.upsert(event.entry)+ this.bump(event.entry.rev)+ this.acknowledgeVisible(event.entry.botId, event.entry)+ break+ case 'usage':+ this.usage = event.usage+ break+ case 'screen':+ this.screen = event.screen+ break+ case 'accessRequests':+ this.accessRequests = event.requests+ break+ case 'cloud':+ this.cloud = event.cloud+ break+ case 'resync':+ this.restartEvents()+ break+ case 'undecodable':+ // Never skip past data we couldn't read: rewind once and fetch everything again.+ if (!this.rewound) {+ this.rewound = true+ this.rev = 0+ this.restartEvents()+ } else if (!this.unreadable) {+ this.unreadable = true+ if (this.mismatch) this.restartEvents()+ }+ break+ }+ this.changed()+ this.scheduleSave()+ }++ private resetMirror() {+ this.composerDrafts.clear()+ this.bots = new Map()+ const kept = new Map<string, Entry[]>()+ for (const [id, list] of this.entries) {+ const local = list.filter((e) => e.id.startsWith('local-'))+ if (local.length) kept.set(id, local)+ }+ this.entries = kept+ this.selection = null+ this.onRosterChanged?.()+ this.rev = 0+ this.hostId = null+ this.historyComplete = new Set()+ this.screen = null+ this.saveCache()+ }++ private bump(r: number) {+ this.rev = Math.max(this.rev, r)+ }++ // MARK: link++ protected get live(): HostClient | null {+ return this.connection.kind === 'online' && !this.heldDrop && !this.retired ? this.client : null+ }++ /** The client once the link is up. A reconnect in progress is waited out (headers show it). */+ async ready(deadline = Date.now() + ACTION_PATIENCE): Promise<HostClient> {+ let counted = false+ let retried = false+ try {+ while (!this.retired) {+ if (this.live) return this.live+ switch (this.connection.kind) {+ case 'online':+ case 'connecting':+ break+ case 'offline':+ if (!retried) {+ retried = true+ this.restartStream()+ break+ }+ throw HostError.unreachable()+ case 'unpaired':+ throw HostError.unreachable()+ case 'computerOffline':+ throw new HostError(0, 'Your computer is offline.')+ case 'unauthorized':+ throw new HostError(401, this.connection.message)+ }+ if (Date.now() >= deadline) break+ if (!counted) {+ counted = true+ this.waiting+++ this.changed()+ }+ await sleep(100)+ }+ throw HostError.unreachable()+ } finally {+ if (counted) {+ this.waiting--+ this.changed()+ }+ }+ }++ /** Runs `op` once the link is up; with `replay`, a call the link dropped under is tried again. */+ protected async withLink<T>(op: (c: HostClient) => Promise<T>, replay = false): Promise<T> {+ const deadline = Date.now() + ACTION_PATIENCE+ for (;;) {+ const client = await this.ready(deadline)+ try {+ return await op(client)+ } catch (error) {+ if (replay && error instanceof HostError && error.isTransient && Date.now() < deadline) {+ await sleep(500)+ continue+ }+ throw error+ }+ }+ }++ protected perform(op: (c: HostClient) => Promise<unknown>, replay = false) {+ void this.withLink(op, replay).catch((error: unknown) => {+ this.lastError = error instanceof Error ? error.message : String(error)+ this.changed()+ })+ }++ /** Views register while visible. Multiple windows may read the same conversation. */+ setReading(token: string, botId: string, thread: string | null, active: boolean) {+ if (active) {+ this.readingViews.set(token, { botId, thread })+ if (this.connection.kind === 'online') this.markRead(botId, thread)+ } else {+ this.readingViews.delete(token)+ }+ }++ private acknowledgeVisible(botId: string, entry?: Entry) {+ if (this.connection.kind !== 'online') return+ const seen = new Set<string>()+ for (const scope of this.readingViews.values()) {+ if (scope.botId !== botId) continue+ if (entry && (!isChat(entry) || (entry.threadId ?? null) !== scope.thread)) continue+ const key = `${scope.botId}/${scope.thread}`+ if (seen.has(key)) continue+ seen.add(key)+ this.markRead(botId, scope.thread)+ }+ }++ markRead(botId: string, thread: string | null = null) {+ void (async () => {+ if (!this.live) await sleep(INITIAL_GRACE)+ const client = this.live+ if (!client) return+ try {+ await client.call('markRead', { botId, threadId: thread, all: false })+ } catch {+ // The visible scope is acknowledged again when the link recovers.+ }+ })()+ }++}diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.mdindex 2f1299db..58389b2c 100644--- a/docs/architecture/desktop-app.md+++ b/docs/architecture/desktop-app.md@@ -21,7 +21,7 @@ The iPhone app stays native SwiftUI; its package moved from `kit/` into `apps/io|---|---|| `src/main/` | Main process: host service (`host-controller.ts`), loopback HTTP/SSE proxy (`host-proxy.ts`), menu bar/tray, windows, account sign-in (Clerk Frontend API, `account.ts`), cloud API and device key (`cloud.ts`), updates (`updates.ts`), SSH tunnels (`ssh.ts`), Codync Screen agent (`screen.ts`), on-device speech (`speech.ts`), browser sign-in callbacks (`auth.ts`) || `src/preload/` | The `window.codync` bridge (types in `src/shared/ipc.ts`) |-| `src/renderer/store/` | `BotStore` (port of kit's), `AppModel` (window state, approvals), `CloudModel` (claims, cloud default), `AccountSession` |+| `src/renderer/store/` | `BotStore` (port of kit's; `bot-store.ts` actions over `bot-sync.ts` events stream and `bot-mirror.ts` state), `AppModel` (window state, approvals), `CloudModel` (claims, cloud default), `AccountSession` || `src/renderer/components/` | Design system: controls, overlays (sheets, dialogs, menus), SF Symbol icons, character avatars, thinking orbs || `src/renderer/views/` | Screens, mirroring kit's folders (`thread/`, `bots/`, `marketplace/`, `settings/`, `routines/`, `call/`) || `native/speech-macos/` | `codync-speech`, a Swift helper running SFSpeechRecognizer for on-device calls |diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex 436a7614..c211ea6f 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -95,7 +95,7 @@ Codync/| iOS navigation, pairing, account settings | `apps/ios/Views/RootView.swift`, `BotListView.swift`, `PairingView.swift`, `AccountSwitcherView.swift`, `SettingsView.swift` || Apple account sessions / public environment config | `apps/ios/App/AccountSession.swift`, `apps/shared/Config/` || Desktop local host / SSH lifecycle | `apps/desktop/src/main/host-controller.ts`, `ssh.ts` |-| Desktop store, chat and controls | `apps/desktop/src/renderer/store/bot-store.ts`, `views/thread/`, `components/` |+| Desktop store, chat and controls | `apps/desktop/src/renderer/store/bot-store.ts` (actions; state in `bot-mirror.ts`, events stream in `bot-sync.ts`), `views/thread/`, `components/` || Cloud routes / authentication / relay | `cloud/src/index.ts`, `api.ts`, `routes/`, `auth.ts`, `relay.ts` || Push encryption / APNs delivery / decryption | `host/src/remote/push.rs`, `relay/src/`, `apps/ios/NotificationService/` || Widget and activity rendering | `apps/ios/Kit/Sources/CodyncKit/Design/`, `apps/ios/Widgets/` |diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex 773d646f..56683ed8 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -8,7 +8,7 @@ The conversation keeps the native glass buttons over the chat with a soft top scDo not wrap those toolbar controls in `IconButtonStyle`, hand-sized rounded backgrounds or another glass effect. The account avatar is toolbar content, with the system supplying the enclosing surface. This is the explicit exception to the custom-chrome rule below.-Connecting and reconnecting are background work. `BotStore` gives initial offline reports 1 second to recover and holds drops from online (including relay "computer offline" reports) for 5 seconds. "No access" shows immediately. Automatic read acknowledgements never open an error dialog and visible conversations are acknowledged again after reconnecting. An action taken during a reconnect (back in the foreground, a new network, a drop still inside its grace) waits for the link, up to 20 seconds, instead of failing; while one waits, headers read `Connecting…` and the conversation's connection label shows a spinner. Calls that are safe to repeat (send, stop, approvals, pin, hide, mark as read, delete) are tried again when the link drops under them. Tapping while the header says Offline because the computer can't be reached starts a fresh connection attempt and waits for it, instead of failing until the backoff gets there; a computer the relay reports as off fails at once, since the relay says when it is back. A permission card shows a spinner on the chosen option, dims the others and takes no second answer until the computer has it. The desktop app's `BotStore` (`apps/desktop/src/renderer/store/bot-store.ts`) applies the same graces and 20-second wait. The TUI follows the same rule over loopback: a command the host can't be reached for is retried for up to 20 seconds behind its "Reconnecting…" indicator (the `hello` probe that explains an unreachable host still answers at once), and its permission cards spin on the chosen option. The "Something went wrong" dialog is left for a computer that is off, a refused device, the computer's own answers, and reconnects that outlast the wait. Background work (cloud refresh, device registration, automatic access requests) logs connection, busy-cloud and stale-token failures instead of showing them. The iOS app disconnects only in `.background`, not `.inactive`. Connection status lives only in headers and their menus. The roster header shows a small summary (`1 connected`, `1/2 connected`, `2 offline`, or `Connecting…`). Its computer menu supports multiple selections, Show only, All computers, reconnect, and management. At least one available computer stays selected; if saved exclusions would hide every computer, the list falls back to all. Filters persist on the device. Bots sort pinned first, then by recency. On iPhone, when more than one computer is shown, each computer gets a light heading (badge, name, connection, and "No bots yet" when empty) above its own bots; with one computer the list stays flat. Tapping a heading folds that computer's bots away (chevron; saved on the device). Long-press a heading to lift the whole section and drag it up or down; the other sections slide out of its way and the order is saved on the device on release (`AccountStore.move`; VoiceOver: Move up / Move down). The desktop app shows a flat roster. There are no connection banners. The compact desktop rail uses a computer icon for the same menu. Conversation headers show a small connection label, with the computer name available in the header menu or help text. Pull-to-refresh remains available on iPhone. Computer setup and access requests live under Manage computers.+Connecting and reconnecting are background work. `BotStore` gives initial offline reports 1 second to recover and holds drops from online (including relay "computer offline" reports) for 5 seconds. "No access" shows immediately. Automatic read acknowledgements never open an error dialog and visible conversations are acknowledged again after reconnecting. An action taken during a reconnect (back in the foreground, a new network, a drop still inside its grace) waits for the link, up to 20 seconds, instead of failing; while one waits, headers read `Connecting…` and the conversation's connection label shows a spinner. Calls that are safe to repeat (send, stop, approvals, pin, hide, mark as read, delete) are tried again when the link drops under them. Tapping while the header says Offline because the computer can't be reached starts a fresh connection attempt and waits for it, instead of failing until the backoff gets there; a computer the relay reports as off fails at once, since the relay says when it is back. A permission card shows a spinner on the chosen option, dims the others and takes no second answer until the computer has it. The desktop app's `BotStore` (link handling in `apps/desktop/src/renderer/store/bot-sync.ts`) applies the same graces and 20-second wait. The TUI follows the same rule over loopback: a command the host can't be reached for is retried for up to 20 seconds behind its "Reconnecting…" indicator (the `hello` probe that explains an unreachable host still answers at once), and its permission cards spin on the chosen option. The "Something went wrong" dialog is left for a computer that is off, a refused device, the computer's own answers, and reconnects that outlast the wait. Background work (cloud refresh, device registration, automatic access requests) logs connection, busy-cloud and stale-token failures instead of showing them. The iOS app disconnects only in `.background`, not `.inactive`. Connection status lives only in headers and their menus. The roster header shows a small summary (`1 connected`, `1/2 connected`, `2 offline`, or `Connecting…`). Its computer menu supports multiple selections, Show only, All computers, reconnect, and management. At least one available computer stays selected; if saved exclusions would hide every computer, the list falls back to all. Filters persist on the device. Bots sort pinned first, then by recency. On iPhone, when more than one computer is shown, each computer gets a light heading (badge, name, connection, and "No bots yet" when empty) above its own bots; with one computer the list stays flat. Tapping a heading folds that computer's bots away (chevron; saved on the device). Long-press a heading to lift the whole section and drag it up or down; the other sections slide out of its way and the order is saved on the device on release (`AccountStore.move`; VoiceOver: Move up / Move down). The desktop app shows a flat roster. There are no connection banners. The compact desktop rail uses a computer icon for the same menu. Conversation headers show a small connection label, with the computer name available in the header menu or help text. Pull-to-refresh remains available on iPhone. Computer setup and access requests live under Manage computers.Sources: `apps/ios/Views/BotListView.swift`, `AccountSwitcherView.swift`, `apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift`, `Bots/ComputerFilterHeader.swift`, `Store/ComputerSelection.swift`, `Bots/BotRow.swift`; desktop: `apps/desktop/src/renderer/views/ChatWindow.tsx`, `ComputerFilterHeader.tsx`, `BotRow.tsx`.