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: show a bot's memory read-only, changed by talking to the bot
leepokaid2c7ee52ad38
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex a3737686..e34638e1 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -161,12 +161,6 @@ function registerIPC(tray: Tray) {ipcMain.on('app:openExternal', (_e, url: string) => {if (/^(https?|mailto|x-apple\.systempreferences):/.test(url)) void shell.openExternal(url)})- ipcMain.on('app:openMemoryFile', (_e, path: string) => {- // A note's own name in a memory folder, nothing else: the renderer can't open arbitrary files through this.- if (/[\\/](shared-memory|bot-memory)[\\/][a-z0-9-]+\.md$/.test(path) && !/(^|[\\/])\.\.([\\/]|$)/.test(path)) {- void shell.openPath(path)- }- })ipcMain.on('app:openSettings', (_e, url: string) => {if (url.startsWith('x-apple.systempreferences:')) void shell.openExternal(url)})diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex 8b4eb844..453d7d0f 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -103,7 +103,6 @@ const bridge: CodyncBridge = {app: {reportError: (report) => ipcRenderer.send('app:reportError', report),openExternal: (url) => ipcRenderer.send('app:openExternal', url),- openMemoryFile: (path) => ipcRenderer.send('app:openMemoryFile', path),copy: (text) => ipcRenderer.send('app:copy', text),pickFiles: () => ipcRenderer.invoke('app:pickFiles'),readClipboardFiles: () => ipcRenderer.invoke('app:clipboardFiles'),diff --git a/apps/desktop/src/renderer/demo/bridge.ts b/apps/desktop/src/renderer/demo/bridge.tsindex d4c93f5e..93636b3f 100644--- a/apps/desktop/src/renderer/demo/bridge.ts+++ b/apps/desktop/src/renderer/demo/bridge.ts@@ -93,7 +93,6 @@ const bridge: CodyncBridge = {app: {reportError() {},openExternal: (url) => void window.open(url, '_blank', 'noopener'),- openMemoryFile: () => {},copy: (text) => void navigator.clipboard?.writeText(text).catch(() => {}),pickFiles: async () => [],readClipboardFiles: async () => [],diff --git a/apps/desktop/src/renderer/store/memory-store.ts b/apps/desktop/src/renderer/store/memory-store.tsindex a4b4b473..c34092e7 100644--- a/apps/desktop/src/renderer/store/memory-store.ts+++ b/apps/desktop/src/renderer/store/memory-store.ts@@ -19,7 +19,7 @@ export interface MemoryEntry {export interface MemoryLayer { entries: MemoryEntry[]; used: number; cap: number }-/** One dreaming run: what it added and archived; it can be undone. */+/** One dreaming run: what it added and archived (`undone` when an older app undid it). */export interface DreamRun {id: numberat: number@@ -34,8 +34,6 @@ export interface DreamRun {export interface MemoryFile {bot: string | nullname: string- /** SHA-256 of what it holds; a save is made over it. */- hash: stringdescription: string | nulltokens: numberdeleted: boolean@@ -50,26 +48,12 @@ export interface MemoryFiles {folderCap: number}-export interface MemoryFileVersion {- id: number- /** null: the file was deleted. */- content: string | null- /** user · bot · dream · computer */- author: string- authorBot: string | null- /** edit · delete · restore · undo · dream */- cause: string- at: number-}--/** A file as it is on disk now, with its recent versions. */+/** A file as it is on disk now. */export interface MemoryFileDetail {file: stringshared: booleancontent: string | null- hash: string | nullpath: string- versions: MemoryFileVersion[]}export interface MemoryView {@@ -87,10 +71,9 @@ export interface MemoryView {const OLDER_HOST = "Update Codync on your computer to see this bot's memory."-/** One bot's memory: fetches it, and changes it through the host. */+/** One bot's memory, read-only: the bot changes it. */export class MemoryStore extends Observable {view: MemoryView | null = null- busy = falseerror: string | null = nullprivate request = 0@@ -112,7 +95,7 @@ export class MemoryStore extends Observable {this.changed()}- /** A long-form file as it is now, with its versions. */+ /** A long-form file as it is now. */async file(name: string, shared: boolean): Promise<MemoryFileDetail | null> {try {return await (await this.client()).call<MemoryFileDetail>('memoryFile', { botId: this.botId, file: name, shared })@@ -122,31 +105,6 @@ export class MemoryStore extends Observable {return null}}-- /** Saves (`content`), deletes (neither) or brings back `version` of a file, over what was loaded (`base`). */- changeFile(name: string, shared: boolean, base: string | null, change: { content?: string; version?: number } = {}) {- const method = change.version !== undefined ? 'restoreMemoryFile' : change.content !== undefined ? 'saveMemoryFile' : 'deleteMemoryFile'- return this.mutate(method, { file: name, shared, base, ...change })- }-- /** A memory method for this bot; reloads after it. */- async mutate(method: string, body: object = {}) {- if (this.busy) return false- this.busy = true- this.error = null- this.changed()- try {- await (await this.client()).call(method, { botId: this.botId, ...body })- await this.load()- return true- } catch (error) {- this.error = message(error)- return false- } finally {- this.busy = false- this.changed()- }- }}/** Who wrote an entry, for its detail line. */@@ -159,17 +117,4 @@ export function authorLabel(entry: MemoryEntry, botName: (id: string | null) =>}}-/** Who made a file's version and why, for its row. */-export function versionLabel(version: MemoryFileVersion, botName: (id: string | null) => string) {- const by = version.author === 'user' ? 'You'- : version.author === 'bot' ? botName(version.authorBot)- : version.author === 'dream' ? 'Dreaming' : 'This computer'- switch (version.cause) {- case 'delete': return `${by} deleted it`- case 'restore': return `${by} brought back a version`- case 'undo': return `${by} undid a change`- default: return `${by} changed it`- }-}-function message(error: unknown) { return error instanceof Error ? error.message : String(error) }diff --git a/apps/desktop/src/renderer/views/bots/HarnessMemorySheet.tsx b/apps/desktop/src/renderer/views/bots/HarnessMemorySheet.tsxdeleted file mode 100644index e0632b25..00000000--- a/apps/desktop/src/renderer/views/bots/HarnessMemorySheet.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { CardForm, CardSection } from '../../components/Controls'-import { Icon } from '../../components/Icon'-import { ModalHeader, SheetPage } from '../../components/Overlay'-import { HStack, IconSlot, VStack } from '../../components/Stack'-import { Text } from '../../components/Text'--/**- * The memory screen's info button beside the harness's own memory switch: what turning it on means. The same text- * as the kit's; the terminal UI says it short in a confirmation before turning it on. `readable`: Codync shows its- * notes (Claude Code's are a file).- */-export function HarnessMemorySheet({ harness, readable }: { harness: string; readable: boolean }) {- const details = [- { icon: 'brain', title: 'A memory of its own', detail: `${harness} keeps notes apart from Codync's memory. It's off by default, so this bot has one memory and you see and change all of it here.` },- { icon: 'square.on.square', title: 'Remembered twice', detail: 'With both on, the bot may save the same thing twice, and the two can disagree after something changes.' },- { icon: 'trash', title: 'Forgetting', detail: `Forgetting something here doesn't remove it from ${harness}'s notes. Codync can't change them.` },- { icon: 'eye', title: 'Where to see it', detail: readable ? `Its notes show read-only under the ${harness} tab.` : `Codync can't show it; look in ${harness} itself.` },- ]- return (- <SheetPage>- <ModalHeader icon="brain" title={`${harness}'s own memory`} />- <CardForm>- <CardSection>- {details.map((d) => (- <HStack key={d.title} align="flex-start" gap={12}>- <IconSlot width={20} tone="secondary" className="memory-info-icon">- <Icon name={d.icon} size={15} />- </IconSlot>- <VStack gap={2} grow>- <span>{d.title}</span>- <Text size="footnote" tone="secondary">{d.detail}</Text>- </VStack>- </HStack>- ))}- </CardSection>- </CardForm>- </SheetPage>- )-}diff --git a/apps/desktop/src/renderer/views/bots/MemoryFiles.tsx b/apps/desktop/src/renderer/views/bots/MemoryFiles.tsxindex b1fe3414..bce85499 100644--- a/apps/desktop/src/renderer/views/bots/MemoryFiles.tsx+++ b/apps/desktop/src/renderer/views/bots/MemoryFiles.tsx@@ -1,104 +1,47 @@import { useEffect, useState, type ReactElement } from 'react'-import { CardForm, CardSection, IconButton, Spinner } from '../../components/Controls'+import { CardForm, CardSection } from '../../components/Controls'import { Icon } from '../../components/Icon'-import { Dialog, ModalHeader } from '../../components/Overlay'-import { useApp, useStore } from '../../store/context'-import { type MemoryFile, type MemoryFileDetail, type MemoryFiles, type MemoryStore, versionLabel } from '../../store/memory-store'-import { Field } from '../marketplace/pieces'+import { ModalHeader } from '../../components/Overlay'+import type { MemoryFile, MemoryFileDetail, MemoryFiles, MemoryStore } from '../../store/memory-store'import { relativeTime } from '../thread/chat-items'-/** What a note sheet opens: a file, or (`name` null) a new one. */-export interface FileTarget { name: string | null; shared: boolean }+/** The note a sheet opens. */+export interface FileTarget { name: string; shared: boolean }-const TEMPLATE = '---\ndescription: When to read this note\n---\n'--/** One layer's long-form notes, as rows under its entries: name, description, size and date, marked past a cap. */-export function fileRows(memory: MemoryStore, files: MemoryFiles, shared: boolean, open: (target: FileTarget) => void): ReactElement[] {- const folder = shared ? files.yours : files.bot- const live = folder.files.filter((f) => !f.deleted)- const gone = folder.files.filter((f) => f.deleted)+/** One layer's long-form notes, as rows under its entries: name, description, size and date, marked past a cap. Read-only: the bot writes them. */+export function fileRows(files: MemoryFiles, shared: boolean, open: (target: FileTarget) => void): ReactElement[] {+ const live = (shared ? files.yours : files.bot).files.filter((f) => !f.deleted)return [- <div key="notes" className="memory-notes-header">- <span>Notes</span>- <IconButton title="New note" icon="doc.badge.plus" disabled={memory.busy} onClick={() => open({ name: null, shared })} />- </div>,+ <p key="notes" className="memory-notes-header">Notes</p>,...(live.length === 0 ? [<p key="notes-empty" className="memory-muted">Longer notes, one topic each. The bot reads one when its topic comes up.</p>] : []),- ...(live.length > files.folderCap ? [<p key="notes-cap" className="memory-attention">{live.length} notes, over the {files.folderCap}-note cap. Merge some.</p>] : []),- ...[...live, ...gone].map((file) => <FileRow key={file.name} file={file} cap={files.cap} open={() => open({ name: file.name, shared })} />),+ ...(live.length > files.folderCap ? [<p key="notes-cap" className="memory-attention">{live.length} notes, over the {files.folderCap}-note cap. Ask the bot to merge some.</p>] : []),+ ...live.map((file) => <FileRow key={file.name} file={file} cap={files.cap} open={() => open({ name: file.name, shared })} />),]}function FileRow({ file, cap, open }: { file: MemoryFile; cap: number; open: () => void }) {- const over = !file.deleted && file.tokens > cap+ const over = file.tokens > capreturn <button className="press memory-content fade-in" onClick={open}>- <strong className={file.deleted ? 'memory-archived' : undefined}><Icon name={file.deleted ? 'doc' : 'doc.text'} size={11} />{file.name}</strong>- {file.description && !file.deleted ? <span className="memory-muted">{file.description}</span> : null}+ <strong><Icon name="doc.text" size={11} />{file.name}</strong>+ {file.description ? <span className="memory-muted">{file.description}</span> : null}<small className={over ? 'memory-attention' : undefined}>- {file.deleted ? `Deleted ${relativeTime.day(file.updatedAt)}` : `${file.tokens} tokens${over ? `, over the ${cap} cap` : ''} · ${relativeTime.day(file.updatedAt)}`}+ {file.tokens} tokens{over ? `, over the ${cap} cap` : ''} · {relativeTime.day(file.updatedAt)}</small></button>}-/** One note: read it, edit it, open it in an editor, delete it, or bring back an earlier version. */-export function MemoryFileSheet({ memory, target, onClose }: { memory: MemoryStore; target: FileTarget; onClose: () => void }) {- const host = useStore()- // A note opens in an editor only when the host is this computer.- const local = useApp().local === host+/** One note, to read. */+export function MemoryFileSheet({ memory, target }: { memory: MemoryStore; target: FileTarget }) {const [detail, setDetail] = useState<MemoryFileDetail | null>(null)- const [draft, setDraft] = useState<string | null>(target.name ? null : TEMPLATE)- const [name, setName] = useState('')- const [confirmDelete, setConfirmDelete] = useState(false)- useEffect(() => {- if (target.name) void memory.file(target.name, target.shared).then(setDetail)- }, [memory, target])-- const validName = /^[a-z0-9-]+\.md$/.test(name)- const change = async (change: { content?: string; version?: number }) => {- const file = target.name ?? name- const ok = await memory.changeFile(file, target.shared, target.name ? detail?.hash ?? null : null, change)- if (!ok) return- if (!target.name || (change.content === undefined && change.version === undefined)) return onClose()- setDraft(null)- setDetail(await memory.file(file, target.shared))- }-- const actions = memory.busy ? <Spinner /> : draft !== null- ? <IconButton title="Save" icon="checkmark" disabled={!draft.trim() || (!target.name && !validName)} onClick={() => void change({ content: draft })} />- : detail?.content != null ? <div className="memory-header-actions">- <IconButton title="Edit" icon="pencil" onClick={() => setDraft(detail.content)} />- {local ? <IconButton title="Open in your editor" icon="arrow.up.right.square" onClick={() => window.codync.app.openMemoryFile(detail.path)} /> : null}- <IconButton title="Delete" icon="trash" onClick={() => setConfirmDelete(true)} />- </div> : null+ useEffect(() => { void memory.file(target.name, target.shared).then(setDetail) }, [memory, target])return <div className="memory-file-sheet">- <ModalHeader title={target.name ?? 'New note'} trailing={actions} />+ <ModalHeader title={target.name} /><CardForm>{memory.error ? <CardSection><p role="alert" className="memory-error">{memory.error}</p></CardSection> : null}- {draft !== null ? <>- {!target.name ? <CardSection footer="Lowercase letters, digits and dashes, ending in .md.">- <Field value={name} onChange={setName} placeholder="people.md" label="File name" mono />- </CardSection> : null}- <CardSection footer="The description: line says when the bot should read it.">- <Field value={draft} onChange={setDraft} label="Note" lines={[12, 32]} mono />- </CardSection>- </> : detail ? <>- <CardSection footer={detail.path}>- {detail.content != null ? <pre className="memory-file-text">{detail.content}</pre> : <p className="memory-muted">Deleted. Bring back a version below.</p>}- </CardSection>- <CardSection title="Versions">- {detail.versions.map((version) => <div key={version.id} className="memory-item">- <div className="memory-content">- <span>{versionLabel(version, (id) => host.authorName(id))}</span>- <small>{relativeTime.day(version.at)}</small>- </div>- {version.content != null && version.content !== detail.content- ? <IconButton title="Bring back this version" icon="arrow.uturn.backward" disabled={memory.busy} onClick={() => void change({ version: version.id })} />- : null}- </div>)}- </CardSection>- </> : <CardSection><p className="memory-muted">Loading…</p></CardSection>}+ {detail+ ? <CardSection footer={detail.path}><pre className="memory-file-text">{detail.content ?? 'Deleted.'}</pre></CardSection>+ : <CardSection><p className="memory-muted">Loading…</p></CardSection>}</CardForm>- <Dialog open={confirmDelete} title={`Delete ${target.name ?? 'this note'}?`} message="Its versions stay, so you can bring it back."- actions={[{ title: 'Delete', destructive: true, action: () => void change({}) }]} onClose={() => setConfirmDelete(false)} /></div>}diff --git a/apps/desktop/src/renderer/views/bots/MemoryInfoSheet.tsx b/apps/desktop/src/renderer/views/bots/MemoryInfoSheet.tsxnew file mode 100644index 00000000..b313c251--- /dev/null+++ b/apps/desktop/src/renderer/views/bots/MemoryInfoSheet.tsx@@ -0,0 +1,50 @@+import { CardForm, CardSection } from '../../components/Controls'+import { Icon } from '../../components/Icon'+import { ModalHeader, SheetPage } from '../../components/Overlay'+import { HStack, IconSlot, VStack } from '../../components/Stack'+import { Text } from '../../components/Text'++interface Point { icon: string; title: string; detail: string }++/** What the harness's own memory switch means. `readable`: Codync shows its notes (Claude Code's are a file). */+export function harnessInfo(harness: string, readable: boolean): Point[] {+ return [+ { icon: 'brain', title: 'A memory of its own', detail: `${harness} keeps notes apart from Codync's memory. It's off by default, so this bot has one memory and you see all of it here.` },+ { icon: 'square.on.square', title: 'Remembered twice', detail: 'With both on, the bot may save the same thing twice, and the two can disagree after something changes.' },+ { icon: 'trash', title: 'Forgetting', detail: `What the bot forgets in Codync stays in ${harness}'s notes. Codync can't change them.` },+ { icon: 'eye', title: 'Where to see it', detail: readable ? `Its notes show read-only under the ${harness} tab.` : `Codync can't show it; look in ${harness} itself.` },+ ]+}++/** What dreaming does, beside its read-only log. */+export const dreamsInfo: Point[] = [+ { icon: 'moon', title: 'Tidying between chats', detail: 'After five quiet minutes or eight messages, the bot reads what you said since its last run and updates its memory.' },+ { icon: 'plus.circle', title: 'Adds and archives', detail: 'Green lines are memories it added. Red lines are ones it archived because they went out of date or moved into a note. It can also add a line to a note.' },+ { icon: 'text.bubble', title: 'Only your words', detail: "What it adds quotes something you typed yourself; pasted text, the bot's replies and other bots don't count. It never changes what you wrote. It may also put a passed date in the past tense, or move a detail into a note when memory is full." },+ { icon: 'lock.shield', title: 'Kept apart', detail: 'It runs in its own session, away from the chat, and fixed checks decide what it may save.' },+ { icon: 'eye', title: 'A record', detail: 'This tab only shows what it did. To change a memory, tell the bot.' },+]++/** The memory screen's info buttons: a title and what to know, one point per row. The same text as the kit's; the terminal UI says it short in place. */+export function MemoryInfoSheet({ icon, title, points }: { icon: string; title: string; points: Point[] }) {+ return (+ <SheetPage>+ <ModalHeader icon={icon} title={title} />+ <CardForm>+ <CardSection>+ {points.map((d) => (+ <HStack key={d.title} align="flex-start" gap={12}>+ <IconSlot width={20} tone="secondary" className="memory-info-icon">+ <Icon name={d.icon} size={15} />+ </IconSlot>+ <VStack gap={2} grow>+ <span>{d.title}</span>+ <Text size="footnote" tone="secondary">{d.detail}</Text>+ </VStack>+ </HStack>+ ))}+ </CardSection>+ </CardForm>+ </SheetPage>+ )+}diff --git a/apps/desktop/src/renderer/views/bots/MemoryView.tsx b/apps/desktop/src/renderer/views/bots/MemoryView.tsxindex 8f3b6121..29d43af8 100644--- a/apps/desktop/src/renderer/views/bots/MemoryView.tsx+++ b/apps/desktop/src/renderer/views/bots/MemoryView.tsx@@ -1,31 +1,32 @@import { useEffect, useMemo, useState } from 'react'-import { Button, CardSection, DropdownMenu, IconButton, Switch, TabChoice } from '../../components/Controls'+import { CardSection, IconButton, Switch, TabChoice } from '../../components/Controls'import { Icon } from '../../components/Icon'-import { Dialog, ModalHeader, Sheet } from '../../components/Overlay'+import { Sheet } from '../../components/Overlay'import { HStack } from '../../components/Stack'+import { Text } from '../../components/Text'import { useModel } from '../../lib/observable'import { useStore } from '../../store/context'import { useScreenViewed } from '../../store/analytics'import { MemoryStore, authorLabel, type MemoryEntry } from '../../store/memory-store'import { FormSheet } from '../marketplace/pieces'import { relativeTime } from '../thread/chat-items'-import { HarnessMemorySheet } from './HarnessMemorySheet'+import { MemoryInfoSheet, dreamsInfo, harnessInfo } from './MemoryInfoSheet'import { type FileTarget, MemoryFileSheet, fileRows } from './MemoryFiles'import './memory.css'type Section = 'yours' | 'bot' | 'dreams' | 'harness'+/** What an info button explains. */+type Info = 'harness' | 'dreams'-/** A bot's memory: what all your bots know about you, what this one knows, its dreams, and its harness's own notes when the user kept them on. */+/** A bot's memory, read-only: what all your bots know about you, what this one knows, its dreams, and its harness's own notes when the user kept them on. The user changes memory by telling the bot. */export function MemoryCard({ botId }: { botId: string }) {const host = useStore()const memory = useModel(useMemo(() => new MemoryStore(botId, () => host.ready()), [botId, host]))useScreenViewed('memory')const bot = host.bots.get(botId)const [section, setSection] = useState<Section>('bot')- const [draft, setDraft] = useState<{ id?: number; text: string } | null>(null)- const [confirmClear, setConfirmClear] = useState(false)const [file, setFile] = useState<FileTarget | null>(null)- const [aboutHarness, setAboutHarness] = useState(false)+ const [info, setInfo] = useState<Info | null>(null)// Memory changes anywhere move the bot's `memoryRev`: fetch again.useEffect(() => { void memory.load() }, [memory, bot?.memoryRev, bot?.sharedMemory, bot?.harnessMemory])@@ -38,10 +39,6 @@ export function MemoryCard({ botId }: { botId: string }) {...(view?.projectMemory ? [{ id: 'harness' as const, label: harness }] : []),]const layer = section === 'yours' ? view?.yours : section === 'bot' ? view?.bot : undefined- const save = () => {- if (!draft?.text.trim()) return- void memory.mutate('saveMemory', { id: draft.id, shared: section === 'yours', text: draft.text.trim() }).then((ok) => { if (ok) setDraft(null) })- }return <><div className="memory-panel">@@ -53,45 +50,36 @@ export function MemoryCard({ botId }: { botId: string }) {<CardSection>{memory.error && <p role="alert" className="memory-error">{memory.error}</p>}{!view && !memory.error && <p className="memory-muted">Loading memory…</p>}- {view && bot && section === 'yours' && <Switch on={bot.sharedMemory} disabled={memory.busy} onChange={(on) => host.setSharedMemory(bot, on)}>+ {view && bot && section === 'yours' && <Switch on={bot.sharedMemory} onChange={(on) => host.setSharedMemory(bot, on)}>Use what your bots share</Switch>}{view && bot && section === 'bot' && bot.harnessMemory !== null && <HStack gap={4}><span>{harness}'s own memory</span>- <IconButton title={`About ${harness}'s own memory`} icon="info.circle" onClick={() => setAboutHarness(true)} />- <Switch on={bot.harnessMemory} disabled={memory.busy} onChange={(on) => host.setHarnessMemory(bot, on)} label={`${harness}'s own memory`} className="memory-harness-switch" />+ <IconButton title={`About ${harness}'s own memory`} icon="info.circle" onClick={() => setInfo('harness')} />+ <Switch on={bot.harnessMemory} onChange={(on) => host.setHarnessMemory(bot, on)} label={`${harness}'s own memory`} className="memory-harness-switch" /></HStack>}{layer && [- <div key="note" className="memory-layer-note">- <p className="memory-muted">{section === 'yours'- ? 'Your name, time zone, people and lasting preferences, shared by your bots.'- : 'What this bot learned about you.'} {layer.used} of {layer.cap} in use.</p>- <div className="memory-header-actions">- <IconButton title="Add memory" icon="plus" onClick={() => setDraft({ text: '' })} disabled={memory.busy} />- <DropdownMenu className="icon-button memory-menu" title="More" items={() => [- { title: 'Refresh', icon: 'arrow.clockwise', action: () => void memory.load() },- { title: 'Forget everything here', icon: 'trash', destructive: true, divider: true, action: () => setConfirmClear(true) },- ]}><Icon name="ellipsis" size={14} weight="medium" /></DropdownMenu>- </div>- </div>,+ <p key="note" className="memory-muted">{section === 'yours'+ ? 'Your name, time zone, people and lasting preferences, shared by your bots.'+ : 'What this bot learned about you.'} {layer.used} of {layer.cap} in use. To change it, tell the bot.</p>,...(layer.entries.length ? [] : [<div key="empty" className="memory-empty"><Icon name="brain" size={20} color="var(--tertiary)" />- <span>{section === 'yours' ? 'Nothing shared yet.' : 'Nothing yet. What this bot learns about you shows up here, and you can change any of it.'}</span>+ <span>{section === 'yours' ? 'Nothing shared yet.' : 'Nothing yet. What this bot learns about you shows up here.'}</span></div>]),- ...layer.entries.map((entry) => <EntryRow key={entry.id} entry={entry} memory={memory} edit={() => setDraft({ id: entry.id, text: entry.text })} />),- ...(view?.files ? fileRows(memory, view.files, section === 'yours', setFile) : []),+ ...layer.entries.map((entry) => <EntryRow key={entry.id} entry={entry} />),+ ...(view?.files ? fileRows(view.files, section === 'yours', setFile) : []),]}{view && section === 'dreams' && [- <p key="note" className="memory-muted">Between chats the bot tidies its memory from your own words. Each run can be undone.</p>,+ <div key="note" className="memory-layer-note">+ <p className="memory-muted">Between chats the bot tidies its memory from your own words.</p>+ <IconButton title="About dreaming" icon="info.circle" onClick={() => setInfo('dreams')} />+ </div>,...(view.dreams.length ? [] : [<div key="empty" className="memory-empty"><Icon name="moon" size={20} color="var(--tertiary)" /><span>No dreams yet.</span></div>]),- ...view.dreams.map((dream) => <div className="memory-item fade-in" key={dream.id}>- <div className="memory-content">- <strong>{relativeTime.day(dream.at)}{dream.undone ? ' · undone' : ''}</strong>- {dream.added.map((c) => <span key={`a${c.id}`} className="line-clamp memory-clamp" title={c.text}>+ {c.text}</span>)}- {dream.archived.map((c) => <span key={`r${c.id}`} className="line-clamp memory-clamp memory-archived" title={c.text}>− {c.text}</span>)}- {(dream.files ?? []).map((f) => <span key={`f${f.version}`} className="memory-muted">Added to {f.name}</span>)}- </div>- {!dream.undone && <IconButton title="Undo this dream" icon="arrow.uturn.backward" disabled={memory.busy} onClick={() => void memory.mutate('undoDream', { id: dream.id })} />}+ ...view.dreams.map((dream) => <div className="memory-content fade-in" key={dream.id}>+ <strong>{relativeTime.day(dream.at)}{dream.undone ? ' · undone' : ''}</strong>+ {dream.added.map((c) => <Text key={`a${c.id}`} tone="added" className="line-clamp memory-clamp" title={c.text}>+ {c.text}</Text>)}+ {dream.archived.map((c) => <Text key={`r${c.id}`} tone="removed" className="line-clamp memory-clamp" title={c.text}>− {c.text}</Text>)}+ {(dream.files ?? []).map((f) => <span key={`f${f.version}`} className="memory-muted">Added to {f.name}</span>)}</div>),]}{view?.projectMemory && section === 'harness' && <div className="memory-content">@@ -103,42 +91,21 @@ export function MemoryCard({ botId }: { botId: string }) {</div>}</CardSection></div>- <Sheet open={draft !== null} onClose={() => setDraft(null)} width={520}>- <ModalHeader icon="brain" title={draft?.id ? 'Edit memory' : section === 'yours' ? 'Add to what your bots share' : 'Add memory'} />- {draft && <div className="memory-editor">- <textarea aria-label="Memory" rows={3} autoFocus placeholder="One short fact" value={draft.text}- onChange={(e) => setDraft({ ...draft, text: e.target.value })}- onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); save() } }} />- {memory.error && <p role="alert" className="memory-error">{memory.error}</p>}- <Button disabled={memory.busy || !draft.text.trim()} onClick={save}>{memory.busy ? 'Saving…' : 'Save'}</Button>- </div>}- </Sheet><Sheet open={file !== null} onClose={() => setFile(null)} width={640}>- {file && <MemoryFileSheet memory={memory} target={file} onClose={() => setFile(null)} />}+ {file && <MemoryFileSheet memory={memory} target={file} />}</Sheet>- <FormSheet open={aboutHarness} onClose={() => setAboutHarness(false)} height={460}>- <HarnessMemorySheet harness={harness} readable={bot?.backend === 'claude'} />+ <FormSheet open={info !== null} onClose={() => setInfo(null)} height={560}>+ {info === 'harness' && <MemoryInfoSheet icon="brain" title={`${harness}'s own memory`} points={harnessInfo(harness, bot?.backend === 'claude')} />}+ {info === 'dreams' && <MemoryInfoSheet icon="moon" title="Dreaming" points={dreamsInfo} />}</FormSheet>- <Dialog open={confirmClear}- title={section === 'yours' ? 'Forget everything your bots share about you?' : 'Forget everything this bot remembers?'}- actions={[{ title: 'Forget everything', destructive: true, action: () => { void memory.mutate('clearMemory', { shared: section === 'yours' }) } }]}- onClose={() => setConfirmClear(false)} /></>}-function EntryRow({ entry, memory, edit }: { entry: MemoryEntry; memory: MemoryStore; edit: () => void }) {+function EntryRow({ entry }: { entry: MemoryEntry }) {const host = useStore()const archived = entry.state === 'archived'- return <div className="memory-item fade-in">- <button className="press memory-content" onClick={edit}>- <strong className={archived ? 'memory-archived' : undefined}>{entry.pinned && <Icon name="pin.fill" size={10} color="var(--secondary)" />}<span className="line-clamp memory-clamp" title={entry.text}>{entry.text}</span></strong>- <small>{authorLabel(entry, (id) => host.authorName(id))} · {relativeTime.day(entry.updatedAt)}{archived ? ' · archived' : ''}</small>- </button>- <DropdownMenu className="icon-button memory-menu" title="Memory actions" items={() => [- { title: 'Edit', icon: 'pencil', action: edit },- { title: entry.pinned ? 'Unpin' : 'Pin', icon: entry.pinned ? 'pin.slash' : 'pin', action: () => void memory.mutate('pinMemory', { id: entry.id, pinned: !entry.pinned }) },- { title: archived ? 'Bring back' : 'Archive', icon: archived ? 'tray.and.arrow.up' : 'archivebox', action: () => void memory.mutate('archiveMemory', { id: entry.id, archived: !archived }) },- { title: 'Forget', icon: 'trash', destructive: true, divider: true, action: () => void memory.mutate('forgetMemory', { id: entry.id }) },- ]}><Icon name="ellipsis" size={14} weight="medium" /></DropdownMenu>+ return <div className="memory-content fade-in">+ <strong className={archived ? 'memory-archived' : undefined}>{entry.pinned && <Icon name="pin.fill" size={10} color="var(--secondary)" />}<span className="line-clamp memory-clamp" title={entry.text}>{entry.text}</span></strong>+ <small>{authorLabel(entry, (id) => host.authorName(id))} · {relativeTime.day(entry.updatedAt)}{archived ? ' · archived' : ''}</small></div>}diff --git a/apps/desktop/src/renderer/views/bots/memory.css b/apps/desktop/src/renderer/views/bots/memory.cssindex 227309da..3a1b8d0b 100644--- a/apps/desktop/src/renderer/views/bots/memory.css+++ b/apps/desktop/src/renderer/views/bots/memory.css@@ -2,28 +2,20 @@.memory-panel > .tab-choice { flex-wrap: wrap; }.memory-layer-note { display: flex; align-items: flex-start; gap: 8px; }.memory-layer-note > p { flex: 1; min-width: 0; }-.memory-header-actions { display: flex; align-items: center; gap: 2px; }-.memory-menu { width: 28px; height: 28px; border-radius: var(--radius-s); }.memory-empty { display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 18px 12px; text-align: center; color: var(--secondary); line-height: 1.45; }-.memory-item { display: flex; align-items: flex-start; gap: 8px; }-.memory-item .memory-menu { margin: -4px -6px 0 0; }.memory-content { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; text-align: left; }.memory-content strong { display: flex; align-items: center; gap: 6px; font-weight: 500; overflow-wrap: anywhere; }.memory-content span { white-space: pre-wrap; overflow-wrap: anywhere; }.memory-content small, .memory-muted { color: var(--secondary); }.memory-archived { color: var(--tertiary); }-/* A long memory stops at a few lines, more the taller the details panel is (width just rewraps it); its tooltip and editor show the rest. */+/* A long memory stops at a few lines, more the taller the details panel is (width just rewraps it); its tooltip shows the rest. */.memory-clamp { -webkit-line-clamp: 3; }@container details (max-height: 599px) { .memory-clamp { -webkit-line-clamp: 2; } }@container details (min-height: 800px) { .memory-clamp { -webkit-line-clamp: 5; } }@container details (min-height: 1100px) { .memory-clamp { -webkit-line-clamp: 8; } }-.memory-editor { display: flex; flex-direction: column; gap: 14px; padding: 8px 20px 20px; max-height: 70vh; overflow: auto; }-.memory-editor textarea { padding: 9px 12px; background: var(--bubble-user); color: var(--text); border: 0; border-radius: var(--radius-s); font: inherit; line-height: 1.4; field-sizing: content; min-height: calc(3lh + 18px); max-height: calc(10lh + 18px); }-.memory-editor textarea:focus { outline: 2px solid rgba(var(--text-rgb), 0.3); }-.memory-editor > .styled-button { align-self: flex-end; }.memory-history { white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; user-select: text; margin: 0; }.memory-error { color: var(--danger); white-space: pre-wrap; }-.memory-notes-header { display: flex; align-items: center; justify-content: space-between; color: var(--secondary); font-size: var(--text-callout); font-weight: 600; }+.memory-notes-header { margin: 0; color: var(--secondary); font-size: var(--text-callout); font-weight: 600; }.memory-attention { color: var(--attention); }.memory-file-sheet { display: flex; flex-direction: column; height: 100%; background: var(--background); }.memory-file-text { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; user-select: text; font: var(--text-callout)/1.5 var(--mono); }diff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.tsindex 282a260e..4c3c0e3a 100644--- a/apps/desktop/src/shared/ipc.ts+++ b/apps/desktop/src/shared/ipc.ts@@ -198,8 +198,6 @@ export interface CodyncBridge {/** Error tracking: an uncaught error in this window (shared/error-report.ts). */reportError(report: ErrorReport): voidopenExternal(url: string): void- /** A long-form memory note in the user's editor; only paths inside a memory folder open. */- openMemoryFile(path: string): voidcopy(text: string): void/** Files picked in the system dialog: name and bytes. */pickFiles(): Promise<{ name: string; data: Uint8Array }[]>diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Memory.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Memory.swiftindex 4b3c6464..5d693f8e 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Memory.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Memory.swift@@ -23,7 +23,7 @@ public struct MemoryLayer: Decodable, Hashable, Sendable {public var cap: Int}-/// One dreaming run: what it added and archived. It can be undone.+/// One dreaming run: what it added and archived (`undone` when an older app undid it).public struct DreamRun: Decodable, Identifiable, Hashable, Sendable {public struct Change: Decodable, Hashable, Sendable {public var id: Int64@@ -77,9 +77,4 @@ extension HostClient {public func memory(botId: String) async throws -> MemoryView {try await call("memory", ["botId": botId])}-- /// A memory method on one bot (`saveMemory`, `pinMemory`, `archiveMemory`, `forgetMemory`, `clearMemory`, `undoDream`).- public func memoryCall(_ method: String, _ body: some Encodable) async throws {- let _: Empty = try await call(method, body)- }}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/MemoryFiles.swift b/apps/ios/Kit/Sources/CodyncKit/Models/MemoryFiles.swiftindex fd72aba8..897c9cb4 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/MemoryFiles.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/MemoryFiles.swift@@ -5,8 +5,6 @@ public struct MemoryFile: Decodable, Identifiable, Hashable, Sendable {/// The bot whose folder holds it; nil for what all bots share.public var bot: String?public var name: String- /// SHA-256 of what it holds; a save is made over it.- public var hash: Stringpublic var description: String?public var tokens: Intpublic var deleted: Bool@@ -32,29 +30,13 @@ public struct MemoryFiles: Decodable, Hashable, Sendable {public var folderCap: Int}-/// One version of a file: who made it, why, and what it held then.-public struct MemoryFileVersion: Decodable, Identifiable, Hashable, Sendable {- public var id: Int64- /// nil: the file was deleted.- public var content: String?- /// user · bot · dream · computer- public var author: String- public var authorBot: String?- /// edit · delete · restore · undo · dream- public var cause: String- public var at: Int64-}--/// A file as it is on disk now, with its recent versions.+/// A file as it is on disk now.public struct MemoryFileDetail: Decodable, Hashable, Sendable {public var file: Stringpublic var shared: Bool/// nil when the file is gone.public var content: String?- /// The hash to save over; nil when the file is gone.- public var hash: String?public var path: String- public var versions: [MemoryFileVersion]}extension HostClient {@@ -62,15 +44,4 @@ extension HostClient {struct Body: Encodable { var botId: String; var file: String; var shared: Bool }return try await call("memoryFile", Body(botId: botId, file: file, shared: shared))}-- /// Saves (`content`), deletes (`content` and `version` nil) or brings back a version of a file, over the content- /// whose hash is `base` (nil: a new file).- public func changeMemoryFile(botId: String, file: String, shared: Bool, base: String?, content: String? = nil,- version: Int64? = nil) async throws {- struct Body: Encodable {- var botId: String; var file: String; var shared: Bool; var base: String?; var content: String?; var version: Int64?- }- let method = version != nil ? "restoreMemoryFile" : content != nil ? "saveMemoryFile" : "deleteMemoryFile"- let _: Empty = try await call(method, Body(botId: botId, file: file, shared: shared, base: base, content: content, version: version))- }}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/HarnessMemorySheet.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/HarnessMemorySheet.swiftdeleted file mode 100644index 4600dc7e..00000000--- a/apps/ios/Kit/Sources/CodyncUI/Bots/HarnessMemorySheet.swift+++ /dev/null@@ -1,43 +0,0 @@-import CodyncKit-import SwiftUI--/// The memory screen's info button beside the harness's own memory switch: what turning it on means. The same-/// text as the desktop app's; the terminal UI says it short in a confirmation before turning it on.-struct HarnessMemorySheet: View {- /// The harness's name ("Claude Code").- let harness: String- /// Whether Codync can show the harness's notes (Claude Code's are a file on the computer).- let readable: Bool-- private var details: [(icon: String, title: String, detail: String)] {- [("brain", "A memory of its own", "\(harness) keeps notes apart from Codync's memory. It's off by default, so this bot has one memory and you see and change all of it here."),- ("square.on.square", "Remembered twice", "With both on, the bot may save the same thing twice, and the two can disagree after something changes."),- ("trash", "Forgetting", "Forgetting something here doesn't remove it from \(harness)'s notes. Codync can't change them."),- ("eye", "Where to see it", readable ? "Its notes show read-only under the \(harness) tab." : "Codync can't show it; look in \(harness) itself.")]- }-- var body: some View {- VStack(spacing: 0) {- ModalHeader("\(harness)'s own memory")- CardForm {- CardSection {- ForEach(details, id: \.title) { item in- HStack(alignment: .firstTextBaseline, spacing: 12) {- Image(systemName: item.icon)- .foregroundStyle(Palette.secondary)- .frame(width: 22)- VStack(alignment: .leading, spacing: 2) {- Text(item.title)- Text(item.detail)- .font(.footnote)- .foregroundStyle(Palette.secondary)- .fixedSize(horizontal: false, vertical: true)- }- }- }- }- }- }- .background(Palette.background)- }-}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryEditorView.swiftdeleted file mode 100644index 4b970128..00000000--- a/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryEditorView.swift+++ /dev/null@@ -1,48 +0,0 @@-import CodyncKit-import SwiftUI--/// Writes one memory: a new one, or a change to an entry.-struct MemoryEditorView: View {- let memory: MemoryStore- let target: MemoryEditTarget- @State private var text: String- @Environment(\.dismissModal) private var dismiss-- init(memory: MemoryStore, target: MemoryEditTarget) {- self.memory = memory- self.target = target- _text = State(initialValue: target.text)- }-- var body: some View {- VStack(spacing: 0) {- ModalHeader(target.entry != nil ? "Edit memory" : target.shared ? "Add to what your bots share" : "Add memory") { EmptyView() }- VStack(alignment: .leading, spacing: 16) {- TextField("One short fact", text: $text, axis: .vertical)- .lineLimit(2...6)- .textFieldStyle(.plain)- .padding(12)- .background(Palette.surface, in: RoundedRectangle(cornerRadius: 12))- if let error = memory.error { Text(error).foregroundStyle(Palette.danger) }- Button(memory.busy ? "Saving…" : "Save") {- Task {- let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)- if await memory.mutate("saveMemory", id: target.entry, shared: target.shared, text: trimmed) { dismiss() }- }- }- .buttonStyle(PrimaryButtonStyle())- .disabled(memory.busy || text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)- }- .padding(20)- Spacer(minLength: 0)- }- }-}--/// What the editor opens on: an entry (`entry`), or a new one in a layer.-struct MemoryEditTarget: Identifiable {- let id = UUID()- let entry: Int64?- let shared: Bool- let text: String-}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryFilesView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryFilesView.swiftindex cdfeebc7..54b7cb2b 100644--- a/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryFilesView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryFilesView.swift@@ -1,7 +1,8 @@import CodyncKitimport SwiftUI-/// One layer's long-form notes, under its entries: name, description, size and date, marked past a cap.+/// One layer's long-form notes, under its entries: name, description, size and date, marked past a cap. Read-only:+/// the bot writes them.struct MemoryFilesList: View {let memory: MemoryStorelet files: MemoryFiles@@ -10,28 +11,19 @@ struct MemoryFilesList: View {@Environment(\.noteLines) private var noteLinesvar body: some View {- let folder = shared ? files.yours : files.bot- let live = folder.files.filter { !$0.deleted }- let gone = folder.files.filter(\.deleted)- HStack(spacing: 8) {- Text("Notes").font(.footnote.weight(.semibold)).foregroundStyle(Palette.secondary)- Spacer(minLength: 0)- IconButton("New note", systemImage: "doc.badge.plus") {- withAnimation(Motion.layout) { open = MemoryFileTarget(name: nil, shared: shared) }- }- .disabled(memory.busy)- }- .padding(.top, 6)- .codyncSheet(item: $open) { target in MemoryFileView(memory: memory, target: target) }+ let live = (shared ? files.yours : files.bot).files.filter { !$0.deleted }+ Text("Notes").font(.footnote.weight(.semibold)).foregroundStyle(Palette.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.top, 6)+ .codyncSheet(item: $open) { target in MemoryFileView(memory: memory, target: target) }if live.isEmpty {Text("Longer notes, one topic each. The bot reads one when its topic comes up.").font(.footnote).foregroundStyle(Palette.tertiary)} else if live.count > files.folderCap {- Text("\(live.count) notes, over the \(files.folderCap)-note cap. Merge some.")+ Text("\(live.count) notes, over the \(files.folderCap)-note cap. Ask the bot to merge some.").font(.footnote).foregroundStyle(Palette.attention)}ForEach(live) { file in row(file, cap: files.cap) }- ForEach(gone) { file in row(file, cap: files.cap) }}private func row(_ file: MemoryFile, cap: Int) -> some View {@@ -39,14 +31,13 @@ struct MemoryFilesList: View {withAnimation(Motion.layout) { open = MemoryFileTarget(name: file.name, shared: shared) }} label: {VStack(alignment: .leading, spacing: 4) {- Label(file.name, systemImage: file.deleted ? "doc" : "doc.text")- .foregroundStyle(file.deleted ? Palette.tertiary : Palette.text)- if let description = file.description, !file.deleted {+ Label(file.name, systemImage: "doc.text")+ if let description = file.description {Text(description).font(.footnote).foregroundStyle(Palette.secondary).lineLimit(noteLines)}- Text(caption(file, cap: cap))+ Text("\(file.tokens) tokens\(file.tokens > cap ? ", over the \(cap) cap" : "") · \(Date(milliseconds: file.updatedAt).formatted(.relative(presentation: .named)))").font(.caption)- .foregroundStyle(file.tokens > cap && !file.deleted ? Palette.attention : Palette.secondary)+ .foregroundStyle(file.tokens > cap ? Palette.attention : Palette.secondary)}.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())@@ -54,157 +45,41 @@ struct MemoryFilesList: View {.buttonStyle(.plain).padding(.vertical, 6)}-- private func caption(_ file: MemoryFile, cap: Int) -> String {- let when = Date(milliseconds: file.updatedAt).formatted(.relative(presentation: .named))- if file.deleted { return "Deleted \(when)" }- return "\(file.tokens) tokens\(file.tokens > cap ? ", over the \(cap) cap" : "") · \(when)"- }}-/// What a note sheet opens: a file, or (`name` nil) a new one.+/// The note a sheet opens.struct MemoryFileTarget: Identifiable {- let id = UUID()- let name: String?+ let name: Stringlet shared: Bool+ var id: String { "\(shared)-\(name)" }}-/// One note: read it, edit it, delete it, or bring back an earlier version.+/// One note, to read.struct MemoryFileView: View {let memory: MemoryStorelet target: MemoryFileTarget@State private var detail: MemoryFileDetail?- /// Editing, with the text being edited. Not an optional binding: the editor still reads it while it animates out.- @State private var editing = false- @State private var draft = ""- @State private var name = ""- @State private var confirmDelete = false- @Environment(BotStore.self) private var host- @Environment(\.dismissModal) private var dismiss-- private static let template = "---\ndescription: When to read this note\n---\n"var body: some View {VStack(spacing: 0) {- ModalHeader(target.name ?? "New note") { actions }+ ModalHeader(target.name)CardForm {if let error = memory.error {CardSection { Text(error).foregroundStyle(Palette.danger).textSelection(.enabled) }}- if editing {- editor- } else if let detail {- reader(detail)+ if let detail {+ CardSection(footer: detail.path) {+ Text(detail.content ?? "Deleted.")+ .font(.footnote.monospaced())+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ }} else {CardSection { Text("Loading…").foregroundStyle(Palette.secondary) }}}}.background(Palette.background)- .task {- if let file = target.name {- detail = await memory.file(file, shared: target.shared)- } else {- draft = Self.template- editing = true- }- }- .codyncDialog("Delete \(target.name ?? "this note")?", isPresented: $confirmDelete,- message: "Its versions stay, so you can bring it back.") {- [DialogAction("Delete", destructive: true) {- Task { await change(content: nil) }- }]- }- }-- @ViewBuilder private var actions: some View {- if memory.busy {- Spinner()- } else if editing {- IconButton("Save", systemImage: "checkmark") { Task { await change(content: draft) } }- .disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || (target.name == nil && !validName))- } else if let detail, let content = detail.content {- HStack(spacing: 2) {- IconButton("Edit", systemImage: "pencil") {- draft = content- withAnimation(Motion.layout) { editing = true }- }- IconButton("Delete", systemImage: "trash") { withAnimation(Motion.layout) { confirmDelete = true } }- }- }- }-- private var validName: Bool { name.range(of: #"^[a-z0-9-]+\.md$"#, options: .regularExpression) != nil }-- @ViewBuilder private var editor: some View {- if target.name == nil {- CardSection(footer: "Lowercase letters, digits and dashes, ending in .md.") {- TextField("people.md", text: $name)- .textInputAutocapitalization(.never)- .autocorrectionDisabled()- }- }- CardSection(footer: "The description: line says when the bot should read it.") {- TextField("", text: $draft, axis: .vertical)- .lineLimit(12...40)- .font(.footnote.monospaced())- }- .textFieldStyle(.plain)- }-- @ViewBuilder private func reader(_ detail: MemoryFileDetail) -> some View {- CardSection(footer: detail.path) {- if let content = detail.content {- Text(content).font(.footnote.monospaced()).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)- } else {- Text("Deleted. Bring back a version below.").foregroundStyle(Palette.secondary)- }- }- CardSection("Versions") {- ForEach(detail.versions) { version in- HStack(spacing: 8) {- VStack(alignment: .leading, spacing: 2) {- Text(who(version))- Text(Date(milliseconds: version.at).formatted(.relative(presentation: .named)))- .font(.caption).foregroundStyle(Palette.secondary)- }- .frame(maxWidth: .infinity, alignment: .leading)- if let content = version.content, content != detail.content {- IconButton("Bring back this version", systemImage: "arrow.uturn.backward") {- Task { await change(version: version.id) }- }- .disabled(memory.busy)- }- }- .padding(.vertical, 4)- }- }- }-- private func who(_ version: MemoryFileVersion) -> String {- let by = switch version.author {- case "user": "You"- case "bot": host.bots[version.authorBot ?? ""]?.name ?? "A bot"- case "dream": "Dreaming"- default: "This computer"- }- return switch version.cause {- case "delete": "\(by) deleted it"- case "restore": "\(by) brought back a version"- case "undo": "\(by) undid a change"- default: "\(by) changed it"- }- }-- /// Saves (`content`), deletes (nil) or restores `version`, over what was loaded.- private func change(content: String? = nil, version: Int64? = nil) async {- let file = target.name ?? name- let base = target.name == nil ? nil : detail?.hash- if await memory.changeFile(file, shared: target.shared, base: base, content: content, version: version) {- if content == nil && version == nil { dismiss(); return }- withAnimation(Motion.layout) { editing = false }- if target.name == nil { dismiss(); return }- detail = await memory.file(file, shared: target.shared)- }+ .task { detail = await memory.file(target.name, shared: target.shared) }}}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryInfoSheet.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryInfoSheet.swiftnew file mode 100644index 00000000..5af35c3e--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryInfoSheet.swift@@ -0,0 +1,58 @@+import CodyncKit+import SwiftUI++/// The memory screen's info buttons: what the harness's own memory switch means, and what dreaming does. The same+/// text as the desktop app's; the terminal UI says it short in place.+struct MemoryInfoSheet: View {+ struct Point {+ let icon: String+ let title: String+ let detail: String+ }++ let title: String+ let points: [Point]++ /// `readable`: Codync can show the harness's notes (Claude Code's are a file on the computer).+ static func harness(_ harness: String, readable: Bool) -> MemoryInfoSheet {+ MemoryInfoSheet(title: "\(harness)'s own memory", points: [+ Point(icon: "brain", title: "A memory of its own", detail: "\(harness) keeps notes apart from Codync's memory. It's off by default, so this bot has one memory and you see all of it here."),+ Point(icon: "square.on.square", title: "Remembered twice", detail: "With both on, the bot may save the same thing twice, and the two can disagree after something changes."),+ Point(icon: "trash", title: "Forgetting", detail: "What the bot forgets in Codync stays in \(harness)'s notes. Codync can't change them."),+ Point(icon: "eye", title: "Where to see it", detail: readable ? "Its notes show read-only under the \(harness) tab." : "Codync can't show it; look in \(harness) itself."),+ ])+ }++ static let dreams = MemoryInfoSheet(title: "Dreaming", points: [+ Point(icon: "moon", title: "Tidying between chats", detail: "After five quiet minutes or eight messages, the bot reads what you said since its last run and updates its memory."),+ Point(icon: "plus.circle", title: "Adds and archives", detail: "Green lines are memories it added. Red lines are ones it archived because they went out of date or moved into a note. It can also add a line to a note."),+ Point(icon: "text.bubble", title: "Only your words", detail: "What it adds quotes something you typed yourself; pasted text, the bot's replies and other bots don't count. It never changes what you wrote. It may also put a passed date in the past tense, or move a detail into a note when memory is full."),+ Point(icon: "lock.shield", title: "Kept apart", detail: "It runs in its own session, away from the chat, and fixed checks decide what it may save."),+ Point(icon: "eye", title: "A record", detail: "This tab only shows what it did. To change a memory, tell the bot."),+ ])++ var body: some View {+ VStack(spacing: 0) {+ ModalHeader(title)+ CardForm {+ CardSection {+ ForEach(points, id: \.title) { item in+ HStack(alignment: .firstTextBaseline, spacing: 12) {+ Image(systemName: item.icon)+ .foregroundStyle(Palette.secondary)+ .frame(width: 22)+ VStack(alignment: .leading, spacing: 2) {+ Text(item.title)+ Text(item.detail)+ .font(.footnote)+ .foregroundStyle(Palette.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+ }+ }+ }+ }+ }+ .background(Palette.background)+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryView.swiftindex 9cdbe283..f7890b0d 100644--- a/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryView.swift@@ -1,25 +1,34 @@import CodyncKitimport SwiftUI-/// A bot's memory: what all your bots know about you, what this one knows, its dreams, and its harness's own notes-/// when the user kept them on.+/// A bot's memory, read-only: what all your bots know about you, what this one knows, its dreams, and its harness's+/// own notes when the user kept them on. The user changes memory by telling the bot.struct MemoryCard: View {let botId: String@Environment(BotStore.self) private var host@Environment(\.verticalSizeClass) private var verticalSizeClass@State private var memory: MemoryStore?@State private var section: Section = .bot- @State private var editor: MemoryEditTarget?- @State private var confirmClear = false- @State private var aboutHarness = false- @State private var openDreams: Set<DreamRun.ID> = []+ @State private var info: Info?+ /// Entries and dreams showing all their lines.+ @State private var unfolded: Set<Fold> = []enum Section: Hashable { case yours, bot, dreams, harness }+ /// What an info button explains.+ enum Info: Identifiable { case harness, dreams; var id: Self { self } }+ /// What a tap unfolds.+ enum Fold: Hashable { case entry(Int64), dream(Int64) }private var bot: Bot? { host.bots[botId] }- /// A long memory stops at a few lines, fewer when the screen is short (landscape); tapping it shows the rest- /// (an entry opens its editor, a dream unfolds).- private var lines: Int { verticalSizeClass == .compact ? 2 : 5 }+ /// A long memory stops at a few lines, fewer when the screen is short (landscape); tapping it shows the rest.+ private func lines(_ key: Fold) -> Int? {+ if unfolded.contains(key) { return nil }+ return verticalSizeClass == .compact ? 2 : 5+ }++ private func unfold(_ key: Fold) {+ withAnimation(Motion.layout) { unfolded.formSymmetricDifference([key]) }+ }var body: some View {VStack(spacing: 10) {@@ -44,17 +53,11 @@ struct MemoryCard: View {.onChange(of: memory?.view.map { $0.projectMemory == nil } ?? false) { _, gone inif gone && section == .harness { section = .bot }}- .codyncSheet(isPresented: $aboutHarness) {- if let bot { HarnessMemorySheet(harness: host.backendName(bot.backend), readable: bot.backend == "claude") }- }- .codyncSheet(item: $editor) { target in- if let memory { MemoryEditorView(memory: memory, target: target) }- }- .codyncDialog(section == .yours ? "Forget everything your bots share about you?" : "Forget everything this bot remembers?",- isPresented: $confirmClear) {- [DialogAction("Forget everything", destructive: true) {- Task { await memory?.mutate("clearMemory", shared: section == .yours) }- }]+ .codyncSheet(item: $info) { info in+ switch info {+ case .harness: if let bot { MemoryInfoSheet.harness(host.backendName(bot.backend), readable: bot.backend == "claude") }+ case .dreams: MemoryInfoSheet.dreams+ }}}@@ -63,7 +66,7 @@ struct MemoryCard: View {if let view = memory.view {switch section {case .yours, .bot: layer(memory, view: view)- case .dreams: dreams(memory, view.dreams)+ case .dreams: dreams(view.dreams)case .harness: harness(view.projectMemory)}} else if memory.error == nil {@@ -88,75 +91,59 @@ struct MemoryCard: View {HStack(spacing: 4) {Text("\(name)'s own memory").lineLimit(1).layoutPriority(1)IconButton("About \(name)'s own memory", systemImage: "info.circle") {- withAnimation(Motion.layout) { aboutHarness = true }+ withAnimation(Motion.layout) { info = .harness }}Toggle(isOn: Binding(get: { on }, set: { host.setHarnessMemory(bot, $0) })) { EmptyView() }.toggleStyle(.codync)- .disabled(memory.busy).accessibilityLabel("\(name)'s own memory")}}- HStack(alignment: .top, spacing: 8) {- Text("\(shared ? "Your name, time zone, people and lasting preferences, shared by your bots." : "What this bot learned about you.") \(layer.used) of \(layer.cap) in use.")- .font(.footnote).foregroundStyle(Palette.secondary)- .frame(maxWidth: .infinity, alignment: .leading)- IconButton("Add memory", systemImage: "plus") {- withAnimation(Motion.layout) { editor = MemoryEditTarget(entry: nil, shared: shared, text: "") }- }- .disabled(memory.busy)- moreMenu(memory)- }+ Text("\(shared ? "Your name, time zone, people and lasting preferences, shared by your bots." : "What this bot learned about you.") \(layer.used) of \(layer.cap) in use. To change it, tell the bot.")+ .font(.footnote).foregroundStyle(Palette.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)if layer.entries.isEmpty {- empty("brain", shared ? "Nothing shared yet." : "Nothing yet. What this bot learns about you shows up here, and you can change any of it.")+ empty("brain", shared ? "Nothing shared yet." : "Nothing yet. What this bot learns about you shows up here.")}ForEach(layer.entries) { entry in- HStack(alignment: .top, spacing: 8) {- Button {- withAnimation(Motion.layout) { editor = MemoryEditTarget(entry: entry.id, shared: shared, text: entry.text) }- } label: {- VStack(alignment: .leading, spacing: 4) {- HStack(alignment: .firstTextBaseline, spacing: 6) {- if entry.pinned { Image(systemName: "pin.fill").font(.caption2).foregroundStyle(Palette.secondary) }- Text(entry.text).foregroundStyle(entry.archived ? Palette.tertiary : Palette.text).lineLimit(lines)- }- Text("\(author(entry)) · \(Date(milliseconds: entry.updatedAt).formatted(.relative(presentation: .named)))\(entry.archived ? " · archived" : "")")- .font(.caption).foregroundStyle(Palette.secondary)- }- .frame(maxWidth: .infinity, alignment: .leading)- .contentShape(Rectangle())+ VStack(alignment: .leading, spacing: 4) {+ HStack(alignment: .firstTextBaseline, spacing: 6) {+ if entry.pinned { Image(systemName: "pin.fill").font(.caption2).foregroundStyle(Palette.secondary) }+ Text(entry.text).foregroundStyle(entry.archived ? Palette.tertiary : Palette.text).lineLimit(lines(.entry(entry.id)))}- .buttonStyle(.plain)- entryMenu(memory, entry, shared: shared)+ Text("\(author(entry)) · \(Date(milliseconds: entry.updatedAt).formatted(.relative(presentation: .named)))\(entry.archived ? " · archived" : "")")+ .font(.caption).foregroundStyle(Palette.secondary)}+ .frame(maxWidth: .infinity, alignment: .leading)+ .contentShape(Rectangle())+ .onTapGesture { unfold(.entry(entry.id)) }.padding(.vertical, 6)}if let files = view.files { MemoryFilesList(memory: memory, files: files, shared: shared) }}- @ViewBuilder private func dreams(_ memory: MemoryStore, _ runs: [DreamRun]) -> some View {- Text("Between chats the bot tidies its memory from your own words. Each run can be undone.")- .font(.footnote).foregroundStyle(Palette.secondary)+ /// What dreaming did.+ @ViewBuilder private func dreams(_ runs: [DreamRun]) -> some View {+ HStack(alignment: .top, spacing: 8) {+ Text("Between chats the bot tidies its memory from your own words.")+ .font(.footnote).foregroundStyle(Palette.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)+ IconButton("About dreaming", systemImage: "info.circle") {+ withAnimation(Motion.layout) { info = .dreams }+ }+ }if runs.isEmpty { empty("moon", "No dreams yet.") }ForEach(runs) { run in- HStack(alignment: .top, spacing: 8) {- VStack(alignment: .leading, spacing: 4) {- Text("\(Date(milliseconds: run.at).formatted(.relative(presentation: .named)))\(run.undone ? " · undone" : "")")- .fontWeight(.semibold)- let limit = openDreams.contains(run.id) ? nil : lines- ForEach(run.added, id: \.id) { Text("+ \($0.text)").lineLimit(limit) }- ForEach(run.archived, id: \.id) { Text("− \($0.text)").foregroundStyle(Palette.tertiary).lineLimit(limit) }- ForEach(run.files ?? [], id: \.version) { Label("Added to \($0.name)", systemImage: "doc.text").foregroundStyle(Palette.secondary) }- }- .frame(maxWidth: .infinity, alignment: .leading)- .contentShape(Rectangle())- .onTapGesture { withAnimation(Motion.layout) { openDreams.formSymmetricDifference([run.id]) } }- if !run.undone {- IconButton("Undo this dream", systemImage: "arrow.uturn.backward") {- Task { await memory.mutate("undoDream", id: run.id) }- }- .disabled(memory.busy)- }+ VStack(alignment: .leading, spacing: 4) {+ Text("\(Date(milliseconds: run.at).formatted(.relative(presentation: .named)))\(run.undone ? " · undone" : "")")+ .fontWeight(.semibold)+ let limit = lines(.dream(run.id))+ ForEach(run.added, id: \.id) { Text("+ \($0.text)").foregroundStyle(Palette.added).lineLimit(limit) }+ ForEach(run.archived, id: \.id) { Text("− \($0.text)").foregroundStyle(Palette.removed).lineLimit(limit) }+ ForEach(run.files ?? [], id: \.version) { Label("Added to \($0.name)", systemImage: "doc.text").foregroundStyle(Palette.secondary) }}+ .frame(maxWidth: .infinity, alignment: .leading)+ .contentShape(Rectangle())+ .onTapGesture { unfold(.dream(run.id)) }.padding(.vertical, 6)}}@@ -188,40 +175,4 @@ struct MemoryCard: View {default: "Moved from the old memory"}}-- private func moreMenu(_ memory: MemoryStore) -> some View {- DropdownMenu {- [MenuItem("Refresh", icon: "arrow.clockwise") { Task { await memory.load() } },- MenuItem("Forget everything here", icon: "trash", destructive: true, divider: true) {- withAnimation(Motion.layout) { confirmClear = true }- }]- } label: { menuLabel("More") }- }-- private func entryMenu(_ memory: MemoryStore, _ entry: MemoryEntry, shared: Bool) -> some View {- DropdownMenu {- [MenuItem("Edit", icon: "pencil") {- withAnimation(Motion.layout) { editor = MemoryEditTarget(entry: entry.id, shared: shared, text: entry.text) }- },- MenuItem(entry.pinned ? "Unpin" : "Pin", icon: entry.pinned ? "pin.slash" : "pin") {- Task { await memory.mutate("pinMemory", id: entry.id, pinned: !entry.pinned) }- },- MenuItem(entry.archived ? "Bring back" : "Archive", icon: entry.archived ? "tray.and.arrow.up" : "archivebox") {- Task { await memory.mutate("archiveMemory", id: entry.id, archived: !entry.archived) }- },- MenuItem("Forget", icon: "trash", destructive: true, divider: true) {- Task { await memory.mutate("forgetMemory", id: entry.id) }- }]- } label: { menuLabel("Memory actions") }- .disabled(memory.busy)- }-- private func menuLabel(_ title: String) -> some View {- Image(systemName: "ellipsis")- .font(.body.weight(.medium))- .foregroundStyle(Palette.secondary)- .frame(width: 32, height: 32)- .contentShape(Rectangle())- .accessibilityLabel(title)- }}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/MemoryStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/MemoryStore.swiftindex f3f76425..5a333c28 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/MemoryStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/MemoryStore.swift@@ -2,13 +2,12 @@ import CodyncKitimport Foundationimport Observation-/// One bot's memory: fetches it, and changes it through the host.+/// One bot's memory, read-only: the bot changes it.@MainActor @Observablefinal class MemoryStore {let botId: Stringprivate let client: () async throws -> HostClientvar view: MemoryView?- var busy = falsevar error: String?private var request = 0@@ -34,7 +33,7 @@ final class MemoryStore {}}- /// A long-form file as it is now, with its versions.+ /// A long-form file as it is now.func file(_ name: String, shared: Bool) async -> MemoryFileDetail? {do {return try await client().memoryFile(botId: botId, file: name, shared: shared)@@ -43,43 +42,4 @@ final class MemoryStore {return nil}}-- /// Saves, deletes (`content` and `version` nil) or brings back a version of a file over what was loaded (`base`);- /// reloads after it.- @discardableResult- func changeFile(_ name: String, shared: Bool, base: String?, content: String? = nil, version: Int64? = nil) async -> Bool {- guard !busy else { return false }- busy = true- error = nil- defer { busy = false }- do {- try await client().changeMemoryFile(botId: botId, file: name, shared: shared, base: base, content: content, version: version)- await load()- return true- } catch {- self.error = error.localizedDescription- return false- }- }-- /// A memory method for this bot; reloads after it.- @discardableResult- func mutate(_ method: String, id: Int64? = nil, pinned: Bool? = nil, archived: Bool? = nil, shared: Bool? = nil,- text: String? = nil) async -> Bool {- guard !busy else { return false }- struct Body: Encodable {- var botId: String; var id: Int64?; var pinned: Bool?; var archived: Bool?; var shared: Bool?; var text: String?- }- busy = true- error = nil- defer { busy = false }- do {- try await client().memoryCall(method, Body(botId: botId, id: id, pinned: pinned, archived: archived, shared: shared, text: text))- await load()- return true- } catch {- self.error = error.localizedDescription- return false- }- }}diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex e057dcf8..5a7bb907 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -10,6 +10,8 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o### zh-Hant- Routine 還沒動手就失敗(例如額度用完)時,會在 1、5、15 分鐘後自動再試;已經動過手或超過時間上限的失敗,通知旁有重試按鈕讓你決定+- Bot 的記憶頁改成唯讀,想改記憶直接跟 bot 說;Dreams 分頁新增的記憶是綠色、封存的是紅色,旁邊的資訊按鈕說明做夢在做什麼### en-US- A routine that fails before doing anything (a usage limit, say) tries again on its own after 1, 5 and 15 minutes; one that already acted or hit its time limit gets a retry button on its failure notice, so you decide+- A bot's memory is now read-only: to change it, tell the bot. In the Dreams tab, added memories show in green, archived ones in red, and an info button explains what dreaming doesdiff --git a/docs/design/bot-memory.md b/docs/design/bot-memory.mdindex 316d7482..6c77e1cd 100644--- a/docs/design/bot-memory.md+++ b/docs/design/bot-memory.md@@ -26,7 +26,8 @@ Built differently from the plan below, for now:- Search is a substring scan, not an FTS5 trigram index. Memory has a few hundred entries; the transcript scantook 0.6 s over 180k messages of one bot, so the index waits until a bot's search passes a second.-- No revision history per entry; the dream log and the chat lines carry undo.+- No revision history per entry. Since 2.21.0 the apps show memory read-only; the user changes it by telling the+ bot.- No proposals: since 2026-10-18 every bot writes memory at once, and nothing about memory shows in the chat.- Health, religion and politics get no special notice yet; voice transcripts aren't marked, and group roomsdon't feed dreaming.@@ -389,7 +390,7 @@ run is never overwritten (OpenClaw uses optimistic concurrency the same way).removed") don't do this.- **Time review, daily.** Future tense turns into the past once the date passes. Relative dates become absolute atwrite time.-- **Dream log.** Every run's changes are visible and can be undone in one tap.+- **Dream log.** Every run's changes are visible, read-only since 2.21.0.- **Migrated entries.** Entries imported from Engram or Markdown change only on contrary evidence.### Frozen opening@@ -609,14 +610,12 @@ build.message.- **A per-bot switch** for "yours".- **Bot writes:** nothing in the chat (changed 2026-10-18 at the owner's request: memory lines and cards cluttered the- chat). Every bot writes at once whatever its permission, and the user reviews, edits or forgets in the memory- settings.-- **The dream log** with undo.-- **Entry actions:** edit, pin, forget, and forget everything.+ chat). Every bot writes at once whatever its permission; the user reviews it in the memory settings, which are+ read-only since 2.21.0 (the owner's call: the user changes memory by telling the bot).+- **The dream log** (added green, archived red) with an info button saying what dreaming does.- **The harness's own memory switch** in the bot's section, off by default, with an info button; kept on, Claude Code's `MEMORY.md` shows read-only.- **Long-form memory** under each layer's cards: the files with name, description, size and date, an over-cap- mark, and a detail view to read, edit, and restore any version. The desktop app can open a file in the user's- editor.+ mark, and a view to read one.- **In the chat**, only an editable handoff draft at rollover, folding to one line once sent; compactions and akept handoff leave no line (2026-10-18, at the owner's request).diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex 7d53b6a1..5ca5148d 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -95,7 +95,7 @@ Desktop conversations start with the details inspector closed; the title menu opPreserve the original character avatar design: dotted shading, highlight-only color, silhouettes and animation. Desktop roster avatars remain 30 points and iPhone roster avatars remain 46 points. iPhone shares readable secondary text and message previews; its native navigation remains platform-specific. Terminal avatars already use solid color and the terminal has no persistent details inspector; its secondary text uses the same readable palette.-The details inspector (`apps/desktop/src/renderer/views/thread/DetailsPanel.tsx`) copies Grok Bot's: share (Create template) and close (X) as round buttons in the corner, in the page color with a soft ring, over a 54-point band that drags the window; the bot's 60-point avatar, name and runtime centered on top; then page tabs (`TabChoice`: plain labels, the chosen one on a light capsule) for **Details**, **Memory** and **Settings**, all in one scroll. The chat's `<<` button (in the same ringed style) and the title pill open it; hovering the pill shows a `>` after the name. Details holds what changes often: Instructions, Agent (the agent with its logo, its model and fast mode), the Use the computer switch and Routines (one card per routine); Settings holds the rest: Profile (avatar row, name, and "Created by" for a bot another bot created), Workspace (computer, workspace, permissions), Activity, Connectors and Skills. Both are parts of `BotSettingsForm` (`part`), saved as you edit; the editor sheet shows all of it. Every bot settings form (these, the editor sheets, the terminal's form) keeps a change made elsewhere while it is open (a bot that manages the team, another device): it takes the new value in each field not edited there, or the terminal sends only what it changed. Memory is the memory card, its sections in the same tabs and the add/more actions beside each layer's note. Every group in the panel is Grok Bot's outlined card (an outline on the page, no fill, inputs filled instead), a row with a note puts its control under the note, and long notes (skill descriptions, explanations, a note's description) stop at two lines with an ellipsis. A group shows its avatar, name, bot count and members instead of tabs. Use 16-point horizontal insets and 28-point section gaps; sections use the `CardSection` look: filled 16-point groups without borders, hairline-split rows, a note under each option. The iPhone's Details sheet (`BotDetailsView`, from the title menu's Details, Settings and Routines) has the same corner buttons, header, tabs, pages, outlined cards (`cardStyle`) and two-line notes (`noteLines`), and saves as you edit too.+The details inspector (`apps/desktop/src/renderer/views/thread/DetailsPanel.tsx`) copies Grok Bot's: share (Create template) and close (X) as round buttons in the corner, in the page color with a soft ring, over a 54-point band that drags the window; the bot's 60-point avatar, name and runtime centered on top; then page tabs (`TabChoice`: plain labels, the chosen one on a light capsule) for **Details**, **Memory** and **Settings**, all in one scroll. The chat's `<<` button (in the same ringed style) and the title pill open it; hovering the pill shows a `>` after the name. Details holds what changes often: Instructions, Agent (the agent with its logo, its model and fast mode), the Use the computer switch and Routines (one card per routine); Settings holds the rest: Profile (avatar row, name, and "Created by" for a bot another bot created), Workspace (computer, workspace, permissions), Activity, Connectors and Skills. Both are parts of `BotSettingsForm` (`part`), saved as you edit; the editor sheet shows all of it. Every bot settings form (these, the editor sheets, the terminal's form) keeps a change made elsewhere while it is open (a bot that manages the team, another device): it takes the new value in each field not edited there, or the terminal sends only what it changed. Memory is the read-only memory card, its sections in the same tabs; each layer's note ends with "To change it, tell the bot." and the Dreams tab has an info button. Every group in the panel is Grok Bot's outlined card (an outline on the page, no fill, inputs filled instead), a row with a note puts its control under the note, and long notes (skill descriptions, explanations, a note's description) stop at two lines with an ellipsis. A group shows its avatar, name, bot count and members instead of tabs. Use 16-point horizontal insets and 28-point section gaps; sections use the `CardSection` look: filled 16-point groups without borders, hairline-split rows, a note under each option. The iPhone's Details sheet (`BotDetailsView`, from the title menu's Details, Settings and Routines) has the same corner buttons, header, tabs, pages, outlined cards (`cardStyle`) and two-line notes (`noteLines`), and saves as you edit too.Routines are a compact grouped list: name, a one-line schedule (or the live run state), and an on/off switch per row; tapping a row opens the same form as +, filled in, with delete and test run beside Save. On the desktop the form card fits its content. The header's chat button asks the bot (puts "I want a routine that " in the composer); + opens the form, where When to run is a type choice (a segmented control on the desktop, the system menu on iPhone) and a schedule is a Repeat choice (Hourly, Daily, Weekdays, Weekly, Custom) with only the fields that choice needs (minute, time, weekday, or a typed cron for Custom) and a time zone picked from a searchable list. On the desktop these sit in one `CardSection` of labeled rows, Repeat and the weekday as `ChipChoice` chips with the chosen one on a light capsule. The empty state is one line of text. A saved webhook routine's form shows the public URL and key as monospaced rows (in the same group on the desktop) with copy, show/hide and replace-key (confirmed) icon buttons, and one caption on how to send and that deliveries pass through the Codync cloud. Agent metadata uses Runtime and Workspace labels for personal bots, or Project folder for explicitly configured projects; project paths remain selectable and wrap. Personal workspace paths stay out of the default details UI. Keep status and section headings readable in both appearances through `Palette`.diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.mdindex 3cb3e251..971c6542 100644--- a/docs/features/context-and-memory.md+++ b/docs/features/context-and-memory.md@@ -57,9 +57,9 @@ the `codync-mem` crate; `chat/memory` runs them in the host.- **The bot's tools** (built-in `memory` MCP server): `remember`, `revise_memory`, `archive_memory`,`search_memory`, `search_history`. Every bot writes at once, in any turn and to either layer, whatever itspermission: memory isn't an action on the user's computer. Nothing about memory shows in the chat (no lines,- cards or working line); the user reviews and changes it in the bot's memory settings. A forgotten memory is never- written again by a bot or dreaming, reworded or not: its text stays closed to that layer, and the message it came- from to both layers the bot uses. Entry ids are never reused, so a stale id can't reach a newer entry. Memory+ cards or working line); the user reviews it in the bot's memory settings and changes it by telling the bot. A+ forgotten memory is never written again by a bot or dreaming, reworded or not: its text stays closed to that+ layer, and the message it came from to both layers the bot uses. Entry ids are never reused, so a stale id can't reach a newer entry. Memorylines and cards that older hosts put in the chat are hidden by the apps; `answerMemory` and `undoMemory` stillanswer them for older apps.- **Checks** on every write but the user's own (`codync_mem::check`): no hidden characters, prompt-carrying@@ -78,8 +78,8 @@ the `codync-mem` crate; `chat/memory` runs them in the host.once it settles). A change from a bot's tool call that changes files (an edit, delete or move, or one withdiffs, naming the path; a read doesn't count) runs the checks, the cap and the description; one that fails isput back (logged, nothing in the chat). Other changes (an editor, another program) are recorded as "this- computer". The note's versions in the memory settings show every change and bring any one back; a description- that fails the checks is withheld from the index.+ computer". The host keeps every version (the apps don't list them); a description that fails the checks is+ withheld from the index.- Every host write (the apps, `edit_memory`, dreaming, undo) is compare-and-swap on the content's hash, through atemporary file renamed over the note. `search_memory` also returns matching lines of the files.- Deleting a bot deletes its folder and versions; "Forget everything" deletes a layer's files and versions; a@@ -108,12 +108,14 @@ the `codync-mem` crate; `chat/memory` runs them in the host.(empty until it saves something). An edit to another harness turns the switch off. Using the harness's memoryinstead of Codync's is planned: [harness memory](../plans/harness-memory.md).- **The apps** (iPhone, desktop, terminal) show "About you", "This bot", the dream log and Claude Code's notes,- with add, edit, pin, archive, forget and forget-everything. Under each layer's entries (the terminal: a Notes- section) they list its notes with description, size and date, marked past a cap; a note opens to read, edit,- delete or bring back any version, and on the desktop, when the host is this computer, in the user's editor. They- fetch with `memory` and fetch again when the bot's `memoryRev` moves. Methods: `memory`, `saveMemory`,- `pinMemory`, `archiveMemory`, `forgetMemory`, `clearMemory`, `undoDream`, `memoryFile`, `saveMemoryFile`,- `deleteMemoryFile`, `restoreMemoryFile`.+ read-only since 2.21.0: the user changes memory by telling the bot in the chat. Each layer shows its entries with+ who wrote them, then its notes (the terminal: a Notes section) with description, size and date, marked past a+ cap; a note opens to read. The dream log shows added lines green and archived red, beside an info button (the+ terminal: a short paragraph above it) saying what dreaming does. The switches stay: "Use what your bots share"+ and the harness's own memory. They fetch with `memory` and `memoryFile`, and fetch again when the bot's+ `memoryRev` moves. The host still answers the edit methods older apps call: `saveMemory`, `pinMemory`,+ `archiveMemory`, `forgetMemory`, `clearMemory`, `undoDream`, `saveMemoryFile`, `deleteMemoryFile`,+ `restoreMemoryFile`.- **Moving the old memory**: on the first start of this version, each bot's Engram database (or the Markdownmemory before it) moves in once. What the old opening showed comes in active as far as the cap allows (theprofile and pinned facts first, then the newest), the rest archived; then the old files (deleted bots' too) anddiff --git a/docs/plans/android-app.md b/docs/plans/android-app.mdindex f6810015..6956f211 100644--- a/docs/plans/android-app.md+++ b/docs/plans/android-app.md@@ -20,7 +20,7 @@ emulator against a real host; device acceptance is listed separately.| Conversation | Ported: bubbles, Markdown/code, permissions, reactions, quote replies, Full conversation, bot-to-bot exchange lines and their conversation, routine notices that open their routine, files a bot shares (verified download, then the share sheet), sent images full size, pull down to reconnect, jump to latest, read receipts for every conversation on screen | Physical keyboard and TalkBack || Composer | Ported: files/photos/paste (groups too, image thumbnails, Paste only when the clipboard holds files), `/` commands (Fast mode, skills listed fresh on `/`), @mentions in groups, call/send/stop/interrupt button | — || Bot and group editors | Ported: avatar, profile, agent and model options, Fast mode, workspace folder picker, permissions, activity, connectors, skills (with their details) | — |-| Memory | Ported: search, filters, add/edit, pin, review, history and timeline, export/import, forget all | — |+| Memory | Broken since 2.18.0: the screen calls removed host methods (see [Not ported yet](#not-ported-yet)) | Port the read-only memory screen from `MemoryView.swift`, `MemoryFilesView.swift` and `MemoryInfoSheet.swift`, without add, edit, pin or forget || Routines | Ported: list with switches, editor (schedule, webhook panel, run settings), test run, delete | Live provider/routine acceptance || Extensions | Ported: agents (install, sign-in, setup terminal), registry connectors, Composio apps, skills, installed list, custom connector, own skill, credentials, chat connection request card | Real provider OAuth, 1Password || Voice | Ported: call bar (provider name, fallback notice), Voice chat settings (engine, mode, models, voice, minutes this month), on device (the call's language through Android's on-device recognizer, Vosk English as the fallback, replies read by an offline voice for their language), OpenAI Realtime (WebRTC), Gemini Live, Speech mode, fallback to on device, group calls | Both providers with a real key on a device; a live microphone on a device |@@ -50,9 +50,10 @@ was walked through on an emulator against a real host.- **Bot memory (2.18.0).** The host's memory moved out of Engram ([bot memory](../design/bot-memory.md)). Thememory screen still calls the removed `memoryDetail`, `reviewMemory`, `exportMemory` and `importMemory`(`MemoryModel.kt`, `MemoryCard.kt`, `LiveMemoryTest.kt`), so it shows an error. Missing too: the two layers- (yours and the bot's) with archived entries, memory notes (long-form files with versions), the harness's own- memory switch with its info sheet (2.19.0) and the handoff card. Port them from the iPhone (`MemoryView.swift`,- `MemoryFilesView.swift`, `HarnessMemorySheet.swift`, `HandoffRows.swift`).+ (yours and the bot's) with archived entries, memory notes, the dream log with its info sheet, the harness's own+ memory switch with its info sheet (2.19.0) and the handoff card. Since 2.21.0 the memory screen is read-only+ (the user changes memory by telling the bot), so the port drops its add and edit controls. Port them from the+ iPhone (`MemoryView.swift`, `MemoryFilesView.swift`, `MemoryInfoSheet.swift`, `HandoffRows.swift`).### Not verified (needs an account, a key, a device or the real Mac)diff --git a/host/src/tui/app/input.rs b/host/src/tui/app/input.rsindex d995fa44..37a885fd 100644--- a/host/src/tui/app/input.rs+++ b/host/src/tui/app/input.rs@@ -51,7 +51,6 @@ impl App {},Overlay::Market(m) => Some(&mut m.query),Overlay::Fields(f) => f.current().map(|i| &mut i.ed),- Overlay::Memory(m) => m.editor(),Overlay::Routine(f) => Some(match f.field {super::super::manage::RoutineField::Name => &mut f.name,super::super::manage::RoutineField::Instruction => &mut f.instruction,diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rsindex 686280d5..a04e00c4 100644--- a/host/src/tui/app/overlay_keys.rs+++ b/host/src/tui/app/overlay_keys.rs@@ -69,16 +69,9 @@ impl App {match &c.act {ConfirmAct::Delete(id) => self.call("deleteBot", json!({"botId": id}), After::Nothing),ConfirmAct::NewSession(id) => self.call("newSession", json!({"botId": id}), After::Nothing),- ConfirmAct::ClearMemory(id, shared) => {- self.call("clearMemory", json!({"botId": id, "shared": shared}), changed);- }ConfirmAct::KeepHarnessMemory(id) => {self.call("updateBot", json!({"id": id, "harnessMemory": true}), changed);}- ConfirmAct::DeleteMemoryFile { bot, shared, name, base } => {- let body = json!({"botId": bot, "file": name, "shared": shared, "base": base});- self.call("deleteMemoryFile", body, changed);- }ConfirmAct::DeleteRoutine(bot, id) => {self.call("deleteRoutine", json!({"botId": bot, "id": id}), changed);}diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rsindex 1a39985d..767b2187 100644--- a/host/src/tui/app/ui.rs+++ b/host/src/tui/app/ui.rs@@ -89,21 +89,12 @@ pub struct Goto {pub enum ConfirmAct {Delete(String),NewSession(String),- /// A bot's own memory, or (`true`) the one all bots share.- ClearMemory(String, bool),/// Keeps a bot's harness's own memory on beside Codync's.KeepHarnessMemory(String),DeleteRoutine(String, String),RotateRoutineKey(String, String),RemoveConnector(String),RemoveSkill(String),- /// A long-form memory note, over the content with hash `base`.- DeleteMemoryFile {- bot: String,- shared: bool,- name: String,- base: Option<String>,- },}pub struct Confirm {diff --git a/host/src/tui/manage/fields.rs b/host/src/tui/manage/fields.rsindex 6ff97eb6..452b97af 100644--- a/host/src/tui/manage/fields.rs+++ b/host/src/tui/manage/fields.rs@@ -78,13 +78,6 @@ impl App {Submit::Handoff(entry) => {self.sheet("editHandoff", json!({"entryId": entry, "text": values["text"]}), Reply::FieldsSaved);}- Submit::MemoryFile { bot, shared, name, base } => {- let file = name.clone().map_or_else(|| values.get("file").cloned().unwrap_or_default(), Value::from);- // A note keeps its text as typed: trimming would drop its last line break.- let content = f.inputs.iter().find(|i| i.name == "content").map_or("", |i| i.ed.text.as_str());- let body = json!({"botId": bot, "file": file, "shared": shared, "content": content, "base": base});- self.sheet("saveMemoryFile", body, Reply::FieldsSaved);- }}}}@@ -111,32 +104,3 @@ pub fn handoff_fields(entry: &Entry) -> Fields {submit: Submit::Handoff(entry.id.clone()),}}--/// Writes a long-form note: a new one (`name` none) or a change over what was loaded (`base`).-pub fn memory_file_fields(bot: &str, shared: bool, name: Option<&str>, base: Option<String>, content: &str) -> Fields {- let input = |name: &str, label: &str, multiline: bool, placeholder: &str, text: &str| Input {- name: name.into(),- label: label.into(),- secret: false,- required: true,- multiline,- placeholder: placeholder.into(),- ed: Editor::with(text),- };- let mut inputs = Vec::new();- if name.is_none() {- inputs.push(input("file", "File name", false, "people.md", ""));- }- inputs.push(input("content", "Note", true, "", content));- Fields {- title: name.map_or_else(|| "New note".to_owned(), str::to_owned),- note: "Starts with a description: line saying when the bot should read it. ⇧↵ new line, ↵ saves.".into(),- choices: vec![],- choice: 0,- inputs,- cursor: 0,- error: None,- saving: false,- submit: Submit::MemoryFile { bot: bot.to_owned(), shared, name: name.map(str::to_owned), base },- }-}diff --git a/host/src/tui/manage/memory.rs b/host/src/tui/manage/memory.rsindex 12234e3a..ffcabdb2 100644--- a/host/src/tui/manage/memory.rs+++ b/host/src/tui/manage/memory.rs@@ -1,11 +1,13 @@-//! A bot's memory, as in the other apps: what it knows about you (shared by your bots) and on its own, its dream-//! log, and Claude Code's own memory where the user kept it on, driven from the keyboard.+//! A bot's memory, read-only as in the other apps: what it knows about you (shared by your bots) and on its own,+//! its notes, its dream log, and Claude Code's own memory where the user kept it on. The user changes memory by+//! telling the bot.-use super::super::app::{App, Confirm, ConfirmAct, Editor, Overlay};+use super::super::app::{App, Confirm, ConfirmAct, Overlay};use super::s;-use super::{Page, Reply};+use super::{Page, Reply, ctrl};use crossterm::event::{KeyCode, KeyEvent};use serde_json::{Value, json};+use std::cell::Cell;#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Section {@@ -30,15 +32,6 @@ impl Section {Self::Harness => "Claude Code",}}-- /// Whether the section holds memory entries, and of which layer: `Some(true)` the shared one.- pub fn shared(self) -> Option<bool> {- match self {- Self::Yours => Some(true),- Self::Bot => Some(false),- Self::Notes | Self::Dreams | Self::Harness => None,- }- }}pub struct MemorySheet {@@ -46,7 +39,10 @@ pub struct MemorySheet {/// The host's `memory` reply.pub view: Option<Value>,pub section: Section,+ /// The row picked in the section's list.pub cursor: usize,+ /// The open note's, or Claude Code's memory's, scroll.+ pub scroll: Scroll,pub mode: MemoryMode,pub error: Option<String>,pub busy: bool,@@ -54,12 +50,7 @@ pub struct MemorySheet {pub enum MemoryMode {Browse,- /// Writing a new entry (`id` none) or changing one.- Edit {- id: Option<i64>,- editor: Editor,- },- /// One note: what it holds and its versions (`detail`, once fetched). The cursor moves over the versions.+ /// One note: what it holds (`detail`, once fetched).File {name: String,shared: bool,@@ -67,27 +58,48 @@ pub enum MemoryMode {},}+/// A read-only text's scroll, by wrapped row; the last draw sets how far it goes and a page's height.+#[derive(Default)]+pub struct Scroll {+ pub pos: usize,+ pub max: Cell<usize>,+ pub page: Cell<usize>,+}++impl Scroll {+ /// ↑↓, PageUp/PageDown and Ctrl-d/u; false for a key it doesn't take.+ fn key(&mut self, k: KeyEvent) -> bool {+ let max = self.max.get();+ let half = (self.page.get() / 2).max(1);+ // A refresh or a resize can leave the position past the end.+ let pos = self.pos.min(max);+ self.pos = match k.code {+ KeyCode::Down | KeyCode::Char('j') => (pos + 1).min(max),+ KeyCode::Up | KeyCode::Char('k') => pos.saturating_sub(1),+ KeyCode::PageDown => (pos + half).min(max),+ KeyCode::PageUp => pos.saturating_sub(half),+ KeyCode::Char('d') if ctrl(k) => (pos + half).min(max),+ KeyCode::Char('u') if ctrl(k) => pos.saturating_sub(half),+ _ => return false,+ };+ true+ }+}+impl MemorySheet {pub fn body(&self) -> Value {json!({"botId": self.bot})}- pub fn editor(&mut self) -> Option<&mut Editor> {- match &mut self.mode {- MemoryMode::Edit { editor, .. } => Some(editor),- MemoryMode::Browse | MemoryMode::File { .. } => None,- }- }-/// The note sheet's fetch, when one is open.pub fn file_body(&self) -> Option<Value> {match &self.mode {MemoryMode::File { name, shared, .. } => Some(json!({"botId": self.bot, "file": name, "shared": shared})),- _ => None,+ MemoryMode::Browse => None,}}- /// The current section's rows: entries, or dream runs.+ /// The current section's rows: entries, notes (deleted ones left out), or dream runs.pub fn rows(&self) -> Vec<Value> {let Some(view) = &self.view else { return Vec::new() };let list = match self.section {@@ -98,7 +110,9 @@ impl MemorySheet {// This bot's own first, then the shared ones; each row says which.let mut rows = Vec::new();for (layer, shared) in [("bot", false), ("yours", true)] {- for file in view["files"][layer]["files"].as_array().into_iter().flatten() {+ for file in+ view["files"][layer]["files"].as_array().into_iter().flatten().filter(|f| f["deleted"] != true)+ {let mut file = file.clone();file["shared"] = shared.into();rows.push(file);@@ -117,10 +131,8 @@ impl MemorySheet {let was = self.rows().get(self.cursor).map(key);self.view = Some(view);if !self.sections().contains(&self.section) {- // Claude Code's memory was just turned off; its scroll position means nothing elsewhere.+ // Claude Code's memory was just turned off.self.section = Section::Bot;- self.cursor = 0;- return;}let rows = self.rows();self.cursor = was@@ -139,6 +151,7 @@ impl MemorySheet {let at = sections.iter().position(|s| *s == self.section).unwrap_or(0);self.section = sections[at.saturating_add_signed(by).min(sections.len() - 1)];self.cursor = 0;+ self.scroll = Scroll::default();}}@@ -153,6 +166,7 @@ impl App {view: None,section: Section::Bot,cursor: 0,+ scroll: Scroll::default(),mode: MemoryMode::Browse,error: None,busy: true,@@ -185,19 +199,10 @@ impl App {pub(in crate::tui) fn memory_key(&mut self, mut m: MemorySheet, k: KeyEvent) -> Option<Overlay> {if let MemoryMode::File { .. } = m.mode {- return self.note_key(m, k);- }- if let MemoryMode::Edit { id, editor } = &mut m.mode {- match k.code {- KeyCode::Esc => m.mode = MemoryMode::Browse,- KeyCode::Enter if !m.busy && !editor.text.trim().is_empty() => {- m.busy = true;- let body = json!({"botId": m.bot, "id": id, "shared": m.section == Section::Yours, "text": editor.text.trim()});- self.sheet("saveMemory", body, Reply::MemorySaved(m.bot.clone()));- }- _ => {- editor.key(k);- }+ if matches!(k.code, KeyCode::Esc | KeyCode::Char('q')) {+ m.mode = MemoryMode::Browse;+ } else {+ m.scroll.key(k);}return Some(Overlay::Memory(m));}@@ -205,75 +210,28 @@ impl App {self.open_page(page);return None;}+ // Claude Code's memory scrolls; the other sections move between rows.+ if m.section == Section::Harness && m.scroll.key(k) {+ return Some(Overlay::Memory(m));+ }let rows = m.rows();- let selected = rows.get(m.cursor).cloned();- let entry = selected.as_ref().filter(|_| m.section.shared().is_some());match k.code {KeyCode::Esc | KeyCode::Char('q' | 'M') => return None,KeyCode::Tab | KeyCode::Right | KeyCode::Char('l') => self.step_section(&mut m, 1),KeyCode::BackTab | KeyCode::Left | KeyCode::Char('h') => self.step_section(&mut m, -1),- KeyCode::Down | KeyCode::Char('j') => {- // Claude Code's memory scrolls by line; the other sections move between rows.- let last = if m.section == Section::Harness {- m.view- .as_ref()- .map_or(0, |v| v["projectMemory"]["text"].as_str().unwrap_or_default().lines().count())- } else {- rows.len()- };- m.cursor = (m.cursor + 1).min(last.saturating_sub(1));- }+ KeyCode::Down | KeyCode::Char('j') => m.cursor = (m.cursor + 1).min(rows.len().saturating_sub(1)),KeyCode::Up | KeyCode::Char('k') => m.cursor = m.cursor.saturating_sub(1),KeyCode::Char('r') => {m.busy = true;self.sheet("memory", m.body(), Reply::Memory(m.bot.clone()));}- KeyCode::Char('n') if m.section.shared().is_some() => {- m.mode = MemoryMode::Edit { id: None, editor: Editor::default() };- }- KeyCode::Char('n') if m.section == Section::Notes => {- let fields = super::memory_file_fields(&m.bot, false, None, None, NOTE_TEMPLATE);- self.overlays.push(Overlay::Memory(m));- self.overlays.push(Overlay::Fields(Box::new(fields)));- return None;- }- KeyCode::Enter | KeyCode::Char('e') if m.section == Section::Notes && selected.is_some() => {- let file = selected.expect("checked above");- m.mode = MemoryMode::File { name: s(&file, "name"), shared: file["shared"] == true, detail: None };- m.cursor = 0;- if let Some(body) = m.file_body() {- self.sheet("memoryFile", body, Reply::MemoryFile(m.bot.clone()));- }- }- KeyCode::Enter | KeyCode::Char('e') if entry.is_some() => {- let e = entry.expect("checked above");- m.mode = MemoryMode::Edit {- id: e["id"].as_i64(),- editor: Editor::with(e["text"].as_str().unwrap_or_default()),- };- }- KeyCode::Char('p' | 'a' | 'x') if entry.is_some() && !m.busy => {- let e = entry.expect("checked above");- let (method, body) = match k.code {- KeyCode::Char('p') => {- ("pinMemory", json!({"botId": m.bot, "id": e["id"], "pinned": e["pinned"] != true}))- }- KeyCode::Char('a') => {- ("archiveMemory", json!({"botId": m.bot, "id": e["id"], "archived": e["state"] != "archived"}))+ KeyCode::Enter if m.section == Section::Notes => {+ if let Some(file) = rows.get(m.cursor) {+ m.mode = MemoryMode::File { name: s(file, "name"), shared: file["shared"] == true, detail: None };+ m.scroll = Scroll::default();+ if let Some(body) = m.file_body() {+ self.sheet("memoryFile", body, Reply::MemoryFile(m.bot.clone()));}- _ => ("forgetMemory", json!({"botId": m.bot, "id": e["id"]})),- };- m.busy = true;- self.sheet(method, body, Reply::MemorySaved(m.bot.clone()));- }- KeyCode::Char('u') if m.section == Section::Dreams && !m.busy => {- if let Some(dream) = selected.filter(|d| d["undone"] != true) {- m.busy = true;- self.sheet(- "undoDream",- json!({"botId": m.bot, "id": dream["id"]}),- Reply::MemorySaved(m.bot.clone()),- );}}KeyCode::Char('s') if !m.busy => {@@ -286,30 +244,6 @@ impl App {);}KeyCode::Char('m') if !m.busy => return self.harness_memory_key(m),- KeyCode::Char('D') if !rows.is_empty() && !m.busy => {- if let Some(shared) = m.section.shared() {- let c = Confirm {- title: if shared {- "Forget everything shared about you?"- } else {- "Forget everything this bot remembers?"- }- .into(),- detail: if shared {- "Every bot loses these memories."- } else {- "This bot's own memories are removed."- }- .into(),- note: "The chat stays.".into(),- button: "Forget everything",- act: ConfirmAct::ClearMemory(m.bot.clone(), shared),- };- self.overlays.push(Overlay::Memory(m));- self.overlays.push(Overlay::Confirm(c));- return None;- }- }_ => {}}Some(Overlay::Memory(m))@@ -353,65 +287,8 @@ impl App {}Some(Overlay::Memory(m))}-- /// Keys on a note: read it, edit it, delete it, or bring back a version.- fn note_key(&mut self, mut m: MemorySheet, k: KeyEvent) -> Option<Overlay> {- let MemoryMode::File { name, shared, detail } = &m.mode else { return Some(Overlay::Memory(m)) };- let (name, shared) = (name.clone(), *shared);- let content = detail.as_ref().and_then(|d| d["content"].as_str()).map(str::to_owned);- let base = detail.as_ref().and_then(|d| d["hash"].as_str()).map(str::to_owned);- let versions = detail.as_ref().and_then(|d| d["versions"].as_array()).cloned().unwrap_or_default();- match k.code {- KeyCode::Esc | KeyCode::Char('q') => {- m.mode = MemoryMode::Browse;- m.cursor = 0;- }- KeyCode::Down | KeyCode::Char('j') => m.cursor = (m.cursor + 1).min(versions.len().saturating_sub(1)),- KeyCode::Up | KeyCode::Char('k') => m.cursor = m.cursor.saturating_sub(1),- KeyCode::Char('e') if content.is_some() => {- let fields = super::memory_file_fields(- &m.bot,- shared,- Some(&name),- base,- content.as_deref().unwrap_or_default(),- );- self.overlays.push(Overlay::Memory(m));- self.overlays.push(Overlay::Fields(Box::new(fields)));- return None;- }- KeyCode::Char('x') if content.is_some() && !m.busy => {- let c = Confirm {- title: format!("Delete {name}?"),- detail: "The bot no longer sees it.".into(),- note: "Its versions stay, so you can bring it back.".into(),- button: "Delete",- act: ConfirmAct::DeleteMemoryFile { bot: m.bot.clone(), shared, name, base },- };- self.overlays.push(Overlay::Memory(m));- self.overlays.push(Overlay::Confirm(c));- return None;- }- KeyCode::Enter | KeyCode::Char('r') if !m.busy => {- if let Some(version) = versions- .get(m.cursor)- .filter(|v| v["content"].is_string() && v["content"].as_str() != content.as_deref())- {- m.busy = true;- let body =- json!({"botId": m.bot, "file": name, "shared": shared, "version": version["id"], "base": base});- self.sheet("restoreMemoryFile", body, Reply::MemorySaved(m.bot.clone()));- }- }- _ => {}- }- Some(Overlay::Memory(m))- }}-/// What a new note starts with.-const NOTE_TEMPLATE: &str = "---\ndescription: When to read this note\n---\n";-#[cfg(test)]mod tests {use super::*;@@ -424,6 +301,7 @@ mod tests {view: Some(view([1, 2, 3])),section: Section::Bot,cursor: 2,+ scroll: Scroll::default(),mode: MemoryMode::Browse,error: None,busy: false,@@ -434,6 +312,39 @@ mod tests {assert_eq!(m.cursor, 0, "gone: the cursor stays in range");}+ #[test]+ fn a_memory_change_keeps_an_open_notes_scroll_and_its_row() {+ let files = |names: [&str; 2]| json!({"files": {"bot": {"files": names.map(|n| json!({"name": n}))}}});+ let mut m = MemorySheet {+ bot: "b".into(),+ view: Some(files(["a", "n"])),+ section: Section::Notes,+ cursor: 1,+ scroll: Scroll { pos: 10, ..Scroll::default() },+ mode: MemoryMode::File { name: "n".into(), shared: false, detail: None },+ error: None,+ busy: false,+ };+ m.show(files(["n", "a"]));+ assert_eq!((m.cursor, m.scroll.pos), (0, 10), "the list keeps its row, the note its scroll");+ }++ #[test]+ fn scrolling_stops_at_the_end_the_draw_set() {+ let key = |code| KeyEvent::from(code);+ let mut scroll = Scroll { pos: 10, ..Scroll::default() };+ scroll.max.set(30);+ scroll.page.set(20);+ assert!(scroll.key(key(KeyCode::PageDown)));+ assert_eq!(scroll.pos, 20);+ assert!(scroll.key(key(KeyCode::PageDown)));+ assert_eq!(scroll.pos, 30, "no further than the last wrapped row");+ scroll.max.set(5);+ assert!(scroll.key(key(KeyCode::Up)));+ assert_eq!(scroll.pos, 4, "a shorter text: the first ↑ moves from its end");+ assert!(!scroll.key(key(KeyCode::Enter)));+ }+#[test]fn turning_claude_codes_memory_off_leaves_its_section() {let entries = json!({"entries": [{"id": 1}, {"id": 2}]});@@ -441,12 +352,13 @@ mod tests {bot: "b".into(),view: Some(json!({"bot": entries, "projectMemory": {"path": "p", "text": "a\nb\nc\nd"}})),section: Section::Harness,- cursor: 3,+ cursor: 0,+ scroll: Scroll { pos: 3, ..Scroll::default() },mode: MemoryMode::Browse,error: None,busy: false,};m.show(json!({"bot": entries, "projectMemory": null}));- assert_eq!((m.section, m.cursor), (Section::Bot, 0), "its scroll position isn't a row");+ assert_eq!((m.section, m.cursor), (Section::Bot, 0));}}diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rsindex 2ea63d2d..79f0f39e 100644--- a/host/src/tui/manage/mod.rs+++ b/host/src/tui/manage/mod.rs@@ -18,8 +18,8 @@ mod skill;mod when;pub use analytics::AnalyticsSheet;-pub use fields::{handoff_fields, memory_file_fields};-pub use memory::{MemoryMode, MemorySheet, Section};+pub use fields::handoff_fields;+pub use memory::{MemoryMode, MemorySheet, Scroll, Section};pub use pages::Page;pub use skill::SkillSheet;pub use when::{complete_zone, local_zone};@@ -176,13 +176,6 @@ pub enum Submit {Import,/// A handoff card's text (the card's entry id).Handoff(String),- /// A long-form memory note: a new one (`name` none) or a change over the content with hash `base`.- MemoryFile {- bot: String,- shared: bool,- name: Option<String>,- base: Option<String>,- },}/// A few labeled text fields: an agent's keys, a connector's setup, a pasted MCP config.diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rsindex 315fec6d..19060db8 100644--- a/host/src/tui/manage/replies.rs+++ b/host/src/tui/manage/replies.rs@@ -31,9 +31,6 @@ impl App {if let Overlay::Memory(m) = o&& m.bot == bot{- if let MemoryMode::Edit { .. } = m.mode {- m.mode = MemoryMode::Browse;- }m.busy = false;}}@@ -45,9 +42,7 @@ impl App {&& m.bot == bot&& let MemoryMode::File { detail, .. } = &mut m.mode{- let versions = v["versions"].as_array().map_or(0, Vec::len);*detail = Some(v.clone());- m.cursor = m.cursor.min(versions.saturating_sub(1));m.busy = false;}}diff --git a/host/src/tui/sheets/memory_view.rs b/host/src/tui/sheets/memory_view.rsindex bf2c2c85..a04c2051 100644--- a/host/src/tui/sheets/memory_view.rs+++ b/host/src/tui/sheets/memory_view.rs@@ -1,12 +1,11 @@//! A bot's memory: about you, this bot's own, its dreams and Claude Code's own memory where it is kept on.-use super::{- App, Buffer, Rect, centered, footer, frame_box, input_line, name_of, page_tabs, put, row, s, theme, u, window,-};-use crate::tui::manage::{MemoryMode, MemorySheet, Page, Section};-use crate::tui::md::truncate;+use super::{App, Buffer, Rect, centered, footer, frame_box, name_of, page_tabs, put, row, s, theme, u, window};+use crate::tui::manage::{MemoryMode, MemorySheet, Page, Scroll, Section};+use crate::tui::md::{truncate, wrap};use crate::tui::view::when;-use ratatui::widgets::{Paragraph, Widget, Wrap};+use ratatui::text::Span;+use ratatui::widgets::{Paragraph, Widget};use serde_json::Value;pub fn draw(buf: &mut Buffer, area: Rect, app: &App, memory: &MemorySheet) {@@ -18,36 +17,26 @@ pub fn draw(buf: &mut Buffer, area: Rect, app: &App, memory: &MemorySheet) {tabs(buf, inner, memory);let body = Rect::new(inner.x, inner.y + 2, inner.width, inner.height.saturating_sub(5));let keys = match &memory.mode {- MemoryMode::Edit { id, editor } => {- let label = match (id, memory.section) {- (Some(_), _) => "Change this memory",- (None, Section::Yours) => "Something every bot should know about you",- (None, _) => "Something this bot should remember",- };- put(buf, body.x, body.y, body.width, label, palette.secondary.patch(palette.panel));- input_line(buf, body, body.y + 1, editor, "One short fact", true, false);- "Enter save · Esc cancel"- }MemoryMode::File { detail, .. } => {- note(buf, body, app, memory, detail.as_ref());- "↑↓ version · ↵ bring it back · e edit · x delete · Esc back"+ note(buf, body, detail.as_ref(), &memory.scroll);+ "↑↓ scroll · Esc back"}MemoryMode::Browse => match memory.section {Section::Notes => {notes(buf, body, memory);- "←→ section · ↑↓ move · ↵ open · n new note · Esc close"+ "←→ section · ↑↓ move · ↵ open · Esc close · the bot writes notes"}Section::Yours | Section::Bot => {entries(buf, body, app, memory);- "←→ section · ↑↓ move · n add · ↵ edit · p pin · a archive · x forget · s shared · D clear"+ "←→ section · ↑↓ move · s shared · Esc close · tell the bot to change it"}Section::Dreams => {dreams(buf, body, memory);- "←→ section · ↑↓ move · u undo · r refresh · Esc close"+ "←→ section · ↑↓ move · r refresh · Esc close · read-only"}Section::Harness => {harness(buf, body, memory);- "←→ section · read-only: Claude Code's own notes · r refresh · m turns them off · Esc close"+ "←→ section · ↑↓ scroll · r refresh · m turn off · Esc close · read-only"}},};@@ -97,7 +86,7 @@ fn entries(buf: &mut Buffer, body: Rect, app: &App, memory: &MemorySheet) {let empty = if memory.section == Section::Yours {"Nothing shared yet. Facts every bot should know (your name, time zone, people) go here."} else {- "Nothing yet. What this bot learns about you shows up here, and you can change any of it."+ "Nothing yet. What this bot learns about you shows up here."};put(buf, body.x, body.y + 2, body.width, empty, palette.secondary);return;@@ -129,24 +118,23 @@ fn author(app: &App, e: &Value) -> String {}}+/// What dreaming did, read-only, under what it does (the other apps' info sheet, short).fn dreams(buf: &mut Buffer, body: Rect, memory: &MemorySheet) {let palette = theme();- put(- buf,- body.x,- body.y,- body.width,- "Between chats the bot tidies its memory from your own words. Each run can be undone.",- palette.secondary.patch(palette.panel),- );+ let about = "Between chats the bot tidies its memory from what you typed, away from the chat: + added, − archived. \+ Pasted text and its replies never count. A record: to change a memory, tell the bot.";+ let muted = palette.secondary.patch(palette.panel);+ let lines = wrap(&[Span::styled(about, muted)], usize::from(body.width), &[], &[]);+ let top = u(lines.len()).min(body.height) + 1;+ Paragraph::new(lines).style(muted).render(Rect::new(body.x, body.y, body.width, top - 1), buf);let rows = memory.rows();if rows.is_empty() {- put(buf, body.x, body.y + 2, body.width, "No dreams yet.", palette.secondary);+ put(buf, body.x, body.y + top, body.width, "No dreams yet.", palette.secondary);return;}- let height = usize::from(body.height.saturating_sub(2)) / 2;+ let height = usize::from(body.height.saturating_sub(top)) / 2;for (position, (index, d)) in rows.iter().enumerate().skip(window(memory.cursor, height)).take(height).enumerate() {- let y = body.y + 2 + u(position * 2);+ let y = body.y + top + u(position * 2);let base = row(buf, body, y, index == memory.cursor);let count = |k: &str| d[k].as_array().map_or(0, Vec::len);let head = format!(@@ -157,14 +145,13 @@ fn dreams(buf: &mut Buffer, body: Rect, memory: &MemorySheet) {if d["undone"] == true { " · undone" } else { "" });put(buf, body.x, y, body.width, &head, palette.text.patch(base));- let changes: Vec<String> = d["added"]- .as_array()- .into_iter()- .flatten()- .map(|c| format!("+ {}", s(c, "text")))- .chain(d["archived"].as_array().into_iter().flatten().map(|c| format!("− {}", s(c, "text"))))- .collect();- put(buf, body.x, y + 1, body.width, &changes.join(" "), palette.dim.patch(palette.panel));+ let mut x = body.x;+ for (sign, key, style) in [("+", "added", palette.green), ("−", "archived", palette.red)] {+ for c in d[key].as_array().into_iter().flatten() {+ let change = format!("{sign} {} ", s(c, "text"));+ x = put(buf, x, y + 1, body.right().saturating_sub(x), &change, style.patch(palette.panel));+ }+ }}}@@ -182,7 +169,7 @@ fn notes(buf: &mut Buffer, body: Rect, memory: &MemorySheet) {);let rows = memory.rows();if rows.is_empty() {- put(buf, body.x, body.y + 2, body.width, "No notes yet. n writes one.", palette.secondary);+ put(buf, body.x, body.y + 2, body.width, "No notes yet.", palette.secondary);return;}let cap = view["files"]["cap"].as_u64().unwrap_or(2_000);@@ -190,80 +177,89 @@ fn notes(buf: &mut Buffer, body: Rect, memory: &MemorySheet) {for (position, (index, f)) in rows.iter().enumerate().skip(window(memory.cursor, height)).take(height).enumerate() {let y = body.y + 2 + u(position * 2);let base = row(buf, body, y, index == memory.cursor);- let deleted = f["deleted"] == true;let layer = if f["shared"] == true { "shared" } else { "this bot" };- let head = format!("{} · {layer}{}", s(f, "name"), if deleted { " · deleted" } else { "" });- put(buf, body.x, y, body.width, &head, if deleted { palette.dim } else { palette.text }.patch(base));+ put(buf, body.x, y, body.width, &format!("{} · {layer}", s(f, "name")), palette.text.patch(base));let tokens = f["tokens"].as_u64().unwrap_or(0);- let over = if tokens > cap && !deleted { format!(", over the {cap} cap") } else { String::new() };+ let over = if tokens > cap { format!(", over the {cap} cap") } else { String::new() };let detail =format!("{} · {tokens} tokens{over} · {}", s(f, "description"), when(f["updatedAt"].as_i64().unwrap_or(0)));put(buf, body.x, y + 1, body.width, &detail, palette.dim.patch(palette.panel));}}-/// One note: what it holds, then its versions to bring one back.-fn note(buf: &mut Buffer, body: Rect, app: &App, memory: &MemorySheet, detail: Option<&Value>) {- let palette = theme();+/// One note, to read.+fn note(buf: &mut Buffer, body: Rect, detail: Option<&Value>, scroll: &Scroll) {let Some(detail) = detail else {+ let palette = theme();put(buf, body.x, body.y, body.width, "Loading…", palette.dim.patch(palette.panel));return;};- put(- buf,- body.x,- body.y,- body.width,- &truncate(s(detail, "path"), usize::from(body.width)),- palette.dim.patch(palette.panel),- );- let versions = detail["versions"].as_array().cloned().unwrap_or_default();- let listed = u(versions.len().min(6));- let text = Rect::new(body.x, body.y + 2, body.width, body.height.saturating_sub(4 + listed));- let content = detail["content"].as_str().unwrap_or("Deleted. Bring back a version below.");- Paragraph::new(content).wrap(Wrap { trim: false }).style(palette.text.patch(palette.panel)).render(text, buf);- let top = text.bottom() + 1;- put(buf, body.x, top, body.width, "Versions", palette.secondary.patch(palette.panel));- for (position, (index, v)) in versions.iter().enumerate().skip(window(memory.cursor, 6)).take(6).enumerate() {- let y = top + 1 + u(position);- let base = row(buf, body, y, index == memory.cursor);- let by = match s(v, "author") {- "user" => "You".to_owned(),- "bot" => name_of(app, s(v, "authorBot")),- "dream" => "Dreaming".to_owned(),- _ => "This computer".to_owned(),- };- let what = match s(v, "cause") {- "delete" => "deleted it",- "restore" => "brought back a version",- "undo" => "undid a change",- _ => "changed it",- };- let line = format!("{by} {what} · {}", when(v["at"].as_i64().unwrap_or(0)));- put(buf, body.x, y, body.width, &line, palette.text.patch(base));- }+ read(buf, body, s(detail, "path"), detail["content"].as_str().unwrap_or("Deleted."), scroll);}fn harness(buf: &mut Buffer, body: Rect, memory: &MemorySheet) {- let palette = theme();let Some(project) = memory.view.as_ref().map(|v| &v["projectMemory"]) else { return };- put(- buf,- body.x,- body.y,- body.width,- &truncate(s(project, "path"), usize::from(body.width)),- palette.dim.patch(palette.panel),- );- if s(project, "text").is_empty() {+ let text = s(project, "text");+ read(buf, body, s(project, "path"), text, &memory.scroll);+ if text.is_empty() {let empty = "Nothing yet. Claude Code's notes show up here once it saves some.";- put(buf, body.x, body.y + 2, body.width, empty, palette.secondary);- return;+ put(buf, body.x, body.y + 2, body.width, empty, theme().secondary);}- let text = Rect::new(body.x, body.y + 2, body.width, body.height.saturating_sub(2));- Paragraph::new(s(project, "text"))- .wrap(Wrap { trim: false })- .scroll((u(memory.cursor), 0))+}++/// `path` over its `text`, scrolled by wrapped row; the draw tells `scroll` how far it goes and a page's height.+fn read(buf: &mut Buffer, body: Rect, path: &str, text: &str, scroll: &Scroll) {+ let palette = theme();+ put(buf, body.x, body.y, body.width, &truncate(path, usize::from(body.width)), palette.dim.patch(palette.panel));+ let rect = Rect::new(body.x, body.y + 2, body.width, body.height.saturating_sub(2));+ let lines = wrap(&[Span::raw(text.to_owned())], usize::from(rect.width), &[], &[]);+ let height = usize::from(rect.height);+ scroll.max.set(lines.len().saturating_sub(height));+ scroll.page.set(height);+ Paragraph::new(lines)+ .scroll((u(scroll.pos.min(scroll.max.get())), 0)).style(palette.text.patch(palette.panel))- .render(text, buf);+ .render(rect, buf);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_note_scrolls_to_its_last_wrapped_row() {+ let area = Rect::new(0, 0, 20, 6);+ let detail = serde_json::json!({"path": "p", "content": format!("{}end", "word ".repeat(30))});+ let mut scroll = Scroll::default();+ note(&mut Buffer::empty(area), area, Some(&detail), &scroll);+ assert_eq!(scroll.max.get(), 4, "one line, 8 rows wrapped, 4 shown under the path");+ scroll.pos = scroll.max.get();+ let mut buf = Buffer::empty(area);+ note(&mut buf, area, Some(&detail), &scroll);+ let last = (0..area.width).map(|x| buf[(x, area.bottom() - 1)].symbol()).collect::<String>();+ assert!(last.trim_end().ends_with("end"), "{last}");+ }++ #[test]+ fn dreams_paragraph_wraps_whole_and_the_log_starts_under_it() {+ // 80 and 60 columns leave the sheet's body 74 and 54 wide.+ for (width, rows) in [(74, 3), (54, 4)] {+ let area = Rect::new(0, 0, width, 12);+ let mut buf = Buffer::empty(area);+ let memory = MemorySheet {+ bot: String::new(),+ view: None,+ section: Section::Dreams,+ cursor: 0,+ scroll: Scroll::default(),+ mode: MemoryMode::Browse,+ error: None,+ busy: false,+ };+ dreams(&mut buf, area, &memory);+ let line = |y: u16| (0..width).map(|x| buf[(x, y)].symbol()).collect::<String>();+ assert!(line(rows - 1).trim_end().ends_with("tell the bot."), "{width}: {}", line(rows - 1));+ assert_eq!(line(rows + 1).trim_end(), "No dreams yet.", "{width}");+ }+ }}