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(desktop): keep composer drafts across restarts on every client
leepokai35d2a5b3ce23
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 6ffbe074..ac349aae 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -15,7 +15,7 @@"dev": "node tools/account-config.mjs dev && electron-vite dev","build": "electron-vite build","typecheck": "tsc --noEmit -p tsconfig.json",- "test": "node --test --experimental-strip-types src/shared/*.test.ts src/renderer/store/*.test.ts src/renderer/views/thread/*.test.ts",+ "test": "node --test --experimental-strip-types src/shared/*.test.ts src/renderer/views/thread/*.test.ts","icons": "swift tools/export-symbols.swift","dist:mac:dev": "node tools/account-config.mjs dev && node tools/native-host.mjs dev && node tools/native-screen.mjs && electron-vite build && CSC_NAME=\"Pokai Lee (6KFK5J2LB4)\" electron-builder --mac","dist:mac:main": "node tools/account-config.mjs main && node tools/native-host.mjs main && node tools/native-screen.mjs && electron-vite build && electron-builder --mac",diff --git a/apps/desktop/src/renderer/components/Overlay.tsx b/apps/desktop/src/renderer/components/Overlay.tsxindex 60b74a96..e70f2b3e 100644--- a/apps/desktop/src/renderer/components/Overlay.tsx+++ b/apps/desktop/src/renderer/components/Overlay.tsx@@ -6,14 +6,23 @@ import { Icon } from './Icon'import './overlay.css'/** Keeps a layer mounted while it animates away; `shown` drives the CSS transition. */-export function usePresence(open: boolean, exitMs = 300) {+export function usePresence(open: boolean, exitMs = 300, animateOnMount = true) {const [mounted, setMounted] = useState(open)- const [shown, setShown] = useState(false)+ const [shown, setShown] = useState(open && !animateOnMount)useLayoutEffect(() => {+ if (reduceMotion()) {+ setMounted(open)+ setShown(open)+ return+ }if (open) {setMounted(true)- const frame = requestAnimationFrame(() => requestAnimationFrame(() => setShown(true)))- return () => cancelAnimationFrame(frame)+ let reveal = 0+ const frame = requestAnimationFrame(() => { reveal = requestAnimationFrame(() => setShown(true)) })+ return () => {+ cancelAnimationFrame(frame)+ cancelAnimationFrame(reveal)+ }}setShown(false)const timer = setTimeout(() => setMounted(false), reduceMotion() ? 0 : exitMs)diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex 0f453637..d3c44d2f 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -17,7 +17,7 @@ import {} from '@shared/models'import { HostClient, HostError, type HostEvent, type HostRoute, type HostTransport } from '../client/host-client'import { Observable } from '../lib/observable'-import { ComposerDrafts } from './composer-drafts'+import { ComposerDrafts } from '@shared/composer-drafts'export type Connection =| { kind: 'unpaired' }@@ -66,8 +66,7 @@ export class BotStore extends Observable {cloud: CloudStatus | null = nullhistoryComplete = new Set<string>()routineDrafts = new Map<string, string>()- private composerDrafts = new ComposerDrafts()- subscribeComposerDrafts = this.composerDrafts.subscribe+ readonly composerDrafts: ComposerDraftslastError: string | null = null/** A kit view selected a bot on this store (new chat, editor); the account picks it up. */selection: string | null = null@@ -102,6 +101,8 @@ export class BotStore extends Observable {) {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()}@@ -208,7 +209,7 @@ export class BotStore extends Observable {retire() {this.retired = true- this.composerDrafts.clear()+ this.composerDrafts.retire()this.stopTransport()if (this.saveTimer) clearTimeout(this.saveTimer)this.onRosterChanged = null@@ -367,9 +368,9 @@ export class BotStore extends Observable {if (event.bot.unread > 0) this.acknowledgeVisible(event.bot.id)breakcase 'botDeleted':+ this.composerDrafts.removeBot(event.id)this.bots.delete(event.id)this.entries.delete(event.id)- this.composerDrafts.deleteBot(event.id)this.bump(event.rev)if (this.selection === event.id) this.selection = nullthis.onRosterChanged?.()@@ -411,8 +412,8 @@ export class BotStore extends Observable {}private resetMirror() {- this.bots = new Map()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-'))@@ -528,22 +529,6 @@ export class BotStore extends Observable {})}- composerDraft(botId: string, thread: string | null = null) {- return this.composerDrafts.get(botId, thread)- }-- setComposerDraft(text: string, botId: string, thread: string | null = null) {- if (!this.retired) this.composerDrafts.set(botId, thread, text)- }-- sendComposerDraft(botId: string, thread: string | null = null, files: OutgoingFile[] = []) {- if (this.retired) return false- const text = this.composerDrafts.take(botId, thread, files.length > 0)- if (text === null) return false- this.send(text, botId, thread, files)- return true- }-send(text: string, botId: string, thread: string | null = null, files: OutgoingFile[] = [], nonce: string = crypto.randomUUID()) {const trimmed = text.trim()if ((!trimmed && !files.length) || this.retired) return@@ -752,9 +737,9 @@ export class BotStore extends Observable {}delete(bot: Bot) {+ this.composerDrafts.removeBot(bot.id)this.bots.delete(bot.id)this.entries.delete(bot.id)- this.composerDrafts.deleteBot(bot.id)this.onRosterChanged?.()this.changed()this.perform((c) => c.call('deleteBot', { botId: bot.id }), true)diff --git a/apps/desktop/src/renderer/store/composer-drafts.test.ts b/apps/desktop/src/renderer/store/composer-drafts.test.tsdeleted file mode 100644index 29936906..00000000--- a/apps/desktop/src/renderer/store/composer-drafts.test.ts+++ /dev/null@@ -1,69 +0,0 @@-import assert from 'node:assert/strict'-import { test } from 'node:test'-import { ComposerDrafts } from './composer-drafts.ts'--test('switching bots, threads and computers restores each exact draft', () => {- const first = new ComposerDrafts()- const second = new ComposerDrafts()- const multiline = 'Unfinished message\n with spacing and @mention '- first.set('bot', null, multiline)- first.set('other', null, 'Another bot')- first.set('bot', 'thread', 'Thread reply')- second.set('bot', null, 'Another computer')- assert.equal(first.get('bot'), multiline)- assert.equal(first.get('other'), 'Another bot')- assert.equal(first.get('bot', 'thread'), 'Thread reply')- assert.equal(first.get('bot', 'another-thread'), '')- assert.equal(second.get('bot'), 'Another computer')-})--test('sending consumes only that destination and cannot clear a later draft', async () => {- const drafts = new ComposerDrafts()- drafts.set('bot', null, 'Message being sent')- drafts.set('bot', 'thread', 'Unsent reply')- drafts.set('other', null, 'Unsent message')- const sent = drafts.take('bot', null)- assert.equal(sent, 'Message being sent')- assert.equal(drafts.get('bot'), '')- drafts.set('bot', null, 'Next unfinished message')- await Promise.resolve(sent)- assert.equal(drafts.get('bot'), 'Next unfinished message')- assert.equal(drafts.get('bot', 'thread'), 'Unsent reply')- assert.equal(drafts.get('other'), 'Unsent message')-})--test('blank text is retained unless there are attachments to send', () => {- const drafts = new ComposerDrafts()- drafts.set('bot', null, ' \n ')- assert.equal(drafts.take('bot', null), null)- assert.equal(drafts.get('bot'), ' \n ')- assert.equal(drafts.take('bot', null, true), ' \n ')- assert.equal(drafts.get('bot'), '')- assert.equal(drafts.take('bot', null, true), '')-})--test('deleting a bot clears its chat and thread drafts; retiring a computer clears all', () => {- const drafts = new ComposerDrafts()- drafts.set('bot', null, 'Chat')- drafts.set('bot', 'thread', 'Reply')- drafts.set('other', null, 'Other chat')- drafts.deleteBot('bot')- assert.equal(drafts.get('bot'), '')- assert.equal(drafts.get('bot', 'thread'), '')- assert.equal(drafts.get('other'), 'Other chat')- drafts.clear()- assert.equal(drafts.get('other'), '')-})--test('mounted composers see edits and clears immediately, without retaining old subscriptions', () => {- const drafts = new ComposerDrafts()- const seen: string[] = []- const unsubscribe = drafts.subscribe(() => seen.push(drafts.get('bot')))- drafts.set('bot', null, 'Typing')- drafts.set('bot', null, 'Typing')- drafts.take('bot', null)- assert.deepEqual(seen, ['Typing', ''])- unsubscribe()- drafts.set('bot', null, 'Later')- assert.deepEqual(seen, ['Typing', ''])-})diff --git a/apps/desktop/src/renderer/store/composer-drafts.ts b/apps/desktop/src/renderer/store/composer-drafts.tsdeleted file mode 100644index 09ff835a..00000000--- a/apps/desktop/src/renderer/store/composer-drafts.ts+++ /dev/null@@ -1,49 +0,0 @@-/** Unsent text belongs to a conversation, independently of its mounted composer. */-export class ComposerDrafts {- private bots = new Map<string, Map<string | null, string>>()- private listeners = new Set<() => void>()-- subscribe = (listener: () => void) => {- this.listeners.add(listener)- return () => { this.listeners.delete(listener) }- }-- get(botId: string, thread: string | null = null): string {- return this.bots.get(botId)?.get(thread) ?? ''- }-- set(botId: string, thread: string | null, text: string) {- if (this.get(botId, thread) === text) return- const threads = this.bots.get(botId) ?? new Map<string | null, string>()- if (text) {- threads.set(thread, text)- this.bots.set(botId, threads)- } else {- threads.delete(thread)- if (!threads.size) this.bots.delete(botId)- }- this.changed()- }-- /** Transfer a draft to a send; asynchronous delivery never owns the next draft. */- take(botId: string, thread: string | null, hasFiles = false): string | null {- const text = this.get(botId, thread)- if (!text.trim() && !hasFiles) return null- this.set(botId, thread, '')- return text- }-- deleteBot(botId: string) {- if (this.bots.delete(botId)) this.changed()- }-- clear() {- if (!this.bots.size) return- this.bots.clear()- this.changed()- }-- private changed() {- for (const listener of [...this.listeners]) listener()- }-}diff --git a/apps/desktop/src/renderer/views/thread/ChatSidePanel.tsx b/apps/desktop/src/renderer/views/thread/ChatSidePanel.tsxnew file mode 100644index 00000000..0fc4be17--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/ChatSidePanel.tsx@@ -0,0 +1,21 @@+import { useRef, type ReactNode } from 'react'+import { usePresence } from '../../components/Overlay'++/** Animate the available conversation width on both opening and closing. */+export function ChatSidePanel({ open, width, children }: { open: boolean; width: number; children: ReactNode }) {+ // A new bot mounts a fresh conversation with details already open.+ // Only subsequent open/close actions should animate the available width.+ const { mounted, shown } = usePresence(open, 300, false)+ const last = useRef({ width, children })+ if (open) last.current = { width, children }+ const content = open ? { width, children } : last.current+ return (+ <div className={`side-panel ${shown ? 'shown' : ''}`} inert={!open}+ style={{ width: shown ? content.width + 1 : 0 }}>+ {mounted ? <>+ <div className="side-panel-border" />+ <div style={{ width: content.width, height: '100%', flex: 'none' }}>{content.children}</div>+ </> : null}+ </div>+ )+}diff --git a/apps/desktop/src/renderer/views/thread/Composer.tsx b/apps/desktop/src/renderer/views/thread/Composer.tsxindex a683b82e..13cd4735 100644--- a/apps/desktop/src/renderer/views/thread/Composer.tsx+++ b/apps/desktop/src/renderer/views/thread/Composer.tsx@@ -1,10 +1,12 @@-import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react'+import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'import { isGroup, isWorkingIn, type Bot } from '@shared/models'import { BotAvatar } from '../../components/Avatar'import { Icon } from '../../components/Icon'+import { usePresence } from '../../components/Overlay'import { font } from '../../lib/fonts'import { useStore } from '../../store/context'import { MAX_FILE_SIZE, type OutgoingFile } from '../../store/bot-store'+import { composerEnter } from './composer-keyboard'import { ComposerAttachment } from './ComposerAttachment'type Trailing = 'interrupt' | 'stop' | 'call' | 'send'@@ -20,13 +22,25 @@ export function Composer({ botId, thread = null, onCall, onInterrupt }: {onCall?: (() => void) | null/** Interrupts the bot while it is speaking in a voice call. */onInterrupt?: (() => void) | null+}) {+ const store = useStore()+ // Remount transient editor state (selection, attachments, IME) when its destination changes.+ return <DestinationComposer key={JSON.stringify([store.contextId, store.computer.id, botId, thread])}+ botId={botId} thread={thread} onCall={onCall} onInterrupt={onInterrupt} />+}++function DestinationComposer({ botId, thread, onCall, onInterrupt }: {+ botId: string; thread: string | null; onCall?: (() => void) | null; onInterrupt?: (() => void) | null}) {const store = useStore()const bot = store.bots.get(botId) ?? null- const draft = useSyncExternalStore(store.subscribeComposerDrafts, () => store.composerDraft(botId, thread))- const setDraft = (text: string) => store.setComposerDraft(text, botId, thread)+ const drafts = store.composerDrafts+ const draft = useSyncExternalStore(drafts.subscribe, () => drafts.get(botId, thread))+ const setDraft = (text: string) => drafts.set(botId, thread, text)const [files, setFiles] = useState<OutgoingFile[]>([])const field = useRef<HTMLTextAreaElement>(null)+ const measure = useRef<HTMLDivElement>(null)+ const composing = useRef(false)const working = !!bot && isWorkingIn(bot, botId, thread)const empty = !draft.trim() && !files.lengthconst canSend = !empty && (store.connection.kind === 'online' || (store.canQueue && !files.length))@@ -38,20 +52,31 @@ export function Composer({ botId, thread = null, onCall, onInterrupt }: {const routineDraft = store.routineDrafts.get(botId)useEffect(() => {if (thread || routineDraft === undefined) return- const current = store.composerDraft(botId, thread)- store.setComposerDraft(current ? `${current}\n${routineDraft}` : routineDraft, botId, thread)- store.consumeRoutineDraft(botId)+ const incoming = store.consumeRoutineDraft(botId)+ if (incoming === undefined) return+ const previous = drafts.get(botId, thread)+ drafts.set(botId, thread, previous ? `${previous}\n${incoming}` : incoming)field.current?.focus()- }, [routineDraft, thread, botId, store])+ }, [routineDraft, thread, botId, store, drafts])- // One to eight lines, growing with the text.+ // Measure a separate, wrapping copy: collapsing the live textarea to zero breaks its+ // height transition, caret scroll and IME composition. Observe font/width changes too.useLayoutEffect(() => {const el = field.current- if (!el) return- el.style.height = '0px'- const line = parseFloat(getComputedStyle(el).lineHeight) || 15- el.style.height = `${Math.min(el.scrollHeight, line * 8)}px`- }, [draft])+ const mirror = measure.current+ if (!el || !mirror) return+ const resize = () => {+ const style = getComputedStyle(el)+ const line = parseFloat(style.lineHeight)+ const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom)+ const height = Math.min(mirror.getBoundingClientRect().height, line * 8 + padding)+ el.style.height = `${height}px`+ }+ resize()+ const observer = new ResizeObserver(resize)+ observer.observe(mirror)+ return () => observer.disconnect()+ }, [])const mentionQuery = (() => {if (!bot || !isGroup(bot)) return null@@ -86,23 +111,26 @@ export function Composer({ botId, thread = null, onCall, onInterrupt }: {const submit = () => {if (!canSend) return- if (store.sendComposerDraft(botId, thread, files)) setFiles([])+ store.send(draft, botId, thread, files)+ setDraft('')+ setFiles([])+ field.current?.focus()}const trailing: Trailing = onInterrupt && !draft && !files.length ? 'interrupt' : working && !draft && !files.length ? 'stop' : onCall && !draft && !files.length ? 'call' : 'send'- const [symbol, label, size] = ({- interrupt: ['stop.fill', 'Interrupt', 12],- stop: ['stop.fill', 'Stop', 12],- call: ['waveform', 'Call', 15],- send: ['arrow.up', 'Send', 14],+ const [symbol, label] = ({+ interrupt: ['stop.fill', 'Interrupt'],+ stop: ['stop.fill', 'Stop'],+ call: ['waveform', 'Call'],+ send: ['arrow.up', 'Send'],} as const)[trailing]const fill = trailing === 'interrupt' ? 'var(--danger)' : trailing === 'send' ? (canSend ? 'var(--accent-fill)' : 'var(--accent-dim)') : 'var(--accent-fill)'const ink = trailing === 'interrupt' ? '#fff' : trailing === 'send' ? (canSend ? 'var(--on-accent)' : 'var(--tertiary)') : 'var(--on-accent)'const enabled = trailing !== 'send' || canSendreturn (- <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>- {suggestions.length ? (+ <div style={{ display: 'flex', flexDirection: 'column' }}>+ <ComposerReveal open={suggestions.length > 0}><div className="mentions">{suggestions.map((m) => (<button key={m.id} className="press mention" onClick={() => mention(m)}>@@ -111,7 +139,7 @@ export function Composer({ botId, thread = null, onCall, onInterrupt }: {</button>))}</div>- ) : null}+ </ComposerReveal><divclassName="composer"onDragOver={(e) => {@@ -124,13 +152,13 @@ export function Composer({ botId, thread = null, onCall, onInterrupt }: {}}><div className="composer-surface">- {files.length ? (+ <ComposerReveal open={files.length > 0}><div className="file-chips">{files.map((f) => (<ComposerAttachment key={f.id} file={f} remove={() => setFiles((list) => list.filter((x) => x.id !== f.id))} />))}</div>- ) : null}+ </ComposerReveal><div className="composer-box">{/* One capsule: attachments, the field, and send / stop / call. */}{canAttach ? (@@ -138,33 +166,42 @@ export function Composer({ botId, thread = null, onCall, onInterrupt }: {<Icon name="plus" size={13} weight="medium" color="var(--text)" /></button>) : null}- <textarea- ref={field}- rows={1}- value={draft}- placeholder={placeholder}- spellCheck- onChange={(e) => setDraft(e.target.value)}- onKeyDown={(e) => {- // Return sends, Shift-Return adds a line; an input method's Return picks its candidate.- if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && e.keyCode !== 229) {+ <div className="composer-field">+ <div ref={measure} className="composer-measure" aria-hidden="true">{draft + '\u200b'}</div>+ <textarea+ ref={field}+ rows={1}+ value={draft}+ placeholder={placeholder}+ spellCheck+ aria-label={thread ? 'Reply' : 'Message'}+ aria-keyshortcuts="Enter Shift+Enter"+ onCompositionStart={() => { composing.current = true }}+ onCompositionEnd={() => { composing.current = false }}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ // Return sends, Shift-Return adds a line; an input method's Return picks its candidate.+ const action = composerEnter({ key: e.key, shiftKey: e.shiftKey, altKey: e.altKey, repeat: e.repeat, isComposing: composing.current || e.nativeEvent.isComposing, keyCode: e.keyCode })+ if (e.key === 'Enter' && e.repeat && !e.shiftKey && !e.altKey) e.preventDefault()+ if (action === 'send') {+ e.preventDefault()+ submit()+ }+ }}+ onPaste={(e) => {+ // ⌘V with a copied file or image: attach it (the field alone would paste a name).+ if (!canAttach) return+ const types = [...e.clipboardData.types]+ const hasFiles = types.includes('Files')+ if (!hasFiles || (types.includes('text/plain') && !e.clipboardData.files.length)) returne.preventDefault()- submit()- }- }}- onPaste={(e) => {- // ⌘V with a copied file or image: attach it (the field alone would paste a name).- if (!canAttach) return- const types = [...e.clipboardData.types]- const hasFiles = types.includes('Files')- if (!hasFiles || (types.includes('text/plain') && !e.clipboardData.files.length)) return- e.preventDefault()- void window.codync.app.readClipboardFiles().then((picked) => {- if (picked.length) return append(picked)- return Promise.all([...e.clipboardData.files].map(async (f) => ({ name: f.name || `pasted-${Date.now()}.png`, data: new Uint8Array(await f.arrayBuffer()) }))).then(append)- })- }}- />+ void window.codync.app.readClipboardFiles().then((picked) => {+ if (picked.length) return append(picked)+ return Promise.all([...e.clipboardData.files].map(async (f) => ({ name: f.name || `pasted-${Date.now()}.png`, data: new Uint8Array(await f.arrayBuffer()) }))).then(append)+ })+ }}+ />+ </div><buttonclassName="press composer-send"disabled={!enabled}@@ -178,7 +215,11 @@ export function Composer({ botId, thread = null, onCall, onInterrupt }: {else submit()}}>- <Icon key={symbol} name={symbol} size={size} weight="bold" className="symbol-swap" />+ {(['stop.fill', 'waveform', 'arrow.up'] as const).map((name) => (+ <span key={name} aria-hidden="true" className={`composer-symbol ${name === symbol ? 'active' : ''}`}>+ <Icon name={name} size={name === 'stop.fill' ? 12 : name === 'waveform' ? 15 : 14} weight="bold" />+ </span>+ ))}</button></div></div>@@ -186,3 +227,13 @@ export function Composer({ botId, thread = null, onCall, onInterrupt }: {</div>)}++/** Keep the outgoing row until its height/fade transition finishes. */+function ComposerReveal({ open, children }: { open: boolean; children: ReactNode }) {+ const { mounted, shown } = usePresence(open)+ const last = useRef(children)+ if (open) last.current = children+ return <div className={`composer-reveal ${shown ? 'shown' : ''}`} inert={!open}>+ <div>{mounted ? (open ? children : last.current) : null}</div>+ </div>+}diff --git a/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx b/apps/desktop/src/renderer/views/thread/DetailsPanel.tsxindex 4dce0710..0bf8f072 100644--- a/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx+++ b/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx@@ -1,4 +1,4 @@-import type { ReactNode } from 'react'+import { useState, type ReactNode } from 'react'import { folderName, isGroup, isWorking, type Bot } from '@shared/models'import { AgentIcon } from '../../components/AgentIcon'import { BotAvatar } from '../../components/Avatar'@@ -25,11 +25,15 @@ export function DetailsPanel({ botId, routineId, editing, setEditing, editGroup,}) {const store = useStore()const bot = store.bots.get(botId) ?? null+ const [returnedFromSettings, setReturnedFromSettings] = useState(false)let header: ReactNodeif (editing) {header = (<>- <RoundButton label="Back to details" symbol="chevron.left" action={() => setEditing(false)} />+ <RoundButton label="Back to details" symbol="chevron.left" action={() => {+ setReturnedFromSettings(true)+ setEditing(false)+ }} /><PanelTitle>Settings</PanelTitle><span style={{ flex: 1 }} /></>@@ -66,7 +70,7 @@ export function DetailsPanel({ botId, routineId, editing, setEditing, editGroup,<BotSettingsPanel botId={botId} /></div>) : (- <div className="panel-slide from-leading" style={{ height: '100%', overflowY: 'auto' }}>+ <div className={returnedFromSettings ? 'panel-slide from-leading' : undefined} style={{ height: '100%', overflowY: 'auto' }}><div style={{ display: 'flex', flexDirection: 'column', gap: 28, padding: '4px 16px 24px' }}><ComputerSummary botId={botId} /><RoutinesView botId={botId} initialId={routineId} />diff --git a/apps/desktop/src/renderer/views/thread/ThreadView.tsx b/apps/desktop/src/renderer/views/thread/ThreadView.tsxindex aca83305..620a1854 100644--- a/apps/desktop/src/renderer/views/thread/ThreadView.tsx+++ b/apps/desktop/src/renderer/views/thread/ThreadView.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'import { draftOf, isGroup, isWorkingIn, type Bot, type BotDraft } from '@shared/models'import { BotAvatar, GroupAvatar } from '../../components/Avatar'import { Spinner } from '../../components/Controls'@@ -10,6 +10,7 @@ import { UpdateNeededCard } from '../UpdateNeededCard'import { buildChat, relativeTime, type ChatItem } from './chat-items'import { ChatRow, WorkingIndicator } from './ChatRows'import { Composer } from './Composer'+import { ChatSidePanel } from './ChatSidePanel'import { DetailsPanel } from './DetailsPanel'import { RepliesView } from './RepliesView'import { TraceView } from './TraceView'@@ -159,13 +160,9 @@ export function ThreadView({ botId }: { botId: string }) {</div>) : null}</div>- {openThread && wide ? (- <SidePanel key={openThread} width={Math.min(420, width * 0.45)}>- <RepliesView botId={botId} rootId={openThread} close={closeThread} />- </SidePanel>- ) : showSettings && wide ? (- <SidePanel width={292}>{details}</SidePanel>- ) : null}+ <ChatSidePanel open={wide && (!!openThread || showSettings)} width={openThread ? Math.min(420, width * 0.45) : 292}>+ {openThread ? <RepliesView key={openThread} botId={botId} rootId={openThread} close={closeThread} /> : details}+ </ChatSidePanel><Sheet open={compactDetails} onClose={() => setCompactDetails(false)} width={340} height={600}>{details}@@ -186,16 +183,6 @@ export function ThreadView({ botId }: { botId: string }) {)}-/** The panel beside the chat (a thread, or the bot's details), sliding in from the trailing edge. */-function SidePanel({ width, children }: { width: number; children: ReactNode }) {- return (- <div className="side-panel" style={{ width: width + 1 }}>- <div className="side-panel-border" />- <div style={{ width, height: '100%' }}>{children}</div>- </div>- )-}-/** The top edge of the chat: messages fade out gradually as they scroll under the title pill. */function TopFade() {return <div className="top-fade" />diff --git a/apps/desktop/src/renderer/views/thread/composer-keyboard.test.ts b/apps/desktop/src/renderer/views/thread/composer-keyboard.test.tsnew file mode 100644index 00000000..b52fd9cf--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/composer-keyboard.test.ts@@ -0,0 +1,16 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { composerEnter } from './composer-keyboard.ts'+const enter = { key: 'Enter', shiftKey: false, altKey: false, repeat: false, isComposing: false, keyCode: 13 }++test('Enter sends; Shift/Option-Enter preserve multiline input', () => {+ assert.equal(composerEnter(enter), 'send')+ assert.equal(composerEnter({ ...enter, shiftKey: true }), 'newline')+ assert.equal(composerEnter({ ...enter, altKey: true }), 'newline')+})++test('CJK candidate confirmation and a held Enter never send', () => {+ assert.equal(composerEnter({ ...enter, isComposing: true }), 'ignore')+ assert.equal(composerEnter({ ...enter, keyCode: 229 }), 'ignore')+ assert.equal(composerEnter({ ...enter, repeat: true }), 'ignore')+})diff --git a/apps/desktop/src/renderer/views/thread/composer-keyboard.ts b/apps/desktop/src/renderer/views/thread/composer-keyboard.tsnew file mode 100644index 00000000..90fc554b--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/composer-keyboard.ts@@ -0,0 +1,8 @@+export function composerEnter(event: {+ key: string; shiftKey: boolean; altKey: boolean; repeat: boolean+ isComposing: boolean; keyCode: number+}): 'send' | 'newline' | 'ignore' {+ if (event.key !== 'Enter' || event.isComposing || event.keyCode === 229) return 'ignore'+ if (event.shiftKey || event.altKey) return 'newline'+ return event.repeat ? 'ignore' : 'send'+}diff --git a/apps/desktop/src/renderer/views/thread/thread.css b/apps/desktop/src/renderer/views/thread/thread.cssindex 1a3b621b..a402c4fb 100644--- a/apps/desktop/src/renderer/views/thread/thread.css+++ b/apps/desktop/src/renderer/views/thread/thread.css@@ -244,7 +244,7 @@.mentions {display: flex;gap: 6px;- padding: 0 16px;+ padding: 0 16px 6px;overflow-x: auto;}.mention {@@ -291,7 +291,13 @@gap: 8px;padding: 4px 6px 4px 8px;}-.composer-box textarea {+.composer-field {+ flex: 1;+ min-width: 0;+ position: relative;+}+.composer-box textarea,+.composer-measure {flex: 1;min-width: 0;font-size: var(--conversation);@@ -301,6 +307,37 @@user-select: text;cursor: text;}+.composer-box textarea {+ display: block;+ width: 100%;+ height: calc(round(up, calc(var(--conversation) * 1.25), 1px) + 14px);+ transition: height var(--layout);+}+.composer-measure {+ position: absolute;+ inset: 0 0 auto;+ visibility: hidden;+ pointer-events: none;+ white-space: pre-wrap;+ overflow-wrap: break-word;+}+.composer-reveal {+ display: grid;+ grid-template-rows: 0fr;+ opacity: 0;+ transition: grid-template-rows var(--layout), opacity var(--morph);+}+.composer-reveal.shown { grid-template-rows: 1fr; opacity: 1; }+.composer-reveal > div { min-height: 0; overflow: hidden; }+.composer-symbol {+ grid-area: 1 / 1;+ display: grid;+ place-items: center;+ opacity: 0;+ transform: scale(0.55) rotate(-35deg);+ transition: opacity var(--morph), transform var(--morph);+}+.composer-symbol.active { opacity: 1; transform: scale(1) rotate(0); }.composer-send {width: 28px;height: 28px;@@ -386,9 +423,11 @@height: 100%;display: flex;flex: none;- animation: panel-slide var(--morph) both;+ opacity: 0;+ transition: width var(--layout), opacity var(--morph);overflow: hidden;}+.side-panel.shown { opacity: 1; }.side-panel-border {width: 1px;background: var(--border);diff --git a/apps/desktop/src/shared/composer-drafts.test.ts b/apps/desktop/src/shared/composer-drafts.test.tsnew file mode 100644index 00000000..43f4e7e3--- /dev/null+++ b/apps/desktop/src/shared/composer-drafts.test.ts@@ -0,0 +1,63 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { ComposerDrafts } from './composer-drafts.ts'++function storage() {+ const data = new Map<string, string>()+ return { getItem: (key: string) => data.get(key) ?? null, setItem: (key: string, value: string) => { data.set(key, value) } }+}++test('drafts survive reopening with whitespace and isolate bots, threads and accounts', () => {+ const disk = storage()+ const drafts = new ComposerDrafts(disk, 'account/computer')+ const text = ' 中文\nunfinished 🐱\n'+ drafts.set('bot', null, text)+ drafts.set('bot', 'thread', 'reply')+ drafts.set('other', null, 'other draft')+ const reopened = new ComposerDrafts(disk, 'account/computer')+ assert.equal(reopened.get('bot'), text)+ assert.equal(reopened.get('bot', 'thread'), 'reply')+ assert.equal(reopened.get('other'), 'other draft')+ assert.equal(new ComposerDrafts(disk, 'other-account/computer').get('bot'), '')+ assert.equal(new ComposerDrafts(disk, 'account/other-computer').get('bot'), '')+ reopened.set('bot', null, '')+ assert.equal(new ComposerDrafts(disk, 'account/computer').get('bot'), '')+ assert.equal(reopened.get('bot', 'thread'), 'reply')+ assert.equal(reopened.get('other'), 'other draft')+})++test('deleting a bot removes its main and thread drafts, but preserves other bots', () => {+ const drafts = new ComposerDrafts(storage(), 'drafts')+ drafts.set('bot', null, 'main')+ drafts.set('bot', 'thread', 'reply')+ drafts.set('other', null, 'keep')+ drafts.removeBot('bot')+ assert.equal(drafts.get('bot'), '')+ assert.equal(drafts.get('bot', 'thread'), '')+ assert.equal(drafts.get('other'), 'keep')+})++test('malformed or unavailable persistence does not destroy editable in-memory text', () => {+ const disk = { getItem: () => '{bad', setItem: () => { throw new Error('full') } }+ const drafts = new ComposerDrafts(disk, 'drafts')+ let updates = 0+ const unsubscribe = drafts.subscribe(() => updates++)+ drafts.set('bot', null, 'kept')+ assert.equal(drafts.get('bot'), 'kept')+ assert.equal(updates, 1)+ unsubscribe()+ drafts.set('bot', null, 'next')+ assert.equal(updates, 1)+})++test('late edits from a retired store cannot overwrite a reopened conversation', () => {+ const disk = storage()+ const previous = new ComposerDrafts(disk, 'account/computer')+ previous.set('bot', null, 'old text')+ previous.retire()+ const current = new ComposerDrafts(disk, 'account/computer')+ current.set('bot', null, 'new text')+ previous.set('bot', null, 'late edit')+ previous.clear()+ assert.equal(new ComposerDrafts(disk, 'account/computer').get('bot'), 'new text')+})diff --git a/apps/desktop/src/shared/composer-drafts.ts b/apps/desktop/src/shared/composer-drafts.tsnew file mode 100644index 00000000..046d4e3a--- /dev/null+++ b/apps/desktop/src/shared/composer-drafts.ts@@ -0,0 +1,67 @@+/** Text belongs to a destination, independent of a mounted editor or transcript cache. */+export class ComposerDrafts {+ private values = new Map<string, string>()+ private listeners = new Set<() => void>()+ private retired = false++ private storage: Pick<Storage, 'getItem' | 'setItem'>+ private key: string+ private onSaveError?: () => void++ constructor(storage: Pick<Storage, 'getItem' | 'setItem'>, key: string, onSaveError?: () => void) {+ this.storage = storage+ this.key = key+ this.onSaveError = onSaveError+ try {+ const saved: unknown = JSON.parse(storage.getItem(key) ?? 'null')+ if (Array.isArray(saved)) {+ for (const row of saved) {+ if (Array.isArray(row) && row.length === 2 && typeof row[0] === 'string' && typeof row[1] === 'string') {+ this.values.set(row[0], row[1])+ }+ }+ }+ } catch { /* A damaged or unavailable store must not prevent typing. */ }+ }++ subscribe = (listener: () => void) => {+ this.listeners.add(listener)+ return () => { this.listeners.delete(listener) }+ }++ get(bot: string, thread: string | null = null) {+ return this.values.get(JSON.stringify([bot, thread])) ?? ''+ }++ set(bot: string, thread: string | null, text: string) {+ if (this.retired) return+ const destination = JSON.stringify([bot, thread])+ if (text) this.values.set(destination, text)+ else this.values.delete(destination)+ this.save()+ }++ removeBot(bot: string) {+ if (this.retired) return+ for (const key of this.values.keys()) {+ try { if (JSON.parse(key)[0] === bot) this.values.delete(key) } catch { this.values.delete(key) }+ }+ this.save()+ }++ clear() {+ if (this.retired) return+ this.values.clear()+ this.save()+ }++ retire() {+ this.retired = true+ }++ private save() {+ // Save on each edit, including clearing after submission; no unmount/debounce race.+ try { this.storage.setItem(this.key, JSON.stringify([...this.values])) } catch { this.onSaveError?.() }+ for (const listener of this.listeners) listener()+ }+}diff --git a/apps/desktop/tools/composer-check/index.html b/apps/desktop/tools/composer-check/index.htmlnew file mode 100644index 00000000..ee1536b8--- /dev/null+++ b/apps/desktop/tools/composer-check/index.html@@ -0,0 +1,7 @@+<!doctype html><html><head><meta charset="utf-8"><title>Composer regression checks</title></head>+<body><div id="root"></div><script>+window.codync = { platform: 'linux', appVersion: '2.7.0', app: {+ pickFiles: async () => [{ name: 'example.txt', data: new TextEncoder().encode('fixture') }],+ readClipboardFiles: async () => [], onCommand: () => () => {}+} };+</script><script type="module" src="./main.tsx"></script></body></html>diff --git a/apps/desktop/tools/composer-check/main.tsx b/apps/desktop/tools/composer-check/main.tsxnew file mode 100644index 00000000..894708fa--- /dev/null+++ b/apps/desktop/tools/composer-check/main.tsx@@ -0,0 +1,51 @@+import React, { useState } from 'react'+import { createRoot } from 'react-dom/client'+import { ChatSidePanel } from '../../src/renderer/views/thread/ChatSidePanel'+import { Composer } from '../../src/renderer/views/thread/Composer'+import { StoreContext } from '../../src/renderer/store/context'+import { BotStore } from '../../src/renderer/store/bot-store'+import { normalizeBot } from '../../src/shared/models'+import '../../src/renderer/styles/theme.css'+import '../../src/renderer/views/thread/thread.css'+import '../../src/renderer/views/thread/chat-controls.css'++// Actual store and component, with no connection to the user's host or account.+const store = new BotStore({ id: 'composer-check', name: 'Fixture', signKey: '', urls: [] }, true,+ () => { throw new Error('Fixture must not connect to a host') }, 'mac', '2.7.0', 'composer-check')+store.connection = { kind: 'online' }+for (const id of ['first', 'second', 'group']) store.bots.set(id, normalizeBot({ id, name: id, kind: id === 'group' ? 'group' : 'agent', members: ['first', 'second'] }))+const sent: unknown[] = []+store.send = (text, botId, thread, files) => { sent.push({ text, botId, thread, files: files?.length }); renderCount(n => n + 1) }+store.stop = () => { store.bots.get('first')!.status = 'idle'; renderCount(n => n + 1) }+let renderCount: React.Dispatch<React.SetStateAction<number>> = () => {}+function Check() {+ const [bot, setBot] = useState('first')+ const [thread, setThread] = useState<string | null>(null)+ const [mounted, setMounted] = useState(true)+ const [calling, setCalling] = useState(false)+ const [panel, setPanel] = useState(false)+ const [width, setWidth] = useState(620)+ const [, update] = useState(0)+ renderCount = update+ return <StoreContext.Provider value={store}>+ <main style={{ padding: 32, '--conversation': '16px' } as React.CSSProperties}>+ <h1>Composer regression checks</h1>+ <nav style={{ display: 'flex', gap: 18, margin: '24px 0' }}>+ {['first', 'second', 'group'].map(id => <button key={id} onClick={() => setBot(id)}>{id}</button>)}+ <button onClick={() => setThread(t => t ? null : 'root')}>Toggle thread</button>+ <button onClick={() => setMounted(m => !m)}>Toggle composer</button>+ <button onClick={() => setPanel(p => !p)}>Toggle panel</button>+ <button onClick={() => setWidth(w => w === 620 ? 300 : 620)}>Resize</button>+ <button onClick={() => { const b = store.bots.get(bot)!; b.status = b.status === 'working' ? 'idle' : 'working'; update(n => n + 1) }}>Toggle working</button>+ <button onClick={() => { store.connection = store.connection.kind === 'online' ? { kind: 'offline', message: 'fixture' } : { kind: 'online' }; update(n => n + 1) }}>Toggle offline</button>+ </nav>+ <p>{bot} / {thread ?? 'main'} / {calling ? 'calling' : 'silent'}</p>+ <div style={{ width, paddingTop: 20 }}>+ {mounted ? <Composer botId={bot} thread={thread} onCall={() => setCalling(true)} onInterrupt={calling ? () => setCalling(false) : null} /> : null}+ </div>+ <div style={{ display: 'flex', height: 100 }}><ChatSidePanel open={panel} width={292}><p>Details fixture</p></ChatSidePanel></div>+ <output aria-label="Sent messages">{JSON.stringify(sent)}</output>+ </main>+ </StoreContext.Provider>+}+createRoot(document.getElementById('root')!).render(<Check />)diff --git a/apps/desktop/tools/composer-check/serve.mjs b/apps/desktop/tools/composer-check/serve.mjsnew file mode 100644index 00000000..801c2333--- /dev/null+++ b/apps/desktop/tools/composer-check/serve.mjs@@ -0,0 +1,11 @@+import { createServer } from 'vite'+import react from '@vitejs/plugin-react'+import { fileURLToPath } from 'node:url'+const root = fileURLToPath(new URL('../../', import.meta.url))+const server = await createServer({+ configFile: false, root, plugins: [react()],+ resolve: { alias: { '@shared': `${root}src/shared` } },+ server: { host: '127.0.0.1', port: 5198, strictPort: true },+})+await server.listen()+console.log('Composer check: http://127.0.0.1:5198/tools/composer-check/')diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swiftindex f777ae88..853160b4 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"]+ private static let names = ["computers", "bots", "usage", "lastComputerId", "composerDrafts"]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()@@ -58,6 +58,12 @@ public enum SharedStore {get { read([ComputerID: Usage].self, "usage") ?? [:] }nonmutating set { write(newValue, "usage") }}+ /// Unsent text, isolated by account, computer, bot and thread; not a transcript cache.+ public var composerDrafts: [ComputerID: [String: String]] {+ get { read([ComputerID: [String: String]].self, "composerDrafts") ?? [:] }+ nonmutating set { write(newValue, "composerDrafts") }+ }+/// The most recently active computer; the Usage widget shows only this one.public var lastComputerId: ComputerID? {get { defaults.string(forKey: key("lastComputerId")) }diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftindex 87d652d3..844f4dd1 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift@@ -58,13 +58,8 @@ public final class BotStore {public private(set) var installedSkills: [InstalledSkill] = []/// Bots whose older history has been fully paged in.public private(set) var historyComplete: Set<String> = []+ private var composerDrafts: [String: String] = [:]public var routineDrafts: [String: String] = [:]- /// Unsent composer text belongs to a conversation, not the view displaying it.- private struct ComposerDestination: Hashable {- let botId: String- let thread: String?- }- private var composerDrafts: [ComposerDestination: String] = [:]public var lastError: String?/// The open conversation (iOS navigation path / Mac sidebar selection).public var selection: String?@@ -134,6 +129,7 @@ public final class BotStore {self.storage = storagemakeTransport = transportusage = storage.usage[computer.id] ?? Usage()+ composerDrafts = storage.composerDrafts[computer.id] ?? [:]loadCache()}@@ -214,8 +210,9 @@ public final class BotStore {}private func resetMirror() {- bots = [:]composerDrafts = [:]+ persistComposerDrafts()+ bots = [:]entries = entries.mapValues { $0.filter { $0.id.hasPrefix("local-") } }.filter { !$0.value.isEmpty }selection = nilonRosterChanged?()@@ -235,7 +232,6 @@ public final class BotStore {voiceCalls.removeAll()setActive(false)retired = true- composerDrafts = [:]for call in calls { call.end() }saveTask?.cancel()dropTimer?.cancel()@@ -524,7 +520,7 @@ public final class BotStore {}}case let .botDeleted(id, r):- composerDrafts = composerDrafts.filter { $0.key.botId != id }+ removeComposerDrafts(for: id)bots[id] = nilentries[id] = nilbump(r)@@ -657,17 +653,34 @@ public final class BotStore {}}+ private func composerKey(_ botId: String, _ thread: String?) -> String {+ // Encode the tuple so a main chat cannot collide with a thread's ID.+ String(decoding: (try? JSONEncoder().encode([botId, thread])) ?? Data(), as: UTF8.self)+ }+func composerDraft(for botId: String, thread: String? = nil) -> String {- composerDrafts[ComposerDestination(botId: botId, thread: thread)] ?? ""+ composerDrafts[composerKey(botId, thread)] ?? ""}func setComposerDraft(_ text: String, for botId: String, thread: String? = nil) {guard !retired else { return }- let destination = ComposerDestination(botId: botId, thread: thread)- composerDrafts[destination] = text.isEmpty ? nil : text+ composerDrafts[composerKey(botId, thread)] = text.isEmpty ? nil : text+ persistComposerDrafts()+ }++ private func persistComposerDrafts() {+ storage.composerDrafts[computer.id] = composerDrafts.isEmpty ? nil : composerDrafts+ }++ private func removeComposerDrafts(for botId: String) {+ composerDrafts = composerDrafts.filter { key, _ in+ let destination = try? JSONDecoder().decode([String?].self, from: Data(key.utf8))+ return destination?.first != botId+ }+ persistComposerDrafts()}- /// Submission moves the text to the local message/outbox; later delivery never clears a new draft.+ /// Transfer to the outbox now; an eventual acknowledgement must not erase a newer draft.@discardableResultfunc sendComposerDraft(to botId: String, thread: String? = nil, files: [OutgoingFile] = []) -> Bool {let text = composerDraft(for: botId, thread: thread)@@ -978,7 +991,7 @@ public final class BotStore {}public func delete(_ bot: Bot) {- composerDrafts = composerDrafts.filter { $0.key.botId != bot.id }+ removeComposerDrafts(for: bot.id)bots[bot.id] = nilentries[bot.id] = nilperform(replay: true) { try await $0.deleteBot(bot.id) }diff --git a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swiftindex 852f1cc0..d5c49bad 100644--- a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift+++ b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift@@ -690,27 +690,35 @@ private func helloJSON(version: String, minApp: String? = nil, backends: String}}-@MainActor @Test func composerDraftsRestoreSeparatelyForEachBotAndThread() {+@MainActor @Test func composerDraftsPersistAcrossNavigationAndReopening() {let (storage, suite) = context()defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }- let store = BotStore(computer: randomComputer("Mac"), clientKind: "ios", storage: storage) {- FakeRemote(.connecting)- }- defer { store.retire() }- let text = " Unfinished message\nnext line 🐱\n"- store.selection = "first"+ let computer = randomComputer("Mac")+ let store = BotStore(computer: computer, clientKind: "ios", storage: storage) { FakeRemote(.connecting) }+ let text = " 中文\nunfinished 🐱\n"store.setComposerDraft(text, for: "first")+ store.setComposerDraft("Other draft", for: "second")+ store.setComposerDraft("Reply", for: "first", thread: "root")store.selection = "second"- #expect(store.composerDraft(for: "second").isEmpty)- store.setComposerDraft("Other bot's draft", for: "second")- store.setComposerDraft("Thread reply", for: "first", thread: "root")- store.selection = "first"#expect(store.composerDraft(for: "first") == text)- #expect(store.composerDraft(for: "second") == "Other bot's draft")- #expect(store.composerDraft(for: "first", thread: "root") == "Thread reply")-}--@MainActor @Test func sendingComposerDraftClearsOnlyThatConversation() async {+ store.retire()+ store.setComposerDraft("late edit", for: "first")+ let reopened = BotStore(computer: computer, clientKind: "ios", storage: storage) { FakeRemote(.connecting) }+ defer { reopened.retire() }+ #expect(reopened.composerDraft(for: "first") == text)+ #expect(reopened.composerDraft(for: "first", thread: "root") == "Reply")+ reopened.setComposerDraft("", for: "first")+ #expect(reopened.composerDraft(for: "first").isEmpty)+ #expect(reopened.composerDraft(for: "second") == "Other draft")+ #expect(reopened.composerDraft(for: "first", thread: "root") == "Reply")+ let other = BotStore(computer: randomComputer("Other"), clientKind: "ios", storage: storage) { FakeRemote(.connecting) }+ defer { other.retire() }+ #expect(other.composerDraft(for: "first").isEmpty)+ storage.erase()+ #expect(storage.composerDrafts.isEmpty)+}++@MainActor @Test func sendingDraftNeverClearsAnotherConversationOrLaterText() async {let (storage, suite) = context()defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }let fake = FakeRemote(.ready(.direct))@@ -721,13 +729,15 @@ private func helloJSON(version: String, minApp: String? = nil, backends: Stringawait fake.emit(botEvent("first", name: "First", rev: 1))#expect(await until { store.connection == .online })store.setComposerDraft("First message", for: "first")- store.setComposerDraft("Other bot's draft", for: "second")- store.setComposerDraft("Thread reply", for: "first", thread: "root")+ store.setComposerDraft("Other draft", for: "second")+ store.setComposerDraft("Reply", for: "first", thread: "root")#expect(store.sendComposerDraft(to: "first"))#expect(store.composerDraft(for: "first").isEmpty)- #expect(store.composerDraft(for: "second") == "Other bot's draft")- #expect(store.composerDraft(for: "first", thread: "root") == "Thread reply")store.setComposerDraft("Next unfinished message", for: "first")#expect(await until { store.chat("first").last?.id == "e1" })#expect(store.composerDraft(for: "first") == "Next unfinished message")+ #expect(store.composerDraft(for: "second") == "Other draft")+ #expect(store.composerDraft(for: "first", thread: "root") == "Reply")+ let anotherAccount = SharedStore.Context(accountID: "another-user", suite: suite)+ #expect(anotherAccount.composerDrafts.isEmpty)}diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.mdindex 2153d6fe..2f1299db 100644--- a/docs/architecture/desktop-app.md+++ b/docs/architecture/desktop-app.md@@ -30,12 +30,11 @@ The iPhone app stays native SwiftUI; its package moved from `kit/` into `apps/ioThe renderer owns all state; closing the window hides it, so the menu bar keeps its data.HTTP to the host leaves from the main process (the loopback API has no CORS).-Unsent composer text is retained in each computer’s `BotStore`, separately for every bot-and reply thread. Switching conversations or closing a reply panel restores the exact text.-Submitting clears only that conversation’s draft; completion or failure of the send does-not clear a newer draft. Drafts last for the window’s session and are cleared when the-computer is removed, its host identity changes, or the bot is deleted. iOS and the TUI-already retain drafts per conversation; the shared desktop behavior covers macOS and Linux.+Unsent composer text is kept per computer, separately for every bot and reply thread, and+saved to `localStorage`, so switching conversations, closing a reply panel or restarting the+app restores the exact text. Submitting clears only that conversation's draft. Drafts are+cleared when the host identity changes or the bot is deleted. iOS and the TUI keep drafts the+same way; the shared desktop behavior covers macOS and Linux.## Platform notes@@ -105,6 +104,9 @@ Mac chat redesign that was in progress at the time (larger chat text, actions beone composer capsule, circular chat controls, Jump to latest). It was checked side by side withthe SwiftUI build against the same host using screenshots from Computer Use.+Composer keyboard behavior, animation and durable draft storage, with a host-free+regression fixture: [composer checks](../guides/composer.md).+## The SwiftUI apps in the history`apps/macos/`, `apps/linux/` and the Mac code paths in `kit/` are in Git. The commit thatdiff --git a/docs/guides/composer.md b/docs/guides/composer.mdnew file mode 100644index 00000000..6da3720f--- /dev/null+++ b/docs/guides/composer.md@@ -0,0 +1,64 @@+# Composer behavior and regression checks++The Electron composer restores the draft and layout behavior previously fixed in+`080b602` (per-conversation drafts), `4c7a26d` (animated field growth), and `f0abd80`+(Shift-Return). Drafts also survive restarting the client.++## Text and keyboard++- Desktop: Return sends; Shift-Return and Option/Alt-Return insert a newline.+ Confirming a CJK input-method candidate or holding Return does not send.+- The field grows and shrinks from one to eight lines, then scrolls internally.+ Window width and text-size changes remeasure wrapped text. The live textarea+ remains mounted during measurement, preserving selection and composition.+- The call, send, stop and interrupt actions share one button. Its symbol and+ colors transition without replacing the button or losing keyboard focus.+- Attachment rows, mention suggestions and the conversation inspector animate+ both opening and closing. Rapid toggles cancel pending reveal callbacks.+ Reduced Motion removes these transitions.+- iOS keeps its native multiline field, keyboard and existing Motion animations.+ The terminal uses immediate text layout, with Shift/Alt-Enter (where supported)+ or Ctrl+J for a newline; it has no voice button or graphical inspector animation.++## Draft lifetime++Text is saved exactly, including leading/trailing whitespace, blank lines and emoji.+Main chats and individual threads have separate drafts. Switching destinations or+reopening the client restores their text. Deleting a bot removes its drafts.++Desktop stores text in a versioned localStorage record per account context and+computer, independently of transcript caches. iOS uses its account-scoped+SharedStore defaults with a separate map per computer. Signing out on iOS erases+these values with the rest of the account data. Retired desktop/iOS stores cannot+write late edits over a newly opened store.++The terminal saves text under `CODYNC_HOME` (normally `~/.codync`), in a private,+atomically replaced `tui-drafts-<URL hash>.json` file for each host endpoint.+Its existing send flow keeps a draft until delivery succeeds and preserves newer+text if an earlier send finishes later. Save failures leave text in the session+and display an error. Desktop/iOS submission transfers the text to their existing+message/outbox flow and clears only that destination's draft.++Drafts are local to each client, not synchronized between devices. Attachment+bytes are not persisted across restarts.++## Verification++Run desktop type checking and unit tests, the iOS package tests, and host CI checks+as described in [development](development.md#component-checks). Regression tests+cover exact-text restoration, independent destinations, selective clearing,+retired stores, and send acknowledgements arriving after new text is entered.++For a host-free visual check using the actual Electron renderer components:++```sh+cd apps/desktop+node tools/composer-check/serve.mjs+# Open http://127.0.0.1:5198/tools/composer-check/+```++The fixture never connects to the host or sends to a real bot. Check typing,+Shift-Return, CJK composition, eight-line overflow, width changes, bot/thread+switching, reload restoration, offline sending, call/send/stop/interrupt changes,+attachment removal, inspector opening/closing and Reduced Motion. The fixture's+sent-message log and drafts are separate from real account data.diff --git a/host/src/tui/app.rs b/host/src/tui/app.rsindex a75573e7..c3c62ba5 100644--- a/host/src/tui/app.rs+++ b/host/src/tui/app.rs@@ -1029,6 +1029,9 @@ impl App {if v["deleted"].as_bool().unwrap_or(false) {self.bots.remove(id);self.entries.remove(id);+ let prefix = format!("{id}#");+ self.drafts.retain(|key, _| key != id && !key.starts_with(&prefix));+ self.files.retain(|key, _| key != id && !key.starts_with(&prefix));if self.selected.as_deref() == Some(id) {self.selected = None;self.thread = None;diff --git a/host/src/tui/drafts.rs b/host/src/tui/drafts.rsnew file mode 100644index 00000000..33dedfb2--- /dev/null+++ b/host/src/tui/drafts.rs@@ -0,0 +1,109 @@+//! Durable text only. Attachments remain session-local, as on the phone and desktop.+use super::app::Editor;+use anyhow::Result;+use sha2::{Digest, Sha256};+use std::collections::HashMap;+use std::io::Write;+use std::path::PathBuf;++pub struct Drafts {+ path: PathBuf,+ saved: HashMap<String, String>,+}++impl Drafts {+ pub async fn load(url: &str) -> Result<Self> {+ use std::fmt::Write as _;+ let digest = Sha256::digest(url.as_bytes()).iter().fold(String::with_capacity(64), |mut out, byte| {+ let _ = write!(out, "{byte:02x}");+ out+ });+ let name = format!("tui-drafts-{digest}.json");+ let path = crate::service::data_dir().join(name);+ Self::at(path).await+ }++ async fn at(path: PathBuf) -> Result<Self> {+ tokio::task::spawn_blocking(move || {+ let saved = match std::fs::read(&path) {+ Ok(bytes) => serde_json::from_slice(&bytes)?,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => HashMap::new(),+ Err(e) => return Err(e.into()),+ };+ Ok(Self { path, saved })+ })+ .await?+ }++ pub fn restore(&self) -> HashMap<String, Editor> {+ self.saved.iter().map(|(key, text)| (key.clone(), Editor::with(text))).collect()+ }++ pub async fn save(&mut self, drafts: &HashMap<String, Editor>) -> Result<()> {+ let next: HashMap<_, _> = drafts+ .iter()+ .filter(|(_, editor)| !editor.text.is_empty())+ .map(|(key, editor)| (key.clone(), editor.text.clone()))+ .collect();+ if next == self.saved {+ return Ok(());+ }+ let bytes = serde_json::to_vec(&next)?;+ let path = self.path.clone();+ tokio::task::spawn_blocking(move || -> Result<()> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }+ let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));+ let result = (|| -> Result<()> {+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create_new(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ options.mode(0o600);+ }+ let mut file = options.open(&temporary)?;+ file.write_all(&bytes)?;+ file.sync_all()?;+ std::fs::rename(&temporary, &path)?;+ Ok(())+ })();+ if result.is_err() {+ let _ = std::fs::remove_file(temporary);+ }+ result+ })+ .await??;+ self.saved = next;+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn reopening_restores_exact_text_and_clears_only_the_sent_destination() {+ let dir = std::env::temp_dir().join(format!("codync-drafts-{}", uuid::Uuid::new_v4()));+ let path = dir.join("drafts.json");+ let mut store = Drafts::at(path.clone()).await.unwrap();+ let mut drafts = HashMap::from([+ ("bot".into(), Editor::with(" 中文\nunfinished 🐱\n")),+ ("bot#thread".into(), Editor::with("reply")),+ ("other".into(), Editor::with("other bot")),+ ]);+ store.save(&drafts).await.unwrap();+ let restored = Drafts::at(path.clone()).await.unwrap().restore();+ assert_eq!(restored["bot"].text, drafts["bot"].text);+ assert_eq!(restored["bot#thread"].text, "reply");+ drafts.remove("bot");+ store.save(&drafts).await.unwrap();+ let restored = Drafts::at(path).await.unwrap().restore();+ assert!(!restored.contains_key("bot"));+ assert_eq!(restored["other"].text, "other bot");+ assert_eq!(restored["bot#thread"].text, "reply");+ std::fs::remove_dir_all(dir).unwrap();+ }+}diff --git a/host/src/tui/mod.rs b/host/src/tui/mod.rsindex 5d34e8cf..478d4ad6 100644--- a/host/src/tui/mod.rs+++ b/host/src/tui/mod.rs@@ -3,6 +3,7 @@mod app;mod connections;+mod drafts;mod manage;mod md;mod net;@@ -47,6 +48,16 @@ pub async fn run(url: String, token: Option<String>) -> Result<()> {let client = net::Client::new(&url, token.as_deref());let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();let mut app = app::App::new(client.clone(), tx.clone(), url);+ let mut drafts = match drafts::Drafts::load(&app.url).await {+ Ok(saved) => {+ app.drafts = saved.restore();+ Some(saved)+ }+ Err(error) => {+ app.flash(&format!("Couldn't restore drafts: {error}"));+ None+ }+ };terminal::enable_raw_mode().context("this needs an interactive terminal")?;let mut out = std::io::stdout();@@ -118,6 +129,11 @@ pub async fn run(url: String, token: Option<String>) -> Result<()> {}}dirty = true;+ if let Some(saved) = drafts.as_mut()+ && let Err(error) = saved.save(&app.drafts).await+ {+ app.flash(&format!("Couldn't save drafts: {error}. Text stays in this session."));+ }if app.quit {break;}