Skip to content

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.

feat: show bots' memory notes and their changes in every app

leepokai8520ab5c2082
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index c3dead1a..447b5556 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -153,6 +153,12 @@ 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.ts
index 30768f40..77ed6144 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -102,6 +102,7 @@ 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.ts
index ee7e7c66..e0aa46a4 100644
--- a/apps/desktop/src/renderer/demo/bridge.ts
+++ b/apps/desktop/src/renderer/demo/bridge.ts
@@ -92,6 +92,7 @@ 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.ts
index 757e3d1e..1ba300ae 100644
--- a/apps/desktop/src/renderer/store/memory-store.ts
+++ b/apps/desktop/src/renderer/store/memory-store.ts
@@ -26,6 +26,50 @@ export interface DreamRun {
undone: boolean
added: { id: number; text: string }[]
archived: { id: number; text: string }[]
+ /** Long-form files it added a line to. */
+ files?: { name: string; shared: boolean; version: number }[]
+}
+
+/** A long-form memory file as the host last recorded it (`codync_mem::files::File`). */
+export interface MemoryFile {
+ bot: string | null
+ name: string
+ /** SHA-256 of what it holds; a save is made over it. */
+ hash: string
+ description: string | null
+ tokens: number
+ deleted: boolean
+ updatedAt: number
+}
+
+export interface MemoryFiles {
+ yours: { files: MemoryFile[]; folder: string }
+ bot: { files: MemoryFile[]; folder: string }
+ /** Tokens one file may hold, and files one folder may hold. */
+ cap: number
+ 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. */
+export interface MemoryFileDetail {
+ file: string
+ shared: boolean
+ content: string | null
+ hash: string | null
+ path: string
+ versions: MemoryFileVersion[]
}
export interface MemoryView {
@@ -37,6 +81,8 @@ export interface MemoryView {
/** Claude Code's own notes for the bot's project folder, read-only. */
projectMemory: { path: string; text: string } | null
memoryRev: number
+ /** The long-form files of both layers. */
+ files?: MemoryFiles
}
/** One bot's memory: fetches it, and changes it through the host. */
@@ -62,6 +108,23 @@ export class MemoryStore extends Observable {
this.changed()
}
+ /** A long-form file as it is now, with its versions. */
+ async file(name: string, shared: boolean): Promise<MemoryFileDetail | null> {
+ try {
+ return await (await this.client()).call<MemoryFileDetail>('memoryFile', { botId: this.botId, file: name, shared })
+ } catch (error) {
+ this.error = message(error)
+ this.changed()
+ 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
@@ -92,4 +155,17 @@ 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/styles/theme.css b/apps/desktop/src/renderer/styles/theme.css
index 91aecc4f..187beb1b 100644
--- a/apps/desktop/src/renderer/styles/theme.css
+++ b/apps/desktop/src/renderer/styles/theme.css
@@ -17,6 +17,7 @@
--accent-dim: #d9d9d9;
--danger: #c23a2b;
--warning: #f0a030;
+ --attention: #936000;
--code-background: #f4f4f4;
--added: #2e7d32;
--removed: #c62828;
@@ -73,6 +74,7 @@
--accent-dim: #333333;
--danger: #f0a7a7;
--code-background: #111111;
+ --attention: #ecaf52;
--added: #8fd18b;
--removed: #f0a7a7;
--panel: #1b1b1b;
diff --git a/apps/desktop/src/renderer/views/bots/MemoryFiles.tsx b/apps/desktop/src/renderer/views/bots/MemoryFiles.tsx
new file mode 100644
index 00000000..b1fe3414
--- /dev/null
+++ b/apps/desktop/src/renderer/views/bots/MemoryFiles.tsx
@@ -0,0 +1,104 @@
+import { useEffect, useState, type ReactElement } from 'react'
+import { CardForm, CardSection, IconButton, Spinner } 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 { 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 }
+
+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)
+ 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>,
+ ...(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 })} />),
+ ]
+}
+
+function FileRow({ file, cap, open }: { file: MemoryFile; cap: number; open: () => void }) {
+ const over = !file.deleted && file.tokens > cap
+ return <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}
+ <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)}`}
+ </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
+ 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
+
+ return <div className="memory-file-sheet">
+ <ModalHeader title={target.name ?? 'New note'} trailing={actions} />
+ <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>}
+ </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/MemoryView.tsx b/apps/desktop/src/renderer/views/bots/MemoryView.tsx
index c3019e34..4f9bf33b 100644
--- a/apps/desktop/src/renderer/views/bots/MemoryView.tsx
+++ b/apps/desktop/src/renderer/views/bots/MemoryView.tsx
@@ -6,6 +6,7 @@ import { useModel } from '../../lib/observable'
import { useStore } from '../../store/context'
import { MemoryStore, authorLabel, type MemoryEntry } from '../../store/memory-store'
import { relativeTime } from '../thread/chat-items'
+import { type FileTarget, MemoryFileSheet, fileRows } from './MemoryFiles'
import './memory.css'
type Section = 'yours' | 'bot' | 'dreams' | 'project'
@@ -18,6 +19,7 @@ export function MemoryCard({ botId }: { botId: string }) {
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)
// Memory changes anywhere move the bot's `memoryRev`: fetch again.
useEffect(() => { void memory.load() }, [memory, bot?.memoryRev, bot?.sharedMemory])
@@ -55,6 +57,7 @@ export function MemoryCard({ botId }: { botId: string }) {
<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>
</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) : []),
]}
{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>,
@@ -64,6 +67,7 @@ export function MemoryCard({ botId }: { botId: string }) {
<strong>{relativeTime.day(dream.at)}{dream.undone ? ' · undone' : ''}</strong>
{dream.added.map((c) => <span key={`a${c.id}`}>+ {c.text}</span>)}
{dream.archived.map((c) => <span key={`r${c.id}`} className="memory-archived">− {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 })} />}
</div>),
@@ -84,6 +88,9 @@ export function MemoryCard({ botId }: { botId: string }) {
<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)} />}
+ </Sheet>
<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' }) } }]}
diff --git a/apps/desktop/src/renderer/views/bots/memory.css b/apps/desktop/src/renderer/views/bots/memory.css
index 5a342ffc..18c9e562 100644
--- a/apps/desktop/src/renderer/views/bots/memory.css
+++ b/apps/desktop/src/renderer/views/bots/memory.css
@@ -12,3 +12,7 @@
.memory-editor textarea { padding: 10px; background: var(--surface); color: var(--text); border: 0; border-radius: 8px; font: inherit; resize: vertical; }
.memory-history { white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; user-select: text; margin: 0; }
.memory-error { color: var(--danger, #df665e); white-space: pre-wrap; }
+.memory-notes-header { display: flex; align-items: center; justify-content: space-between; color: var(--secondary); font-size: 12px; 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: 12px/1.5 var(--mono, ui-monospace, monospace); }
diff --git a/apps/desktop/src/renderer/views/thread/ChatRows.tsx b/apps/desktop/src/renderer/views/thread/ChatRows.tsx
index 5e9ee56c..269a9e29 100644
--- a/apps/desktop/src/renderer/views/thread/ChatRows.tsx
+++ b/apps/desktop/src/renderer/views/thread/ChatRows.tsx
@@ -15,6 +15,7 @@ import { relativeTime } from './chat-items'
import { MarkdownText } from './Markdown'
import { PermissionCard } from './PermissionCard'
import { ConnectionRequestCard } from '../marketplace/ConnectionRequestCard'
+import { MemoryFileNotice } from './MemoryFileNotice'
import { MemoryNotice } from './MemoryNotice'
import { CompactionNotice, HandoffNotice } from './HandoffNotice'
@@ -63,6 +64,7 @@ export const ChatRow = memo(function ChatRow({ entry, groupStart, chat, openTrac
default:
if (entry.data.connectionRequest) return <div style={{ paddingTop: 12 }}><ConnectionRequestCard entry={entry} /></div>
if (entry.data.memory) return <div style={{ paddingTop: 10 }}><MemoryNotice entry={entry} /></div>
+ if (entry.data.memoryFile) return <div style={{ paddingTop: 10 }}><MemoryFileNotice entry={entry} card={entry.data.memoryFile} /></div>
if (entry.data.handoff) return <div style={{ paddingTop: 10 }}><HandoffNotice entry={entry} card={entry.data.handoff} /></div>
if (entry.data.compaction) return <div style={{ paddingTop: 10 }}><CompactionNotice entry={entry} compaction={entry.data.compaction} /></div>
return <div style={{ paddingTop: 10 }}><NoticeRow entry={entry} /></div>
diff --git a/apps/desktop/src/renderer/views/thread/MemoryFileNotice.tsx b/apps/desktop/src/renderer/views/thread/MemoryFileNotice.tsx
new file mode 100644
index 00000000..5754e610
--- /dev/null
+++ b/apps/desktop/src/renderer/views/thread/MemoryFileNotice.tsx
@@ -0,0 +1,59 @@
+import { useState } from 'react'
+import type { Entry, MemoryFileCard } from '@shared/models'
+import { Button, Disclosure, IconButton, Spinner } from '../../components/Controls'
+import { Icon } from '../../components/Icon'
+import { font } from '../../lib/fonts'
+import { useStore as useLiveStore } from '../../store/context'
+import { memoryActions } from './memory-actions'
+
+/** A bot's change to a memory file: "Updated people.md" with the diff and an undo, a change put back and why, or
+ * for a bot that asks first, the change waiting for the user. */
+export function MemoryFileNotice({ entry, card }: { entry: Entry; card: MemoryFileCard }) {
+ const store = useLiveStore()
+ const [expanded, setExpanded] = useState(false)
+ const actions = memoryActions(card.status)
+ const answering = store.answering.get(entry.id)
+ const line = (
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, ...font('footnote'), color: 'var(--secondary)', minWidth: 0 }}>
+ <Icon name={card.status === 'restored' ? 'exclamationmark.triangle' : 'doc.text'} size={11} />
+ <span style={{ overflowWrap: 'anywhere' }}>{entry.data.text}</span>
+ {card.big && actions === 'undo' ? <span style={{ color: 'var(--attention)' }}>Removes much of it</span> : null}
+ </div>
+ )
+ const diff = card.diff ? <LineDiff text={card.diff} /> : null
+ if (actions === 'answer') {
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 10, padding: 12, borderRadius: 14, background: 'var(--bubble-agent)', maxWidth: 560 }}>
+ {line}
+ {diff}
+ <div style={{ display: 'flex', gap: 8 }}>
+ {answering ? <Spinner /> : <>
+ <Button onClick={() => store.answerMemory(entry, 'approve')}>Allow</Button>
+ <Button kind="secondary" onClick={() => store.answerMemory(entry, 'decline')}>Don't</Button>
+ </>}
+ </div>
+ </div>
+ )
+ }
+ return (
+ <div style={{ display: 'flex', alignItems: expanded ? 'flex-start' : 'center', gap: 4, maxWidth: 620, margin: '0 auto', padding: '0 12px' }}>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ {diff && card.status !== 'restored'
+ ? <Disclosure expanded={expanded} onToggle={() => setExpanded(!expanded)} label={line}>{diff}</Disclosure>
+ : <div style={{ display: 'flex', justifyContent: 'center' }}>{line}</div>}
+ </div>
+ {actions === 'undo' ? (answering ? <Spinner size={11} /> : <IconButton title="Undo" icon="arrow.uturn.backward" onClick={() => store.answerMemory(entry, 'undo')} />) : null}
+ </div>
+ )
+}
+
+/** `- ` removed and `+ ` added lines, colored. */
+function LineDiff({ text }: { text: string }) {
+ return (
+ <pre style={{ margin: 0, padding: 8, borderRadius: 8, background: 'var(--code-background)', ...font('footnote'), fontFamily: 'var(--mono, ui-monospace, monospace)', whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', userSelect: 'text' }}>
+ {text.split('\n').map((line, i) => (
+ <div key={i} style={{ color: line.startsWith('+ ') ? 'var(--added)' : line.startsWith('- ') ? 'var(--removed)' : 'var(--secondary)' }}>{line || ' '}</div>
+ ))}
+ </pre>
+ )
+}
diff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.ts
index 39ed17c2..583e95b1 100644
--- a/apps/desktop/src/shared/ipc.ts
+++ b/apps/desktop/src/shared/ipc.ts
@@ -193,6 +193,8 @@ export interface CodyncBridge {
/** Error tracking: an uncaught error in this window (shared/error-report.ts). */
reportError(report: ErrorReport): void
openExternal(url: string): void
+ /** A long-form memory note in the user's editor; only paths inside a memory folder open. */
+ openMemoryFile(path: string): void
copy(text: string): void
/** Files picked in the system dialog: name and bytes. */
pickFiles(): Promise<{ name: string; data: Uint8Array }[]>
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index 01b01000..106eedc1 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -171,6 +171,23 @@ export interface MemoryWrite {
error?: string
}
+/** A bot's change to a memory file: "Updated people.md" with the diff and an undo, a change put back and why, or
+ * for a bot that asks first, the change waiting for the user. */
+export interface MemoryFileCard {
+ file?: string
+ shared?: boolean
+ /** done · pending · accepted · declined · undone · restored · failed */
+ status?: string
+ /** `- ` removed and `+ ` added lines. */
+ diff?: string
+ created?: boolean
+ deleted?: boolean
+ /** The change removes more than a quarter of the file. */
+ big?: boolean
+ /** Why it was put back, or couldn't be made. */
+ reason?: string
+}
+
/** "Earlier context was summarized": the harness's summary, when it gave one. */
export interface Compaction {
summary?: string | null
@@ -201,6 +218,8 @@ export interface EntryData {
connectionRequest?: ConnectionRequest
/** A bot's memory write shown in the chat (see `MemoryNotice`). */
memory?: MemoryWrite
+ /** A bot's change to one of its memory files (see `MemoryFileNotice`). */
+ memoryFile?: MemoryFileCard
routineId?: string
runId?: string
text?: string
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
index 48571c07..8dfaab72 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
@@ -4,6 +4,8 @@ public struct EntryData: Codable, Hashable, Sendable {
public var connectionRequest: ConnectionRequest?
/// A bot's memory write shown in the chat.
public var memory: MemoryWrite?
+ /// A bot's change to one of its memory files.
+ public var memoryFile: MemoryFileCard?
/// notice: the agent summarized its context.
public var compaction: Compaction?
/// notice: the bot's chat starts over with this handoff.
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Memory.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Memory.swift
index 78b582c8..8211fd04 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Memory.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Memory.swift
@@ -29,11 +29,18 @@ public struct DreamRun: Decodable, Identifiable, Hashable, Sendable {
public var id: Int64
public var text: String
}
+ /// A long-form file the run added a line to.
+ public struct FileNote: Decodable, Hashable, Sendable {
+ public var name: String
+ public var shared: Bool
+ public var version: Int64
+ }
public var id: Int64
public var at: Int64
public var undone: Bool
public var added: [Change]
public var archived: [Change]
+ public var files: [FileNote]?
}
/// A bot's memory as its screen shows it.
@@ -49,6 +56,8 @@ public struct MemoryView: Decodable, Hashable, Sendable {
public var dreams: [DreamRun]
/// Claude Code's own notes for the bot's project folder, read-only.
public var projectMemory: Project?
+ /// The long-form files of both layers.
+ public var files: MemoryFiles?
}
/// The text a single change of a composer's draft inserted, when it is long enough that the user pasted it
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/MemoryFiles.swift b/apps/ios/Kit/Sources/CodyncKit/Models/MemoryFiles.swift
new file mode 100644
index 00000000..50921efd
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/MemoryFiles.swift
@@ -0,0 +1,101 @@
+import Foundation
+
+/// A long-form memory file: a Markdown note on one topic, as the host last recorded it.
+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: String
+ public var description: String?
+ public var tokens: Int
+ public var deleted: Bool
+ public var updatedAt: Int64
+
+ public var id: String { name }
+}
+
+/// One layer's folder of files.
+public struct MemoryFolder: Decodable, Hashable, Sendable {
+ public var files: [MemoryFile]
+ /// Where it is on the computer.
+ public var folder: String
+}
+
+/// Both layers' files, with the caps the host marks.
+public struct MemoryFiles: Decodable, Hashable, Sendable {
+ public var yours: MemoryFolder
+ public var bot: MemoryFolder
+ /// Tokens one file may hold.
+ public var cap: Int
+ /// Files one folder may hold.
+ 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.
+public struct MemoryFileDetail: Decodable, Hashable, Sendable {
+ public var file: String
+ public 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]
+}
+
+/// A bot's change to a memory file in the chat. Every field is optional so a newer host's card still decodes.
+public struct MemoryFileCard: Codable, Hashable, Sendable {
+ public var file: String?
+ public var shared: Bool?
+ /// done · pending · accepted · declined · undone · restored · failed
+ public var status: String?
+ /// `- ` removed and `+ ` added lines.
+ public var diff: String?
+ public var created: Bool?
+ public var deleted: Bool?
+ /// The change removes more than a quarter of the file.
+ public var big: Bool?
+ /// Why it was put back, or couldn't be made.
+ public var reason: String?
+
+ /// What the user can do with it now, as with a memory entry's card.
+ public var choice: MemoryWrite.Choice? {
+ switch status {
+ case "pending": .answer
+ case "done", "accepted": .undo
+ default: nil
+ }
+ }
+}
+
+extension HostClient {
+ public func memoryFile(botId: String, file: String, shared: Bool) async throws -> MemoryFileDetail {
+ 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/MemoryFilesView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryFilesView.swift
new file mode 100644
index 00000000..0c1a666c
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryFilesView.swift
@@ -0,0 +1,204 @@
+import CodyncKit
+import SwiftUI
+
+/// One layer's long-form notes, under its entries: name, description, size and date, marked past a cap.
+struct MemoryFilesList: View {
+ let memory: MemoryStore
+ let files: MemoryFiles
+ let shared: Bool
+ @State private var open: MemoryFileTarget?
+
+ var 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) }
+ 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.")
+ .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 {
+ Button {
+ 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 {
+ Text(description).font(.footnote).foregroundStyle(Palette.secondary)
+ }
+ Text(caption(file, cap: cap))
+ .font(.caption)
+ .foregroundStyle(file.tokens > cap && !file.deleted ? Palette.attention : Palette.secondary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
+ }
+ .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.
+struct MemoryFileTarget: Identifiable {
+ let id = UUID()
+ let name: String?
+ let shared: Bool
+}
+
+/// One note: read it, edit it, delete it, or bring back an earlier version.
+struct MemoryFileView: View {
+ let memory: MemoryStore
+ let target: MemoryFileTarget
+ @State private var detail: MemoryFileDetail?
+ /// The text being edited; nil while reading.
+ @State private var draft: String?
+ @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 }
+ CardForm {
+ if let error = memory.error {
+ CardSection { Text(error).foregroundStyle(Palette.danger).textSelection(.enabled) }
+ }
+ if let text = Binding($draft) {
+ editor(text)
+ } else if let detail {
+ reader(detail)
+ } 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
+ }
+ }
+ .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 let draft {
+ 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") { withAnimation(Motion.layout) { self.draft = content } }
+ 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 func editor(_ text: Binding<String>) -> 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: text, 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) { draft = nil }
+ if target.name == nil { dismiss(); return }
+ detail = await memory.file(file, shared: target.shared)
+ }
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryView.swift
index 156f98a9..f0dfb2de 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryView.swift
@@ -99,6 +99,7 @@ struct MemoryCard: View {
}
.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 {
@@ -112,6 +113,7 @@ struct MemoryCard: View {
.fontWeight(.semibold)
ForEach(run.added, id: \.id) { Text("+ \($0.text)") }
ForEach(run.archived, id: \.id) { Text("− \($0.text)").foregroundStyle(Palette.tertiary) }
+ ForEach(run.files ?? [], id: \.version) { Label("Added to \($0.name)", systemImage: "doc.text").foregroundStyle(Palette.secondary) }
}
.frame(maxWidth: .infinity, alignment: .leading)
if !run.undone {
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/MemoryStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/MemoryStore.swift
index 99524bcd..5581a961 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/MemoryStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/MemoryStore.swift
@@ -31,6 +31,34 @@ final class MemoryStore {
}
}
+ /// A long-form file as it is now, with its versions.
+ func file(_ name: String, shared: Bool) async -> MemoryFileDetail? {
+ do {
+ return try await client().memoryFile(botId: botId, file: name, shared: shared)
+ } catch {
+ self.error = error.localizedDescription
+ 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,
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift
index 1c21c207..305bee38 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift
@@ -51,6 +51,8 @@ struct ChatRow: View {
ConnectionRequestCard(entry: entry, request: request).padding(.top, 12)
} else if let card = entry.data.memory {
MemoryNoticeRow(entry: entry, card: card).padding(.top, 10)
+ } else if let card = entry.data.memoryFile {
+ MemoryFileRow(entry: entry, card: card).padding(.top, 10)
} else if let card = entry.data.handoff {
HandoffCardRow(entry: entry, card: card).padding(.top, 10)
} else if let compaction = entry.data.compaction {
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/MemoryFileRow.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/MemoryFileRow.swift
new file mode 100644
index 00000000..bf37debe
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/MemoryFileRow.swift
@@ -0,0 +1,79 @@
+import CodyncKit
+import SwiftUI
+
+/// A bot's change to a memory file in the chat: "Updated people.md" with the diff and an undo, a change put back
+/// and why, or for a bot that asks first, the change waiting for the user.
+struct MemoryFileRow: View {
+ let entry: Entry
+ let card: MemoryFileCard
+ @Environment(BotStore.self) private var model
+ @State private var expanded = false
+
+ var body: some View {
+ let answering = model.answering[entry.id] != nil
+ if card.choice == .answer {
+ VStack(alignment: .leading, spacing: 10) {
+ line
+ if let diff = card.diff, !diff.isEmpty { LineDiff(text: diff) }
+ HStack(spacing: 8) {
+ if answering {
+ Spinner()
+ } else {
+ Button("Allow") { model.answerMemory(entry, .approve) }.buttonStyle(PrimaryButtonStyle())
+ Button("Don't") { model.answerMemory(entry, .decline) }.buttonStyle(SecondaryButtonStyle())
+ }
+ }
+ }
+ .padding(12)
+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 14))
+ .padding(.trailing, 40)
+ } else {
+ HStack(alignment: expanded ? .top : .center, spacing: 4) {
+ if let diff = card.diff, !diff.isEmpty, card.status != "restored" {
+ Disclosure(isExpanded: $expanded) { LineDiff(text: diff) } label: { line }
+ } else {
+ line.frame(maxWidth: .infinity)
+ }
+ if card.choice == .undo {
+ if answering {
+ Spinner()
+ } else {
+ IconButton("Undo", systemImage: "arrow.uturn.backward") { model.answerMemory(entry, .undo) }
+ }
+ }
+ }
+ .padding(.horizontal, 12)
+ }
+ }
+
+ private var line: some View {
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Image(systemName: card.status == "restored" ? "exclamationmark.triangle" : "doc.text").font(.caption2)
+ Text(entry.data.text ?? "")
+ if card.big == true, card.choice == .undo {
+ Text("Removes much of it").foregroundStyle(Palette.attention)
+ }
+ }
+ .font(.footnote)
+ .foregroundStyle(Palette.secondary)
+ }
+}
+
+/// `- ` removed and `+ ` added lines, colored.
+struct LineDiff: View {
+ let text: String
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 1) {
+ ForEach(Array(text.split(separator: "\n", omittingEmptySubsequences: false).enumerated()), id: \.offset) { _, line in
+ Text(line.isEmpty ? " " : String(line))
+ .foregroundStyle(line.hasPrefix("+ ") ? Palette.added : line.hasPrefix("- ") ? Palette.removed : Palette.secondary)
+ }
+ }
+ .font(.caption.monospaced())
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(8)
+ .background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 8))
+ }
+}
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/MemoryTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/MemoryTests.swift
index 0424503b..efba4570 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/MemoryTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/MemoryTests.swift
@@ -45,3 +45,23 @@ import Testing
#expect(card.handoff?.isDraft == true)
#expect(try decode(#"{"handoff": {"status": "sent"}}"#).handoff?.isDraft == false)
}
+
+@Test func memoryFilesAndTheirChatLinesDecode() throws {
+ let json = """
+ {"shared": false, "yours": {"entries": [], "used": 0, "cap": 400}, "bot": {"entries": [], "used": 0, "cap": 1200},
+ "dreams": [{"id": 1, "bot": "b", "at": 5, "undone": false, "added": [], "archived": [],
+ "files": [{"name": "people.md", "shared": false, "version": 3}]}],
+ "projectMemory": null,
+ "files": {"yours": {"files": [], "folder": "/d/shared-memory"},
+ "bot": {"files": [{"bot": "b", "name": "people.md", "hash": "ab", "size": 40, "mtime": 1,
+ "description": "The user's family", "tokens": 12, "deleted": false, "version": 3, "updatedAt": 2, "rev": 4}],
+ "folder": "/d/bots/b/bot-memory"},
+ "cap": 2000, "folderCap": 20}}
+ """
+ let view = try JSONDecoder().decode(MemoryView.self, from: Data(json.utf8))
+ #expect(view.files?.bot.files.first?.description == "The user's family")
+ #expect(view.dreams.first?.files?.first?.name == "people.md")
+ let line = try JSONDecoder().decode(EntryData.self, from: Data(#"{"text": "Updated people.md", "memoryFile": {"file": "people.md", "status": "done", "diff": "+ x", "big": true}}"#.utf8))
+ #expect(line.memoryFile?.choice == .undo)
+ #expect(line.memoryFile?.big == true)
+}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index d84f7ba5..125b9622 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -14,6 +14,7 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
- bot 會在空檔時整理記憶,只採用你親口打的字,貼上或引用的內容不算;每次整理都列在 Dreams 裡,可以復原。
- 原本的記憶會自動搬過來。
- 對話太長時,bot 會先摘要較早的內容,摘要可以在聊天裡展開;摘要也不夠用時,會改用一張卡片開新對話,你可以先編輯它要帶過去的內容,或選擇保留原本的對話。
+- bot 可以把較長的細節寫成筆記(每個主題一份),在記憶裡就能閱讀、編輯、刪除或還原任何一個版本;bot 改了筆記時,聊天裡會顯示改了哪些地方,一鍵就能復原。
### en-US
@@ -22,6 +23,7 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
- Between chats, bots tidy their memory using only words you typed yourself, not pasted or quoted text. Every run is listed under Dreams and can be undone.
- Your existing memory moves over automatically.
- When a chat runs long, the bot summarizes the earlier part, and you can open the summary in the chat. When that's no longer enough, a card offers a fresh conversation: edit what it carries over, or keep the current one.
+- Bots can keep longer notes, one topic each. Read, edit, delete or bring back any version from memory, and when a bot changes a note, the chat shows what changed with a one-tap undo.
## 2.17.5
diff --git a/docs/design/bot-memory.md b/docs/design/bot-memory.md
index c886b1fb..0ecdad00 100644
--- a/docs/design/bot-memory.md
+++ b/docs/design/bot-memory.md
@@ -1,8 +1,8 @@
# Bot memory and compaction
Status (2026-10-18): the cards, the move from Engram, writes by permission, the checks, dreaming and all three
-apps are built in 2.18.0 (M0). So are instructions for every harness (M1) and the cache-safe opening with
-host-run compaction and the handoff (M2). How it works today is in
+apps are built in 2.18.0 (M0). So are instructions for every harness (M1), the cache-safe opening with
+host-run compaction and the handoff (M2), and long-form memory files (M3). How it works today is in
[context and memory](../features/context-and-memory.md). The plan from there is in [Rollout](#rollout): instructions for every harness (M1), the cache-safe opening and
compaction (M2), long-form memory files (M3), evaluation (M4) and the public mirror (M5). The research behind it
is in [bot memory research](bot-memory-research.md). The numbers are starting values to be tuned against the
@@ -26,6 +26,10 @@ Built differently from the plan below, for now:
compaction line in the chat has no summary, since Codex reports none; its handoff is built from the chat.
- The handoff card appears as soon as a rollover is due, not when the user returns, so it can be edited before
the message that sends it.
+- A memory file changed by no bot's tool call (an editor, another program) is recorded without the checks or a
+ chat line: the user owns their computer. Its description is left out of the index when it fails the checks.
+- "Drops more than a quarter" is measured as the file getting more than a quarter shorter, so a changed line
+ isn't flagged; the diff shows a rewrite either way.
In one line: **memory records the person, the transcript stays in the host, the opening stays frozen until
compaction, and the host decides when to compact.**
@@ -782,7 +786,7 @@ Each milestone ships as its own minor release, with an e2e pass on all three app
- The keep-list: Claude through `/compact`, Codex through `compact_prompt`.
- The summary card, the editable handoff and its history bookmark.
- Cache tokens asserted in e2e.
-- **M3. Long-form memory.**
+- **M3. Long-form memory (built).**
- The folders, the naming and cap rules, `memory_files` and `memory_file_versions`.
- The turn-end scan, versions, checks and restore; compare-and-swap host writes.
- The index in the opening; `read_memory`, `edit_memory`, and `search_memory` over files;
diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.md
index 5b571bee..75b36668 100644
--- a/docs/features/context-and-memory.md
+++ b/docs/features/context-and-memory.md
@@ -73,7 +73,7 @@ the `codync-mem` crate; `chat/memory` runs them in the host.
full content: mtime and size first, then SHA-256; a file younger than 2 s waits (the turn-end scan looks again
once it settles). A change from a bot's tool call (its `locations` or diffs name the path) runs the checks, the
cap and the description; one that fails is put back and the chat says why. Otherwise the chat shows
- "Updated people.md" with the diff and an undo, flagged when it removes more than a quarter. Other changes (an
+ "Updated people.md" with the diff and an undo, flagged when it leaves the file more than a quarter shorter. Other changes (an
editor, another program) are recorded as "this computer" with no chat line; 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 a
@@ -96,9 +96,13 @@ the `codync-mem` crate; `chat/memory` runs them in the host.
every bot. Gemini CLI, Kilo Code and Kiro have no switch Codync can use. A project bot's `MEMORY.md` shows
read-only on its memory screen.
- **The apps** (iPhone, desktop, terminal) show "About you", "This bot", the dream log and the project's notes,
- with add, edit, pin, archive, forget and forget-everything. They fetch with `memory` and fetch again when the
- bot's `memoryRev` moves. Methods: `memory`, `saveMemory`, `pinMemory`, `archiveMemory`, `forgetMemory`,
- `clearMemory`, `undoDream`, `answerMemory`, `undoMemory`.
+ 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. In
+ the chat a note's change shows its diff, with an undo, or Allow and Don't for a bot that asks first. They fetch
+ with `memory` and fetch again when the bot's `memoryRev` moves. Methods: `memory`, `saveMemory`, `pinMemory`,
+ `archiveMemory`, `forgetMemory`, `clearMemory`, `undoDream`, `answerMemory`, `undoMemory` (entry and note
+ lines alike), `memoryFile`, `saveMemoryFile`, `deleteMemoryFile`, `restoreMemoryFile`.
- **Moving the old memory**: on the first start of this version, each bot's Engram database (or the Markdown
memory before it) moves in once. What the old opening showed comes in active as far as the cap allows (the
profile and pinned facts first, then the newest), the rest archived; then the old files (deleted bots' too) and
diff --git a/host/crates/memory/src/files.rs b/host/crates/memory/src/files.rs
index 1dba0756..310ba833 100644
--- a/host/crates/memory/src/files.rs
+++ b/host/crates/memory/src/files.rs
@@ -147,16 +147,10 @@ pub fn check(content: &str) -> std::result::Result<(), Refusal> {
Ok(())
}
-/// Whether going from `before` to `after` removes more than a quarter of the file.
+/// Whether going from `before` to `after` leaves the file more than a quarter shorter. A changed line is a change,
+/// not a loss; the diff shows a rewrite either way.
pub fn drops_much(before: &str, after: &str) -> bool {
- let removed: usize = ops(before, after)
- .iter()
- .filter_map(|op| match op {
- Op::Remove(line) => Some(tokens::estimate(line) + 1),
- Op::Keep(_) | Op::Add(_) => None,
- })
- .sum();
- removed * 4 > tokens::estimate(before) + before.lines().count()
+ tokens::estimate(after) * 4 < tokens::estimate(before) * 3
}
/// The lines that changed, `- ` removed and `+ ` added, with two unchanged lines (` `) around each change and `…`
@@ -571,6 +565,7 @@ mod tests {
assert_eq!(diff(before, after), " c\n d\n- e\n+ E\n f\n g");
assert!(!drops_much(before, after));
assert!(drops_much(before, "a\nb"));
+ assert!(!drops_much("- Allergic to peanuts", "- Allergic to peanuts and kiwi"), "a changed line is no loss");
assert_eq!(diff("", "x"), "+ x");
}
diff --git a/host/src/tui/app/navigate.rs b/host/src/tui/app/navigate.rs
index 694e868b..3dcdb757 100644
--- a/host/src/tui/app/navigate.rs
+++ b/host/src/tui/app/navigate.rs
@@ -186,9 +186,7 @@ impl App {
KeyCode::Enter if picked.as_ref().is_some_and(|e| e.data["connectionRequest"]["status"] == "pending") => {
self.open_connection();
}
- KeyCode::Char(c @ ('y' | 'n'))
- if picked.as_ref().is_some_and(|e| e.data["memory"]["status"] == "pending") =>
- {
+ KeyCode::Char(c @ ('y' | 'n')) if picked.as_ref().is_some_and(|e| memory_status(e) == Some("pending")) => {
if let Some(e) = picked {
self.call(
"answerMemory",
@@ -198,9 +196,7 @@ impl App {
}
}
KeyCode::Char('u')
- if picked
- .as_ref()
- .is_some_and(|e| matches!(e.data["memory"]["status"].as_str(), Some("done" | "accepted"))) =>
+ if picked.as_ref().is_some_and(|e| matches!(memory_status(e), Some("done" | "accepted"))) =>
{
if let Some(e) = picked {
self.call("undoMemory", json!({"entryId": e.id}), After::Answered(e.id.clone()));
@@ -299,6 +295,11 @@ impl App {
}
}
+/// The status of a memory line: an entry's or a note's.
+fn memory_status(e: &super::Entry) -> Option<&str> {
+ e.data["memory"]["status"].as_str().or_else(|| e.data["memoryFile"]["status"].as_str())
+}
+
#[cfg(test)]
mod tests {
use super::super::{Bot, test_app};
diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rs
index 3932ae70..4d9b7081 100644
--- a/host/src/tui/app/overlay_keys.rs
+++ b/host/src/tui/app/overlay_keys.rs
@@ -84,6 +84,10 @@ impl App {
ConfirmAct::ClearMemory(id, shared) => {
self.call("clearMemory", json!({"botId": id, "shared": shared}), 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.rs
index bf6faf90..db318915 100644
--- a/host/src/tui/app/ui.rs
+++ b/host/src/tui/app/ui.rs
@@ -97,6 +97,13 @@ pub enum ConfirmAct {
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.rs
index 452b97af..6ec4f712 100644
--- a/host/src/tui/manage/fields.rs
+++ b/host/src/tui/manage/fields.rs
@@ -78,6 +78,12 @@ 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);
+ let body =
+ json!({"botId": bot, "file": file, "shared": shared, "content": values["content"], "base": base});
+ self.sheet("saveMemoryFile", body, Reply::FieldsSaved);
+ }
}
}
}
@@ -104,3 +110,32 @@ 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.rs
index 7afc0458..891a6b96 100644
--- a/host/src/tui/manage/memory.rs
+++ b/host/src/tui/manage/memory.rs
@@ -3,6 +3,7 @@
use super::super::app::{App, Confirm, ConfirmAct, Editor, Overlay};
use super::Reply;
+use super::s;
use crossterm::event::{KeyCode, KeyEvent};
use serde_json::{Value, json};
@@ -10,18 +11,21 @@ use serde_json::{Value, json};
pub enum Section {
Yours,
Bot,
+ /// Both layers' long-form files.
+ Notes,
Dreams,
/// The project folder's own memory (Claude Code's `MEMORY.md`), read-only.
Project,
}
impl Section {
- const ALL: [Self; 4] = [Self::Yours, Self::Bot, Self::Dreams, Self::Project];
+ const ALL: [Self; 5] = [Self::Yours, Self::Bot, Self::Notes, Self::Dreams, Self::Project];
pub fn label(self) -> &'static str {
match self {
Self::Yours => "About you",
Self::Bot => "This bot",
+ Self::Notes => "Notes",
Self::Dreams => "Dreams",
Self::Project => "Project memory",
}
@@ -32,7 +36,7 @@ impl Section {
match self {
Self::Yours => Some(true),
Self::Bot => Some(false),
- Self::Dreams | Self::Project => None,
+ Self::Notes | Self::Dreams | Self::Project => None,
}
}
}
@@ -55,6 +59,12 @@ pub enum MemoryMode {
id: Option<i64>,
editor: Editor,
},
+ /// One note: what it holds and its versions (`detail`, once fetched). The cursor moves over the versions.
+ File {
+ name: String,
+ shared: bool,
+ detail: Option<Value>,
+ },
}
impl MemorySheet {
@@ -65,7 +75,15 @@ impl MemorySheet {
pub fn editor(&mut self) -> Option<&mut Editor> {
match &mut self.mode {
MemoryMode::Edit { editor, .. } => Some(editor),
- MemoryMode::Browse => None,
+ 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,
}
}
@@ -76,6 +94,18 @@ impl MemorySheet {
Section::Yours => &view["yours"]["entries"],
Section::Bot => &view["bot"]["entries"],
Section::Dreams => &view["dreams"],
+ Section::Notes => {
+ // 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() {
+ let mut file = file.clone();
+ file["shared"] = shared.into();
+ rows.push(file);
+ }
+ }
+ return rows;
+ }
Section::Project => return Vec::new(),
};
list.as_array().cloned().unwrap_or_default()
@@ -131,6 +161,9 @@ 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,
@@ -171,6 +204,20 @@ impl App {
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 {
@@ -239,4 +286,61 @@ 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";
diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rs
index fcc5a5d5..9393aba3 100644
--- a/host/src/tui/manage/mod.rs
+++ b/host/src/tui/manage/mod.rs
@@ -16,7 +16,7 @@ mod routines;
mod skill;
pub use analytics::AnalyticsSheet;
-pub use fields::handoff_fields;
+pub use fields::{handoff_fields, memory_file_fields};
pub use memory::{MemoryMode, MemorySheet, Section};
pub use routines::local_zone;
pub use skill::SkillSheet;
@@ -36,6 +36,8 @@ pub const REACTIONS: [&str; 6] = ["👍", "❤️", "😂", "🎉", "👀", "✅
pub enum Reply {
Memory(String),
MemorySaved(String),
+ /// A note the bot's memory sheet has open.
+ MemoryFile(String),
Routines(String),
RoutineSaved,
/// A routine's webhook URL and key: copied as a ready-to-run curl.
@@ -169,6 +171,13 @@ 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.rs
index 1ff56f34..d6a0755f 100644
--- a/host/src/tui/manage/replies.rs
+++ b/host/src/tui/manage/replies.rs
@@ -32,12 +32,27 @@ impl App {
if let Overlay::Memory(m) = o
&& m.bot == bot
{
- m.mode = MemoryMode::Browse;
+ if let MemoryMode::Edit { .. } = m.mode {
+ m.mode = MemoryMode::Browse;
+ }
m.busy = false;
}
}
self.refresh_sheets();
}
+ Reply::MemoryFile(bot) => {
+ for o in &mut self.overlays {
+ if let Overlay::Memory(m) = o
+ && 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;
+ }
+ }
+ }
Reply::SkillDetails(id) => {
for o in &mut self.overlays {
if let Overlay::Skill(s) = o
@@ -239,7 +254,7 @@ impl App {
}
}
}
- Reply::Memory(_) | Reply::MemorySaved(_) | Reply::Routines(_) => {
+ Reply::Memory(_) | Reply::MemorySaved(_) | Reply::MemoryFile(_) | Reply::Routines(_) => {
for o in &mut self.overlays {
match o {
Overlay::Memory(m) => {
@@ -265,6 +280,9 @@ impl App {
match o {
Overlay::Memory(m) => {
calls.push(("memory", m.body(), After::Sheet(Reply::Memory(m.bot.clone()))));
+ if let Some(body) = m.file_body() {
+ calls.push(("memoryFile", body, After::Sheet(Reply::MemoryFile(m.bot.clone()))));
+ }
}
Overlay::Routines(l) => {
calls.push(("routines", json!({"botId": l.bot}), After::Sheet(Reply::Routines(l.bot.clone()))));
diff --git a/host/src/tui/sheets/memory_view.rs b/host/src/tui/sheets/memory_view.rs
index 6901c63a..571cab1a 100644
--- a/host/src/tui/sheets/memory_view.rs
+++ b/host/src/tui/sheets/memory_view.rs
@@ -24,7 +24,15 @@ pub fn draw(buf: &mut Buffer, area: Rect, app: &App, memory: &MemorySheet) {
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"
+ }
MemoryMode::Browse => match memory.section {
+ Section::Notes => {
+ notes(buf, body, memory);
+ "←→ section · ↑↓ move · ↵ open · n new note · Esc close"
+ }
Section::Yours | Section::Bot => {
entries(buf, body, app, memory);
"←→ section · ↑↓ move · n add · ↵ edit · p pin · a archive · x forget · s shared · D clear"
@@ -152,6 +160,75 @@ fn dreams(buf: &mut Buffer, body: Rect, memory: &MemorySheet) {
}
}
+/// Both layers' long-form notes: name, where it lives, description, size and date, marked past a cap.
+fn notes(buf: &mut Buffer, body: Rect, memory: &MemorySheet) {
+ let palette = theme();
+ let Some(view) = &memory.view else { return };
+ put(
+ buf,
+ body.x,
+ body.y,
+ body.width,
+ "Longer notes, one topic each. The bot reads one when its topic comes up.",
+ palette.secondary.patch(palette.panel),
+ );
+ 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);
+ return;
+ }
+ let cap = view["files"]["cap"].as_u64().unwrap_or(2_000);
+ let height = usize::from(body.height.saturating_sub(2)) / 2;
+ 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));
+ let tokens = f["tokens"].as_u64().unwrap_or(0);
+ let over = if tokens > cap && !deleted { 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();
+ let Some(detail) = detail else {
+ put(buf, body.x, body.y, body.width, "Loading…", palette.dim.patch(palette.panel));
+ return;
+ };
+ put(buf, body.x, body.y, body.width, s(detail, "path"), 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));
+ }
+}
+
fn project(buf: &mut Buffer, body: Rect, memory: &MemorySheet) {
let palette = theme();
let Some(project) = memory.view.as_ref().map(|v| &v["projectMemory"]) else { return };
diff --git a/host/src/tui/view/help.rs b/host/src/tui/view/help.rs
index 2af7004d..eaf7a4f9 100644
--- a/host/src/tui/view/help.rs
+++ b/host/src/tui/view/help.rs
@@ -34,7 +34,7 @@ const HELP: [(&str, &str, &str); 59] = [
("CHAT", "j k ↵", "picking: move / open"),
("CHAT", "1…6", "picking: react"),
("CHAT", "f", "picking: save its files"),
- ("CHAT", "o", "picking: show a summary or handoff"),
+ ("CHAT", "o", "picking: show a summary, handoff or note change"),
("CHAT", "e K", "picking a handoff: edit / keep the chat"),
("CHAT", "↵", "picking a bot message: open its conversation"),
("CHAT", "esc", "close the thread"),
diff --git a/host/src/tui/view/transcript.rs b/host/src/tui/view/transcript.rs
index b17a8320..4274057f 100644
--- a/host/src/tui/view/transcript.rs
+++ b/host/src/tui/view/transcript.rs
@@ -303,6 +303,14 @@ fn entry_lines(
_ => "",
};
format!("{}{hint}", e.notice_text())
+ } else if let Some(status) = e.data["memoryFile"]["status"].as_str() {
+ // A bot's change to a memory note: the same keys, and the diff unfolds.
+ let hint = match status {
+ "pending" => " · o shows the change · y allows · n declines",
+ "done" | "accepted" => " · o shows the change · u undoes",
+ _ => "",
+ };
+ format!("{}{hint}", e.notice_text())
} else if let Some(status) = e.data["handoff"]["status"].as_str() {
// The chat starts over with a handoff: read it, edit it or keep the conversation while it's a draft.
let hint =
@@ -352,9 +360,13 @@ fn entry_lines(
}
}
-/// The full text a chat line folds away: a compaction's summary, or what a handoff carries.
+/// The full text a chat line folds away: a compaction's summary, what a handoff carries, or a note's change.
pub(in crate::tui) fn unfoldable(e: &Entry) -> Option<&str> {
- e.data["handoff"]["text"].as_str().or_else(|| e.data["compaction"]["summary"].as_str()).filter(|t| !t.is_empty())
+ e.data["handoff"]["text"]
+ .as_str()
+ .or_else(|| e.data["compaction"]["summary"].as_str())
+ .or_else(|| e.data["memoryFile"]["diff"].as_str())
+ .filter(|t| !t.is_empty())
}
/// A bot-to-bot exchange, or a run of them, as one compact line ("· Messaged ▌O▐ Owen",