feat: connect conversations with Magic Notes

Let users retain useful assistant replies or complete conversations without
leaving their chat workflow. Preview and edit captured text, choose an existing
note or atomically create a note with its first entry, and return to the source
conversation or message from saved records.

Add an application-scoped Notes workbar tab with title/body search and quick
text appends. Preserve drafts across conversation switches and guard closing,
replacement and disabling. Schema 48 stores optional source metadata without
rewriting file-backed bodies; source deletion retains the saved note. Older
clients cannot reopen an upgraded database without a pre-upgrade backup.

Release note: 可将助手回答或完整会话预览、编辑后加入魔法笔记,并从笔记返回原会话或消息。右侧快速笔记支持搜索和追加文字,切换会话保留草稿;采集本身不调用模型,保存后自动评论仍遵循已有设置。

Validation: isolated HEAD-based candidate passed 22 files / 930 focused tests,
plus 20 gateway tests after including its create-result fixture adjustment.
Real Electron App/preload/IPC/SQLite acceptance passed for all 502 historical
messages, exact-entry/source navigation, native keyboard input in a 214px
panel, reopen and source-deletion retention, with zero capture model calls.
Repository lint and web TypeScript passed. Cached whitespace and secret-pattern
checks passed; native-client changes and unrelated IPC extraction are excluded.

Validation limits: the isolated source tree reuses installed node_modules,
where a parallel task upgraded DSH from the committed 0.1.2-rc.1 to 0.1.7-rc.2.
Full typecheck reports 14 DSH errors in three unchanged files; the full-suite
attempt with --bail=1 also fails in deepseek-harness-host.test.ts. These are not
all-green repository or release-package results. Earlier execution-time full
suite failures and fixture repairs remain recorded in the feature progress doc.
This commit is contained in:
mesalogo
2026-09-27 08:17:54 +08:00
parent 55efca3ee1
commit 1094433a7d
51 changed files with 1949 additions and 56 deletions
@@ -1,5 +1,8 @@
// @vitest-environment node
import { mkdtemp, rm } from 'node:fs/promises'
import fs from 'node:fs'
import { randomUUID } from 'node:crypto'
import { DatabaseSync } from 'node:sqlite'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -91,12 +94,104 @@ describe('production preload -> registered IPC -> SQLite canvas persistence', ()
open()
})
afterEach(async () => {
vi.restoreAllMocks()
await dispose?.()
database?.close()
bridge.handlers.clear()
await rm(directory, { recursive: true, force: true })
})
it('captures verified source labels and preserves them after source deletion, edits and reopen', async () => {
const project = database.createProject({ name: 'Actual project', rootPath: directory,
description: '', defaultWorkMode: 'execute', runtimeSelection: { provider: 'opencode' } })
const header = { id: randomUUID(), title: 'Actual conversation', projectId: project.id, updatedAt: 1 }
const messages = Array.from({ length: 120 }, (_, index) => ({ id: randomUUID(),
role: index % 2 ? 'assistant' as const : 'user' as const,
content: `History ${index}`, state: 'complete' as const, createdAt: index }))
database.saveLocalConversations([{ header, messages }])
const source = { kind: 'conversation' as const, conversationId: header.id,
messageIds: messages.map(message => message.id), capturedAt: '2026-09-26T01:02:03.000Z',
conversationTitle: 'Forged title', projectId: randomUUID(), projectName: 'Forged project' }
const content = { version: 1 as const, ops: [{ insert: messages.map(message => `${message.role}: ${message.content}\n`).join('') }] }
const created = await api.create({ title: 'Captured history', content, source })
expect(created.createdEntryId).toBe(created.entries[0]!.id)
const expectedSource = { ...source, conversationTitle: header.title, projectId: project.id, projectName: project.name }
expect(created.entries[0]!.source).toEqual(expectedSource)
expect(created.entries[0]!.content).toEqual(content)
const appended = await api.createEntry({ noteId: created.id, content,
source: { ...source, kind: 'message', messageIds: [messages[1]!.id] } })
expect(appended.entries.find(entry => entry.id === appended.createdEntryId)?.source)
.toEqual({ ...expectedSource, kind: 'message', messageIds: [messages[1]!.id] })
database.deleteLocalConversation(header.id)
const edited = await api.updateEntry({ entryId: created.createdEntryId!, expectedRevision: 0,
content: { version: 1, ops: [{ insert: 'Edited copy\n' }] } })
expect(edited.entries[0]!.source).toEqual(expectedSource)
await reopen()
expect(await api.get(created.id)).toEqual(edited)
const sql = new DatabaseSync(join(directory, 'assistant.sqlite'))
try {
const row = sql.prepare('SELECT source_json FROM magic_note_entries WHERE id = ?').get(created.createdEntryId!) as { source_json: string }
expect(JSON.parse(row.source_json)).toEqual(expectedSource)
} finally { sql.close() }
await api.remove(created.id)
await expect(api.get(created.id)).rejects.toThrow()
})
it('rejects invalid source identities and source-only creates without leaving empty notes', async () => {
const header = { id: randomUUID(), title: 'Global conversation', updatedAt: 1 }
const message = { id: randomUUID(), role: 'assistant' as const, content: 'Answer', state: 'error' as const, createdAt: 1 }
database.saveLocalConversations([{ header, messages: [message] }])
const content = { version: 1 as const, ops: [{ insert: 'Edited preview\n' }] }
const source = { kind: 'message' as const, conversationId: header.id, messageIds: [message.id],
capturedAt: new Date().toISOString(), conversationTitle: 'Untrusted', projectId: randomUUID(), projectName: 'Untrusted' }
await expect(api.create({ title: 'Invalid', source })).rejects.toThrow()
await expect(api.create({ title: 'Invalid', content, source: { ...source, messageIds: [randomUUID()] } })).rejects.toThrow()
await expect(api.create({ title: 'Invalid', content, source: { ...source, messageIds: [message.id, message.id] } })).rejects.toThrow()
await expect(api.create({ title: 'Invalid', content, source: { ...source, conversationId: randomUUID() } })).rejects.toThrow()
expect((await api.list()).notes).toEqual([])
const note = await api.create({ title: 'Partial answer', content, source })
expect(note.entries[0]!.source).toEqual({ kind: 'message', conversationId: header.id,
messageIds: [message.id], capturedAt: source.capturedAt, conversationTitle: header.title })
await api.remove(note.id)
expect(database.getConversation(header.id).messages).toEqual([message])
})
it('rolls back a new note when writing its initial body fails and allows retry', async () => {
const rename = fs.renameSync
const failure = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {
if (String(to).includes('entries')) throw new Error('Initial body write failed')
rename(from, to)
})
const input = { title: 'Atomic capture', content: { version: 1 as const, ops: [{ insert: 'Saved once\n' }] } }
await expect(api.create(input)).rejects.toThrow('Initial body write failed')
expect((await api.list()).notes).toEqual([])
failure.mockRestore()
const note = await api.create(input)
expect(note.entries).toHaveLength(1)
expect(note.createdEntryId).toBe(note.entries[0]!.id)
expect((await api.list()).notes).toHaveLength(1)
})
it('searches titles and all entry bodies with note-level limits while preserving Agent entry results', async () => {
const titleOnly = await api.create({ title: 'Needle title' })
expect(titleOnly.createdEntryId).toBeUndefined()
const bodyOnly = await api.create({ title: 'Body only', content: { version: 1, ops: [{ insert: 'Needle body\n' }] } })
for (let index = 0; index < 4; index++) {
await api.createEntry({ noteId: bodyOnly.id, content: { version: 1, ops: [{ insert: `Needle ${index}\n` }] } })
}
await api.createEntry({ noteId: bodyOnly.id, content: { version: 1, ops: [{ insert: 'Latest unrelated preview\n' }] } })
const results = await api.search({ query: ' Needle ', limit: 2 })
expect(new Set(results.map(note => note.id))).toEqual(new Set([bodyOnly.id, titleOnly.id]))
expect(results.find(note => note.id === bodyOnly.id)).toMatchObject({ entryCount: 6, preview: 'Latest unrelated preview' })
expect(database.searchMagicNotes('Needle', 20).filter(result => result.noteId === bodyOnly.id)).toHaveLength(5)
await api.update({ noteId: titleOnly.id, pinned: true, expectedRevision: titleOnly.revision })
expect((await api.search({ query: 'Needle', limit: 1 })).map(note => note.id)).toEqual([titleOnly.id])
expect(await api.search({ query: '%' })).toEqual([])
expect(await api.search({ query: '' })).toHaveLength(2)
await expect(api.search({ query: 'Needle', limit: 0 })).rejects.toThrow()
await expect(api.search({ query: 'Needle', limit: 201 })).rejects.toThrow()
})
it.each([true, false])('limits saved, draft and todo input using persisted page order and count (vision=%s)', async (supportsImageInput) => {
getResolvedSettings.mockResolvedValue({ workspacePath: directory, supportsImageInput })
const requests: AgentExecutionRequest[] = []
@@ -53,6 +53,30 @@ function canvas(size = 40): MagicNoteCanvasContent {
}
describe('Magic note SQLite and filesystem storage', () => {
it('upgrades schema 47 with nullable sources without rewriting bodies and reopens idempotently', () => {
const { database, sql, path, directory } = setup()
const created = database.createMagicNote({ title: 'Existing note', content: rich })
const before = database.getMagicNote(created.id)
const bodyPath = join(directory, 'notes', created.id, 'entries', `${created.createdEntryId}.json`)
const body = readFileSync(bodyPath)
const modifiedAt = statSync(bodyPath).mtimeMs
database.close()
// Reconstruct the previous released schema; production never downgrades databases.
sql.exec('ALTER TABLE magic_note_entries DROP COLUMN source_json; PRAGMA user_version = 47;')
upgradeAssistantStorage(path, () => undefined)
expect(sql.prepare('PRAGMA user_version').get()).toEqual({ user_version: ASSISTANT_DATABASE_SCHEMA_VERSION })
expect(sql.prepare('SELECT source_json FROM magic_note_entries').get()).toEqual({ source_json: null })
expect(sql.prepare('PRAGMA integrity_check').get()).toEqual({ integrity_check: 'ok' })
database.initialize(directory)
expect(database.getMagicNote(created.id)).toEqual(before)
expect(database.getMagicNote(created.id).entries[0]).not.toHaveProperty('source')
expect(readFileSync(bodyPath)).toEqual(body)
expect(statSync(bodyPath).mtimeMs).toBe(modifiedAt)
database.close()
database.initialize(directory)
expect(database.getMagicNote(created.id)).toEqual(before)
})
it('preserves textual data URLs and arbitrary $asset objects through save, migration and reopen', () => {
const { database, sql, path, directory } = setup()
const text = 'data:text/plain;base64,aGVsbG8'
@@ -61,7 +85,7 @@ describe('Magic note SQLite and filesystem storage', () => {
const drawing = canvas()
drawing.pages[0]!.objects.push({ type: 'IText', ...custom }, { type: 'Group', objects: [{ type: 'Image', src: png, name: text, custom }] })
drawing.flow!.ops.push({ insert: text }, { insert: { image: png } }, { insert: { custom } })
const notes = [richText, drawing].map((content) => database.createMagicNote({ title: 'Literal URLs', content }))
const notes = [richText, drawing].map((content) => database.getMagicNote(database.createMagicNote({ title: 'Literal URLs', content }).id))
for (const [index, note] of notes.entries()) expect(note.entries[0]!.content).toEqual([richText, drawing][index])
const disk = JSON.parse(readFileSync(join(directory, 'notes', notes[1]!.id, 'entries', `${notes[1]!.entries[0]!.id}.json`), 'utf8'))
expect(disk.content.pages[0].objects[2]).toEqual({ type: 'IText', ...custom })
@@ -125,7 +149,7 @@ describe('Magic note SQLite and filesystem storage', () => {
expect(existsSync(root)).toBe(true)
expect(logged).toHaveBeenCalled()
// A delayed reset cleanup must not remove notes created afterwards.
const retained = database.createMagicNote({ title: 'New note', content: canvas() })
const retained = database.getMagicNote(database.createMagicNote({ title: 'New note', content: canvas() }).id)
failing = false
database.listMagicNotes()
expect(existsSync(root)).toBe(false)
@@ -134,7 +158,7 @@ describe('Magic note SQLite and filesystem storage', () => {
it('still rejects authoritative body rename failures before committing SQL', () => {
const { database } = setup()
const note = database.createMagicNote({ title: 'Body error', content: rich })
const note = database.getMagicNote(database.createMagicNote({ title: 'Body error', content: rich }).id)
const entry = note.entries[0]!
vi.spyOn(fs, 'renameSync').mockImplementation((source, target) => {
if (String(target).endsWith(`${entry.id}.json`)) throw new Error('body rename blocked')
@@ -229,6 +253,7 @@ describe('Magic note SQLite and filesystem storage', () => {
DROP TABLE IF EXISTS supervision_review_navigation; DROP TABLE IF EXISTS supervision_review_batches;
DROP TABLE IF EXISTS supervision_review_sources; DROP TABLE IF EXISTS supervision_review_runs;
DROP TABLE review_checkpoints; ALTER TABLE messages DROP COLUMN review_revision;
ALTER TABLE magic_note_entries DROP COLUMN source_json;
PRAGMA user_version = 37`)
rmSync(join(directory, 'notes'), { recursive: true })
const progress: number[] = []
@@ -270,7 +295,7 @@ describe('Magic note SQLite and filesystem storage', () => {
it('reclaims migrated SQLite payload space and restores a coordinated database/files backup', async () => {
const { database, sql, directory, path } = setup()
const note = database.createMagicNote({ title: 'Large legacy PDF', content: canvas(2 * 1024 * 1024) })
const note = database.getMagicNote(database.createMagicNote({ title: 'Large legacy PDF', content: canvas(2 * 1024 * 1024) }).id)
const entry = note.entries[0]!
database.close()
sql.prepare('UPDATE magic_note_entries SET content_json = ? WHERE id = ?').run(JSON.stringify(entry.content), entry.id)
@@ -340,7 +365,7 @@ describe('Magic note SQLite and filesystem storage', () => {
it('rolls back failed creates and cleans their unaccepted files without affecting existing notes', () => {
const { database, sql, directory } = setup()
const retained = database.createMagicNote({ title: 'Keep', content: rich })
const retained = database.getMagicNote(database.createMagicNote({ title: 'Keep', content: rich }).id)
sql.exec(`CREATE TRIGGER fail_note_insert BEFORE INSERT ON magic_note_entries
BEGIN SELECT RAISE(ABORT, 'insert unavailable'); END`)
expect(() => database.createMagicNote({ title: 'Failed', content: canvas() })).toThrow('insert unavailable')