diff --git a/configs/feed.test.js b/configs/feed.test.js index 2b5c126..9b3ea71 100644 --- a/configs/feed.test.js +++ b/configs/feed.test.js @@ -674,8 +674,8 @@ test("a few sources are fetched at a time, and those waiting their turn already assert.ok(!started.includes("/6"), "the source under test is definitely queued"); if (action === "pause") service.setSourceStatus(ids[6], "pause"); else if (action === "delete") { - const result = service.knowledge.trash([ids[6]], "queue-test"); - if (result.status === "confirmation") service.knowledge.trash([ids[6]], "queue-test", result.preview.token); + const result = service.knowledge.trash([ids[6]], "queue-test", { kind: "workspace" }); + if (result.status === "confirmation") service.knowledge.trash([ids[6]], "queue-test", { kind: "workspace" }, result.preview.token); } else service.knowledge.attributes.write(ids[6], { feed_url: "https://example.org/changed" }); while (releases.length) { @@ -803,8 +803,8 @@ test("an item becomes a real paper and only replaces a recycled or missing paper assert.equal(knowledge.get(current).attributes.source_snapshot.feedURL, "https://rss.arxiv.org/atom/cs.LG"); assert.equal(service.importItem(item.id), current); for (const state of ["recycled", "missing"]) { - const trash = knowledge.trash([current], "trash"); - knowledge.trash([current], "trash", trash.preview.token); + const trash = knowledge.trash([current], "trash", { kind: "workspace" }); + knowledge.trash([current], "trash", { kind: "workspace" }, trash.preview.token); if (state === "missing") { const preview = purge.purge([current], "purge"); purge.purge([current], "purge", preview.token); diff --git a/main/feed/service.ts b/main/feed/service.ts index 4a4c087..5eee7c2 100644 --- a/main/feed/service.ts +++ b/main/feed/service.ts @@ -112,7 +112,7 @@ export function getItem(id: string): FeedItemDetail { function updateSource(id: string, name: string, values: Record): void { return commit.run({ sourceTab: "", feed: true, history: false, updateModified: false }, () => { const page = knowledge.get(id), title = page.blocks[page.titleBlockId]; - edits.commitEdit({ pageId: id, tabId: "feed-settings", batch: 0, blocks: name === page.title ? [] : [{ ...title, payload: payload("title", name) }], attributes: values }); + edits.commitEdit({ pageId: id, tabId: "feed-settings", batch: 0, blocks: name === page.title ? [] : [{ ...title, payload: payload("title", name) }], attributes: values }, false); commit.invalidate(["page:" + id, "block:" + page.titleBlockId]); }); diff --git a/main/history/ipc.ts b/main/history/ipc.ts index 1874c80..d0c1e3f 100644 --- a/main/history/ipc.ts +++ b/main/history/ipc.ts @@ -1,17 +1,21 @@ import { type BrowserWindow } from "electron"; import typia from "typia"; -import { historyChannels, type HistoryAPI } from "../../shared/history/ipc"; +import { historyChannels, historyChanged, type HistoryAPI } from "../../shared/history/ipc"; import { invalid, register, route, type Routes } from "../ipc"; import * as history from "../knowledge/history"; +import * as events from "../knowledge/events"; type Args = Parameters; export const routes = { state: route(typia.createAssert>(invalid), history.state), - apply: route(typia.createAssert>(invalid), history.apply), - closeTab: route(typia.createAssert>(invalid), history.close) + apply: route(typia.createAssert>(invalid), history.apply) } satisfies Routes; export function registerHistoryIPCs(window: BrowserWindow): void { const contents = window.webContents; register(contents, historyChannels, routes); + const unsubscribe = events.subscribe(event => { + if (event.type === "history" && !contents.isDestroyed()) contents.send(historyChanged, event.sources); + }); + contents.once("destroyed", unsubscribe); } \ No newline at end of file diff --git a/main/knowledge/commit.ts b/main/knowledge/commit.ts index bf1fff8..4375707 100644 --- a/main/knowledge/commit.ts +++ b/main/knowledge/commit.ts @@ -1,3 +1,4 @@ +import type { HistorySource } from "../../shared/history/ipc"; import { type ChangePreview, type CommitResult, type KnowledgeChange } from "../../shared/types/content"; import { withFileCleanup } from "../storage/files"; import * as workspace from "../workspace-state"; @@ -11,7 +12,8 @@ import * as timers from "./timer-state"; export type Options = { sourceTab: string; - history?: boolean; + history?: HistorySource | false; + replay?: history.Replay; updateModified?: boolean; confirmation?: string; feed?: boolean; @@ -20,14 +22,13 @@ export type Options = { export type Context = { change(change: Partial): void; after(action: () => void): void; - invalidate(keys: string[], exceptTab?: string): void; - clearHistory(): void; + invalidate(keys: string[], permanent?: boolean): void; persist(plan: EditChanges, pageId?: string): void; cleanup(): string[]; skip(): void; }; let effects: (() => void)[] = []; -const contexts: { options: Options; context: Context; feed: boolean }[] = []; +const contexts: { options: Options; context: Context; captures: history.Capture[]; invalid: history.Invalidation[]; feed: boolean }[] = []; export function release(): void { effects = []; contexts.length = 0; @@ -38,14 +39,15 @@ export function current(): Context { if (!contexts.length) throw new Error("A write requires a commit context"); return contexts[contexts.length - 1].context; } -export function invalidate(keys: string[], exceptTab?: string): void { - current().invalidate(keys, exceptTab); +export function invalidate(keys: string[]): void { + current().invalidate(keys); } export function run(options: Options, action: (context: Context) => T): T { const session = workspace.requireWorkspace(), start = effects.length; let cleanup: (() => string[]) | undefined; const write = (): T => session.database.transaction(() => { const changed: KnowledgeChange = { sourceTab: options.sourceTab, pages: [], blocks: [] }; + const captures: history.Capture[] = [], invalid: history.Invalidation[] = []; let publish = true; const context: Context = { change(change) { @@ -57,17 +59,14 @@ export function run(options: Options, action: (context: Context) => T): T { after(action) { effects.push(action); }, - invalidate(keys, exceptTab) { - effects.push(() => history.invalidate(keys, exceptTab)); - }, - clearHistory() { - effects.push(() => history.clear()); + invalidate(keys, permanent = false) { + invalid.push({ keys, permanent }); }, persist(plan, pageId) { if (options.updateModified === false) plan.touches.clear(); plan.persist(); for (const change of plan.timerChanges()) timers.recalculate(change.pageId, change.fields); - if (options.history && pageId) effects.push(() => history.capture(options.sourceTab, pageId, plan.rows)); + if (options.history && pageId) captures.push({ source: options.history, page: pageId, rows: plan.rows, replay: options.replay }); context.change(plan.changed()); }, cleanup() { @@ -79,7 +78,7 @@ export function run(options: Options, action: (context: Context) => T): T { publish = false; } }; - const scope = { options, context, feed: !!options.feed }; + const scope = { options, context, captures, invalid, feed: !!options.feed }; contexts.push(scope); try { const result = action(context); @@ -88,9 +87,15 @@ export function run(options: Options, action: (context: Context) => T): T { const parent = contexts[contexts.length - 2]; if (parent) { parent.context.change(changed); + parent.captures.push(...captures); + parent.invalid.push(...invalid); parent.feed ||= scope.feed; } - else effects.push(() => events.publish(changed, scope.feed)); + else effects.push(() => { + const change = events.expand(changed); + history.finish(captures, invalid, change.summaryPages ?? change.pages); + events.publish(change, scope.feed); + }); } return result; } diff --git a/main/knowledge/edits.ts b/main/knowledge/edits.ts index 5fe01f8..22b9414 100644 --- a/main/knowledge/edits.ts +++ b/main/knowledge/edits.ts @@ -1,3 +1,4 @@ +import type { HistoryOrigin, HistorySource } from "../../shared/history/ipc"; import { randomUUID } from "node:crypto"; import { attributeTargets, decodeValue, record, validUUID } from "../../shared/attrs/values"; import { blockText, payload, references, validateBlock } from "../../shared/content/blocks"; @@ -21,10 +22,10 @@ class DefinitionRollback extends Error { super("definition preview"); } } -function transact(tabId: string, action: () => CommitResult, confirmation?: string): CommitResult { +function transact(tabId: string, source: HistorySource | false, action: () => CommitResult, confirmation?: string): CommitResult { workspace.requireWorkspace(); checkTab(tabId); - return commit.run({ sourceTab: tabId, history: true, confirmation }, action); + return commit.run({ sourceTab: tabId, history: source, confirmation }, action); } function putBlock(block: ContentBlock): void { const plan = new EditChanges(); @@ -36,7 +37,7 @@ export function create(kind: PageKind = "editable", title = "", initial: Record< if (!record(initial)) throw new LabloomError({ kind: "page-invalid-attributes" }); for (const id of Object.keys(initial)) if (attributes.definition(id).readonly || id === "deleted") throw new LabloomError({ kind: "page-create-readonly" }); if (kind === "annotation") throw new LabloomError({ kind: "annotation-selection-required" }); - return createPage(kind, title, initial, parentId, tabId); + return insertPage(kind, title, initial, parentId, tabId, false); } function writable(id: string): ReturnType { const page = data.header(id); @@ -83,9 +84,9 @@ export function previewEdit(input: EditCommit): ChangePreview | null { return workspace.native().transaction(() => commit.preview(planEdit(input), input))(); } -export function commitEdit(input: EditCommit, confirmation?: string): CommitResult { +export function commitEdit(input: EditCommit, source: HistorySource | false, confirmation?: string): CommitResult { workspace.requireWorkspace(); - return transact(input?.tabId, () => { + return transact(input?.tabId, source, () => { const plan = planEdit(input); return commit.finish(plan, input.pageId, input.batch, commit.preview(plan, input)); }, confirmation); @@ -129,9 +130,9 @@ function deletionSubject(block: ContentBlock): string { return excerpt ? `“${excerpt}”` : names[block.type]; } -export function deleteBlock(input: BlockDeletion, confirmation?: string): CommitResult { +export function deleteBlock(input: BlockDeletion, source: HistorySource, confirmation?: string): CommitResult { workspace.requireWorkspace(); - return transact(input?.tabId, () => { + return transact(input?.tabId, source, () => { const { pageId, blockId } = input; writable(pageId); const plan = new EditChanges(), block = plan.block(blockId), pages = data.owners(blockId); @@ -147,9 +148,9 @@ export function deleteBlock(input: BlockDeletion, confirmation?: string): Commit }, confirmation); } -export function place(input: Placement, confirmation?: string): CommitResult { +export function place(input: Placement, source: HistorySource, confirmation?: string): CommitResult { workspace.requireWorkspace(); - return transact(input?.tabId, () => { + return transact(input?.tabId, source, () => { const { position, action } = input; if (!record(position) || !Number.isSafeInteger(position.index) || position.index < 0 || !validUUID(position.blockId)) throw new LabloomError({ kind: "block-invalid-position" }); const { pageId, containerId, index } = position; @@ -213,9 +214,9 @@ function selectPages(ids: string[]): string[] { return [...new Set(ids)]; } -export function trash(ids: string[], tabId: string, confirmation?: string): CommitResult { +export function trash(ids: string[], tabId: string, source: HistorySource, confirmation?: string): CommitResult { workspace.requireWorkspace(); - return transact(tabId, () => { + return transact(tabId, source, () => { const selected = selectPages(ids), plan = new EditChanges(); for (const id of selected) { plan.attributes(id, { deleted: true, recycle_reason: "manual_delete", recycled_at: nowSeconds() }, [], true); @@ -225,9 +226,9 @@ export function trash(ids: string[], tabId: string, confirmation?: string): Comm }, confirmation); } -export function restore(ids: string[], tabId: string): CommitResult { +export function restore(ids: string[], tabId: string, source: HistorySource): CommitResult { workspace.requireWorkspace(); - return transact(tabId, () => { + return transact(tabId, source, () => { const selected = selectPages(ids), plan = new EditChanges(); for (const id of selected) { plan.attributes(id, { deleted: false, recycle_reason: null, recycled_at: null }, [], true); @@ -238,11 +239,14 @@ export function restore(ids: string[], tabId: string): CommitResult { }); } -export function createPage(kind: PageKind = "editable", title = "", initial: Record = {}, parentId?: string, tabId = ""): PageRecord { +export function createPage(kind: PageKind = "editable", title = "", initial: Record = {}, parentId?: string, origin?: HistoryOrigin): PageRecord { + return insertPage(kind, title, initial, parentId, origin?.tabId ?? "", kind === "annotation" && parentId && origin ? origin.source : false); +} +function insertPage(kind: PageKind, title: string, initial: Record, parentId: string | undefined, tabId: string, history: HistorySource | false): PageRecord { workspace.requireWorkspace(); if (!pageKinds.includes(kind) || typeof title !== "string" || !record(initial)) throw new LabloomError({ kind: "page-invalid-create" }); const changed = { pages: [] as string[], blocks: [] as string[] }; - const page = commit.run({ sourceTab: tabId, history: !!parentId && kind === "annotation" && !!tabId }, context => { + const page = commit.run({ sourceTab: tabId, history }, context => { if (parentId) writable(parentId); if (kind === "annotation" && initial.annotation_file != null) { if (!parentId || data.header(parentId).kind !== "paper") throw new LabloomError({ kind: "annotation-paper-required" }); diff --git a/main/knowledge/events.ts b/main/knowledge/events.ts index f97ee96..d778a16 100644 --- a/main/knowledge/events.ts +++ b/main/knowledge/events.ts @@ -1,9 +1,11 @@ +import type { HistorySource } from "../../shared/history/ipc"; import { type KnowledgeChange, type PageKind } from "../../shared/types/content"; import { type Notice } from "../../shared/types/knowledge"; import * as workspace from "../workspace-state"; import * as data from "./records"; export type Event = + | { type: "history"; sources: HistorySource[] } | { type: "knowledge"; change: KnowledgeChange } | { type: "feed" } | { type: "reminder"; notice: Notice; body: string }; @@ -19,7 +21,7 @@ function emit(event: Event): void { for (const listener of listeners) listener(event); } /** Every writer uses the same owner expansion and page-kind calculation. */ -export function publish(input: KnowledgeChange, feed = false): void { +export function expand(input: KnowledgeChange): KnowledgeChange { workspace.requireWorkspace(); const change = { ...input }; if (change.blocks.length) { @@ -34,6 +36,12 @@ export function publish(input: KnowledgeChange, feed = false): void { const rows = data.statement("SELECT id,kind FROM pages WHERE id IN (SELECT value FROM json_each(?))").all(JSON.stringify(pages)) as { id: string; kind: PageKind }[]; change.kinds = Object.fromEntries(rows.map(row => [row.id, row.kind])); } + return change; +} +export function historyChanged(sources: HistorySource[]): void { + if (sources.length) emit({ type: "history", sources }); +} +export function publish(change: KnowledgeChange, feed: boolean): void { emit({ type: "knowledge", change }); if (feed || Object.values(change.kinds ?? {}).includes("feed") || change.purged?.length) emit({ type: "feed" }); } diff --git a/main/knowledge/history-state.ts b/main/knowledge/history-state.ts index 90597dc..b81b7a0 100644 --- a/main/knowledge/history-state.ts +++ b/main/knowledge/history-state.ts @@ -1,105 +1,191 @@ import { randomUUID } from "node:crypto"; -import { type HistoryState } from "../../shared/types/knowledge"; +import { LabloomError } from "../../shared/failure"; +import type { HistorySource } from "../../shared/history/ipc"; +import type { HistoryState } from "../../shared/types/knowledge"; +import * as settings from "../settings/store"; import * as workspace from "../workspace-state"; -import { type RowChanges, type StoredState } from "./changes"; -import { checkTab } from "./validation"; +import type { RowChanges, StoredState } from "./changes"; +import * as events from "./events"; + +type Entry = RowChanges & { id: string; page: string; keys: string[]; dependencies: Set; time: number; order: number; nodes: Map }; +type Node = { entry: Entry; parent: Node | null; children: Set }; +type Tree = { source: HistorySource; roots: Set; cursor: Node | null }; +export type Replay = { tree: Tree; node: Node; direction: "undo" | "redo" }; +export type Invalidation = { keys: string[]; permanent: boolean }; +export type Capture = { source: HistorySource; page: string; rows: RowChanges; replay?: Replay }; + +const trees = new Map(); +// Map iteration follows insertion order, including after unrelated records are removed. +const entries = new Map(); +const objects = new Map>>(); +// A replay also needs its context page and the blocks named by stored child lists +// to exist. Editing their contents is safe, physically deleting them is not. +const dependents = new Map>(); +let sequence = 0; +const treeKey = (source: HistorySource): string => source.kind === "page" ? "page:" + source.id : "workspace"; -type Node = { id: string; tab: string; parent: string | null; children: Set; page: string; before: StoredState; after: StoredState; keys: string[]; time: number; order: number }; -type Tab = { cursor: string | null; nodes: Set }; -type Store = { tabs: Map; nodes: Map; objects: Map>; sequence: number }; -let store: Store = { tabs: new Map(), nodes: new Map(), objects: new Map(), sequence: 0 }; export function release(): void { - store = { tabs: new Map(), nodes: new Map(), objects: new Map(), sequence: 0 }; + trees.clear(); + entries.clear(); + objects.clear(); + dependents.clear(); + sequence = 0; } -export function capture(tabId: string, pageId: string, rows: RowChanges): void { - workspace.requireWorkspace(); - const keys = [...new Set([...Object.keys(rows.before), ...Object.keys(rows.after)])]; - if (!keys.length) return; - invalidate(keys, tabId); - const definitions = new Set(); - for (const state of [rows.before, rows.after]) for (const [key, value] of Object.entries(state)) { - if (key.startsWith("page:") && value && "values" in value) for (const id of Object.keys(value.values ?? {})) definitions.add("attribute:" + id); +function treeFor(source: HistorySource): Tree { + const key = treeKey(source); + let tree = trees.get(key); + if (!tree) { + tree = { source, roots: new Set(), cursor: null }; + trees.set(key, tree); } - const tab = store.tabs.get(tabId) ?? { cursor: null, nodes: new Set() }; - store.tabs.set(tabId, tab); - const node: Node = { - id: randomUUID(), tab: tabId, parent: tab.cursor, children: new Set(), page: pageId, - ...structuredClone(rows), keys: [...keys, ...definitions], time: workspace.clock(), order: ++store.sequence - }; - store.nodes.set(node.id, node); - if (node.parent) store.nodes.get(node.parent)!.children.add(node.id); - tab.nodes.add(node.id); - tab.cursor = node.id; - for (const key of node.keys) { - const nodes = store.objects.get(key) ?? new Set(); - nodes.add(node.id); - store.objects.set(key, nodes); + return tree; +} +function children(tree: Tree, parent: Node | null): Set { + return parent?.children ?? tree.roots; +} +export function state(source: HistorySource): HistoryState { + workspace.requireWorkspace(); + const tree = trees.get(treeKey(source)); + if (!tree) return { canUndo: false, redo: [] }; + const redo = [...children(tree, tree.cursor)].map(node => node.entry).sort((a, b) => b.order - a.order); + return { canUndo: !!tree.cursor, redo: redo.map(({ id, time }) => ({ id, time })) }; +} +export function select(source: HistorySource, direction: Replay["direction"], branchId?: string): Replay { + workspace.requireWorkspace(); + const tree = trees.get(treeKey(source)); + if (!tree) throw new LabloomError({ kind: "history-empty" }); + let node = tree.cursor; + if (direction === "redo") { + const id = branchId ?? state(source).redo[0]?.id; + node = id ? entries.get(id)?.nodes.get(tree) ?? null : null; + if (node?.parent !== tree.cursor) node = null; } + if (!node) throw new LabloomError({ kind: "history-branch-invalid" }); + return { tree, node, direction }; } - -function remove(node: Node): void { - store.nodes.delete(node.id); - store.tabs.get(node.tab)?.nodes.delete(node.id); - if (node.parent) store.nodes.get(node.parent)?.children.delete(node.id); - for (const key of node.keys) { - const nodes = store.objects.get(key)!; - nodes.delete(node.id); - if (!nodes.size) store.objects.delete(key); +function attach(tree: Tree, entry: Entry): void { + const node: Node = { entry, parent: tree.cursor, children: new Set() }; + children(tree, tree.cursor).add(node); + tree.cursor = node; + entry.nodes.set(tree, node); + for (const key of entry.keys) { + let holders = objects.get(key); + if (!holders) objects.set(key, holders = new Map()); + let nodes = holders.get(tree); + if (!nodes) holders.set(tree, nodes = new Set()); + nodes.add(node); } } - -export function invalidate(keys: string[], exceptTab = ""): void { - workspace.requireWorkspace(); - const removed = new Map(); - for (const key of keys) for (const id of store.objects.get(key) ?? []) { - const node = store.nodes.get(id)!; - if (node.tab !== exceptTab) removed.set(id, node); +function remove(tree: Tree, node: Node): void { + const siblings = children(tree, node.parent); + siblings.delete(node); + for (const child of node.children) { + child.parent = node.parent; + siblings.add(child); } - const parentOf = (node: Node): string | null => { - let parent = node.parent; - while (parent && removed.has(parent)) parent = removed.get(parent)!.parent; - return parent; - }; - for (const node of removed.values()) { - const parent = parentOf(node); - for (const id of node.children) { - if (removed.has(id)) continue; - store.nodes.get(id)!.parent = parent; - if (parent) store.nodes.get(parent)!.children.add(id); + if (tree.cursor === node) tree.cursor = node.parent; + const entry = node.entry; + entry.nodes.delete(tree); + if (!entry.nodes.size) { + entries.delete(entry.id); + for (const key of entry.dependencies) { + const records = dependents.get(key)!; + records.delete(entry); + if (!records.size) dependents.delete(key); } - const tab = store.tabs.get(node.tab)!; - if (tab.cursor === node.id) tab.cursor = parent; } - for (const node of removed.values()) remove(node); + for (const key of entry.keys) { + const holders = objects.get(key)!, nodes = holders.get(tree)!; + nodes.delete(node); + if (!nodes.size) holders.delete(tree); + if (!holders.size) objects.delete(key); + } + if (!tree.roots.size) trees.delete(treeKey(tree.source)); } - -export function state(tabId: string): HistoryState { - workspace.requireWorkspace(); - checkTab(tabId); - const tab = store.tabs.get(tabId); - if (!tab) return { canUndo: false, redo: [] }; - const redo = [...tab.nodes].map(id => store.nodes.get(id)!).filter(node => node.parent === tab.cursor).sort((a, b) => b.order - a.order); - return { canUndo: tab.cursor !== null, redo: redo.map(node => ({ id: node.id, time: node.time })) }; +function invalidate(keys: Iterable, changed: Set, except?: Set): void { + for (const key of keys) for (const [tree, nodes] of objects.get(key) ?? []) { + if (except?.has(tree)) continue; + changed.add(tree); + for (const node of nodes) remove(tree, node); + } } - -export function close(tabId: string): void { - workspace.requireWorkspace(); - checkTab(tabId); - for (const id of store.tabs.get(tabId)?.nodes ?? []) remove(store.nodes.get(id)!); - store.tabs.delete(tabId); +function mergeState(target: StoredState, state: StoredState): void { + for (const [key, value] of Object.entries(state)) { + const previous = target[key]; + if (previous && value && !("content" in previous) && !("content" in value)) { + target[key] = { ...previous, ...value, values: { ...previous.values, ...value.values } }; + } + else target[key] = value; + } } - -export function clear(): void { - workspace.requireWorkspace(); - store.tabs.clear(); - store.nodes.clear(); - store.objects.clear(); +function capture(inputs: Capture[], pages: string[], changed: Set): void { + if (!inputs.length) return; + let rows = inputs[0].rows; + if (inputs.length > 1) { + rows = { before: {}, after: {} }; + for (const input of inputs) mergeState(rows.after, input.rows.after); + for (let i = inputs.length - 1; i >= 0; i--) mergeState(rows.before, inputs[i].rows.before); + } + const keys = new Set([...Object.keys(rows.before), ...Object.keys(rows.after)]); + if (!keys.size && !inputs.some(input => input.replay)) return; + const targets = new Set(pages.map(id => treeFor({ kind: "page", id }))); + for (const { source, replay } of inputs) { + targets.add(treeFor(source)); + if (!replay) continue; + for (const tree of replay.node.entry.nodes.keys()) targets.add(tree); + replay.tree.cursor = replay.direction === "undo" ? replay.node.parent : replay.node; + changed.add(replay.tree); + } + invalidate(keys, changed, targets); + for (const { replay } of inputs) if (replay) targets.delete(replay.tree); + if (!targets.size) return; + const dependencies = new Set(inputs.map(({ page }) => "page:" + page)); + // Attribute definitions are dependencies of saved page values. A definition change + // invalidates those values, while editing the same field on a different page does not. + for (const side of [rows.before, rows.after]) for (const value of Object.values(side)) { + for (const id of value?.children ?? []) dependencies.add("block:" + id); + if (value && "values" in value) for (const id of Object.keys(value.values ?? {})) keys.add("attribute:" + id); + } + const entry: Entry = { ...structuredClone(rows), id: randomUUID(), page: inputs[0].page, keys: [...keys], dependencies, + time: workspace.clock(), order: ++sequence, nodes: new Map() }; + entries.set(entry.id, entry); + for (const key of dependencies) { + let records = dependents.get(key); + if (!records) dependents.set(key, records = new Set()); + records.add(entry); + } + for (const tree of targets) { + attach(tree, entry); + changed.add(tree); + } } -export function tab(id: string): Tab | undefined { - workspace.requireWorkspace(); - return store.tabs.get(id); +function trim(limit: number | null, changed: Set): void { + if (limit === null || entries.size <= limit) return; + for (const entry of entries.values()) { + for (const [tree, node] of entry.nodes) { + remove(tree, node); + changed.add(tree); + } + if (entries.size <= limit) break; + } } -export function node(id: string): Node | undefined { - workspace.requireWorkspace(); - return store.nodes.get(id); -} \ No newline at end of file +export function finish(captures: Capture[], invalid: Invalidation[], pages: string[]): void { + const changed = new Set(); + capture(captures, pages, changed); + for (const { keys, permanent } of invalid) { + invalidate(keys, changed); + if (permanent) for (const key of keys) for (const entry of dependents.get(key) ?? []) { + for (const [tree, node] of entry.nodes) { + remove(tree, node); + changed.add(tree); + } + } + } + trim(settings.get().settings.history.limit, changed); + events.historyChanged([...changed].map(tree => tree.source)); +} +settings.subscribe(snapshot => { + const changed = new Set(); + trim(snapshot.settings.history.limit, changed); + events.historyChanged([...changed].map(tree => tree.source)); +}); \ No newline at end of file diff --git a/main/knowledge/history.ts b/main/knowledge/history.ts index 17eeb76..38a22f0 100644 --- a/main/knowledge/history.ts +++ b/main/knowledge/history.ts @@ -1,6 +1,5 @@ -import * as workspace from "../workspace-state"; +import type { HistorySource } from "../../shared/history/ipc"; import { decodeValue } from "../../shared/attrs/values"; -import { LabloomError } from "../../shared/failure"; import { type AttributeValue } from "../../shared/types/attributes"; import { type CommitResult } from "../../shared/types/content"; import * as attributes from "./attributes"; @@ -9,15 +8,10 @@ import * as commit from "./commit"; import * as history from "./history-state"; import { decodeBlock } from "./records"; import * as retention from "./retention"; -export { clear, close, state } from "./history-state"; -export function apply(tabId: string, direction: "undo" | "redo", branchId?: string, confirmation?: string): CommitResult { - workspace.requireWorkspace(); - return commit.run({ sourceTab: tabId, history: false, confirmation }, context => { - const tab = history.tab(tabId); - if (!tab || !["undo", "redo"].includes(direction)) throw new LabloomError({ kind: "history-empty" }); - const id = direction === "undo" ? tab.cursor : history.state(tabId).redo.find(node => !branchId || node.id === branchId)?.id; - const node = id ? history.node(id) : undefined; - if (!node) throw new LabloomError({ kind: "history-branch-invalid" }); +export { state } from "./history-state"; +export function apply(source: HistorySource, direction: "undo" | "redo", branchId?: string, confirmation?: string): CommitResult { + const replay = history.select(source, direction, branchId), node = replay.node.entry; + return commit.run({ sourceTab: "", history: source, replay, confirmation }, () => { const desired = direction === "undo" ? node.before : node.after; const plan = new EditChanges(); for (const [key, value] of Object.entries(desired)) { @@ -45,11 +39,6 @@ export function apply(tabId: string, direction: "undo" | "redo", branchId?: stri plan.pages.add(node.page); plan.touches.add(node.page); plan.verifyContainment(); - const result = commit.finish(plan, node.page, 0, commit.preview(plan, { direction, tabId, node: node.id })); - if (result.status === "saved") context.after(() => { - history.invalidate([...new Set([...Object.keys(desired), ...Object.keys(plan.rows.after)])], tabId); - tab.cursor = direction === "undo" ? node.parent : node.id; - }); - return result; + return commit.finish(plan, node.page, 0, commit.preview(plan, { direction, source, node: node.id })); }); } \ No newline at end of file diff --git a/main/knowledge/papers.ts b/main/knowledge/papers.ts index 8b39de9..4c4aa9e 100644 --- a/main/knowledge/papers.ts +++ b/main/knowledge/papers.ts @@ -1,3 +1,4 @@ +import type { HistoryOrigin, HistorySource } from "../../shared/history/ipc"; import { eq, sql } from "drizzle-orm"; import { randomUUID } from "node:crypto"; import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; @@ -188,36 +189,36 @@ function importing(action: (store: (path: string) => Attachment) => T, source } } -function append(pageId: string, attributeId: string, files: Attachment[], tabId?: string): void { +function append(pageId: string, attributeId: string, files: Attachment[], origin?: HistoryOrigin): void { const definition = attributes.definition(attributeId), page = data.get(pageId); if (definition.type !== "file" && definition.type !== "files") throw new LabloomError({ kind: "attribute-file-required" }); if (definition.type === "file" && files.length !== 1) throw new LabloomError({ kind: "attribute-single-file" }); const current = page.attributes[attributeId]; const value = definition.type === "file" ? files[0].id : [...new Set([...(Array.isArray(current) ? current as string[] : []), ...files.map(file => file.id)])]; - const result = edits.commitEdit({ pageId, tabId: tabId ?? "file-import", batch: 0, blocks: [], attributes: { [attributeId]: value } }); + const result = edits.commitEdit({ pageId, tabId: origin?.tabId ?? "file-import", batch: 0, blocks: [], attributes: { [attributeId]: value } }, origin?.source ?? false); if (result.status !== "saved") throw new LabloomError({ kind: "attachment-write-failed" }); - if (!tabId) commit.invalidate(["page:" + pageId]); + if (!origin) commit.invalidate(["page:" + pageId]); } -export function attachFiles(paths: string[], pageId: string, attributeId: string, tabId?: string): Attachment[] { +export function attachFiles(paths: string[], pageId: string, attributeId: string, origin?: HistoryOrigin): Attachment[] { workspace.requireWorkspace(); if (!Array.isArray(paths) || !paths.length) throw new LabloomError({ kind: "attachment-selection-required" }); return importing(store => { const localFiles = paths.map(store); - append(pageId, attributeId, localFiles, tabId); + append(pageId, attributeId, localFiles, origin); return localFiles; - }, tabId); + }, origin?.tabId); } -export function importFile(path: string, pageId?: string, tabId?: string): PaperImport { +export function importFile(path: string, pageId?: string, origin?: HistoryOrigin): PaperImport { workspace.requireWorkspace(); if (pageId) paper(pageId, true); return importing(store => { const file = store(path); const page = pageId ? paper(pageId, true) : edits.createPage("paper", basename(path, extname(path)), { source_snapshot: { originalName: basename(path) } }); - append(page.id, "paper_files", [file], tabId); + append(page.id, "paper_files", [file], origin); return { pageId: page.id }; - }, tabId); + }, origin?.tabId); } export function read(id: string): Uint8Array { @@ -306,20 +307,20 @@ async function prepareAnnotation(pageId: string, value: AnnotationInput): Promis return { fileId: value.fileId, pageNumber: value.pageNumber, rectangles, quote, context: quote, extractorVersion: PDF_EXTRACTOR_VERSION }; } -export function changeAnnotation(id: string, color: string, tabId: string): CommitResult { +export function changeAnnotation(id: string, color: string, tabId: string, source: HistorySource): CommitResult { workspace.requireWorkspace(); if (!Object.hasOwn(annotationColors, color)) throw new LabloomError({ kind: "annotation-invalid-color" }); if (data.header(id).kind !== "annotation") throw new LabloomError({ kind: "annotation-unavailable" }); - return edits.commitEdit({ pageId: id, tabId, batch: 0, blocks: [], attributes: { annotation_color: color } }); + return edits.commitEdit({ pageId: id, tabId, batch: 0, blocks: [], attributes: { annotation_color: color } }, source); } -export function deleteAnnotation(id: string, tabId: string, confirmation?: string): CommitResult { +export function deleteAnnotation(id: string, tabId: string, source: HistorySource, confirmation?: string): CommitResult { workspace.requireWorkspace(); if (data.header(id).kind !== "annotation") throw new LabloomError({ kind: "annotation-unavailable" }); - return edits.trash([id], tabId, confirmation); + return edits.trash([id], tabId, source, confirmation); } -export async function annotate(pageId: string, input: AnnotationInput | string, tabId: string, color = "yellow"): Promise { +export async function annotate(pageId: string, input: AnnotationInput | string, tabId: string, source: HistorySource, color = "yellow"): Promise { const session = workspace.requireWorkspace(); if (!Object.hasOwn(annotationColors, color)) throw new LabloomError({ kind: "annotation-invalid-color" }); if (typeof input === "string") { @@ -338,7 +339,7 @@ export async function annotate(pageId: string, input: AnnotationInput | string, return edits.createPage("annotation", [...prepared.quote].slice(0, 70).join(""), { annotation_file: prepared.fileId, annotation_position: localPosition, annotation_color: color, annotation_quote: prepared.quote, annotation_context: prepared.context, annotation_extractor: PDF_EXTRACTOR_VERSION - }, pageId, tabId).id; + }, pageId, { tabId, source }).id; }); } diff --git a/main/knowledge/purge.ts b/main/knowledge/purge.ts index b106c3f..803cc97 100644 --- a/main/knowledge/purge.ts +++ b/main/knowledge/purge.ts @@ -25,7 +25,7 @@ export function purge(ids: string[] | null, tabId: string, confirmation?: string } if (plan.pages.length) data.statement("DELETE FROM pages WHERE id IN (SELECT value FROM json_each(?))").run(JSON.stringify(plan.pages)); const blocks = context.cleanup(); - if (plan.pages.length || blocks.length) context.clearHistory(); + context.invalidate([...plan.pages.map(id => "page:" + id), ...blocks.map(id => "block:" + id)], true); context.change({ pages: plan.pages, blocks, backlinks: plan.pages, purged: plan.pages }); return { status: "deleted", pages: plan.pages, blocks }; }); diff --git a/main/papers/ipc.ts b/main/papers/ipc.ts index 642583a..d8e320a 100644 --- a/main/papers/ipc.ts +++ b/main/papers/ipc.ts @@ -10,13 +10,13 @@ type Args = Parameters; export function registerPapersIPCs(window: BrowserWindow): void { const routes = { - importPDF: route(typia.createAssert>(invalid), async (...[pageId, tabId]) => { + importPDF: route(typia.createAssert>(invalid), async (...[pageId, origin]) => { const path = await dialogs.selectPDF(window); - return path ? papers.importFile(path, pageId, tabId) : null; + return path ? papers.importFile(path, pageId, origin) : null; }), - importFiles: route(typia.createAssert>(invalid), async (pageId, attributeId, tabId) => { + importFiles: route(typia.createAssert>(invalid), async (pageId, attributeId, tabId, source) => { const paths = await dialogs.selectFiles(window, papers.fileSelection(attributeId)); - return paths.length ? papers.attachFiles(paths, pageId, attributeId, tabId) : null; + return paths.length ? papers.attachFiles(paths, pageId, attributeId, { tabId, source }) : null; }), files: route(typia.createAssert>(invalid), papers.files), openFile: route(typia.createAssert>(invalid), async id => { diff --git a/main/settings/file.ts b/main/settings/file.ts index 1107efa..b3e5b38 100644 --- a/main/settings/file.ts +++ b/main/settings/file.ts @@ -26,6 +26,7 @@ export function readSettings(path: string): LoadResult { value = null; } if (value && typeof value === "object" && "version" in value && typeof value.version === "number" && value.version > settingsVersion) throw new LabloomError({ kind: "config-newer-version" }); + if (value && typeof value === "object" && !("history" in value)) value = { ...value, history: defaultSettings.history }; if (validSettings(value)) return { settings: value, savedText: JSON.stringify(value) }; const backup = join(dirname(path), "settings.invalid-" + randomUUID() + ".json"); renameSync(path, backup); diff --git a/preload/index.ts b/preload/index.ts index 8962352..d36dda5 100644 --- a/preload/index.ts +++ b/preload/index.ts @@ -1,7 +1,7 @@ import { contextBridge, ipcRenderer } from "electron"; import type { AppAPI, BridgeAPI } from "../shared/ipc"; import type { Channels, InvokeKeys } from "../shared/ipc/contract"; -import { appChannels, beforeQuit, feedChanged, pagesChanged, settingsChanged, pagesChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels } from "../shared/ipc"; +import { appChannels, beforeQuit, feedChanged, historyChanged, pagesChanged, settingsChanged, pagesChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels } from "../shared/ipc"; function methods(channels: Record, call: (channel: string, ...args: unknown[]) => unknown): API { return Object.fromEntries(Object.entries(channels).map(([key, channel]) => [key, (...args: unknown[]) => call(channel, ...args)])) as API; @@ -34,7 +34,7 @@ const api: BridgeAPI = { }, pages: { ...invokes(pagesChannels), onChanged: listener => subscribe(pagesChanged, listener) }, attributes: invokes(attributesChannels), - history: invokes(historyChannels), + history: { ...invokes(historyChannels), onChanged: listener => subscribe(historyChanged, listener) }, papers: invokes(papersChannels), timers: invokes(timersChannels), workspace: invokes(workspaceChannels), diff --git a/renderer/components/Editor/Editor.svelte b/renderer/components/Editor/Editor.svelte index b7f254a..3630f95 100644 --- a/renderer/components/Editor/Editor.svelte +++ b/renderer/components/Editor/Editor.svelte @@ -220,7 +220,7 @@ pendingPaste = null; let saved = false; await session.action(async token => { - const result = await window.api.pages.commitEdit({ ...planned.edit, pageId: session.state.page!.id, tabId, batch: 0, ...(synced ? { sync: choice.clipboard.ids } : {}) }, token); + const result = await window.api.pages.commitEdit({ ...planned.edit, pageId: session.state.page!.id, tabId, batch: 0, ...(synced ? { sync: choice.clipboard.ids } : {}) }, session.source, token); saved = result.status === "saved"; return result; }); @@ -265,7 +265,7 @@ const at = instance.state.doc.resolve(loc.pos), index = at.index() - 1; if (index + direction < 0 || index + direction >= at.parent.childCount - 1) return; const position = { pageId: session.state.page!.id, containerId: at.depth ? at.parent.attrs.blockId as string : session.state.page!.id, index, blockId: loc.node.attrs.blockId as string }; - void perform(() => session.action(token => window.api.pages.place({ position, action: direction < 0 ? "move-up" : "move-down", tabId }, token))); + void perform(() => session.action(token => window.api.pages.place({ position, action: direction < 0 ? "move-up" : "move-down", tabId }, session.source, token))); } function placeholder(): void { if (!editor || !host) return; @@ -366,7 +366,7 @@ if (!loc || !instance) return; const { node, pos } = loc; if (action === "delete") { - void perform(() => session.action(token => window.api.pages.deleteBlock({ pageId: session.state.page!.id, tabId, blockId: node.attrs.blockId }, token))); + void perform(() => session.action(token => window.api.pages.deleteBlock({ pageId: session.state.page!.id, tabId, blockId: node.attrs.blockId }, session.source, token))); return; } if (action === "row" || action === "column") { diff --git a/renderer/components/Editor/Toolbar.svelte b/renderer/components/Editor/Toolbar.svelte index 506fbca..543bf2f 100644 --- a/renderer/components/Editor/Toolbar.svelte +++ b/renderer/components/Editor/Toolbar.svelte @@ -41,13 +41,13 @@
- editor?.chain().focus().undo().run()}> + editor?.chain().focus().undo().run()}> {@html undoIcon} - editor?.chain().focus().redo().run()}> + editor?.chain().focus().redo().run()}> {@html redoIcon} @@ -183,8 +183,7 @@ function readState(instance: Editor | null): { formats: { name: string; label: string; icon: string | null; active: boolean; disabled: boolean }[]; canClear: boolean; - canUndo: boolean; - canRedo: boolean; + ready: boolean; } { const ready = instance !== null && !instance.isDestroyed && instance.isEditable; return { @@ -194,8 +193,7 @@ disabled: !ready || !instance.can().toggleMark(format.name) })), canClear: ready && instance.can().unsetAllMarks(), - canUndo: ready && instance.can().undo(), - canRedo: ready && instance.can().redo() + ready }; } diff --git a/renderer/components/Knowledge/Calendar.svelte b/renderer/components/Knowledge/Calendar.svelte index 02cafeb..e3ca7a3 100644 --- a/renderer/components/Knowledge/Calendar.svelte +++ b/renderer/components/Knowledge/Calendar.svelte @@ -6,7 +6,7 @@

给重要的想法,留出专注的时间。

- +
@@ -119,7 +119,7 @@ import { pageMenu } from "./page-menu"; import { onMount } from "svelte"; import { type PageSummary } from "../../../shared/types/content"; - import { type Notice, type HistoryState } from "../../../shared/types/knowledge"; + import { type Notice } from "../../../shared/types/knowledge"; import ListHistory from "./ListHistory.svelte"; import { dayToSeconds, nowSeconds, scheduleDay, secondsToWall } from "../../../shared/content/time"; import { display } from "../../../shared/attrs/format"; @@ -130,7 +130,6 @@ import { kindNames } from "./labels"; import Icon from "../utils/Icon.svelte"; let { tabId }: { tabId: string } = $props(); - let history = $state.raw({ canUndo: false, redo: [] }); const zone = $derived(currentTimeZone()); let now = $state(nowSeconds()), viewedMonth = $state(), selectedDay = $state(); const today = $derived(secondsToWall(now, zone).slice(0, 10)); @@ -181,7 +180,6 @@ throw problem; } } - history = await window.api.history.state(tabId); scheduled = result.sort((a, b) => Number(a.kind === "event") - Number(b.kind === "event") || Number(b.attributes.modified_at) - Number(a.attributes.modified_at) || a.id.localeCompare(b.id)); error = ""; @@ -204,7 +202,7 @@ await writeFromTab(tabId, async () => { const { page } = await window.api.pages.readObjects(id, [id]); if (!page) throw new LabloomError({ kind: "page-missing" }); - await confirmed(token => window.api.pages.commitEdit({ pageId: id, tabId, batch: 0, blocks: [], attributes: { task_status: page.attributes.task_status === "done" ? "todo" : "done" } }, token)); + await confirmed(token => window.api.pages.commitEdit({ pageId: id, tabId, batch: 0, blocks: [], attributes: { task_status: page.attributes.task_status === "done" ? "todo" : "done" } }, { kind: "workspace" }, token)); }); }); } diff --git a/renderer/components/Knowledge/FileInput.svelte b/renderer/components/Knowledge/FileInput.svelte index 24e2ab9..f7ae91d 100644 --- a/renderer/components/Knowledge/FileInput.svelte +++ b/renderer/components/Knowledge/FileInput.svelte @@ -102,7 +102,7 @@ try { const current = session; await writeFromTab(current.tabId, async () => { - if (await window.api.papers.importFiles(current.state.page!.id, definition.id, current.tabId)) await current.reread([current.state.page!.id]); + if (await window.api.papers.importFiles(current.state.page!.id, definition.id, current.tabId, current.source)) await current.reread([current.state.page!.id]); }); error = ""; } diff --git a/renderer/components/Knowledge/Library.svelte b/renderer/components/Knowledge/Library.svelte index f092ff1..a40c97e 100644 --- a/renderer/components/Knowledge/Library.svelte +++ b/renderer/components/Knowledge/Library.svelte @@ -241,7 +241,7 @@ async function importPDF(): Promise { busy = true; try { - const result = await writeFromTab(tabId, () => window.api.papers.importPDF(undefined, tabId)); + const result = await writeFromTab(tabId, () => window.api.papers.importPDF(undefined, { tabId, source: { kind: "workspace" } })); if (result) { info = "PDF 已复制到工作区。"; openPage(result.pageId); @@ -258,7 +258,7 @@ busy = true; try { const ids = [...selected]; - if (await writeFromTab(tabId, () => confirmed(token => view === "trash" ? window.api.pages.restore(ids, tabId) : window.api.pages.trash(ids, tabId, token)))) selected = []; + if (await writeFromTab(tabId, () => confirmed(token => view === "trash" ? window.api.pages.restore(ids, tabId, { kind: "workspace" }) : window.api.pages.trash(ids, tabId, { kind: "workspace" }, token)))) selected = []; } catch (problem) { error = failure(problem); diff --git a/renderer/components/Knowledge/ListHistory.svelte b/renderer/components/Knowledge/ListHistory.svelte index 25cddaf..b5c8393 100644 --- a/renderer/components/Knowledge/ListHistory.svelte +++ b/renderer/components/Knowledge/ListHistory.svelte @@ -13,11 +13,16 @@ import type { HistoryState } from "../../../shared/types/knowledge"; import { displayMilliseconds } from "../layout/preferences.svelte"; import { confirmed, perform, writeFromTab } from "./state.svelte"; - let { tabId, history = $bindable() }: { tabId: string; history: HistoryState } = $props(); + import { onMount } from "svelte"; + import { watchHistory } from "./history"; + let { tabId }: { tabId: string } = $props(); + let history = $state.raw({ canUndo: false, redo: [] }); + onMount(() => watchHistory({ kind: "workspace" }, state => { + history = state; + })); function apply(direction: "undo" | "redo", branch?: string): void { void perform(async () => { - await writeFromTab(tabId, () => confirmed(token => window.api.history.apply(tabId, direction, branch, token))); - history = await window.api.history.state(tabId); + await writeFromTab(tabId, () => confirmed(token => window.api.history.apply({ kind: "workspace" }, direction, branch, token))); }); } \ No newline at end of file diff --git a/renderer/components/Knowledge/PageView.svelte b/renderer/components/Knowledge/PageView.svelte index e733b38..aea208b 100644 --- a/renderer/components/Knowledge/PageView.svelte +++ b/renderer/components/Knowledge/PageView.svelte @@ -76,6 +76,6 @@ } }); function trash(): void { - void perform(() => current.action(token => page!.attributes.deleted ? window.api.pages.restore([tab.pageId], tab.id) : window.api.pages.trash([tab.pageId], tab.id, token))); + void perform(() => current.action(token => page!.attributes.deleted ? window.api.pages.restore([tab.pageId], tab.id, current.source) : window.api.pages.trash([tab.pageId], tab.id, current.source, token))); } \ No newline at end of file diff --git a/renderer/components/Knowledge/PaperPanel.svelte b/renderer/components/Knowledge/PaperPanel.svelte index 1eb6a83..d09a845 100644 --- a/renderer/components/Knowledge/PaperPanel.svelte +++ b/renderer/components/Knowledge/PaperPanel.svelte @@ -157,7 +157,7 @@ async function attach(): Promise { busy = true; try { - if (await writeFromTab(tabId, () => window.api.papers.importFiles(page.id, "paper_files", tabId))) await load(); + if (await writeFromTab(tabId, () => window.api.papers.importFiles(page.id, "paper_files", tabId, { kind: "page", id: page.id }))) await load(); } catch (problem) { error = failure(problem); @@ -187,8 +187,8 @@ try { const anchor = selection ? $state.snapshot(selection) : null, id = activeHighlight; await writeFromTab(tabId, async () => { - if (id) await window.api.papers.changeAnnotation(id, color, tabId); - else if (anchor) await window.api.papers.annotate(page.id, anchor, tabId, color); + if (id) await window.api.papers.changeAnnotation(id, color, tabId, { kind: "page", id: page.id }); + else if (anchor) await window.api.papers.annotate(page.id, anchor, tabId, { kind: "page", id: page.id }, color); dismiss(); await load(); }); @@ -207,7 +207,7 @@ busy = true; try { await writeFromTab(tabId, async () => { - const id = await window.api.papers.annotate(page.id, anchor, tabId, existing?.color); + const id = await window.api.papers.annotate(page.id, anchor, tabId, { kind: "page", id: page.id }, existing?.color); await session.reread([page.id]); dismiss(); await load(); @@ -224,7 +224,7 @@ function remove(id: string): void { void perform(async () => { await writeFromTab(tabId, async () => { - if (await confirmed(token => window.api.papers.deleteAnnotation(id, tabId, token))) { + if (await confirmed(token => window.api.papers.deleteAnnotation(id, tabId, { kind: "page", id: page.id }, token))) { dismiss(); await session.reread([page.id]); } diff --git a/renderer/components/Knowledge/history.ts b/renderer/components/Knowledge/history.ts new file mode 100644 index 0000000..677ab96 --- /dev/null +++ b/renderer/components/Knowledge/history.ts @@ -0,0 +1,56 @@ +import type { HistorySource } from "../../../shared/history/ipc"; +import type { HistoryState } from "../../../shared/types/knowledge"; +import { tabState } from "../Tab/state.svelte"; +import { knowledgeState } from "./feedback.svelte"; +import { failure } from "../../i18n.svelte"; + +export function historySource(tabId: string): HistorySource { + for (const group of tabState.groups) { + const tab = group.tabs.find(item => item.id === tabId); + if (tab?.type === "page") return { kind: "page", id: tab.pageId }; + } + return { kind: "workspace" }; +} +type Listener = (state: HistoryState) => void; +type Watch = { source: HistorySource; listeners: Set; revision: number; state?: HistoryState }; +const watches = new Map(); +const key = (source: HistorySource): string => source.kind === "page" ? "page:" + source.id : "workspace"; +let unsubscribe: (() => void) | undefined; + +async function read(watch: Watch): Promise { + const revision = ++watch.revision; + try { + const state = await window.api.history.state(watch.source); + if (watch.revision !== revision) return; + watch.state = state; + for (const listener of watch.listeners) listener(state); + } + catch (error) { + if (watch.revision === revision && watch.listeners.size) knowledgeState.error = failure(error); + } +} +export function watchHistory(source: HistorySource, receive: Listener): () => void { + unsubscribe ??= window.api.history.onChanged(sources => { + for (const source of sources) { + const watch = watches.get(key(source)); + if (watch) void read(watch); + } + }); + const id = key(source); + let watch = watches.get(id); + if (!watch) { + watch = { source, listeners: new Set(), revision: 0 }; + watches.set(id, watch); + void read(watch); + } + watch.listeners.add(receive); + if (watch.state) receive(watch.state); + return () => { + watch.listeners.delete(receive); + if (!watch.listeners.size) watches.delete(id); + if (!watches.size) { + unsubscribe?.(); + unsubscribe = undefined; + } + }; +} \ No newline at end of file diff --git a/renderer/components/Knowledge/page-menu.ts b/renderer/components/Knowledge/page-menu.ts index cfcb0d4..b163b61 100644 --- a/renderer/components/Knowledge/page-menu.ts +++ b/renderer/components/Knowledge/page-menu.ts @@ -1,3 +1,4 @@ +import { historySource } from "./history"; import { tabState } from "../Tab/state.svelte"; import type { PageSummary } from "../../../shared/types/content"; import { openDestination, openPage } from "../layout/navigation"; @@ -14,13 +15,13 @@ export function pageMenu(page: PageSummary, tabId: string, ids = [page.id]): { l }); }; if (page.attributes.deleted) return [ - { label: "恢复", run: () => write(source => window.api.pages.restore(ids, source)) }, + { label: "恢复", run: () => write(source => window.api.pages.restore(ids, source, historySource(source))) }, { label: "永久删除", run: () => write(source => purgePages(ids, source)) } ]; return [ { label: "打开", shortcut: "Enter", run: () => openPage(page.id) }, { label: "在另一标签组打开", shortcut: "Ctrl+Enter", run: () => openPage(page.id, { otherGroup: true }) }, - { label: page.attributes.pinned ? "取消固定" : "固定到侧栏", run: () => write(source => window.api.pages.commitEdit({ pageId: page.id, tabId: source, batch: 0, blocks: [], attributes: { pinned: !page.attributes.pinned } })) }, - { label: "移入回收站", shortcut: "Delete", run: () => write(source => confirmed(token => window.api.pages.trash(ids, source, token))) } + { label: page.attributes.pinned ? "取消固定" : "固定到侧栏", run: () => write(source => window.api.pages.commitEdit({ pageId: page.id, tabId: source, batch: 0, blocks: [], attributes: { pinned: !page.attributes.pinned } }, historySource(source))) }, + { label: "移入回收站", shortcut: "Delete", run: () => write(source => confirmed(token => window.api.pages.trash(ids, source, historySource(source), token))) } ]; } \ No newline at end of file diff --git a/renderer/components/Knowledge/session-views.ts b/renderer/components/Knowledge/session-views.ts index 062e504..2d02082 100644 --- a/renderer/components/Knowledge/session-views.ts +++ b/renderer/components/Knowledge/session-views.ts @@ -19,7 +19,7 @@ export class SessionViews implements TabView { return changes[0]; } async flush(): Promise { - // Sequential commits preserve the single tab history's order across pages. + // Flush the paper and its annotation buffers in the order the views opened. for (const view of this.views.keys()) if (!await view.flush()) return false; return true; } diff --git a/renderer/components/Knowledge/state.svelte.ts b/renderer/components/Knowledge/state.svelte.ts index cf26c9d..21e90ae 100644 --- a/renderer/components/Knowledge/state.svelte.ts +++ b/renderer/components/Knowledge/state.svelte.ts @@ -1,3 +1,5 @@ +import { historySource, watchHistory } from "./history"; +import type { HistorySource } from "../../../shared/history/ipc"; import { PageWrites, fallbackFields, fields, reviewEdit, type Fields } from "./page-writes"; import { confirmationText } from "../../../shared/content/confirmation"; import { changedUses, references } from "../../../shared/content/blocks"; @@ -53,7 +55,7 @@ class PageState { } export type PageSession = { state: PageState; refresh(): Promise; reread(ids: string[]): Promise; objects(ids: string[]): Promise; - tabId: string; input: PendingInput; release(): void; + tabId: string; source: HistorySource; input: PendingInput; release(): void; flush(): Promise; stage(edit: Fields): void; review(edit: Fields, rollback: () => void, accept: (saved: boolean) => void, finish: () => void): void; action(commit: (token?: string) => Promise): Promise; @@ -66,7 +68,6 @@ type Listener = (ids: string[], whole: boolean) => void; // This registry is not rendered; each session carries its own reactive state. // eslint-disable-next-line svelte/prefer-svelte-reactivity const sessions = new Map(); -let historyEpoch = 0; // Page views share a tab visit and history, while retaining separate page buffers. // eslint-disable-next-line svelte/prefer-svelte-reactivity const sessionViews = new Map void }>(); @@ -117,6 +118,10 @@ export function registerList(tabId: string, intersection: TabView["intersection" function makeSession(tabId: string, pageId: string): PageSession { const state = new PageState(), api = window.api, input = new PendingInput(); + const source = historySource(tabId); + const stopHistory = watchHistory(source, value => { + state.history = value; + }); // Unacknowledged container edits may change a sync border in another page. // eslint-disable-next-line svelte/prefer-svelte-reactivity const pendingUses = new Set(); @@ -163,9 +168,6 @@ function makeSession(tabId: string, pageId: string): PageSession { }; } function ownChange(change: KnowledgeChange): void { - void history().catch(error => { - knowledgeState.error = failure(error); - }); for (const id of [...(change.summaryPages ?? change.pages), ...change.blocks]) { for (const [read, own] of observers.get(id) ?? []) if (own || change.highlightPages?.includes(id)) void perform(read); } @@ -179,10 +181,6 @@ function makeSession(tabId: string, pageId: string): PageSession { let timer: ReturnType | undefined, composing = false; let reviewing: Promise | undefined, load = 0; const prompt = (p: ChangePreview): Promise => ask(() => t("dialog.change"), () => confirmationText(p, t)); - const history = async (): Promise => { - const epoch = historyEpoch, value = await api.history.state(tabId); - if (epoch === historyEpoch) state.history = value; - }; function updateCounts(ids: string[], uses: Record): void { if (!ids.length || !state.page) return; const counts = state.page.sharedUses ??= {}; @@ -196,7 +194,7 @@ function makeSession(tabId: string, pageId: string): PageSession { if (changed) for (const listener of listeners) listener([], false); } const writes = new PageWrites(tabId, pageId, async input => { - let result = await api.pages.commitEdit(input); + let result = await api.pages.commitEdit(input, source); while (result.status === "confirmation") { // Retention can change between preview and commit. Restore only the disputed fields. const causes = new Set(result.preview.causes); @@ -210,7 +208,7 @@ function makeSession(tabId: string, pageId: string): PageSession { writes.retain(fields(safe)); return; } - result = await api.pages.commitEdit(input, result.preview.token); + result = await api.pages.commitEdit(input, source, result.preview.token); if (result.status === "saved") { for (const key of proposed.keys()) if (!writes.current(key)) proposed.delete(key); apply(fields(proposed)); @@ -219,9 +217,6 @@ function makeSession(tabId: string, pageId: string): PageSession { } input.blocks.forEach(block => newBlocks.delete(block.id)); updateCounts(result.changed.blocks, result.sharedUses ?? {}); - await history().catch(e => { - knowledgeState.error = failure(e); - }); }); function notify(ids: string[], whole = false): void { for (const listener of listeners) listener(ids, whole); @@ -316,16 +311,12 @@ function makeSession(tabId: string, pageId: string): PageSession { if (!await flush()) return; state.loading = true; try { - const epoch = historyEpoch; - const [page, undo] = await Promise.all([api.pages.get(pageId).then(record => { - performance.clearMarks("labloom:page-read"); - performance.mark("labloom:page-read", { detail: pageId }); - return record; - }), api.history.state(tabId)]); + const page = await api.pages.get(pageId); + performance.clearMarks("labloom:page-read"); + performance.mark("labloom:page-read", { detail: pageId }); if (request !== load) return; newBlocks.clear(); state.page = page; - if (epoch === historyEpoch) state.history = undo; state.error = ""; notify([], true); } @@ -371,7 +362,6 @@ function makeSession(tabId: string, pageId: string): PageSession { await objects(ids, true); state.page = { ...state.page }; notify(ids); - await history(); } function review(edit: Fields, rollback: () => void, accept: (saved: boolean) => void, finish: () => void): void { clearTimeout(timer); @@ -384,7 +374,7 @@ function makeSession(tabId: string, pageId: string): PageSession { try { let savedResult: Extract | undefined; await reviewEdit(input, value => api.pages.previewEdit(value), prompt, async (value, token) => { - const result = await api.pages.commitEdit(value, token); + const result = await api.pages.commitEdit(value, source, token); if (result.status === "saved") savedResult = result; return result; }, rollback, saved => { @@ -395,9 +385,6 @@ function makeSession(tabId: string, pageId: string): PageSession { accept(saved); if (savedResult) { updateCounts(savedResult.changed.blocks, savedResult.sharedUses ?? {}); - void history().catch(e => { - knowledgeState.error = failure(e); - }); } }); } @@ -422,7 +409,7 @@ function makeSession(tabId: string, pageId: string): PageSession { return result; }) && changed) { const ids = [...changed.pages, ...changed.blocks]; - // An undo belongs to the tab, and may target its now-closed annotation. + // A paper and its open annotation can both display rows from this commit. for (const value of sessions.values()) if (value.tabId === tabId) { const page = value.state.page; if (page) await value.reread(ids.filter(id => id === page.id || Object.hasOwn(page.blocks, id))); @@ -431,7 +418,10 @@ function makeSession(tabId: string, pageId: string): PageSession { } } const trackedAction = (commit: (token?: string) => Promise): Promise => trackWrite(tabId, action(commit)); - const undo = (direction: "undo" | "redo", branch?: string): Promise => trackedAction(token => api.history.apply(tabId, direction, branch, token)); + const undo = (direction: "undo" | "redo", branch?: string): Promise => { + if (readingTabs.has(tabId)) return Promise.resolve(); + return trackedAction(token => api.history.apply(source, direction, branch, token)); + }; let definitionsDirty = false; const intersection = (change: TabChange): string[] => [ ...change.pages.filter(id => id === pageId), @@ -494,7 +484,9 @@ function makeSession(tabId: string, pageId: string): PageSession { } }); return { - tabId, input, release, state, refresh, reread, objects, flush, stage, review, action: trackedAction, undo, composition, watchObject, ownChange, + tabId, source, input, release() { + stopHistory(); release(); + }, state, refresh, reread, objects, flush, stage, review, action: trackedAction, undo, composition, watchObject, ownChange, attr: (id: string, value: AttributeValue) => stage({ blocks: [], attributes: { [id]: copyData(value) } }), detach: (id: string) => stage({ blocks: [], detach: [id] }), listen(fn: Listener) { @@ -513,10 +505,6 @@ export function session(tabId: string, pageId: string): PageSession { return value; } export function receiveChange(change: KnowledgeChange): void { - if (change.purged && (change.purged.length || change.blocks.length)) { - historyEpoch++; - for (const value of sessions.values()) value.state.history = { canUndo: false, redo: [] }; - } visits.changed(change); for (const value of sessions.values()) if (value.tabId === change.sourceTab) value.ownChange(change); knowledgeState.change = { ...change, seq: knowledgeState.change.seq + 1 }; @@ -556,7 +544,6 @@ export async function closeSession(tabId: string): Promise { return false; } await Promise.all(otherWrites(tabId)); - await window.api.history.closeTab(tabId); for (const [key, value] of sessions) if (value.tabId === tabId) { value.release(); sessions.delete(key); diff --git a/renderer/components/layout/commands.ts b/renderer/components/layout/commands.ts index 42850da..61a62d4 100644 --- a/renderer/components/layout/commands.ts +++ b/renderer/components/layout/commands.ts @@ -1,6 +1,7 @@ import { tick } from "svelte"; import { visits } from "../Tab/activity.svelte"; import { commands, shortcutCommand, type Command } from "../../../shared/content/commands"; +import { historySource } from "../Knowledge/history"; import { confirmed, perform, saveAll, writeFromTab } from "../Knowledge/state.svelte"; import { activateTab, focusGroup, removeTab } from "../Tab/api"; import type { LayoutNode } from "../Tab/defs"; @@ -65,7 +66,7 @@ export function runCommand(id: Command): void { } } else if (id === "importPDF") void perform(async () => { - const action = (): ReturnType => window.api.papers.importPDF(undefined, group.activeTabId ?? undefined); + const action = (): ReturnType => window.api.papers.importPDF(undefined, group.activeTabId ? { tabId: group.activeTabId, source: historySource(group.activeTabId) } : undefined); const result = group.activeTabId ? await writeFromTab(group.activeTabId, action) : await saveAll() && await action(); if (result) openPage(result.pageId); }); @@ -74,9 +75,9 @@ export function runCommand(id: Command): void { const tabId = group.activeTabId; void perform(async () => { await writeFromTab(tabId, async () => { - const history = await window.api.history.state(tabId); + const source = historySource(tabId), history = await window.api.history.state(source); if (id === "undo" ? !history.canUndo : !history.redo.length) return; - await confirmed(token => window.api.history.apply(tabId, id as "undo" | "redo", undefined, token)); + await confirmed(token => window.api.history.apply(source, id as "undo" | "redo", undefined, token)); }); }); } diff --git a/shared/history/ipc.ts b/shared/history/ipc.ts index 459ad13..b1aaf2d 100644 --- a/shared/history/ipc.ts +++ b/shared/history/ipc.ts @@ -1,15 +1,17 @@ import type { CommitResult } from "../types/content"; import type { HistoryState } from "../types/knowledge"; -import type { TabId, Channels } from "../ipc/contract"; +import type { Channels, TabId } from "../ipc/contract"; +export type HistorySource = { kind: "page"; id: string } | { kind: "workspace" }; +export type HistoryOrigin = { tabId: TabId; source: HistorySource }; export type HistoryAPI = { - state(tabId: TabId): Promise; - apply(tabId: TabId, direction: "undo" | "redo", branchId?: string, confirmation?: string): Promise; - closeTab(tabId: TabId): Promise; + state(source: HistorySource): Promise; + apply(source: HistorySource, direction: "undo" | "redo", branchId?: string, confirmation?: string): Promise; + onChanged(listener: (sources: HistorySource[]) => void): () => void; }; export const historyChannels = { state: "history:state", - apply: "history:apply", - closeTab: "history:close-tab" -} as const satisfies Channels; \ No newline at end of file + apply: "history:apply" +} as const satisfies Channels; +export const historyChanged = "history:changed"; \ No newline at end of file diff --git a/shared/pages/ipc.ts b/shared/pages/ipc.ts index 6aba5da..6602f29 100644 --- a/shared/pages/ipc.ts +++ b/shared/pages/ipc.ts @@ -1,3 +1,4 @@ +import type { HistorySource } from "../history/ipc"; import type { AttributeValue } from "../types/attributes"; import type { Backlink, CommitResult, BlockDeletion, ChangePreview, ContentBlock, EditCommit, KnowledgeChange, Placement, ResolvedTarget, PageKind, PageList, PageQuery, PageRecord, PageObjects, Target } from "../types/content"; import type { PurgeResult } from "../types/knowledge"; @@ -11,12 +12,12 @@ export type PagesAPI = { readObjects(pageId: string, ids: string[]): Promise; syncBlocks(workspaceId: string, ids: string[] & tags.MinItems<1>): Promise; create(kind: PageKind, title?: string, initial?: Record, parentId?: string, tabId?: TabId): Promise; - commitEdit(input: EditCommit, confirmation?: string): Promise; + commitEdit(input: EditCommit, source: HistorySource, confirmation?: string): Promise; previewEdit(input: EditCommit): Promise; - deleteBlock(input: BlockDeletion, confirmation?: string): Promise; - place(input: Placement, confirmation?: string): Promise; - trash(ids: string[], tabId: TabId, confirmation?: string): Promise; - restore(ids: string[], tabId: TabId): Promise; + deleteBlock(input: BlockDeletion, source: HistorySource, confirmation?: string): Promise; + place(input: Placement, source: HistorySource, confirmation?: string): Promise; + trash(ids: string[], tabId: TabId, source: HistorySource, confirmation?: string): Promise; + restore(ids: string[], tabId: TabId, source: HistorySource): Promise; purge(ids: string[], tabId: TabId, confirmation?: string): Promise; emptyTrash(tabId: TabId, confirmation?: string): Promise; backlinks(id: string): Promise; diff --git a/shared/papers/ipc.ts b/shared/papers/ipc.ts index 74a0ad2..3f59560 100644 --- a/shared/papers/ipc.ts +++ b/shared/papers/ipc.ts @@ -1,3 +1,4 @@ +import type { HistoryOrigin, HistorySource } from "../history/ipc"; import type { CommitResult } from "../types/content"; import type { PaperAnnotation, AnnotationInput, Attachment, PaperImport, PaperResources, ReadingPosition } from "../types/papers"; import type { TabId, Channels } from "../ipc/contract"; @@ -6,18 +7,18 @@ import type { tags } from "typia"; type SelectedAnnotation = Omit & { rectangles: AnnotationInput["rectangles"] & tags.MinItems<1> }; export type PapersAPI = { - importPDF(pageId?: string, tabId?: TabId): Promise; - importFiles(pageId: string, attributeId: string, tabId: TabId): Promise; + importPDF(pageId?: string, origin?: HistoryOrigin): Promise; + importFiles(pageId: string, attributeId: string, tabId: TabId, source: HistorySource): Promise; files(ids?: string[]): Promise; openFile(fileId: string): Promise; resources(pageId: string): Promise; readFile(fileId: string): Promise; getAnnotation(id: string): Promise; unlockPDF(fileId: string, password: string): Promise; - changeAnnotation(id: string, color: string, tabId: TabId): Promise; + changeAnnotation(id: string, color: string, tabId: TabId, source: HistorySource): Promise; position(pageId: string, fileId: string, value: ReadingPosition, tabId?: TabId): Promise; - deleteAnnotation(id: string, tabId: TabId, confirmation?: string): Promise; - annotate(pageId: string, anchor: SelectedAnnotation | string, tabId: TabId, color?: string): Promise; + deleteAnnotation(id: string, tabId: TabId, source: HistorySource, confirmation?: string): Promise; + annotate(pageId: string, anchor: SelectedAnnotation | string, tabId: TabId, source: HistorySource, color?: string): Promise; }; export const papersChannels = { diff --git a/shared/settings/Settings.ts b/shared/settings/Settings.ts index 387141e..5656b38 100644 --- a/shared/settings/Settings.ts +++ b/shared/settings/Settings.ts @@ -7,12 +7,14 @@ export type Settings = { readonly lastWorkspace: Workspace | null; readonly appearance: Readonly; readonly window: { readonly width: number; readonly height: number; readonly maximized: boolean }; + readonly history: { readonly limit: number | null }; readonly layout: { readonly width: number; readonly collapsed: boolean }; }; export type SettingsPatch = { readonly lastWorkspace?: Workspace | null; readonly appearance?: Partial; readonly window?: Partial; + readonly history?: Partial; readonly layout?: Partial; }; export type SettingsSnapshot = { diff --git a/shared/settings/defaults.ts b/shared/settings/defaults.ts index 6f7a0b9..64acf40 100644 --- a/shared/settings/defaults.ts +++ b/shared/settings/defaults.ts @@ -10,5 +10,6 @@ export const maxPanelWidth = 500; export const defaultSettings: Settings = { version: settingsVersion, lastWorkspace: null, appearance: { ...defaultAppearance }, window: { width: 1280, height: 860, maximized: false }, + history: { limit: null }, layout: { width: 240, collapsed: false } }; \ No newline at end of file diff --git a/shared/settings/merge.ts b/shared/settings/merge.ts index b7ac686..69626b4 100644 --- a/shared/settings/merge.ts +++ b/shared/settings/merge.ts @@ -5,6 +5,7 @@ export function mergeSettings(base: Settings, patch: SettingsPatch): Settings { ...base, ...patch, appearance: { ...base.appearance, ...patch.appearance }, window: { ...base.window, ...patch.window }, + history: { ...base.history, ...patch.history }, layout: { ...base.layout, ...patch.layout } }; } \ No newline at end of file diff --git a/shared/settings/validate.ts b/shared/settings/validate.ts index 369fd79..9ba0180 100644 --- a/shared/settings/validate.ts +++ b/shared/settings/validate.ts @@ -26,17 +26,20 @@ export function validLayout(value: unknown): value is Settings["layout"] { && typeof value.width === "number" && Number.isFinite(value.width) && value.width >= minPanelWidth && value.width <= maxPanelWidth && typeof value.collapsed === "boolean"; } +function validHistory(value: unknown): value is Settings["history"] { + return record(value) && keys(value, ["limit"]) && (value.limit === null || Number.isSafeInteger(value.limit) && Number(value.limit) > 0); +} export function validSettings(value: unknown): value is Settings { - return record(value) && keys(value, ["version", "lastWorkspace", "appearance", "window", "layout"]) + return record(value) && keys(value, ["version", "lastWorkspace", "appearance", "window", "layout", "history"]) && value.version === settingsVersion && validWorkspace(value.lastWorkspace) && record(value.appearance) && keys(value.appearance, ["theme", "readingSize", "motion", "timeZone", "language"]) - && isAppearance(value.appearance) && validWindowSettings(value.window) && validLayout(value.layout); + && isAppearance(value.appearance) && validWindowSettings(value.window) && validLayout(value.layout) && validHistory(value.history); } export function validPatch(value: unknown, base: Settings): value is SettingsPatch { - if (!record(value) || !Object.keys(value).length || !keys(value, ["lastWorkspace", "appearance", "window", "layout"])) return false; + if (!record(value) || !Object.keys(value).length || !keys(value, ["lastWorkspace", "appearance", "window", "layout", "history"])) return false; if (Object.hasOwn(value, "lastWorkspace") && !validWorkspace(value.lastWorkspace)) return false; - const sections = ["appearance", "window", "layout"] as const; - const validators = { appearance: isAppearance, window: validWindowSettings, layout: validLayout }; + const sections = ["appearance", "window", "layout", "history"] as const; + const validators = { appearance: isAppearance, window: validWindowSettings, layout: validLayout, history: validHistory }; for (const section of sections) { if (!Object.hasOwn(value, section)) continue; const patch = value[section]; diff --git a/tests/appearance.test.ts b/tests/appearance.test.ts index 3e57456..f9fd35b 100644 --- a/tests/appearance.test.ts +++ b/tests/appearance.test.ts @@ -1,3 +1,4 @@ +import { pageHistory } from "./support/history"; import assert from "node:assert/strict"; import { test, type TestContext } from "node:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmdirSync, writeFileSync } from "node:fs"; @@ -41,7 +42,7 @@ test("settings snapshots are frozen, merge groups, flush durably and leave confi assert.equal(Object.isFrozen(first.settings.appearance), true); assert.equal(Reflect.set(first.settings.layout, "width", 400), false); const patches = [ - { appearance: { theme: "dark" } }, { appearance: { readingSize: 18, motion: false } }, + { history: { limit: 3 } }, { appearance: { theme: "dark" } }, { appearance: { readingSize: 18, motion: false } }, { window: { width: 950, height: 730, maximized: true } }, { layout: { width: 310, collapsed: true } }, { lastWorkspace: { id: "one", name: "One", path: join(root, "one") } } ]; @@ -59,6 +60,14 @@ test("settings snapshots are frozen, merge groups, flush durably and leave confi assert.equal(existsSync(join(root, "sessions")), false); }); +test("existing settings without a history limit retain their layout and default to unlimited", () => { + const root = folder(), { history: _history, ...legacy } = defaultSettings; + const value = { ...legacy, layout: { width: 311, collapsed: true } }; + writeFileSync(join(root, "settings.json"), JSON.stringify(value)); + assert.equal(settings.initialize(root).notice, undefined); + assert.deepEqual(settings.get().settings, { ...value, history: { limit: null } }); +}); + test("five rapid changes write once within 600ms of the final theme update", async t => { const root = fixture(t), saved: number[] = []; let previous = settings.get().savedRevision, completed = 0; @@ -99,6 +108,7 @@ test("invalid settings patches cannot change memory or disk", async t => { await settings.flush(0); const before = settings.get(), bytes = readFileSync(join(root, "settings.json")); for (const patch of [null, [], {}, { version: 2 }, { appearance: {} }, { layout: { width: 169 } }, + ...[0, -1, 1.5, "3", Infinity].map(limit => ({ history: { limit } })), { window: { width: minWindowWidth - 1 } }, { window: { height: minWindowHeight - 1 } }, { appearance: { readingSize: "18" } }, { appearance: { motion: 1 } }, { appearance: { language: "fr" } }, ...["", null, "+08:00", "Mars/Base"].map(timeZone => ({ appearance: { timeZone } })), @@ -187,7 +197,7 @@ test("workspace settings merge, survive reopen and stay out of page timestamps a const expected = { tabs, feedKeywords: ["Large Models", "AI"] }; assert.deepEqual(workspaceSettings.get(), expected); assert.deepEqual(JSON.parse(opened.database.prepare("SELECT settings FROM workspace_meta").pluck().get() as string), expected); - assert.equal(history.state("a").canUndo, false); + assert.equal(history.state(pageHistory(page.id)).canUndo, false); assert.equal(records.get(page.id).attributes.modified_at, modified); assert.throws(() => commit.run({ sourceTab: "a" }, () => { workspaceSettings.update({ feedKeywords: ["rollback"] }); throw new Error("rollback"); diff --git a/tests/builtin-attrs.test.ts b/tests/builtin-attrs.test.ts index 23d16cc..b0652c9 100644 --- a/tests/builtin-attrs.test.ts +++ b/tests/builtin-attrs.test.ts @@ -1,3 +1,4 @@ +import { pageHistory } from "./support/history"; import { knowledgeServices, session, type Knowledge } from "./support/session"; import { hasFailure } from "./failures"; import assert from "node:assert/strict"; @@ -70,12 +71,12 @@ test("direct writes, edits and creation share builtin permissions and canonical service.setDefinition(boolean.id, boolean, "manager"); for (const values of [{ pinned: 2 }, { [boolean.id]: 2 }, { [custom.id]: null }]) { assert.throws(() => service.attributes.write(page.id, values)); - assert.throws(() => service.commitEdit({ pageId: page.id, tabId: "edit", batch: 1, blocks: [], attributes: values })); + assert.throws(() => service.commitEdit({ pageId: page.id, tabId: "edit", batch: 1, blocks: [], attributes: values }, pageHistory(page.id))); assert.throws(() => service.create("editable", "B", values)); } assert.equal(service.get(page.id).attributes.pinned, false); assert.throws(() => service.attributes.detach(page.id, ["tags"]), hasFailure("attribute-invalid-detach")); - assert.throws(() => service.commitEdit({ pageId: page.id, tabId: "edit", batch: 1, blocks: [], detach: ["tags"] }), hasFailure("attribute-invalid-detach")); + assert.throws(() => service.commitEdit({ pageId: page.id, tabId: "edit", batch: 1, blocks: [], detach: ["tags"] }, pageHistory(page.id)), hasFailure("attribute-invalid-detach")); assert.throws(() => service.attributes.write(page.id, { created_at: 0 }), hasFailure("attribute-readonly")); assert.throws(() => service.attributes.write(page.id, { task_status: "todo" }), hasFailure("attribute-unsupported-builtin")); }); @@ -110,7 +111,7 @@ test("editable tag options persist, rename searchable values and never store the const { service, database, info } = fixture(t), page = service.create("editable", "A"), tags = service.attributes.definition("tags"); tags.metadata.options = [{ id: "paper", name: "论文" }]; service.setDefinition("tags", tags, "manager"); - service.commitEdit({ pageId: page.id, tabId: "edit", batch: 1, blocks: [], attributes: { tags: ["paper"] } }); + service.commitEdit({ pageId: page.id, tabId: "edit", batch: 1, blocks: [], attributes: { tags: ["paper"] } }, pageHistory(page.id)); assert.equal(service.list({ keyword: "论文" }).total, 1); tags.metadata.options[0].name = "研究"; service.setDefinition("tags", tags, "manager"); diff --git a/tests/clipboard.test.ts b/tests/clipboard.test.ts index c394914..f31ce99 100644 --- a/tests/clipboard.test.ts +++ b/tests/clipboard.test.ts @@ -1,3 +1,4 @@ +import { pageHistory, workspaceHistory } from "./support/history"; import { knowledgeServices, historyServices, purgeServices, session, type Knowledge, type History, type Purge } from "./support/session"; import assert from "node:assert/strict"; import { randomUUID } from "node:crypto"; @@ -33,8 +34,7 @@ function fixture(t: TestContext): ClipboardFixture { const a = service.create("editable", "A"), b = service.create("editable", "B"); const parent = a.blocks[a.children[0]], child: ContentBlock = { id: randomUUID(), type: "unordered_list", payload: payload("unordered_list", "Copied child"), children: [] }; const leaf: ContentBlock = { id: randomUUID(), type: "paragraph", payload: payload("paragraph", "Copied leaf"), children: [] }; - service.commitEdit({ pageId: a.id, tabId: "setup", batch: 0, blocks: [{ ...parent, children: [child.id] }, { ...child, children: [leaf.id] }, leaf] }); - history.close("setup"); + service.commitEdit({ pageId: a.id, tabId: "setup", batch: 0, blocks: [{ ...parent, children: [child.id] }, { ...child, children: [leaf.id] }, leaf] }, pageHistory(a.id)); const source = schema.nodeFromJSON(pageDocument(service.get(a.id))), slice = new Slice(Fragment.from(source.lastChild!), 0, 0); const text = writeClipboard(workspace.info.id, slice)!; const clipboard = readClipboard(schema, text)!; @@ -44,7 +44,7 @@ function fixture(t: TestContext): ClipboardFixture { }; const paste = (current?: ContentBlock[]): PageRecord => { const planned = pasteBlocks(target(), clipboard, current); - assert.equal(service.commitEdit({ ...planned.edit, pageId: b.id, tabId: "paste", batch: 0, ...(current ? { sync: clipboard.ids } : {}) }).status, "saved"); + assert.equal(service.commitEdit({ ...planned.edit, pageId: b.id, tabId: "paste", batch: 0, ...(current ? { sync: clipboard.ids } : {}) }, pageHistory(b.id)).status, "saved"); const sync = workspace.database.prepare("SELECT * FROM sync_refs ORDER BY container_kind,container_id,slot,position"); const links = workspace.database.prepare("SELECT * FROM link_refs ORDER BY source_kind,source_id,source_field,target_kind,target_id"); const expectedSync = sync.all(), expectedLinks = links.all(); @@ -68,51 +68,51 @@ test("only closed whole Labloom blocks carry the internal block clipboard format for (const origin of ["live", "recycled", "orphan", "purged", "other-workspace"] as const) { test("ordinary paste fully copies the snapshot with independent IDs: " + origin, t => { const f = fixture(t), { service, history, a, b, parent, child, leaf, clipboard, purge } = f; - if (origin === "recycled" || origin === "purged") confirm(token => service.trash([a.id], "trash", token)); + if (origin === "recycled" || origin === "purged") confirm(token => service.trash([a.id], "trash", workspaceHistory, token)); if (origin === "purged") { const preview = purge.purge([a.id], "purge"); assert.equal(preview.status, "confirmation"); if (preview.status === "confirmation") purge.purge([a.id], "purge", preview.token); } - if (origin === "orphan") confirm(token => service.deleteBlock({ pageId: a.id, blockId: parent.id, tabId: "delete" }, token)); + if (origin === "orphan") confirm(token => service.deleteBlock({ pageId: a.id, blockId: parent.id, tabId: "delete" }, pageHistory(a.id), token)); if (origin === "other-workspace") clipboard.workspaceId = randomUUID(); const available = service.syncBlocks(clipboard.workspaceId, clipboard.ids); assert.equal(available !== null, origin === "live"); - if (origin === "live") service.commitEdit({ pageId: a.id, tabId: "source", batch: 1, blocks: [{ ...leaf, payload: payload("paragraph", "Changed after copy") }] }); + if (origin === "live") service.commitEdit({ pageId: a.id, tabId: "source", batch: 1, blocks: [{ ...leaf, payload: payload("paragraph", "Changed after copy") }] }, pageHistory(a.id)); const result = f.paste(), root = result.blocks[result.children[0]], copiedChild = result.blocks[root.children[0]], copiedLeaf = result.blocks[copiedChild.children[0]]; assert.ok(![parent.id, child.id, leaf.id].includes(root.id)); assert.ok(![parent.id, child.id, leaf.id].includes(copiedChild.id)); assert.ok(![parent.id, child.id, leaf.id].includes(copiedLeaf.id)); assert.equal(copiedLeaf.payload.inline[0].type === "text" && copiedLeaf.payload.inline[0].text, "Copied leaf"); - assert.equal(service.commitEdit({ pageId: b.id, tabId: "edit-copy", batch: 1, blocks: [{ ...copiedLeaf, payload: payload("paragraph", "Independent") }] }).status, "saved"); + assert.equal(service.commitEdit({ pageId: b.id, tabId: "edit-copy", batch: 1, blocks: [{ ...copiedLeaf, payload: payload("paragraph", "Independent") }] }, pageHistory(b.id)).status, "saved"); if (origin === "live") assert.equal(service.get(a.id).blocks[leaf.id].payload.inline[0].type === "text" && (service.get(a.id).blocks[leaf.id].payload.inline[0] as { text: string }).text, "Changed after copy"); - assert.equal(history.state("paste").canUndo, false, "editing the same page in another tab invalidates its history"); + assert.equal(history.state(pageHistory(f.b.id)).canUndo, true, "both edits belong to the destination page"); assert.deepEqual(f.database.pragma("foreign_key_check"), []); }); } test("one full-copy paste is one undo record and redo restores the complete subtree", t => { const f = fixture(t), before = f.service.get(f.b.id).children, copied = f.paste(); - assert.equal(f.history.apply("paste", "undo").status, "saved"); + assert.equal(f.history.apply(pageHistory(f.b.id), "undo").status, "saved"); assert.deepEqual(f.service.get(f.b.id).children, before); - assert.equal(f.history.state("paste").canUndo, false); - assert.equal(f.history.apply("paste", "redo").status, "saved"); + assert.equal(f.history.state(pageHistory(f.b.id)).canUndo, false); + assert.equal(f.history.apply(pageHistory(f.b.id), "redo").status, "saved"); assert.deepEqual(f.service.get(f.b.id).children, copied.children); assert.deepEqual(f.service.get(f.b.id).blocks[copied.children[0]], copied.blocks[copied.children[0]]); }); test("synchronous paste takes current database content, shares identities and undoes once", t => { const f = fixture(t), { service, history, leaf, clipboard } = f, before = service.get(f.b.id).children; - service.commitEdit({ pageId: f.a.id, tabId: "source", batch: 1, blocks: [{ ...leaf, payload: payload("paragraph", "Current database content") }] }); + service.commitEdit({ pageId: f.a.id, tabId: "source", batch: 1, blocks: [{ ...leaf, payload: payload("paragraph", "Current database content") }] }, pageHistory(f.a.id)); const current = service.syncBlocks(clipboard.workspaceId, clipboard.ids)!; const pasted = f.paste(current); assert.deepEqual(pasted.children, [f.parent.id]); assert.equal(pasted.blocks[leaf.id].payload.inline[0].type === "text" && (pasted.blocks[leaf.id].payload.inline[0] as { text: string }).text, "Current database content"); - assert.equal(history.apply("paste", "undo").status, "saved"); + assert.equal(history.apply(pageHistory(f.b.id), "undo").status, "saved"); assert.deepEqual(service.get(f.b.id).children, before); - assert.equal(history.state("paste").canUndo, false); - assert.equal(history.apply("paste", "redo").status, "saved"); - service.commitEdit({ pageId: f.b.id, tabId: "paste", batch: 2, blocks: [{ ...pasted.blocks[leaf.id], payload: payload("paragraph", "Shared edit") }] }); + assert.equal(history.state(pageHistory(f.b.id)).canUndo, false); + assert.equal(history.apply(pageHistory(f.b.id), "redo").status, "saved"); + service.commitEdit({ pageId: f.b.id, tabId: "paste", batch: 2, blocks: [{ ...pasted.blocks[leaf.id], payload: payload("paragraph", "Shared edit") }] }, pageHistory(f.b.id)); assert.deepEqual(service.get(f.a.id).blocks[leaf.id], service.get(f.b.id).blocks[leaf.id]); }); @@ -125,22 +125,22 @@ test("sync eligibility requires every root and is rechecked at commit; cycles an const cycle = EditorState.create({ schema, doc, selection: NodeSelection.create(doc, position), plugins: [identityPlugin()] }); assert.throws(() => pasteBlocks(cycle, clipboard, current), hasFailure("block-cycle")); const feed = service.create("feed", "Feed"); - assert.throws(() => service.commitEdit({ pageId: feed.id, tabId: "feed", batch: 0, blocks: [], pageChildren: clipboard.ids, sync: clipboard.ids }), hasFailure("feed-body-forbidden")); - confirm(token => service.trash([f.a.id], "trash", token)); + assert.throws(() => service.commitEdit({ pageId: feed.id, tabId: "feed", batch: 0, blocks: [], pageChildren: clipboard.ids, sync: clipboard.ids }, pageHistory(feed.id)), hasFailure("feed-body-forbidden")); + confirm(token => service.trash([f.a.id], "trash", workspaceHistory, token)); const before = service.get(f.b.id); - assert.throws(() => service.commitEdit({ ...planned.edit, pageId: f.b.id, tabId: "paste", batch: 0, sync: clipboard.ids }), hasFailure("block-sync-unavailable")); + assert.throws(() => service.commitEdit({ ...planned.edit, pageId: f.b.id, tabId: "paste", batch: 0, sync: clipboard.ids }, pageHistory(f.b.id)), hasFailure("block-sync-unavailable")); assert.deepEqual(service.get(f.b.id), before); }); for (const synced of [false, true]) { test("pasting whole blocks within existing text preserves both text halves without accidental sync: " + synced, t => { const f = fixture(t), original = f.b.blocks[f.b.children[0]]; - f.service.commitEdit({ pageId: f.b.id, tabId: "setup", batch: 1, blocks: [{ ...original, payload: payload("paragraph", "ABCD") }] }); + f.service.commitEdit({ pageId: f.b.id, tabId: "setup", batch: 1, blocks: [{ ...original, payload: payload("paragraph", "ABCD") }] }, pageHistory(f.b.id)); const state = f.target(), position = indexDoc(state.doc).get(original.id)![0].pos + 4; const selected = state.apply(state.tr.setSelection(TextSelection.create(state.doc, position))); const current = synced ? f.service.syncBlocks(f.clipboard.workspaceId, f.clipboard.ids)! : undefined; const planned = pasteBlocks(selected, f.clipboard, current); - assert.equal(f.service.commitEdit({ ...planned.edit, pageId: f.b.id, tabId: "paste", batch: 1, ...(synced ? { sync: f.clipboard.ids } : {}) }).status, "saved"); + assert.equal(f.service.commitEdit({ ...planned.edit, pageId: f.b.id, tabId: "paste", batch: 1, ...(synced ? { sync: f.clipboard.ids } : {}) }, pageHistory(f.b.id)).status, "saved"); const saved = f.service.get(f.b.id), bodies = saved.children.map(id => saved.blocks[id]); assert.equal(bodies.filter(block => block.id === original.id).length, 1); assert.equal(new Set(bodies.map(block => block.id)).size, bodies.length); diff --git a/tests/content.test.ts b/tests/content.test.ts index 87accd3..cd9a3d5 100644 --- a/tests/content.test.ts +++ b/tests/content.test.ts @@ -1,3 +1,4 @@ +import { pageHistory, workspaceHistory } from "./support/history"; import { watchKnowledge } from "./support/session"; import { knowledgeServices, historyServices, session, type Knowledge, type History } from "./support/session"; import { hasFailure } from "./failures"; @@ -28,7 +29,7 @@ function fixture(t: TestContext, options: import("../main/session").SessionOptio return { ...workspace, service, history }; } function edit(service: Knowledge, page: PageRecord, changes: ContentBlock[], children = page.children, tabId = "tab-one"): CommitResult { - return service.commitEdit({ pageId: page.id, tabId, batch: 1, pageChildren: children, blocks: changes }); + return service.commitEdit({ pageId: page.id, tabId, batch: 1, pageChildren: children, blocks: changes }, pageHistory(page.id)); } function text(block: ContentBlock, value: string): ContentBlock { return { ...block, payload: payload(block.type, value) }; @@ -84,7 +85,7 @@ test("unlinking shallow-copies one occurrence and retains all child UUIDs", t => parent.children = [child.id]; edit(service, page, [parent, child], [parent.id, parent.id]); page = service.get(page.id); - service.place({ action: "clone", tabId: "tab-one", position: { pageId: page.id, containerId: page.id, index: 1, blockId: parent.id } }); + service.place({ action: "clone", tabId: "tab-one", position: { pageId: page.id, containerId: page.id, index: 1, blockId: parent.id } }, pageHistory(page.id)); const result = service.get(page.id), copy = result.children[1]; assert.notEqual(copy, parent.id); assert.equal(result.children[0], parent.id); @@ -101,11 +102,11 @@ test("removing one occurrence never garbage-collects content, and stale position edit(service, page, [], [id, id]); page = service.get(page.id); const position = { pageId: page.id, containerId: page.id, index: 1, blockId: id }; - service.place({ action: "remove", tabId: "tab-one", position }); + service.place({ action: "remove", tabId: "tab-one", position }, pageHistory(position.pageId)); assert.deepEqual(service.get(page.id).children, [id]); - assert.throws(() => service.place({ action: "remove", tabId: "tab-one", position }), hasFailure("block-position-changed")); + assert.throws(() => service.place({ action: "remove", tabId: "tab-one", position }, pageHistory(position.pageId)), hasFailure("block-position-changed")); page = service.get(page.id); - service.place({ action: "remove", tabId: "tab-one", position: { ...position, index: 0 } }); + service.place({ action: "remove", tabId: "tab-one", position: { ...position, index: 0 } }, pageHistory(position.pageId)); assert.ok(service.blockRow(id)); }); @@ -144,7 +145,7 @@ test("reference cycles lose retention together and only after the complete previ const backward = { id: randomUUID(), type: "blocked_reference" as const, payload: { ...payload("blocked_reference"), target: { kind: "page" as const, id: a.id } }, children: [] }; edit(service, b, [backward], [backward.id]); const before = snapshot(service), timestamp = database.prepare("SELECT last_modified_at FROM workspace_meta").get(); - const trash = (token?: string): CommitResult => service.trash([root.id], "tab-one", token); + const trash = (token?: string): CommitResult => service.trash([root.id], "tab-one", workspaceHistory, token); const pending = trash(); assert.equal(pending.status, "confirmation"); if (pending.status !== "confirmation") return; @@ -155,7 +156,7 @@ test("reference cycles lose retention together and only after the complete previ assert.equal(service.get(root.id).attributes.recycle_reason, "manual_delete"); assert.equal(service.get(a.id).attributes.recycle_reason, "unreachable"); assert.equal(service.get(b.id).attributes.deleted, true); - service.restore([a.id, b.id], "tab-one"); + service.restore([a.id, b.id], "tab-one", workspaceHistory); assert.equal(service.get(a.id).attributes.independent, true); assert.equal(service.get(a.id).attributes.recycled_at, null); }); @@ -166,11 +167,11 @@ test("a reference to a shared block does not retain every page using that block" const blockId = child.children[0], current = service.get(root.id); const reference = { id: randomUUID(), type: "blocked_reference" as const, payload: { ...payload("blocked_reference"), target: { kind: "block" as const, id: blockId } }, children: [] }; const input: EditCommit = { pageId: root.id, tabId: "tab-one", batch: 1, pageChildren: [reference.id], blocks: [reference] }; - const result = service.commitEdit(input); + const result = service.commitEdit(input, pageHistory(input.pageId)); assert.equal(result.status, "confirmation"); if (result.status !== "confirmation") return; assert.deepEqual(result.preview.recycled.map(page => page.id), [child.id]); - service.commitEdit(input, result.preview.token); + service.commitEdit(input, pageHistory(input.pageId), result.preview.token); assert.ok(service.blockRow(blockId)); assert.equal(service.get(root.id).attributes.deleted, false); }); @@ -178,7 +179,7 @@ test("a reference to a shared block does not retain every page using that block" test("a stale lifecycle confirmation cannot silently cover a changed graph", t => { const { service } = fixture(t); const root = service.create("editable", "Root"); - const trash = (token?: string): CommitResult => service.trash([root.id], "tab-one", token); + const trash = (token?: string): CommitResult => service.trash([root.id], "tab-one", workspaceHistory, token); const preview = trash(); assert.equal(preview.status, "confirmation"); if (preview.status !== "confirmation") return; @@ -196,14 +197,14 @@ test("removing a retaining property previews both its owners and dependent pages const id = `custom:${randomUUID()}`; const tabId = randomUUID(); service.setDefinition(id, { id, type: "page-link", name: "Citation", metadata: {} }, tabId); - service.commitEdit({ pageId: root.id, tabId: "owner", batch: 1, blocks: [], attributes: { [id]: dependent.id } }); - service.commitEdit({ pageId: dependent.id, tabId: "dependent", batch: 1, blocks: [], attributes: { independent: false } }); + service.commitEdit({ pageId: root.id, tabId: "owner", batch: 1, blocks: [], attributes: { [id]: dependent.id } }, pageHistory(root.id)); + service.commitEdit({ pageId: dependent.id, tabId: "dependent", batch: 1, blocks: [], attributes: { independent: false } }, pageHistory(dependent.id)); const preview = service.setDefinition(id, null, tabId)!; assert.deepEqual(preview.pages.map(page => page.id), [root.id]); assert.deepEqual(preview.recycled?.map(page => page.id), [dependent.id]); assert.equal(service.get(root.id).attributes[id], dependent.id); assert.equal(service.get(dependent.id).attributes.deleted, false); - assert.equal(history.state("owner").canUndo, true); + assert.equal(history.state(pageHistory(root.id)).canUndo, true); service.create("editable", "Another edit"); let source: string | undefined; t.after(watchKnowledge(change => { @@ -211,13 +212,13 @@ test("removing a retaining property previews both its owners and dependent pages })); assert.equal(service.setDefinition(id, null, tabId, preview.token), null); assert.equal(source, tabId); - assert.equal(history.state(tabId).canUndo, false); + assert.equal(history.state(workspaceHistory).canUndo, false); assert.equal(Object.hasOwn(service.get(root.id).attributes, id), false); assert.equal(service.get(dependent.id).attributes.recycle_reason, "unreachable"); - assert.equal(history.state("owner").canUndo, false); + assert.equal(history.state(pageHistory(root.id)).canUndo, false); }); -test("cross-tab history invalidates only overlapping operations and preserves redo branches", t => { +test("two tabs advance the same page cursor and preserve redo branches", t => { const { service, history, database, info } = fixture(t); let page = service.create(); const a = page.blocks[page.children[0]], b = { id: randomUUID(), type: "paragraph" as const, payload: payload("paragraph", "B"), children: [] }; @@ -228,24 +229,23 @@ test("cross-tab history invalidates only overlapping operations and preserves re edit(service, page, [text(page.blocks[b.id], "B1")]); page = service.get(page.id); edit(service, page, [text(page.blocks[a.id], "A2")], page.children, "tab-two"); - assert.equal(history.state("tab-one").canUndo, true); - history.apply("tab-one", "undo"); - assert.equal(blockText(service.get(page.id).blocks[a.id]), "A2"); - assert.equal(blockText(service.get(page.id).blocks[b.id]), "B"); - const firstBranch = history.state("tab-one").redo[0].id; + assert.equal(history.state(pageHistory(page.id)).canUndo, true); + history.apply(pageHistory(page.id), "undo"); + assert.equal(blockText(service.get(page.id).blocks[a.id]), "A1"); + assert.equal(blockText(service.get(page.id).blocks[b.id]), "B1"); + const firstBranch = history.state(pageHistory(page.id)).redo[0].id; page = service.get(page.id); edit(service, page, [text(page.blocks[b.id], "B alternate")]); - history.apply("tab-one", "undo"); - assert.equal(history.state("tab-one").redo.length, 2); - history.apply("tab-one", "redo", firstBranch); + history.apply(pageHistory(page.id), "undo"); + assert.equal(history.state(pageHistory(page.id)).redo.length, 2); + history.apply(pageHistory(page.id), "redo", firstBranch); assert.equal(blockText(service.get(page.id).blocks[b.id]), "B1"); session.close(); const reopened = openWorkspace(info.path); t.after(() => session.close()); const restoredHistory = historyServices(); - assert.equal(restoredHistory.state("tab-one").canUndo, false); - restoredHistory.close("tab-one"); - assert.equal(restoredHistory.state("tab-one").canUndo, false); + assert.equal(restoredHistory.state(pageHistory(page.id)).canUndo, false); + assert.equal(blockText(service.get(page.id).blocks[a.id]), "A2"); }); test("deleteBlock removes every use, keeps live links and undo restores nested and repeated positions", t => { @@ -264,7 +264,7 @@ test("deleteBlock removes every use, keeps live links and undo restores nested a edit(service, b, [parent]); edit(service, c, [link]); const target = { kind: "block" as const, id: shared.id }; - const remove = (token?: string): CommitResult => service.deleteBlock({ pageId: a.id, tabId: "delete", blockId: shared.id }, token); + const remove = (token?: string): CommitResult => service.deleteBlock({ pageId: a.id, tabId: "delete", blockId: shared.id }, pageHistory(a.id), token); const pending = remove(); assert.equal(pending.status, "confirmation"); assert.equal(confirmationText(pending.preview), "“Common”将从2个页面的3个位置消失,1个链接引用将显示“已删除”。"); @@ -275,7 +275,7 @@ test("deleteBlock removes every use, keeps live links and undo restores nested a assert.ok(service.blockRow(shared.id)); assert.deepEqual(service.get(c.id).blocks[link.id].payload, link.payload); assert.equal(service.resolve(target)?.status, "deleted"); - assert.equal(history.apply("delete", "undo").status, "saved"); + assert.equal(history.apply(pageHistory(a.id), "undo").status, "saved"); assert.equal(service.resolve(target)?.status, "ok"); assert.deepEqual(service.get(a.id).children, [shared.id, shared.id]); assert.deepEqual(service.get(b.id).blocks[parent.id].children, [shared.id]); @@ -287,7 +287,7 @@ test("reference deletion names its target, omits zero counts and lists all recyc const e = service.create("editable", "E", { independent: false }, d.id); const f = service.create("editable", "F", { independent: false }, e.id); const blockId = service.get(d.id).children.at(-1)!; - const remove = (token?: string): CommitResult => service.deleteBlock({ pageId: d.id, tabId: "delete", blockId }, token); + const remove = (token?: string): CommitResult => service.deleteBlock({ pageId: d.id, tabId: "delete", blockId }, pageHistory(d.id), token); const result = remove(); assert.equal(result.status, "confirmation"); assert.equal(confirmationText(result.preview), "指向「E」的链接引用将从1个页面的1个位置消失。\n将移入回收站:E、F。"); @@ -310,11 +310,11 @@ test("incremental links match rebuilding after changing, clearing and undoing al const inline = { type: "inlineReference" as const, attrs: { target, label: "B" } }; const body = { ...a.blocks[a.children[0]], payload: { ...payload("paragraph"), inline: [inline, inline] } }; const batch = { pageId: a.id, tabId: "links", batch: 1, blocks: [reference, body], pageChildren: [body.id, reference.id], attributes: { links: [b.id] } }; - assert.equal(service.commitEdit(batch).status, "saved"); + assert.equal(service.commitEdit(batch, pageHistory(batch.pageId)).status, "saved"); check(3); - assert.equal(service.commitEdit({ ...batch, blocks: [a.blocks[body.id], { ...reference, payload: { ...reference.payload, target: null } }], attributes: { links: [] } }).status, "saved"); + assert.equal(service.commitEdit({ ...batch, blocks: [a.blocks[body.id], { ...reference, payload: { ...reference.payload, target: null } }], attributes: { links: [] } }, pageHistory(batch.pageId)).status, "saved"); check(0); - history.apply("links", "undo"); + history.apply(pageHistory(a.id), "undo"); check(3); }); @@ -323,11 +323,11 @@ test("detaching and deleting custom page links clears their source index through const id = "custom:" + randomUUID(), definition = { id, type: "page-link" as const, name: "Related", metadata: {} }; assert.equal(service.setDefinition(id, definition, "definitions"), null); const count = (): unknown => service.statement("SELECT count(*) FROM link_refs WHERE source_kind='page' AND source_field=?").pluck().get(id); - service.commitEdit({ pageId: a.id, tabId: "links", batch: 0, blocks: [], attributes: { [id]: b.id } }); + service.commitEdit({ pageId: a.id, tabId: "links", batch: 0, blocks: [], attributes: { [id]: b.id } }, pageHistory(a.id)); assert.equal(count(), 1); - service.commitEdit({ pageId: a.id, tabId: "links", batch: 1, blocks: [], detach: [id] }); + service.commitEdit({ pageId: a.id, tabId: "links", batch: 1, blocks: [], detach: [id] }, pageHistory(a.id)); assert.equal(count(), 0); - service.commitEdit({ pageId: a.id, tabId: "links", batch: 2, blocks: [], attributes: { [id]: b.id } }); + service.commitEdit({ pageId: a.id, tabId: "links", batch: 2, blocks: [], attributes: { [id]: b.id } }, pageHistory(a.id)); const preview = service.setDefinition(id, null, "definitions"); assert.ok(preview); assert.equal(service.setDefinition(id, null, "definitions", preview.token), null); @@ -346,7 +346,7 @@ test("new pages have valid typed values, independent retention and system timest if (kind === "task") { assert.equal(page.attributes.task_status, "todo"); assert.equal(page.attributes.priority, "normal"); - assert.equal(service.commitEdit({ pageId: page.id, tabId: "status", batch: 1, blocks: [], attributes: { task_status: null, priority: null } }).status, "saved"); + assert.equal(service.commitEdit({ pageId: page.id, tabId: "status", batch: 1, blocks: [], attributes: { task_status: null, priority: null } }, pageHistory(page.id)).status, "saved"); assert.equal(service.get(page.id).attributes.task_status, null); assert.equal(service.get(page.id).attributes.priority, null); } @@ -374,7 +374,7 @@ test("keywords and display use the current application timezone on the same open assert.equal(service.list({ keyword: "01:12" }).total, 0); const tag = randomUUID(), definition = service.attributes.definition("tags"); service.setDefinition("tags", { ...definition, metadata: { ...definition.metadata, options: [{ id: tag, name: "Research" }] } }, randomUUID()); - service.commitEdit({ pageId: e.id, tabId: "edit", batch: 1, blocks: [], attributes: { tags: [tag] } }); + service.commitEdit({ pageId: e.id, tabId: "edit", batch: 1, blocks: [], attributes: { tags: [tag] } }, pageHistory(e.id)); assert.equal(service.list({ keyword: tag }).total, 0); assert.equal(service.list({ keyword: "research" }).total, 1); const dt = service.statement("SELECT typeof(value) FROM page_attrs WHERE page_id=? AND attr_id=?").pluck(); diff --git a/tests/feed.test.ts b/tests/feed.test.ts index f90b78e..e139742 100644 --- a/tests/feed.test.ts +++ b/tests/feed.test.ts @@ -1,3 +1,4 @@ +import { pageHistory, workspaceHistory } from "./support/history"; import { knowledgeServices, feedServices, paperServices, historyServices, purgeServices, session } from "./support/session"; import { hasFailure } from "./failures"; import assert from "node:assert/strict"; @@ -50,8 +51,8 @@ test("feed pages own settings and timers while refresh preserves item state and assert.equal(knowledge.get(source.id).attributes.modified_at, modified); assert.equal(knowledge.list({ kind: "feed" }).total, 2); assert.equal(knowledge.list({ keyword: "Saved feed" }).total, 1); - assert.throws(() => knowledge.commitEdit({ pageId: source.id, tabId: "feed", batch: 0, blocks: [], attributes: { feed_refresh: { every: 5, unit: "minute" } } }), hasFailure("feed-invalid-interval")); - assert.throws(() => knowledge.commitEdit({ pageId: source.id, tabId: "feed", batch: 0, blocks: [], pageChildren: [source.titleBlockId] }), hasFailure("feed-body-forbidden")); + assert.throws(() => knowledge.commitEdit({ pageId: source.id, tabId: "feed", batch: 0, blocks: [], attributes: { feed_refresh: { every: 5, unit: "minute" } } }, pageHistory(source.id)), hasFailure("feed-invalid-interval")); + assert.throws(() => knowledge.commitEdit({ pageId: source.id, tabId: "feed", batch: 0, blocks: [], pageChildren: [source.titleBlockId] }, pageHistory(source.id)), hasFailure("feed-body-forbidden")); assert.deepEqual(database.pragma("foreign_key_check"), []); }); @@ -94,8 +95,8 @@ test("a subscription item becomes a paper page in the library and stays linked t assert.deepEqual([second.title, second.attributes.paper_url, second.attributes.paper_year, second.attributes.paper_authors], ["No link or date", "", "", ""]); // A paper in the recycle bin is reported, and only replaced when the reader asks. - const removal = knowledge.trash([pageId], "feed-test"); - if (removal.status === "confirmation") knowledge.trash([pageId], "feed-test", removal.preview.token); + const removal = knowledge.trash([pageId], "feed-test", workspaceHistory); + if (removal.status === "confirmation") knowledge.trash([pageId], "feed-test", workspaceHistory, removal.preview.token); assert.equal(service.getItem(item.id).paperState, "recycled"); assert.throws(() => service.importItem(item.id), hasFailure("feed-reimport-confirmation")); const replacement = service.importItem(item.id, true); @@ -155,7 +156,7 @@ test("a downloaded PDF attaches to its committed paper as independent bytes, and await service.fetchPDF(item.id); assert.equal(requests, 1); assert.deepEqual(knowledge.get(pageId).attributes.paper_files, [downloadedFiles[0].id]); - assert.equal(knowledge.commitEdit({ pageId, tabId: "remove-feed-pdf", batch: 0, blocks: [], attributes: { paper_files: [] } }).status, "saved"); + assert.equal(knowledge.commitEdit({ pageId, tabId: "remove-feed-pdf", batch: 0, blocks: [], attributes: { paper_files: [] } }, pageHistory(pageId)).status, "saved"); assert.equal(papers.hasPDF(pageId), false); assert.notEqual(service.getItem(item.id).pdfStatus, "saved"); await service.fetchPDF(item.id); @@ -176,18 +177,18 @@ test("feed settings, recycling and restoration maintain a single timer and enfor assert.equal(knowledge.header(id).kind, "feed"); assert.deepEqual(knowledge.get(id).children, []); assert.equal(count(), 1); feed.setSourceStatus(id, "pause"); assert.equal(count(), 0); feed.setSourceStatus(id, "resume"); assert.equal(count(), 1); - assert.equal(knowledge.commitEdit({ pageId: id, tabId: "settings", batch: 0, blocks: [], attributes: { feed_refresh: null } }).status, "saved"); assert.equal(count(), 0); - assert.equal(history.apply("settings", "undo").status, "saved"); assert.equal(count(), 1); + assert.equal(knowledge.commitEdit({ pageId: id, tabId: "settings", batch: 0, blocks: [], attributes: { feed_refresh: null } }, pageHistory(id)).status, "saved"); assert.equal(count(), 0); + assert.equal(history.apply(pageHistory(id), "undo").status, "saved"); assert.equal(count(), 1); const page = knowledge.get(id), child = { id: randomUUID(), type: "paragraph" as const, payload: payload("paragraph", "Forbidden"), children: [] }; - assert.throws(() => knowledge.commitEdit({ pageId: id, tabId: "settings", batch: 0, blocks: [child], pageChildren: [child.id] }), hasFailure("feed-body-forbidden")); - assert.throws(() => knowledge.commitEdit({ pageId: id, tabId: "settings", batch: 0, blocks: [{ ...page.blocks[page.titleBlockId], children: [child.id] }] }), hasFailure("feed-body-forbidden")); - assert.throws(() => knowledge.place({ position: { pageId: id, containerId: id, index: 0, blockId: page.titleBlockId }, action: "insert", tabId: "settings" }), hasFailure("feed-body-forbidden")); - const preview = knowledge.trash([id], "trash"); if (preview.status === "confirmation") knowledge.trash([id], "trash", preview.preview.token); + assert.throws(() => knowledge.commitEdit({ pageId: id, tabId: "settings", batch: 0, blocks: [child], pageChildren: [child.id] }, pageHistory(id)), hasFailure("feed-body-forbidden")); + assert.throws(() => knowledge.commitEdit({ pageId: id, tabId: "settings", batch: 0, blocks: [{ ...page.blocks[page.titleBlockId], children: [child.id] }] }, pageHistory(id)), hasFailure("feed-body-forbidden")); + assert.throws(() => knowledge.place({ position: { pageId: id, containerId: id, index: 0, blockId: page.titleBlockId }, action: "insert", tabId: "settings" }, pageHistory(id)), hasFailure("feed-body-forbidden")); + const preview = knowledge.trash([id], "trash", workspaceHistory); if (preview.status === "confirmation") knowledge.trash([id], "trash", workspaceHistory, preview.preview.token); assert.equal(count(), 0); assert.equal(feed.getState({}).sources.length, 0); await assert.rejects(feed.saveSource({ name: "B", url: "https://example.org/feed" }), hasFailure("feed-duplicate")); - knowledge.restore([id], "restore"); assert.equal(count(), 1); + knowledge.restore([id], "restore", workspaceHistory); assert.equal(count(), 1); const title = knowledge.get(id).blocks[page.titleBlockId]; - knowledge.commitEdit({ pageId: id, tabId: "rename", batch: 0, blocks: [{ ...title, payload: payload("title", "B") }] }); + knowledge.commitEdit({ pageId: id, tabId: "rename", batch: 0, blocks: [{ ...title, payload: payload("title", "B") }] }, pageHistory(id)); assert.equal(feed.getState({}).sources[0].name, "B"); assert.ok(knowledge.list({ keyword: "B", kind: "feed" }).items.some(page => page.id === id)); }); @@ -197,7 +198,7 @@ test("permanently deleting a source cascades its entries without deleting import const knowledge = knowledgeServices(), history = historyServices(), papers = paperServices(); const feed = feedServices(); const source = await feed.saveSource({ name: "A", url: "https://example.org/feed" }), paper = feed.importItem(feed.getState({}).items[0].id); - const removal = knowledge.trash([source], "trash"); if (removal.status === "confirmation") knowledge.trash([source], "trash", removal.preview.token); + const removal = knowledge.trash([source], "trash", workspaceHistory); if (removal.status === "confirmation") knowledge.trash([source], "trash", workspaceHistory, removal.preview.token); const purge = purgeServices(), preview = purge.purge([source], "purge"); if (preview.status !== "confirmation") throw new Error("Expected confirmation"); assert.equal(purge.purge([source], "purge", preview.token).status, "deleted"); diff --git a/tests/files.test.ts b/tests/files.test.ts index 08f4e9b..43d8e2c 100644 --- a/tests/files.test.ts +++ b/tests/files.test.ts @@ -1,3 +1,4 @@ +import { pageHistory, workspaceHistory } from "./support/history"; import * as commit from "../main/knowledge/commit"; import { knowledgeServices, historyServices, paperServices, purgeServices, session, type Knowledge, type History, type Papers, type Purge } from "./support/session"; import { hasFailure } from "./failures"; @@ -32,7 +33,7 @@ function changeType(service: Knowledge, item: AttributeDefinition, type: Attribu if (preview) assert.equal(service.setDefinition(item.id, next, "definitions", preview.token), null); } function edit(service: Knowledge, pageId: string, values: Record, tabId = "files"): void { - assert.equal(service.commitEdit({ pageId, tabId, batch: 0, blocks: [], attributes: values }).status, "saved"); + assert.equal(service.commitEdit({ pageId, tabId, batch: 0, blocks: [], attributes: values }, pageHistory(pageId)).status, "saved"); } function checkIndex(service: Knowledge): void { const query = "SELECT * FROM link_refs ORDER BY source_kind,source_id,source_field,target_kind,target_id"; @@ -41,8 +42,8 @@ function checkIndex(service: Knowledge): void { assert.deepEqual(service.statement(query).all(), before); } function trash(service: Knowledge, pageId: string): void { - const result = service.trash([pageId], "trash"); - if (result.status === "confirmation") assert.equal(service.trash([pageId], "trash", result.preview.token).status, "saved"); + const result = service.trash([pageId], "trash", workspaceHistory); + if (result.status === "confirmation") assert.equal(service.trash([pageId], "trash", workspaceHistory, result.preview.token).status, "saved"); } function erase(purge: Purge, pageId: string): void { const preview = purge.purge([pageId], "purge"); @@ -54,7 +55,7 @@ test("file properties validate existing identities, ordered distinct lists and c const { service, papers, info } = fixture(t), page = service.create("paper", "A"), single = definition(service, "file"), many = definition(service, "files"); const a = join(info.path, "A.txt"), b = join(info.path, "B.txt"); writeFileSync(a, "A"); writeFileSync(b, "B"); - const files = papers.attachFiles([a, b], page.id, "paper_files", "files"), [first, second] = files.map(file => file.id); + const files = papers.attachFiles([a, b], page.id, "paper_files", { tabId: "files", source: pageHistory(page.id) }), [first, second] = files.map(file => file.id); assert.deepEqual(service.get(page.id).attributes.paper_files, [first, second]); edit(service, page.id, { paper_files: [], [single.id]: first, [many.id]: [second] }); for (const values of [{ [single.id]: randomUUID() }, { [many.id]: [first, randomUUID()] }, { [many.id]: [first, first] }, { [single.id]: [] }, { [many.id]: null }, { [single.id]: "A.txt" }]) { @@ -96,28 +97,28 @@ test("paper and custom file imports, removals, clears, undo and redo keep the re const { service, papers, history, info } = fixture(t), page = service.create("paper", "A"), item = definition(service, "files"), single = definition(service, "file"); const a = join(info.path, "A.txt"), b = join(info.path, "B.txt"); writeFileSync(a, "A"); writeFileSync(b, "B"); - const files = papers.attachFiles([a, b], page.id, "paper_files", "files"), [first, second] = files.map(file => file.id); + const files = papers.attachFiles([a, b], page.id, "paper_files", { tabId: "files", source: pageHistory(page.id) }), [first, second] = files.map(file => file.id); checkIndex(service); - assert.equal(history.apply("files", "undo").status, "saved"); + assert.equal(history.apply(pageHistory(page.id), "undo").status, "saved"); assert.deepEqual(service.get(page.id).attributes.paper_files, []); checkIndex(service); assert.equal(papers.files().length, 2, "undoing import keeps immutable bytes available for redo"); - assert.equal(history.apply("files", "redo").status, "saved"); checkIndex(service); - const custom = papers.attachFiles([b, a, b], page.id, item.id, "files").map(file => file.id); + assert.equal(history.apply(pageHistory(page.id), "redo").status, "saved"); checkIndex(service); + const custom = papers.attachFiles([b, a, b], page.id, item.id, { tabId: "files", source: pageHistory(page.id) }).map(file => file.id); assert.equal(new Set(custom).size, 3); assert.ok(custom.every(id => ![first, second].includes(id))); assert.deepEqual(service.get(page.id).attributes[item.id], custom); checkIndex(service); edit(service, page.id, { paper_files: [first], [item.id]: [] }); checkIndex(service); - assert.equal(history.apply("files", "undo").status, "saved"); checkIndex(service); + assert.equal(history.apply(pageHistory(page.id), "undo").status, "saved"); checkIndex(service); assert.deepEqual(service.get(page.id).attributes[item.id], custom); - assert.equal(history.apply("files", "redo").status, "saved"); checkIndex(service); - const [before] = papers.attachFiles([a], page.id, single.id, "files"); - const [after] = papers.attachFiles([b], page.id, single.id, "files"); checkIndex(service); + assert.equal(history.apply(pageHistory(page.id), "redo").status, "saved"); checkIndex(service); + const [before] = papers.attachFiles([a], page.id, single.id, { tabId: "files", source: pageHistory(page.id) }); + const [after] = papers.attachFiles([b], page.id, single.id, { tabId: "files", source: pageHistory(page.id) }); checkIndex(service); assert.notEqual(before.id, after.id); assert.equal(service.get(page.id).attributes[single.id], after.id); - assert.equal(history.apply("files", "undo").status, "saved"); + assert.equal(history.apply(pageHistory(page.id), "undo").status, "saved"); assert.equal(service.get(page.id).attributes[single.id], before.id); checkIndex(service); - assert.equal(service.commitEdit({ pageId: page.id, tabId: "files", batch: 0, blocks: [], detach: [single.id] }).status, "saved"); checkIndex(service); - assert.equal(history.apply("files", "undo").status, "saved"); checkIndex(service); + assert.equal(service.commitEdit({ pageId: page.id, tabId: "files", batch: 0, blocks: [], detach: [single.id] }, pageHistory(page.id)).status, "saved"); checkIndex(service); + assert.equal(history.apply(pageHistory(page.id), "undo").status, "saved"); checkIndex(service); const preview = service.setDefinition(item.id, null, "definitions"); if (preview) assert.equal(service.setDefinition(item.id, null, "definitions", preview.token), null); checkIndex(service); @@ -127,7 +128,7 @@ test("arbitrary attachments retain their suffix and names while PDF operations r const { service, papers, info } = fixture(t), page = service.create("paper", "A"), item = definition(service, "file"); const csv = join(info.path, "补充数据.CSV"), pdf = join(info.path, "正文.pdf"); writeFileSync(csv, "a,b\n1,2"); writeFileSync(pdf, knownCoordinatePdf()); - const [data, document] = papers.attachFiles([csv, pdf], page.id, "paper_files", "files"); + const [data, document] = papers.attachFiles([csv, pdf], page.id, "paper_files", { tabId: "files", source: pageHistory(page.id) }); assert.equal(data.mediaType, "text/csv"); assert.equal(document.mediaType, "application/pdf"); const stored = service.statement("SELECT stored_name FROM attachments WHERE id=?").pluck().get(data.id) as string; assert.equal(extname(stored), ".CSV"); @@ -137,7 +138,7 @@ test("arbitrary attachments retain their suffix and names while PDF operations r assert.equal(papers.hasPDF(page.id), true); assert.throws(() => papers.position(page.id, data.id, { page: 1, scale: "auto", rotation: 0, left: 0, top: 0 }), hasFailure("paper-invalid-position")); await assert.rejects(papers.unlockPDF(data.id, ""), hasFailure("attachment-pdf-required")); - await assert.rejects(papers.annotate(page.id, { fileId: data.id, pageNumber: 1, rectangles: [{ x: 1, y: 1, width: 1, height: 1 }], quote: "", context: "", extractorVersion: PDF_EXTRACTOR_VERSION }, "annotations", "yellow"), hasFailure("attachment-pdf-required")); + await assert.rejects(papers.annotate(page.id, { fileId: data.id, pageNumber: 1, rectangles: [{ x: 1, y: 1, width: 1, height: 1 }], quote: "", context: "", extractorVersion: PDF_EXTRACTOR_VERSION }, "annotations", pageHistory(page.id), "yellow"), hasFailure("attachment-pdf-required")); edit(service, page.id, { [item.id]: data.id, paper_files: [] }); assert.equal(papers.hasPDF(page.id), false); const context = { fileName: (id: string): string | undefined => papers.files([id])[0]?.originalName }; @@ -154,12 +155,12 @@ test("arbitrary attachments retain their suffix and names while PDF operations r test("clearing an attachment leaves bytes available for undo, but reopening removes unreferenced files", async t => { const { service, papers, history, info, database } = fixture(t), path = join(info.path, "A.pdf"); writeFileSync(path, knownCoordinatePdf()); - const pageId = papers.importFile(path, undefined, "files").pageId, file = papers.files()[0]; + const pageId = papers.importFile(path, undefined, { tabId: "files", source: workspaceHistory }).pageId, file = papers.files()[0]; const stored = papers.externalPath(file.id); edit(service, pageId, { paper_files: [] }); assert.equal(existsSync(stored), true); assert.deepEqual(unreferencedFiles(service.db).map(row => row.id), [file.id]); - assert.equal(history.apply("files", "undo").status, "saved"); + assert.equal(history.apply(pageHistory(pageId), "undo").status, "saved"); assert.deepEqual(unreferencedFiles(service.db), []); edit(service, pageId, { paper_files: [] }); session.close(); @@ -167,15 +168,15 @@ test("clearing an attachment leaves bytes available for undo, but reopening remo t.after(() => session.close()); assert.equal(existsSync(stored), false); for (const table of ["attachments"]) assert.equal(reopened.database.prepare("SELECT count(*) FROM " + table).pluck().get(), 0); - assert.deepEqual(historyServices().state("files"), { canUndo: false, redo: [] }); + assert.deepEqual(historyServices().state(pageHistory(pageId)), { canUndo: false, redo: [] }); }); test("a recycled page's custom property protects its independently imported file until the page is permanently deleted", async t => { const { service, papers, purge, info, database } = fixture(t), path = join(info.path, "A.pdf"), item = definition(service, "file"); writeFileSync(path, knownCoordinatePdf()); const paperId = papers.importFile(path).pageId, file = papers.files()[0], other = service.create("editable", "B"); - const [owned] = papers.attachFiles([path], other.id, item.id, "other"); - await papers.annotate(paperId, { fileId: file.id, pageNumber: 1, rectangles: [{ x: 50, y: 690, width: 70, height: 30 }], quote: "", context: "", extractorVersion: PDF_EXTRACTOR_VERSION }, "annotations", "yellow"); + const [owned] = papers.attachFiles([path], other.id, item.id, { tabId: "other", source: pageHistory(other.id) }); + await papers.annotate(paperId, { fileId: file.id, pageNumber: 1, rectangles: [{ x: 50, y: 690, width: 70, height: 30 }], quote: "", context: "", extractorVersion: PDF_EXTRACTOR_VERSION }, "annotations", pageHistory(paperId), "yellow"); const stored = papers.externalPath(owned.id), original = papers.externalPath(file.id); trash(service, paperId); trash(service, other.id); erase(purge, paperId); @@ -195,25 +196,25 @@ test("a recycled page's custom property protects its independently imported file test("failed batch import and failed orphan cleanup restore rows, bytes and history", t => { const { service, papers, history, info } = fixture(t), page = service.create("paper", "A"), a = join(info.path, "A.txt"), b = join(info.path, "B.txt"); writeFileSync(a, "A"); writeFileSync(b, "B"); - assert.throws(() => papers.attachFiles([a, join(info.path, "missing.txt")], page.id, "paper_files", "files")); + assert.throws(() => papers.attachFiles([a, join(info.path, "missing.txt")], page.id, "paper_files", { tabId: "files", source: pageHistory(page.id) })); assert.deepEqual(papers.files(), []); assert.deepEqual(service.get(page.id).attributes.paper_files, []); - assert.equal(history.state("files").canUndo, false); - const [first, second] = papers.attachFiles([a, b], page.id, "paper_files", "files"); + assert.equal(history.state(pageHistory(page.id)).canUndo, false); + const [first, second] = papers.attachFiles([a, b], page.id, "paper_files", { tabId: "files", source: pageHistory(page.id) }); const paths = papers.files().map(file => papers.externalPath(file.id)); edit(service, page.id, { paper_files: [] }); - const before = history.state("files"); + const before = history.state(pageHistory(page.id)); service.statement("UPDATE attachments SET stored_name='../invalid.txt' WHERE id=?").run(second.id); assert.throws(() => commit.run({ sourceTab: "cleanup", cleanup: true }, context => context.cleanup()), hasFailure("attachment-invalid-name")); assert.equal(papers.files().length, 2); for (const path of paths) assert.equal(existsSync(path), true); assert.deepEqual(Buffer.from(papers.read(first.id)), readFileSync(a)); - assert.deepEqual(history.state("files"), before); + assert.deepEqual(history.state(pageHistory(page.id)), before); }); test("file ownership rejects other pages, other attributes and recycled owners, while one atomic move remains reversible", t => { const { service, papers, history, info } = fixture(t), first = service.create("paper", "A"), second = service.create("paper", "B"), single = definition(service, "file"), many = definition(service, "files"); const path = join(info.path, "A.txt"); writeFileSync(path, "A"); - const [file] = papers.attachFiles([path], first.id, "paper_files", "files"); + const [file] = papers.attachFiles([path], first.id, "paper_files", { tabId: "files", source: pageHistory(first.id) }); const duplicate = (): void => edit(service, second.id, { [single.id]: file.id }); assert.throws(duplicate, /attachment-owned/); assert.throws(() => edit(service, first.id, { [single.id]: file.id }), /attachment-owned/); @@ -222,9 +223,9 @@ test("file ownership rejects other pages, other attributes and recycled owners, assert.throws(() => service.create("editable", "C", { [single.id]: file.id }), /attachment-owned/); edit(service, first.id, { paper_files: [], [single.id]: file.id }); checkIndex(service); - assert.equal(history.apply("files", "undo").status, "saved"); + assert.equal(history.apply(pageHistory(first.id), "undo").status, "saved"); assert.deepEqual(service.get(first.id).attributes.paper_files, [file.id]); - assert.equal(history.apply("files", "redo").status, "saved"); + assert.equal(history.apply(pageHistory(first.id), "redo").status, "saved"); assert.equal(service.get(first.id).attributes[single.id], file.id); trash(service, first.id); assert.throws(duplicate, /attachment-owned/); diff --git a/tests/history.test.ts b/tests/history.test.ts index 760a3ed..b72a882 100644 --- a/tests/history.test.ts +++ b/tests/history.test.ts @@ -1,155 +1,243 @@ -import { knowledgeServices, historyServices, purgeServices, session, type Knowledge, type History } from "./support/session"; -import { hasFailure } from "./failures"; import assert from "node:assert/strict"; import { randomUUID } from "node:crypto"; import { mkdtempSync } from "node:fs"; import { join } from "node:path"; import { test, type TestContext } from "node:test"; -import { createWorkspace, openWorkspace } from "./support/session"; +import * as settings from "../main/settings/store"; +import * as history from "../main/knowledge/history"; import { blockText, payload } from "../shared/content/blocks"; +import { historyChanged, historyChannels, pagesChannels, settingsChannels, workspaceChannels } from "../shared/ipc"; +import type { HistorySource } from "../shared/history/ipc"; +import type { CommitResult, PageRecord } from "../shared/types/content"; +import type { SettingsResult } from "../shared/settings/Settings"; +import type { SavedTabs } from "../shared/workspace/tabs"; +import type { HistoryState } from "../shared/types/knowledge"; +import { knowledgeServices, session } from "./support/session"; +import { pageHistory, workspaceHistory } from "./support/history"; +import { fixture } from "./support/ipc"; -function fixture(t: TestContext): ReturnType & { service: Knowledge; history: History } { - const workspace = createWorkspace(mkdtempSync(join(process.env.LABLOOM_TEST_ROOT!, "history-"))); - t.after(() => { - session.close(); - }); - const service = knowledgeServices(), history = historyServices(); - return { ...workspace, service, history }; -} - -function edit(service: Knowledge, pageId: string, tabId: string, text: string): void { - const page = service.get(pageId), block = page.blocks[page.children[0]]; - assert.equal(service.commitEdit({ pageId, tabId, batch: 1, blocks: [{ ...block, payload: payload("paragraph", text) }] }).status, "saved"); -} - -function text(service: Knowledge, pageId: string): string { - const page = service.get(pageId); - return blockText(page.blocks[page.children[0]]); +type HistoryFixture = { + path: string; call: ReturnType["call"]; + state(source: HistorySource): Promise; + apply(source: HistorySource, direction: "undo" | "redo", branch?: string, token?: string): Promise; + read(id: string): Promise; create(kind?: string): Promise; + edit(page: PageRecord, tabId: string, text: string, source?: HistorySource): Promise; + text(page: PageRecord): Promise; changed(...expected: HistorySource[]): void; +}; +function setup(t: TestContext): HistoryFixture { + const path = mkdtempSync(join(process.env.LABLOOM_TEST_ROOT!, "history-")); + settings.initialize(path); + session.open(path, "create"); + const { call, contents } = fixture(t); + const notifications: HistorySource[][] = []; + contents.on(historyChanged, (sources: HistorySource[]) => notifications.push(sources)); + const state = (source: HistorySource): Promise => call(historyChannels.state, source); + const apply = (source: HistorySource, direction: "undo" | "redo", branch?: string, token?: string): Promise => + call(historyChannels.apply, source, direction, branch, token); + const read = (id: string): Promise => call(pagesChannels.get, id); + const create = (kind = "editable"): Promise => call(pagesChannels.create, kind); + const edit = async (page: PageRecord, tabId: string, text: string, source = pageHistory(page.id)): Promise => { + const block = page.blocks[page.children[0]]; + assert.equal((await call(pagesChannels.commitEdit, { pageId: page.id, tabId, batch: 1, + blocks: [{ ...block, payload: payload("paragraph", text) }] }, source)).status, "saved"); + }; + const text = async (page: PageRecord): Promise => { + const current = await read(page.id); + return blockText(current.blocks[current.children[0]]); + }; + const changed = (...expected: HistorySource[]): void => { + if (!expected.length) assert.deepEqual(notifications.splice(0), []); + else { + const [sources, ...extra] = notifications.splice(0); + assert.deepEqual(extra, []); + assert.equal(sources?.length, expected.length); + assert.deepEqual(new Set(sources), new Set(expected)); + } + }; + return { path, call, state, apply, read, create, edit, text, changed }; } +const empty = { canUndo: false, redo: [] }; -test("tabs in the same session share history and invalidate overlapping edits", t => { - const { service, history, db } = fixture(t), page = service.create(); - const other = history; - edit(service, page.id, "a", "A"); - assert.equal(other.state("a").canUndo, true); - other.apply("a", "undo"); - assert.equal(text(service, page.id), ""); - history.apply("a", "redo"); - assert.equal(text(service, page.id), "A"); - edit(service, page.id, "b", "B"); - assert.deepEqual(history.state("a"), { canUndo: false, redo: [] }); - assert.equal(history.state("b").canUndo, true); - service.transaction(() => edit(service, page.id, "c", "C")); - assert.equal(history.state("c").canUndo, true); - const before = other.state("c"); - assert.throws(() => service.transaction(() => { - edit(service, page.id, "d", "D"); - throw new Error("Abort another tab"); - }), /Abort another/); - assert.equal(text(service, page.id), "C"); - assert.deepEqual(other.state("c"), before); - assert.equal(other.state("d").canUndo, false); +test("two tabs share one page cursor across tab closure, while reopening the workspace clears it", async t => { + const f = setup(t), page = await f.create(), source = pageHistory(page.id); + const tabs = (ids: string[]): SavedTabs => ({ groups: [{ id: "G", activeTabId: ids.at(-1) ?? null, + tabs: ids.map(id => ({ id, type: "page", pageId: page.id, title: "Page" })) }], focusedGroupId: "G", layout: { type: "group", groupId: "G" } }); + await f.call(workspaceChannels.saveTabs, tabs(["first", "second"])); + await f.edit(page, "first", "A"); f.changed(source); + await f.edit(page, "second", "B"); f.changed(source); + await f.apply(source, "undo"); f.changed(source); + assert.equal(await f.text(page), "A"); + const before = await f.state(source); + await f.call(workspaceChannels.saveTabs, tabs([])); + await f.call(workspaceChannels.saveTabs, tabs(["reopened"])); + assert.deepEqual(await f.state(source), before); f.changed(); + await f.apply(source, "redo", before.redo[0].id); + assert.equal(await f.text(page), "B"); + session.close(); session.open(f.path, "open"); + assert.deepEqual(await f.state(source), empty); + assert.equal(await f.text(page), "B"); }); -test("overlapping ancestors are removed while unrelated descendants and redo branches survive", t => { - const { service, history } = fixture(t), a = service.create(), b = service.create(); - edit(service, a.id, "a", "A"); - edit(service, b.id, "a", "B"); - history.apply("a", "undo"); - const branch = history.state("a").redo[0].id; - edit(service, b.id, "a", "C"); - history.apply("a", "undo"); - assert.equal(history.state("a").redo.length, 2); - edit(service, a.id, "b", "D"); - assert.equal(history.state("a").canUndo, false); - assert.equal(history.state("a").redo.length, 2); - history.apply("a", "redo", branch); - assert.equal(text(service, b.id), "B"); - history.apply("a", "undo"); - assert.equal(text(service, b.id), ""); - assert.equal(text(service, a.id), "D"); +test("one edit of a nested synced block and its inverses reach exactly the other owners", async t => { + const f = setup(t), a = await f.create(), b = await f.create(), A = pageHistory(a.id), B = pageHistory(b.id); + const shared = a.blocks[a.children[0]], parent = b.blocks[b.children[0]]; + await f.call(pagesChannels.commitEdit, { pageId: b.id, tabId: "b", batch: 0, blocks: [{ ...parent, children: [shared.id] }] }, B); + f.changed(A, B); + const prototype = Object.getPrototypeOf(session.getNative().prepare("SELECT 1")); + let expansions = 0; + const all = prototype.all; + const observed = t.mock.method(prototype, "all", function (this: { source: string }, ...args: unknown[]): unknown { + if (/WITH RECURSIVE owners\(/i.test(this.source)) expansions++; + return all.apply(this, args); + }); + await f.edit(a, "a", "shared"); f.changed(A, B); + assert.equal(expansions, 1); + observed.mock.restore(); + assert.ok((await f.state(A)).canUndo && (await f.state(B)).canUndo); + await f.apply(B, "undo"); f.changed(A, B); + assert.equal(await f.text(a), ""); + const branch = (await f.state(B)).redo[0].id; + await f.apply(B, "redo", branch); f.changed(A, B); + assert.equal(await f.text(a), "shared"); + await f.apply(B, "undo"); f.changed(A, B); + await f.apply(A, "undo"); f.changed(A, B); + assert.equal(await f.text(a), "shared"); + await f.apply(B, "undo"); f.changed(A, B); + assert.equal(await f.text(a), ""); }); -test("a rolled-back outer transaction neither captures history nor invalidates other tabs", t => { - const { service, history } = fixture(t), page = service.create(); - edit(service, page.id, "a", "A"); - const before = history.state("a"); - assert.throws(() => service.transaction(() => { - edit(service, page.id, "b", "B"); - throw new Error("Abort outer transaction"); - }), /Abort outer/); - assert.equal(text(service, page.id), "A"); - assert.deepEqual(history.state("a"), before); - assert.deepEqual(history.state("b"), { canUndo: false, redo: [] }); - history.apply("a", "undo"); - assert.equal(text(service, page.id), ""); - const undo = history.state("a"); - assert.ok(Number.isSafeInteger(undo.redo[0].time) && undo.redo[0].time > 1e12); - assert.throws(() => service.transaction(() => { - history.apply("a", "redo"); - throw new Error("Abort redo"); - }), /Abort redo/); - assert.equal(text(service, page.id), ""); - assert.deepEqual(history.state("a"), undo); +test("deleting three papers is one reversible record across the library and all three pages", async t => { + const f = setup(t), papers = await Promise.all([f.create("paper"), f.create("paper"), f.create("paper")]); + const ids = papers.map(page => page.id), sources = ids.map(pageHistory), all = [workspaceHistory, ...sources]; + const preview = await f.call(pagesChannels.trash, ids, "library", workspaceHistory); + assert.equal(preview.status, "confirmation"); f.changed(); + await f.call(pagesChannels.trash, ids, "library", workspaceHistory, preview.preview.token); f.changed(...all); + for (const source of all) assert.ok((await f.state(source)).canUndo); + const deleted = (): Promise => Promise.all(ids.map(async id => (await f.read(id)).attributes.deleted)); + assert.deepEqual(await deleted(), [true, true, true]); + await f.apply(sources[1], "undo"); f.changed(...all); + assert.deepEqual(await deleted(), [false, false, false]); + await f.apply(workspaceHistory, "undo"); f.changed(...all); + assert.deepEqual(await deleted(), [true, true, true]); }); -test("closing a tab removes undo and redo, and reusing its ID starts a fresh tree", t => { - const { service, history } = fixture(t), page = service.create(); - edit(service, page.id, "a", "A"); - history.apply("a", "undo"); - assert.equal(history.state("a").redo.length, 1); - history.close("a"); - assert.deepEqual(history.state("a"), { canUndo: false, redo: [] }); - edit(service, page.id, "b", "B"); - edit(service, page.id, "a", "C"); - assert.equal(history.state("b").canUndo, false); - history.apply("a", "undo"); - assert.equal(text(service, page.id), "B"); - history.close("a"); - assert.throws(() => history.apply("a", "redo"), hasFailure("history-empty")); +test("invalidation splices redo branches onto the nearest surviving ancestor and retreats the cursor", async t => { + const f = setup(t), a = await f.create(), b = await f.create(), c = await f.create(), W = workspaceHistory; + await f.edit(c, "list", "ancestor", W); f.changed(W, pageHistory(c.id)); + await f.edit(a, "list", "overlap", W); f.changed(W, pageHistory(a.id)); + await f.edit(b, "list", "branch one", W); f.changed(W, pageHistory(b.id)); + await f.apply(W, "undo"); f.changed(W, pageHistory(b.id)); + const branch = (await f.state(W)).redo[0].id; + await f.edit(b, "list", "branch two", W); f.changed(W, pageHistory(b.id)); + await f.apply(W, "undo"); f.changed(W, pageHistory(b.id)); + await f.edit(a, "page", "external"); f.changed(W, pageHistory(a.id)); + const spliced = await f.state(W); + assert.equal(spliced.canUndo, true); + assert.equal(spliced.redo.length, 2); + await f.apply(W, "redo", branch); + assert.equal(await f.text(b), "branch one"); + await f.apply(W, "undo"); await f.apply(W, "undo"); + assert.equal(await f.text(c), ""); assert.equal(await f.text(a), "external"); }); -test("reopening preserves content and loses every undo and redo branch", t => { - const { service, history, database, info } = fixture(t), page = service.create(); - edit(service, page.id, "a", "A"); - edit(service, page.id, "a", "B"); - history.apply("a", "undo"); - session.close(); - const workspace = openWorkspace(info.path); - t.after(() => session.close()); - const restored = knowledgeServices(), next = historyServices(); - assert.equal(text(restored, page.id), "A"); - assert.deepEqual(next.state("a"), { canUndo: false, redo: [] }); - assert.throws(() => next.apply("a", "undo"), hasFailure("history-empty")); +test("the global record limit trims shared roots immediately, on commit, and stops at null", async t => { + const f = setup(t), a = await f.create(), b = await f.create(), A = pageHistory(a.id), B = pageHistory(b.id), W = workspaceHistory; + const limit = (value: number | null): Promise => f.call(settingsChannels.update, { history: { limit: value } }); + await f.edit(a, "list", "one", W); f.changed(A, W); + await f.edit(a, "a", "two"); f.changed(A, W); + // The second edit superseded the first workspace node. Share a fresh root across A and W. + await f.edit(a, "list", "three", W); f.changed(A, W); + await f.edit(b, "b", "one"); f.changed(B); + await limit(3); f.changed(A); + await f.edit(b, "b", "two"); f.changed(A, B); + await f.edit(b, "b", "three"); f.changed(A, B, W); + assert.deepEqual(await f.state(A), empty); + assert.deepEqual(await f.state(W), empty); + await f.apply(B, "undo"); f.changed(B); + await f.apply(B, "undo"); f.changed(B); + assert.ok((await f.state(B)).canUndo); + await limit(1); f.changed(B); + const cut = await f.state(B); + assert.equal(cut.canUndo, false); assert.equal(cut.redo.length, 1); + await f.apply(B, "redo", cut.redo[0].id); + assert.equal(await f.text(b), "three"); + await limit(null); + for (const text of ["four", "five", "six"]) await f.edit(b, "b", text); + for (let i = 0; i < 3; i++) await f.apply(B, "undo"); + assert.equal(await f.text(b), "three"); assert.ok((await f.state(B)).canUndo); }); -test("permanent deletion clears unrelated history in every tab only after confirmation", t => { - const { service, history, db, info } = fixture(t), a = service.create(), b = service.create(); - const other = history, purge = purgeServices(); - edit(service, a.id, "a", "A"); - edit(service, b.id, "b", "B"); - const trash = service.trash([a.id], "trash"); +test("emptying trash removes shared deleted records while an unrelated edit stays reversible", async t => { + const f = setup(t), a = await f.create(), b = await f.create(), A = pageHistory(a.id), B = pageHistory(b.id), W = workspaceHistory; + await f.edit(b, "b", "keep"); f.changed(B); + await f.edit(a, "list", "remove", W); f.changed(A, W); + const trash = await f.call(pagesChannels.trash, [a.id], "list", W); assert.equal(trash.status, "confirmation"); - service.trash([a.id], "trash", trash.preview.token); - const before = other.state("b"), preview = purge.purge([a.id], "purge"); + await f.call(pagesChannels.trash, [a.id], "list", W, trash.preview.token); f.changed(A, W); + const preview = await f.call<{ token: string }>(pagesChannels.emptyTrash, "list"); f.changed(); + await f.call(pagesChannels.emptyTrash, "list", preview.token); f.changed(A, W); + assert.deepEqual(await f.state(A), empty); assert.deepEqual(await f.state(W), empty); + await f.apply(B, "undo"); f.changed(B); assert.equal(await f.text(b), ""); + await f.apply(B, "redo"); f.changed(B); assert.equal(await f.text(b), "keep"); +}); + +test("undoing the last retaining link previews recycling and accepts only the current token", async t => { + const f = setup(t), a = await f.create(), b = await f.create(), B = pageHistory(b.id); + const child = await f.call(pagesChannels.create, "editable", "Child", { independent: false }, a.id); + await f.call(pagesChannels.commitEdit, { pageId: b.id, tabId: "B", batch: 0, blocks: [], attributes: { links: [child.id] } }, B); + await f.call(pagesChannels.commitEdit, { pageId: a.id, tabId: "A", batch: 0, blocks: [], pageChildren: a.children }, pageHistory(a.id)); + const before = await f.state(B), preview = await f.apply(B, "undo"); assert.equal(preview.status, "confirmation"); - assert.deepEqual(other.state("b"), before); - const deleted = purge.purge([a.id], "purge", preview.token); - assert.equal(deleted.status, "deleted"); - for (const tab of ["a", "b", "trash"]) assert.deepEqual(other.state(tab), { canUndo: false, redo: [] }); - assert.deepEqual(history.state("b"), { canUndo: false, redo: [] }); - assert.equal(text(service, b.id), "B"); + assert.deepEqual(await f.state(B), before); assert.equal((await f.read(child.id)).attributes.deleted, false); + assert.equal((await f.apply(B, "undo", undefined, "stale")).status, "confirmation"); + assert.equal((await f.apply(B, "undo", undefined, preview.preview.token)).status, "saved"); + assert.equal((await f.read(child.id)).attributes.deleted, true); +}); + +test("nested writes in a single commit retain the earliest before and latest after for each field", async t => { + const f = setup(t), a = await f.create(), b = await f.create(), A = pageHistory(a.id), B = pageHistory(b.id); + const service = knowledgeServices(); + service.transaction(() => { + for (const pinned of [true, false]) service.commitEdit({ pageId: a.id, tabId: "list", batch: 0, + blocks: [], attributes: { pinned } }, workspaceHistory); + service.commitEdit({ pageId: b.id, tabId: "list", batch: 0, blocks: [], attributes: { pinned: true } }, workspaceHistory); + }); + f.changed(A, B, workspaceHistory); + await f.apply(workspaceHistory, "undo"); f.changed(A, B, workspaceHistory); + assert.equal((await f.read(a.id)).attributes.pinned, false); + assert.equal((await f.read(b.id)).attributes.pinned, false); + const state = await f.state(workspaceHistory); + assert.equal(state.canUndo, false); + assert.equal(state.redo.length, 1); + await f.apply(workspaceHistory, "redo"); + assert.equal((await f.read(b.id)).attributes.pinned, true); +}); + +test("rolled-back nested edits and replays keep rows, cursors, and notifications unchanged", async t => { + const f = setup(t), page = await f.create(), source = pageHistory(page.id), service = knowledgeServices(); + await f.edit(page, "a", "A"); f.changed(source); + await f.apply(source, "undo"); f.changed(source); + const before = await f.state(source); + assert.ok(before.redo[0].time > 1e12); + assert.throws(() => service.transaction(() => { + history.apply(source, "redo"); + service.commitEdit({ pageId: page.id, tabId: "b", batch: 0, blocks: [], attributes: { pinned: true } }, workspaceHistory); + throw new Error("abort"); + }), /abort/); + f.changed(); assert.deepEqual(await f.state(source), before); assert.deepEqual(await f.state(workspaceHistory), empty); + assert.equal(await f.text(page), ""); assert.equal((await f.read(page.id)).attributes.pinned, false); }); test("removing a detached attribute definition invalidates history that could restore its values", t => { - const { service, history } = fixture(t), page = service.create(); + setup(t); + const service = knowledgeServices(), page = service.create(), source = pageHistory(page.id); const definition = { id: "custom:" + randomUUID(), type: "string" as const, name: "A", metadata: {} }; service.setDefinition(definition.id, definition, "manager"); - service.commitEdit({ pageId: page.id, tabId: "a", batch: 1, blocks: [], attributes: { [definition.id]: "A" } }); + service.commitEdit({ pageId: page.id, tabId: "a", batch: 1, blocks: [], attributes: { [definition.id]: "A" } }, source); service.setDefinition(definition.id, { ...definition, name: "B" }, "manager"); - assert.equal(history.state("a").canUndo, true); - service.commitEdit({ pageId: page.id, tabId: "a", batch: 2, blocks: [], detach: [definition.id] }); - assert.equal(history.state("a").canUndo, true); + assert.equal(history.state(source).canUndo, true); + service.commitEdit({ pageId: page.id, tabId: "a", batch: 2, blocks: [], detach: [definition.id] }, source); + assert.equal(history.state(source).canUndo, true); service.setDefinition(definition.id, null, "manager"); - assert.deepEqual(history.state("a"), { canUndo: false, redo: [] }); + assert.deepEqual(history.state(source), { canUndo: false, redo: [] }); }); \ No newline at end of file diff --git a/tests/ipc.test.ts b/tests/ipc.test.ts index f6f6301..9972503 100644 --- a/tests/ipc.test.ts +++ b/tests/ipc.test.ts @@ -1,11 +1,10 @@ import assert from "node:assert/strict"; import { randomUUID } from "node:crypto"; -import { EventEmitter } from "node:events"; +import { fixture } from "./support/ipc"; +import { pageHistory, workspaceHistory } from "./support/history"; import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { test, type TestContext } from "node:test"; -import type { BrowserWindow } from "electron"; -import { registerIPCs } from "../main/register"; +import { test } from "node:test"; import * as settings from "../main/settings/store"; import * as session from "../main/session"; import * as edits from "../main/knowledge/edits"; @@ -24,32 +23,7 @@ import type { PaperAnnotation } from "../shared/types/papers"; import { route } from "../main/ipc"; import { routes as pages } from "../main/pages/ipc"; import type { ContentBlock, PageRecord, RichNode } from "../shared/types/content"; -import { appChannels, attributesChannels, feedChanged, feedChannels, historyChannels, pagesChanged, pagesChannels, papersChannels, settingsChanged, settingsChannels, startupChannels, timersChannels, workspaceChannels, type IPCReply } from "../shared/ipc"; - -type Fixture = { - call(channel: string, ...args: unknown[]): Promise; - invoke(channel: string, ...args: unknown[]): Promise>; - send(channel: string, ...args: unknown[]): boolean; - contents: EventEmitter; sent: string[]; devTools: { opened: number }; -}; -function fixture(t?: TestContext): Fixture { - const frame = {}, sent: string[] = [], messages = new EventEmitter(); - const handlers = new Map Promise>>(); - const devTools = { opened: 0 }; - const contents = Object.assign(new EventEmitter(), { mainFrame: frame, isDestroyed: () => false, send: (channel: string) => sent.push(channel), openDevTools: () => devTools.opened++, ipc: Object.assign(messages, { handle: handlers.set.bind(handlers) }) }); - registerIPCs({ webContents: contents } as unknown as BrowserWindow, () => { }); - const invoke = (channel: string, ...args: unknown[]): Promise> => handlers.get(channel)!({ senderFrame: frame }, ...args); - async function call(channel: string, ...args: unknown[]): Promise { - const reply = await invoke(channel, ...args); - if (!reply.ok) assert.fail(channel + ": " + JSON.stringify(reply.failure)); - return reply.value as Value; - } - t?.after(() => { - contents.emit("destroyed"); - session.close(); - }); - return { invoke, call, send: (channel: string, ...args: unknown[]) => messages.emit(channel, { senderFrame: frame }, ...args), contents, sent, devTools }; -} +import { appChannels, attributesChannels, feedChanged, feedChannels, historyChannels, pagesChanged, pagesChannels, papersChannels, settingsChanged, settingsChannels, startupChannels, timersChannels, workspaceChannels } from "../shared/ipc"; test("every group rejects malformed IPC arguments before side effects and accepts its declared shape", async t => { const root = (): string => mkdtempSync(join(process.env.LABLOOM_TEST_ROOT!, "ipc-")); @@ -61,10 +35,13 @@ test("every group rejects malformed IPC arguments before side effects and accept }); const malformed: [string, unknown[][]][] = [ [pagesChannels.get, [[42]]], - [pagesChannels.commitEdit, [[{ pageId: "A", tabId: "B", batch: 0, blocks: [3] }], [{ tabId: "B", batch: 0, blocks: [] }], [{ pageId: "A", tabId: "", batch: 0, blocks: [] }]]], + [pagesChannels.commitEdit, [[{ pageId: "A", tabId: "B", batch: 0, blocks: [3] }, workspaceHistory], + [{ tabId: "B", batch: 0, blocks: [] }, workspaceHistory], [{ pageId: "A", tabId: "", batch: 0, blocks: [] }, workspaceHistory], + [{ pageId: "A", tabId: "B", batch: 0, blocks: [] }]]], [pagesChannels.syncBlocks, [["A", []]]], [attributesChannels.define, [["A", { id: "A", name: 3, type: "string", metadata: {} }, "B"], ["A", { id: "A", type: "string" }, "B"], ["A", { id: "A", type: "string", name: "A", metadata: { options: 1 } }, "B"]]], - [historyChannels.apply, [["B", "wrong"], [], ["", "undo"]]], + [historyChannels.state, [["B"], [{ kind: "page" }], [{ kind: "tab", id: "B" }]]], + [historyChannels.apply, [[workspaceHistory, "wrong"], [], ["", "undo"]]], [papersChannels.position, [["A", "B", { page: "1" }], ["A", "B", {}], ["A", "B", { page: 1, scale: false, rotation: 0, left: 0, top: 0 }]]], [timersChannels.set, [["A", "B", false, 4, "C"], [], ["A", null, 0, true, "C"]]], [workspaceChannels.saveTabs, [[{ groups: "A", layout: {}, focusedGroupId: "B" }], [{ groups: [] }], [{ groups: [], layout: { type: "group", groupId: null }, focusedGroupId: "B" }]]], @@ -91,7 +68,7 @@ test("every group rejects malformed IPC arguments before side effects and accept ipc.send(appChannels.openDevTools); assert.equal(ipc.devTools.opened, 1); const page = edits.create(); - const valid: [string, ...unknown[]][] = [[pagesChannels.list, { extra: true }], [attributesChannels.definitions], [historyChannels.state, "A"], [papersChannels.files, []], [timersChannels.settings, page.id], [workspaceChannels.saveTabs, { groups: [], layout: { type: "group", groupId: "A" }, focusedGroupId: "A" }], [settingsChannels.update, { layout: { width: 320 } }], [startupChannels.getState], [feedChannels.getState, {}]]; + const valid: [string, ...unknown[]][] = [[pagesChannels.list, { extra: true }], [attributesChannels.definitions], [historyChannels.state, workspaceHistory], [papersChannels.files, []], [timersChannels.settings, page.id], [workspaceChannels.saveTabs, { groups: [], layout: { type: "group", groupId: "A" }, focusedGroupId: "A" }], [settingsChannels.update, { layout: { width: 320 } }], [startupChannels.getState], [feedChannels.getState, {}]]; for (const [channel, ...args] of valid) assert.equal((await ipc.invoke(channel, ...args)).ok, true, channel); events.feedChanged(); for (const channel of [pagesChanged, settingsChanged, feedChanged]) assert.ok(ipc.sent.includes(channel), channel); @@ -122,7 +99,7 @@ test("registered page handlers preserve long block text and attribute values on blocks.push({ id: randomUUID(), type: "paragraph", children: [], payload: { type: "paragraph", schemaVersion: 1, inline: [{ type: "inlineReference", attrs: { target: { kind: "page", id: page.id }, label: initial } }] } }); const commit = { pageId: page.id, tabId: "A", batch: 1, blocks, pageChildren: blocks.map(block => block.id), attributes: { [attr]: edited } }; assert.equal(await invoke(pagesChannels.previewEdit, commit), null); - await invoke(pagesChannels.commitEdit, commit); + await invoke(pagesChannels.commitEdit, commit, pageHistory(page.id)); session.close(); session.open(workspace, "open"); const stored = await readPage(); @@ -149,7 +126,7 @@ test("page titles, select options and deep JSON values round-trip through IPC", assert.equal((await call(pagesChannels.get, page.id)).title, title); const block = { ...page.blocks[page.titleBlockId], payload: payload("title", edited) }; const change = { pageId: page.id, tabId: tab, batch: 0, blocks: [block] }; - await call(pagesChannels.commitEdit, change); + await call(pagesChannels.commitEdit, change, pageHistory(page.id)); session.close(); session.open(path, "open"); const stored = await call(pagesChannels.get, page.id); assert.equal(stored.title, edited); @@ -160,8 +137,8 @@ test("page titles, select options and deep JSON values round-trip through IPC", assert.deepEqual(definitions.find(item => item.id === id), definition); const invalid = [ - [pagesChannels.commitEdit, [{ ...change, blocks: [{ ...block, id: "not-a-uuid" }] }], "block-invalid-identity"], - [pagesChannels.commitEdit, [{ ...change, blocks: [{ ...block, children: [page.children[0]] }] }], "block-invalid-title"], + [pagesChannels.commitEdit, [{ ...change, blocks: [{ ...block, id: "not-a-uuid" }] }, pageHistory(page.id)], "block-invalid-identity"], + [pagesChannels.commitEdit, [{ ...change, blocks: [{ ...block, children: [page.children[0]] }] }, pageHistory(page.id)], "block-invalid-title"], [attributesChannels.define, [id, { ...definition, metadata: { options: [options[0], { ...options[1], id: options[0].id }] } }, tab], "attribute-invalid-metadata"] ] as const; for (const [channel, args, kind] of invalid) { @@ -228,9 +205,9 @@ test("registered annotation handlers extract and store a 200000-character PDF se const [file] = (await papers.resources(pageId)).files; const rectangles = lines.map((_, i) => ({ x: 40, y: baseline(i) - 0.1, width: 65, height: 0.7 })); const selection = { fileId: file.id, pageNumber: 1, rectangles, quote, context: quote, extractorVersion: "A".repeat(201) }; - const empty = await invoke(papersChannels.annotate, pageId, { ...selection, rectangles: [] }, "A"); + const empty = await invoke(papersChannels.annotate, pageId, { ...selection, rectangles: [] }, "A", pageHistory(pageId)); assert.equal(empty.ok ? "success" : empty.failure.kind, "invalid-argument"); - const id = await call(papersChannels.annotate, pageId, selection, "A"); + const id = await call(papersChannels.annotate, pageId, selection, "A", pageHistory(pageId)); session.close(); session.open(path, "open"); const stored = await call(papersChannels.getAnnotation, id); assert.deepEqual(stored.rectangles, rectangles); @@ -250,7 +227,7 @@ test("a registered sync paste preserves 12000 shared blocks on disk", async t => const blocks = await call(pagesChannels.syncBlocks, workspace.id, ids); const resolved = performance.now(); const children = [...target.children, ...ids]; - const result = await call<{ status: string }>(pagesChannels.commitEdit, { pageId: target.id, tabId: "A", batch: 1, blocks: [], pageChildren: children, sync: ids }); + const result = await call<{ status: string }>(pagesChannels.commitEdit, { pageId: target.id, tabId: "A", batch: 1, blocks: [], pageChildren: children, sync: ids }, pageHistory(target.id)); t.diagnostic(`12000-block paste | resolve ${(resolved - started).toFixed(2)} ms | resolve + commit ${(performance.now() - started).toFixed(2)} ms`); assert.equal(result.status, "saved"); assert.equal(blocks.length, ids.length); diff --git a/tests/papers.test.ts b/tests/papers.test.ts index d196929..743dba0 100644 --- a/tests/papers.test.ts +++ b/tests/papers.test.ts @@ -1,3 +1,4 @@ +import { pageHistory, workspaceHistory } from "./support/history"; import { openWorkspace, watchKnowledge } from "./support/session"; import { knowledgeServices, paperServices, historyServices, purgeServices, session, type Knowledge, type History, type Papers } from "./support/session"; import { hasFailure } from "./failures"; @@ -58,7 +59,7 @@ test("identical imports create independent papers, attachment rows and files, wi test("annotation creation is retained, reversible and has an empty paragraph, while repeated selections create distinct pages", async t => { const { knowledge, papers, info, history } = fixture(t), paperId = importPDF(papers, join(info.path, "A.pdf")); - const fileId = (await papers.resources(paperId)).files[0].id, input = selection(fileId), id = await papers.annotate(paperId, input, "annotations"); + const fileId = (await papers.resources(paperId)).files[0].id, input = selection(fileId), id = await papers.annotate(paperId, input, "annotations", pageHistory(paperId)); const page = knowledge.get(id); assert.equal(page.kind, "annotation"); assert.equal(page.attributes.independent, false); assert.deepEqual(knowledge.get(paperId).attributes.paper_annotations, [id]); @@ -67,73 +68,73 @@ test("annotation creation is retained, reversible and has an empty paragraph, wh assert.equal(page.attributes.annotation_color, "yellow"); assert.equal(page.attributes.annotation_file, fileId); assert.deepEqual(knowledge.backlinks(id)[0].sourceFields, ["paper_annotations"]); assert.equal((await papers.resources(paperId)).annotations.length, 1); - assert.equal(history.apply("annotations", "undo").status, "saved"); + assert.equal(history.apply(pageHistory(paperId), "undo").status, "saved"); assert.deepEqual(knowledge.get(paperId).attributes.paper_annotations, []); assert.equal(knowledge.get(id).attributes.deleted, true); assert.deepEqual((await papers.resources(paperId)).annotations, []); - assert.equal(history.apply("annotations", "redo").status, "saved"); + assert.equal(history.apply(pageHistory(paperId), "redo").status, "saved"); assert.deepEqual(knowledge.get(paperId).attributes.paper_annotations, [id]); assert.equal((await papers.resources(paperId)).annotations[0].id, id); const read = knowledge.get.bind(knowledge), reads: string[] = []; const observed = t.mock.method(knowledge, "get", (pageId: string) => { reads.push(pageId); return read(pageId); }); - const second = await papers.annotate(paperId, input, "annotations"); + const second = await papers.annotate(paperId, input, "annotations", pageHistory(paperId)); assert.ok(!reads.includes(id), "creating another selection never loads an existing annotation body to compare positions"); observed.mock.restore(); assert.notEqual(second, id); assert.deepEqual(knowledge.get(paperId).attributes.paper_annotations, [id, second]); - assert.equal(await papers.annotate(paperId, id, "annotations"), id, "opening an existing annotation uses its own identity"); + assert.equal(await papers.annotate(paperId, id, "annotations", pageHistory(paperId)), id, "opening an existing annotation uses its own identity"); assert.equal((await papers.resources(paperId)).annotations.length, 2); - history.apply("annotations", "undo"); + history.apply(pageHistory(paperId), "undo"); assert.deepEqual(knowledge.get(paperId).attributes.paper_annotations, [id]); assert.equal(knowledge.flags(second).deleted, true); - history.apply("annotations", "redo"); + history.apply(pageHistory(paperId), "redo"); assert.deepEqual(knowledge.get(paperId).attributes.paper_annotations, [id, second]); - await assert.rejects(papers.annotate(paperId, { ...input, pageNumber: 2 }, "annotations"), hasFailure("pdf-page-range")); - await assert.rejects(papers.annotate(paperId, { ...input, rectangles: [{ x: 600, y: 800, width: 50, height: 10 }] }, "annotations"), hasFailure("annotation-outside-page")); + await assert.rejects(papers.annotate(paperId, { ...input, pageNumber: 2 }, "annotations", pageHistory(paperId)), hasFailure("pdf-page-range")); + await assert.rejects(papers.annotate(paperId, { ...input, rectangles: [{ x: 600, y: 800, width: 50, height: 10 }] }, "annotations", pageHistory(paperId)), hasFailure("annotation-outside-page")); }); test("color, deletion, undo, redo and restore are ordinary annotation edits and preserve paper membership", async t => { const { knowledge, papers, info, history } = fixture(t), paperId = importPDF(papers, join(info.path, "A.pdf")); - const id = await papers.annotate(paperId, selection((await papers.resources(paperId)).files[0].id), "annotations"); - assert.equal(papers.changeAnnotation(id, "green", "annotations").status, "saved"); + const id = await papers.annotate(paperId, selection((await papers.resources(paperId)).files[0].id), "annotations", pageHistory(paperId)); + assert.equal(papers.changeAnnotation(id, "green", "annotations", pageHistory(paperId)).status, "saved"); assert.equal((await papers.resources(paperId)).annotations[0].color, "green"); - assert.equal(history.apply("annotations", "undo").status, "saved"); + assert.equal(history.apply(pageHistory(paperId), "undo").status, "saved"); assert.equal((await papers.resources(paperId)).annotations[0].color, "yellow"); - const preview = papers.deleteAnnotation(id, "annotations"); + const preview = papers.deleteAnnotation(id, "annotations", pageHistory(paperId)); assert.equal(preview.status, "confirmation"); assert.equal(knowledge.get(id).attributes.deleted, false); if (preview.status !== "confirmation") throw new Error("Expected confirmation"); - assert.equal(papers.deleteAnnotation(id, "annotations", preview.preview.token).status, "saved"); + assert.equal(papers.deleteAnnotation(id, "annotations", pageHistory(paperId), preview.preview.token).status, "saved"); assert.equal(knowledge.get(id).attributes.recycle_reason, "manual_delete"); assert.deepEqual(knowledge.get(paperId).attributes.paper_annotations, [id]); assert.equal((await papers.resources(paperId)).annotations.length, 0); - assert.equal(history.apply("annotations", "undo").status, "saved"); + assert.equal(history.apply(pageHistory(paperId), "undo").status, "saved"); assert.equal((await papers.resources(paperId)).annotations[0].id, id); - assert.equal(history.apply("annotations", "redo").status, "saved"); + assert.equal(history.apply(pageHistory(paperId), "redo").status, "saved"); assert.equal((await papers.resources(paperId)).annotations.length, 0); - assert.equal(knowledge.restore([id], "restore").status, "saved"); + assert.equal(knowledge.restore([id], "restore", workspaceHistory).status, "saved"); assert.equal((await papers.resources(paperId)).annotations[0].id, id); assert.equal(knowledge.get(id).attributes.independent, false); }); test("ordinary reference blocks and inline links retain annotations without displaying or searching a special quote block", async t => { const { knowledge, papers, info } = fixture(t), paperId = importPDF(papers, join(info.path, "A.pdf")); - const fileId = (await papers.resources(paperId)).files[0].id, id = await papers.annotate(paperId, selection(fileId), "annotations"); - const inlineId = await papers.annotate(paperId, { ...selection(fileId), rectangles: [{ x: 150, y: 690, width: 60, height: 30 }] }, "annotations"); - const unreferenced = await papers.annotate(paperId, { ...selection(fileId), rectangles: [{ x: 50, y: 690, width: 150, height: 30 }] }, "annotations"); + const fileId = (await papers.resources(paperId)).files[0].id, id = await papers.annotate(paperId, selection(fileId), "annotations", pageHistory(paperId)); + const inlineId = await papers.annotate(paperId, { ...selection(fileId), rectangles: [{ x: 150, y: 690, width: 60, height: 30 }] }, "annotations", pageHistory(paperId)); + const unreferenced = await papers.annotate(paperId, { ...selection(fileId), rectangles: [{ x: 50, y: 690, width: 150, height: 30 }] }, "annotations", pageHistory(paperId)); const note = knowledge.create("editable", "B"); const reference = { id: randomUUID(), type: "blocked_reference" as const, payload: { ...payload("blocked_reference"), target: { kind: "page" as const, id } }, children: [] }; const inline = { id: randomUUID(), type: "paragraph" as const, payload: { ...payload("paragraph"), inline: [{ type: "inlineReference" as const, attrs: { target: { kind: "page" as const, id: inlineId }, label: knowledge.title(inlineId) } }] }, children: [] }; - assert.equal(knowledge.commitEdit({ pageId: note.id, tabId: "note", batch: 0, blocks: [reference, inline], pageChildren: [reference.id, inline.id] }).status, "saved"); + assert.equal(knowledge.commitEdit({ pageId: note.id, tabId: "note", batch: 0, blocks: [reference, inline], pageChildren: [reference.id, inline.id] }, pageHistory(note.id)).status, "saved"); assert.deepEqual(knowledge.statement("SELECT target_kind,target_id FROM link_refs WHERE source_id=?").all(reference.id), [{ target_kind: "page", target_id: id }]); assert.ok(knowledge.list({ keyword: "HELLO" }).items.some(page => page.id === id)); knowledge.attributes.cache(id, { annotation_quote: "unique-cache-phrase" }); assert.deepEqual(knowledge.list({ keyword: "unique-cache-phrase" }).items.map(page => page.id), [id]); - const preview = knowledge.trash([paperId], "trash"); + const preview = knowledge.trash([paperId], "trash", workspaceHistory); if (preview.status !== "confirmation") throw new Error("Expected confirmation"); - assert.equal(knowledge.trash([paperId], "trash", preview.preview.token).status, "saved"); + assert.equal(knowledge.trash([paperId], "trash", workspaceHistory, preview.preview.token).status, "saved"); assert.equal(knowledge.flags(id).deleted, false); assert.equal(knowledge.flags(inlineId).deleted, false); assert.equal(knowledge.flags(unreferenced).deleted, true); @@ -141,13 +142,13 @@ test("ordinary reference blocks and inline links retain annotations without disp test("extractor refresh updates cache attributes without history or modification times", async t => { const { knowledge, papers, info, history, database } = fixture(t), paperId = importPDF(papers, join(info.path, "A.pdf")); - const id = await papers.annotate(paperId, selection((await papers.resources(paperId)).files[0].id), "annotations"), original = await papers.getAnnotation(id); + const id = await papers.annotate(paperId, selection((await papers.resources(paperId)).files[0].id), "annotations", pageHistory(paperId)), original = await papers.getAnnotation(id); knowledge.attributes.cache(id, { annotation_quote: "stale", annotation_context: "stale", annotation_extractor: "old" }); - const before = knowledge.get(id), undo = history.state("annotations"), modified = database.prepare("SELECT last_modified_at FROM workspace_meta").pluck().get(); + const before = knowledge.get(id), undo = history.state(pageHistory(paperId)), modified = database.prepare("SELECT last_modified_at FROM workspace_meta").pluck().get(); const refreshed = await papers.getAnnotation(id); assert.equal(refreshed.quote, original.quote); assert.equal(refreshed.context, original.quote); assert.equal(refreshed.extractorVersion, PDF_EXTRACTOR_VERSION); assert.deepEqual(refreshed.rectangles, original.rectangles); - assert.deepEqual(history.state("annotations"), undo); + assert.deepEqual(history.state(pageHistory(paperId)), undo); assert.equal(knowledge.get(id).attributes.modified_at, before.attributes.modified_at); assert.equal(database.prepare("SELECT last_modified_at FROM workspace_meta").pluck().get(), modified); }); @@ -156,12 +157,12 @@ test("encrypted PDF passwords stay transient and repeated selections produce ind const { knowledge, papers, info, database } = fixture(t), path = join(info.path, "encrypted.pdf"); writeFileSync(path, readFileSync(join(process.cwd(), "tests/fixtures/protected.pdf"))); const paperId = papers.importFile(path).pageId, fileId = (await papers.resources(paperId)).files[0].id; - await assert.rejects(papers.annotate(paperId, selection(fileId), "annotations"), hasFailure("pdf-password-required")); + await assert.rejects(papers.annotate(paperId, selection(fileId), "annotations", pageHistory(paperId)), hasFailure("pdf-password-required")); await assert.rejects(papers.unlockPDF(fileId, "incorrect"), hasFailure("pdf-password-incorrect")); await papers.unlockPDF(fileId, "reader-pass"); - const id = await papers.annotate(paperId, selection(fileId), "annotations"), original = await papers.getAnnotation(id); + const id = await papers.annotate(paperId, selection(fileId), "annotations", pageHistory(paperId)), original = await papers.getAnnotation(id); await assert.rejects(papers.unlockPDF(fileId, "incorrect"), hasFailure("pdf-password-incorrect")); - const second = await papers.annotate(paperId, selection(fileId), "annotations", "green"); + const second = await papers.annotate(paperId, selection(fileId), "annotations", pageHistory(paperId), "green"); assert.notEqual(second, id); assert.equal((await papers.resources(paperId)).annotations.length, 2); assert.equal((await papers.getAnnotation(second)).color, "green"); @@ -177,16 +178,16 @@ test("encrypted PDF passwords stay transient and repeated selections produce ind test("annotation text controls the reader icon, while one tab's undo tree spans paper and popup edits", async t => { const { knowledge, papers, info, history } = fixture(t), paperId = importPDF(papers, join(info.path, "A.pdf")); - const id = await papers.annotate(paperId, selection((await papers.resources(paperId)).files[0].id), "annotations"), tabId = "annotations"; + const id = await papers.annotate(paperId, selection((await papers.resources(paperId)).files[0].id), "annotations", pageHistory(paperId)), tabId = "annotations"; const paper = knowledge.get(paperId), paragraph = { id: randomUUID(), type: "paragraph" as const, payload: payload("paragraph", "Paper edit"), children: [] }; - knowledge.commitEdit({ pageId: paperId, tabId, batch: 0, blocks: [paragraph], pageChildren: [...paper.children, paragraph.id] }); + knowledge.commitEdit({ pageId: paperId, tabId, batch: 0, blocks: [paragraph], pageChildren: [...paper.children, paragraph.id] }, pageHistory(paperId)); const note = knowledge.get(id), body = note.blocks[note.children[0]]; - knowledge.commitEdit({ pageId: id, tabId, batch: 0, blocks: [{ ...body, payload: payload("paragraph", "Popup text") }] }); + knowledge.commitEdit({ pageId: id, tabId, batch: 0, blocks: [{ ...body, payload: payload("paragraph", "Popup text") }] }, pageHistory(paperId)); assert.equal((await papers.resources(paperId)).annotations[0].hasText, true); - assert.equal(history.apply(tabId, "undo").status, "saved"); + assert.equal(history.apply(pageHistory(paperId), "undo").status, "saved"); assert.equal((await papers.resources(paperId)).annotations[0].hasText, false); assert.ok(knowledge.get(paperId).children.includes(paragraph.id)); - assert.equal(history.apply(tabId, "undo").status, "saved"); + assert.equal(history.apply(pageHistory(paperId), "undo").status, "saved"); assert.ok(!knowledge.get(paperId).children.includes(paragraph.id)); }); @@ -214,18 +215,18 @@ test("annotation rectangles stay in PDF user space including non-zero and negati test("annotation file references retain detached files and purging clears membership in the owning paper", async t => { const { knowledge, papers, info, history } = fixture(t), path = join(info.path, "A.pdf"), paperId = importPDF(papers, path); - const file = (await papers.resources(paperId)).files[0], id = await papers.annotate(paperId, selection(file.id), "annotations"); - knowledge.commitEdit({ pageId: paperId, tabId: "files", batch: 0, blocks: [], attributes: { paper_files: [] } }); + const file = (await papers.resources(paperId)).files[0], id = await papers.annotate(paperId, selection(file.id), "annotations", pageHistory(paperId)); + knowledge.commitEdit({ pageId: paperId, tabId: "files", batch: 0, blocks: [], attributes: { paper_files: [] } }, pageHistory(paperId)); assert.deepEqual(unreferencedFiles(knowledge.db), []); assert.equal((await papers.resources(paperId)).annotations.length, 0); assert.match((await papers.getAnnotation(id)).quote, /HELLO/); const other = papers.importFile(path).pageId; - await assert.rejects(papers.annotate(other, selection(file.id), "other"), /paper-file-removed/); + await assert.rejects(papers.annotate(other, selection(file.id), "other", pageHistory(other)), /paper-file-removed/); const otherFile = (await papers.resources(other)).files[0]; - const otherAnnotation = await papers.annotate(other, selection(otherFile.id), "other"); - const removal = papers.deleteAnnotation(id, "annotations"); + const otherAnnotation = await papers.annotate(other, selection(otherFile.id), "other", pageHistory(other)); + const removal = papers.deleteAnnotation(id, "annotations", pageHistory(paperId)); if (removal.status !== "confirmation") throw new Error("Expected confirmation"); - papers.deleteAnnotation(id, "annotations", removal.preview.token); + papers.deleteAnnotation(id, "annotations", pageHistory(paperId), removal.preview.token); const purge = purgeServices(), preview = purge.purge([id], "purge"); if (preview.status !== "confirmation") throw new Error("Expected confirmation"); assert.equal(purge.purge([id], "purge", preview.token).status, "deleted"); @@ -237,34 +238,34 @@ test("annotation file references retain detached files and purging clears member test("identical PDFs have independent annotations and a second paper cannot adopt an existing annotation", async t => { const { knowledge, papers, info, history } = fixture(t), path = join(info.path, "A.pdf"), first = importPDF(papers, path); - const file = (await papers.resources(first)).files[0], id = await papers.annotate(first, selection(file.id), "first"); + const file = (await papers.resources(first)).files[0], id = await papers.annotate(first, selection(file.id), "first", pageHistory(first)); const second = papers.importFile(path).pageId; const secondFile = (await papers.resources(second)).files[0]; - const secondId = await papers.annotate(second, selection(secondFile.id), "second"); + const secondId = await papers.annotate(second, selection(secondFile.id), "second", pageHistory(second)); assert.notEqual(secondId, id); assert.deepEqual((await papers.getAnnotation(secondId)).rectangles, (await papers.getAnnotation(id)).rectangles); assert.throws(() => knowledge.attributes.write(second, { paper_annotations: [id, secondId] }, true), /annotation-owned/); assert.throws(() => knowledge.create("paper", "C", { paper_annotations: [id] }), /annotation-owned/); - assert.equal(history.apply("first", "undo").status, "saved"); + assert.equal(history.apply(pageHistory(first), "undo").status, "saved"); assert.deepEqual(knowledge.get(first).attributes.paper_annotations, []); assert.deepEqual(knowledge.get(second).attributes.paper_annotations, [secondId]); assert.equal(knowledge.flags(id).deleted, true); assert.equal((await papers.resources(second)).annotations[0].id, secondId); - history.apply("first", "redo"); - const removal = knowledge.trash([first], "trash"); - if (removal.status === "confirmation") knowledge.trash([first], "trash", removal.preview.token); + history.apply(pageHistory(first), "redo"); + const removal = knowledge.trash([first], "trash", workspaceHistory); + if (removal.status === "confirmation") knowledge.trash([first], "trash", workspaceHistory, removal.preview.token); assert.throws(() => knowledge.attributes.write(second, { paper_annotations: [id, secondId] }, true), /annotation-owned/, "recycled annotations still belong to their original paper"); }); -test("annotation edits invalidate every retaining paper and cross-tab typing invalidates its creation undo", async t => { +test("annotation edits notify the retaining paper and advance its shared history", async t => { const { knowledge, papers, info, history } = fixture(t), paperId = importPDF(papers, join(info.path, "A.pdf")), fileId = (await papers.resources(paperId)).files[0].id; - const id = await papers.annotate(paperId, selection(fileId), "creator"); - assert.equal(history.state("creator").canUndo, true); + const id = await papers.annotate(paperId, selection(fileId), "creator", pageHistory(paperId)); + assert.equal(history.state(pageHistory(paperId)).canUndo, true); const annotation = knowledge.get(id), body = annotation.blocks[annotation.children[0]], changes: string[][] = []; t.after(watchKnowledge(change => changes.push(change.pages))); - knowledge.commitEdit({ pageId: id, tabId: "other-tab", batch: 0, blocks: [{ ...body, payload: payload("paragraph", "B") }] }); - assert.equal(history.state("creator").canUndo, false); + knowledge.commitEdit({ pageId: id, tabId: "other-tab", batch: 0, blocks: [{ ...body, payload: payload("paragraph", "B") }] }, pageHistory(id)); + assert.equal(history.state(pageHistory(paperId)).canUndo, true); assert.ok(changes[0].includes(id)); assert.ok(changes[0].includes(paperId)); - changes.length = 0; papers.changeAnnotation(id, "pink", "other-tab"); + changes.length = 0; papers.changeAnnotation(id, "pink", "other-tab", pageHistory(id)); assert.ok(changes[0].includes(paperId)); }); \ No newline at end of file diff --git a/tests/perf/bench.ts b/tests/perf/bench.ts index 4a73468..d46e56d 100644 --- a/tests/perf/bench.ts +++ b/tests/perf/bench.ts @@ -1,3 +1,6 @@ +import * as history from "../../main/knowledge/history"; +import * as settings from "../../main/settings/store"; +import { pageHistory } from "../support/history"; import { session, type Knowledge } from "../support/session"; import { fixture, seedLargePage, type SeedPage } from "./fixture"; import assert from "node:assert/strict"; @@ -28,12 +31,12 @@ function measure(label: string, limit: number, prepare: (round: number) => Sampl function prepareText(service: Knowledge, pageId: string, round: number) { const page = service.get(pageId), block = page.blocks[page.children[0]]; const value = { ...block, payload: payload("paragraph", "Edited " + round) }; - return (token?: string): CommitResult => service.commitEdit({ pageId, tabId: "perf", batch: round, blocks: [value] }, token); + return (token?: string): CommitResult => service.commitEdit({ pageId, tabId: "perf", batch: round, blocks: [value] }, pageHistory(pageId), token); } function prepareDeletion(service: Knowledge, pageId: string) { const page = service.get(pageId), blockId = page.children[0]; - return (token?: string): CommitResult => service.deleteBlock({ pageId, blockId, tabId: "perf" }, token); + return (token?: string): CommitResult => service.deleteBlock({ pageId, blockId, tabId: "perf" }, pageHistory(pageId), token); } function confirmed(operation: (token?: string) => CommitResult, recycled: number): Sample { @@ -105,6 +108,45 @@ function largePage(): void { } } +function historyScale(): void { + const { sql, service, makePage } = fixture(); + try { + settings.initialize(session.getPath()); + const pages = sql.transaction(() => Array.from({ length: 100 }, (_, index) => makePage(index === 0 ? 10000 : 2, "History")))(); + const edits = pages.map(page => { + const block = service.readObjects(page.id, [page.children[0]]).blocks[0], source = pageHistory(page.id); + return (round: number): CommitResult => service.commitEdit({ pageId: page.id, tabId: "perf", batch: round, + blocks: [{ ...block, payload: payload("paragraph", "History " + round) }] }, source); + }); + for (let i = 0; i < 10000; i++) assert.equal(edits[i % 100](i).status, "saved"); + const source = pageHistory(pages[0].id); + measure("History | edit one block on a 10000-block page with 10000 records", 30, round => + () => assert.equal(edits[0](10000 + round).status, "saved")); + measure("History | undo one block on the same page", 30, () => + () => assert.equal(history.apply(source, "undo").status, "saved")); + const start = performance.now(); + const result = settings.update({ history: { limit: 100 } }); + const elapsed = performance.now() - start; + assert.ok(result.success); + console.log("History | trim to 100 records", elapsed.toFixed(2), "ms | limit 50", elapsed <= 50 ? "PASS" : "FAIL"); + if (elapsed > 50) exceeded = true; + // The 21 undone commits form one redo branch. Count every retained node by + // walking to the tip and then undoing to the root of each independent page. + let retained = 0; + for (const page of pages) { + const tree = pageHistory(page.id); + while (history.state(tree).redo.length) history.apply(tree, "redo"); + while (history.state(tree).canUndo) { + history.apply(tree, "undo"); retained++; + } + } + assert.equal(retained, 100); + } + finally { + session.close(); + } +} + function retentionGraph(): void { const { sql, service, makePage, attr } = fixture(); try { @@ -153,6 +195,7 @@ console.log(platform(), release(), cpus()[0].model, "Electron", process.versions console.log("Warm database | 1 warm-up +", samples, "samples per measurement | nearest-rank percentiles | timings exclude fixture creation and the confirmation dialog/preview."); workspaceScale(); largePage(); +historyScale(); retentionGraph(); probes(); if (exceeded) process.exitCode = 1; \ No newline at end of file diff --git a/tests/perf/ipc.ts b/tests/perf/ipc.ts index e4b66dd..716321f 100644 --- a/tests/perf/ipc.ts +++ b/tests/perf/ipc.ts @@ -17,10 +17,10 @@ const blocks = Array.from({ length: 1000 }, (_, index) => ({ { type: "text", text: `Research note ${index}`, marks: [{ type: "link", attrs: { href: "https://example.org", metadata: { references: ["A", "B"] } } }] } ] } })); -const commit = [{ pageId: "A", tabId: "B", batch: 1, blocks }]; +const commit = [{ pageId: "A", tabId: "B", batch: 1, blocks }, { kind: "page", id: "A" }]; const sync = ["A", Array.from({ length: 10000 }, (_, index) => `block-${index}`)]; measure("IPC | commitEdit 1000 rich blocks", () => pages.commitEdit.check(commit)); measure("IPC | syncBlocks 10000 ids", () => pages.syncBlocks.check(sync)); const largeBlock = { ...blocks[0], payload: { ...blocks[0].payload, inline: [{ type: "text", text: "A".repeat(1000000) }] } }; -const largeCommit = [{ ...commit[0], blocks: [largeBlock] }]; +const largeCommit = [{ ...commit[0], blocks: [largeBlock] }, commit[1]]; measure("IPC | commitEdit 1 block with 1000000 characters", () => pages.commitEdit.check(largeCommit)); \ No newline at end of file diff --git a/tests/purge.test.ts b/tests/purge.test.ts index a1d26aa..f0d35ae 100644 --- a/tests/purge.test.ts +++ b/tests/purge.test.ts @@ -1,3 +1,4 @@ +import { pageHistory, workspaceHistory } from "./support/history"; import { knowledgeServices, historyServices, paperServices, purgeServices, session, type Knowledge, type History, type Papers, type Purge } from "./support/session"; import { hasFailure } from "./failures"; import assert from "node:assert/strict"; @@ -33,52 +34,52 @@ function erase(purge: Purge, ids: string[] | null, tab = "purger"): string[] { test("permanent deletion requires recycle membership, previews without writes, and empties a single-page recycle bin", t => { const { service, history, purge } = fixture(t), page = service.create("editable", "A"); assert.throws(() => purge.purge([page.id], "a"), hasFailure("purge-recycled-only")); - confirm(token => service.trash([page.id], "a", token)); - const before = history.state("a"), preview = purge.purge(null, "a"); + confirm(token => service.trash([page.id], "a", workspaceHistory, token)); + const before = history.state(pageHistory(page.id)), preview = purge.purge(null, "a"); assert.equal(preview.status, "confirmation"); assert.equal(service.get(page.id).title, "A"); - assert.deepEqual(history.state("a"), before); + assert.deepEqual(history.state(pageHistory(page.id)), before); assert.deepEqual(erase(purge, null), [page.id]); assert.equal(service.list({ deleted: true }).total, 0); assert.equal(service.sql.prepare("SELECT count(*) FROM blocks").pluck().get(), 0); assert.deepEqual(erase(purge, null), []); }); -test("live synchronized blocks survive while soft references remain deleted and every tab loses its history", t => { +test("live synchronized blocks survive while history depending on collected blocks is discarded", t => { const { service, history, purge } = fixture(t), a = service.create("editable", "A"), b = service.create("editable", "B"), c = service.create("editable", "C"); const shared = a.children[0], own = { id: randomUUID(), type: "paragraph" as const, payload: payload("paragraph", "Only A"), children: [] }; - service.commitEdit({ pageId: a.id, tabId: "a", batch: 1, blocks: [own], pageChildren: [shared, own.id] }); - service.commitEdit({ pageId: a.id, tabId: "other", batch: 1, blocks: [{ ...own, payload: payload("paragraph", "Other tab edit") }] }); - service.commitEdit({ pageId: b.id, tabId: "b", batch: 1, blocks: [], pageChildren: [shared] }); + service.commitEdit({ pageId: a.id, tabId: "a", batch: 1, blocks: [own], pageChildren: [shared, own.id] }, pageHistory(a.id)); + service.commitEdit({ pageId: a.id, tabId: "other", batch: 1, blocks: [{ ...own, payload: payload("paragraph", "Other tab edit") }] }, pageHistory(a.id)); + service.commitEdit({ pageId: b.id, tabId: "b", batch: 1, blocks: [], pageChildren: [shared] }, pageHistory(b.id)); const ref = { id: randomUUID(), type: "blocked_reference" as const, payload: { ...payload("blocked_reference"), target: { kind: "page" as const, id: a.id } }, children: [] }; const refBlock = { ...ref, id: randomUUID(), payload: { ...payload("blocked_reference"), target: { kind: "block" as const, id: own.id } } }; - service.commitEdit({ pageId: c.id, tabId: "c", batch: 1, blocks: [ref, refBlock], pageChildren: [ref.id, refBlock.id] }); - confirm(token => service.trash([a.id], "a", token)); + service.commitEdit({ pageId: c.id, tabId: "c", batch: 1, blocks: [ref, refBlock], pageChildren: [ref.id, refBlock.id] }, pageHistory(c.id)); + confirm(token => service.trash([a.id], "a", workspaceHistory, token)); const preview = purge.purge([a.id], "a"); assert.equal(preview.status, "confirmation"); if (preview.status === "confirmation") assert.equal(preview.links, 2); - assert.equal(history.state("other").canUndo, true); + assert.equal(history.state(pageHistory(a.id)).canUndo, true); erase(purge, [a.id], "a"); - assert.equal(history.state("other").canUndo, false); + assert.equal(history.state(pageHistory(a.id)).canUndo, false); assert.ok(service.get(b.id).blocks[shared]); assert.equal(service.resolve({ kind: "page", id: a.id }), null); assert.deepEqual(service.get(c.id).children, [ref.id, refBlock.id]); assert.equal(service.resolve({ kind: "block", id: own.id })?.status, "deleted"); assert.equal(service.blockRow(own.id), null, "soft references in history do not preserve physical target rows"); - assert.equal(history.state("a").canUndo, false); - assert.equal(history.state("b").canUndo, false); - assert.equal(history.state("c").canUndo, false); - assert.throws(() => history.apply("c", "undo"), hasFailure("history-empty")); + assert.equal(history.state(pageHistory(a.id)).canUndo, false); + assert.equal(history.state(pageHistory(b.id)).canUndo, false); + assert.equal(history.state(pageHistory(c.id)).canUndo, false); + assert.throws(() => history.apply(pageHistory(c.id), "undo"), hasFailure("history-empty")); assert.deepEqual(service.sql.prepare("PRAGMA foreign_key_check").all(), []); }); test("purging collects rootless containers together with deleted children and preserves recycled trees", t => { const { service, history, purge } = fixture(t), a = service.create("editable", "A"), d = service.create("editable", "D"), recycled = service.create("editable", "Recycled"); const parent = a.blocks[a.children[0]], child = { id: randomUUID(), type: "paragraph" as const, payload: payload("paragraph", "C"), children: [] }; - service.commitEdit({ pageId: a.id, tabId: "a", batch: 0, blocks: [{ ...parent, children: [child.id] }, child] }); - service.commitEdit({ pageId: d.id, tabId: "d", batch: 0, blocks: [], pageChildren: [child.id] }); + service.commitEdit({ pageId: a.id, tabId: "a", batch: 0, blocks: [{ ...parent, children: [child.id] }, child] }, pageHistory(a.id)); + service.commitEdit({ pageId: d.id, tabId: "d", batch: 0, blocks: [], pageChildren: [child.id] }, pageHistory(d.id)); // A soft link does not retain the rootless parent, but must survive target deletion. - service.commitEdit({ pageId: a.id, tabId: "a", batch: 1, blocks: [{ ...a.blocks[a.titleBlockId], payload: { ...payload("title"), inline: [{ type: "inlineReference", attrs: { target: { kind: "block", id: parent.id }, label: "B" } }] } }] }); - confirm(token => service.deleteBlock({ pageId: a.id, blockId: parent.id, tabId: "a" }, token)); - confirm(token => service.trash([d.id, recycled.id], "trash", token)); + service.commitEdit({ pageId: a.id, tabId: "a", batch: 1, blocks: [{ ...a.blocks[a.titleBlockId], payload: { ...payload("title"), inline: [{ type: "inlineReference", attrs: { target: { kind: "block", id: parent.id }, label: "B" } }] } }] }, pageHistory(a.id)); + confirm(token => service.deleteBlock({ pageId: a.id, blockId: parent.id, tabId: "a" }, pageHistory(a.id), token)); + confirm(token => service.trash([d.id, recycled.id], "trash", workspaceHistory, token)); const preview = purge.purge([d.id], "purge"); assert.equal(preview.status, "confirmation"); if (preview.status === "confirmation") assert.deepEqual(preview.pages.map(page => page.id), [d.id]); @@ -86,7 +87,7 @@ test("purging collects rootless containers together with deleted children and pr assert.equal(service.blockRow(parent.id), null); assert.equal(service.blockRow(child.id), null); assert.ok(service.get(recycled.id).blocks[recycled.children[0]]); - assert.equal(history.state("a").canUndo, false); + assert.equal(history.state(pageHistory(a.id)).canUndo, true); assert.equal(service.statement("SELECT target_id FROM link_refs WHERE source_kind='block' AND source_id=?").pluck().get(a.titleBlockId), parent.id); assert.equal(service.resolve({ kind: "block", id: parent.id })?.status, "deleted"); assert.deepEqual(service.sql.pragma("foreign_key_check"), []); @@ -95,8 +96,8 @@ test("purging collects rootless containers together with deleted children and pr test("reopening collects removed blocks and rootless cycles while keeping live and recycled trees", t => { const { service, database, info } = fixture(t), a = service.create("editable", "A"), recycled = service.create("editable", "Recycled"); const removed = a.children[0], left = randomUUID(), right = randomUUID(); - confirm(token => service.deleteBlock({ pageId: a.id, blockId: removed, tabId: "a" }, token)); - confirm(token => service.trash([recycled.id], "trash", token)); + confirm(token => service.deleteBlock({ pageId: a.id, blockId: removed, tabId: "a" }, pageHistory(a.id), token)); + confirm(token => service.trash([recycled.id], "trash", workspaceHistory, token)); database.transaction(() => { const insert = database.prepare("INSERT INTO blocks(id,type,children) VALUES (?,'paragraph',?)"); insert.run(left, JSON.stringify([right])); insert.run(right, JSON.stringify([left])); @@ -111,30 +112,30 @@ test("reopening collects removed blocks and rootless cycles while keeping live a assert.deepEqual(reopened.database.pragma("foreign_key_check"), []); }); -test("collecting only orphan blocks clears every tab's history even when the recycle bin has no pages", t => { +test("collecting orphan blocks discards dependent history and preserves unrelated page edits", t => { const { service, history, purge } = fixture(t), a = service.create("editable", "A"), b = service.create("editable", "B"); - service.commitEdit({ pageId: b.id, tabId: "b", batch: 0, blocks: [], attributes: { pinned: true } }); - confirm(token => service.deleteBlock({ pageId: a.id, blockId: a.children[0], tabId: "a" }, token)); - assert.equal(history.state("a").canUndo, true); - assert.equal(history.state("b").canUndo, true); + service.commitEdit({ pageId: b.id, tabId: "b", batch: 0, blocks: [], attributes: { pinned: true } }, pageHistory(b.id)); + confirm(token => service.deleteBlock({ pageId: a.id, blockId: a.children[0], tabId: "a" }, pageHistory(a.id), token)); + assert.equal(history.state(pageHistory(a.id)).canUndo, true); + assert.equal(history.state(pageHistory(b.id)).canUndo, true); const result = purge.purge(null, "purge"); assert.equal(result.status, "deleted"); if (result.status === "deleted") { assert.deepEqual(result.pages, []); assert.deepEqual(result.blocks, [a.children[0]]); } - assert.equal(history.state("a").canUndo, false); - assert.equal(history.state("b").canUndo, false); + assert.equal(history.state(pageHistory(a.id)).canUndo, false); + assert.equal(history.state(pageHistory(b.id)).canUndo, true); assert.equal(service.get(b.id).attributes.pinned, true); }); test("a changed recycle set invalidates a previously confirmed empty-trash scope", t => { const { service, purge } = fixture(t), a = service.create("editable", "A"), b = service.create("editable", "B"); - confirm(token => service.trash([a.id], "a", token)); + confirm(token => service.trash([a.id], "a", workspaceHistory, token)); const first = purge.purge(null, "a"); assert.equal(first.status, "confirmation"); if (first.status !== "confirmation") return; - confirm(token => service.trash([b.id], "b", token)); + confirm(token => service.trash([b.id], "b", workspaceHistory, token)); const next = purge.purge(null, "a", first.token); assert.equal(next.status, "confirmation"); assert.equal(service.list({ deleted: true }).total, 2); @@ -143,14 +144,14 @@ async function annotated(t: TestContext): Promise & { const f = fixture(t), path = join(f.info.path, "paper.pdf"); writeFileSync(path, knownCoordinatePdf()); const id = f.papers.importFile(path).pageId, file = (await f.papers.resources(id)).files[0]; - const annotation = await f.papers.annotate(id, { fileId: file.id, pageNumber: 1, rectangles: [{ x: 50, y: 690, width: 70, height: 30 }], quote: "", context: "", extractorVersion: PDF_EXTRACTOR_VERSION }, "annotations"); + const annotation = await f.papers.annotate(id, { fileId: file.id, pageNumber: 1, rectangles: [{ x: 50, y: 690, width: 70, height: 30 }], quote: "", context: "", extractorVersion: PDF_EXTRACTOR_VERSION }, "annotations", pageHistory(id)); const stored = f.database.prepare("SELECT stored_name FROM attachments WHERE id=?").pluck().get(file.id) as string; return { ...f, id, annotation, file: join(f.info.path, "attachments", stored), path }; } test("purging a paper removes its solely retained annotation pages, PDF bytes and timers", async t => { const { service, purge, id, annotation, file } = await annotated(t); service.timers.set(id, "created_at", 0, true); - confirm(token => service.trash([id], "paper", token)); + confirm(token => service.trash([id], "paper", workspaceHistory, token)); assert.equal(service.flags(annotation).deleted, true); const preview = purge.purge([id], "paper"); assert.equal(preview.status, "confirmation"); @@ -163,8 +164,8 @@ test("another live or recycled paper retains an annotation and the immutable att const { service, purge, id, annotation, file } = await annotated(t); const other = service.create("paper", "B"); const ref = { id: randomUUID(), type: "blocked_reference" as const, payload: { ...payload("blocked_reference"), target: { kind: "page" as const, id: annotation } }, children: [] }; - service.commitEdit({ pageId: other.id, tabId: "other", batch: 1, blocks: [ref], pageChildren: [ref.id] }); - confirm(token => service.trash([id, other.id], "both", token)); + service.commitEdit({ pageId: other.id, tabId: "other", batch: 1, blocks: [ref], pageChildren: [ref.id] }, pageHistory(other.id)); + confirm(token => service.trash([id, other.id], "both", workspaceHistory, token)); assert.equal(service.flags(annotation).deleted, true); assert.deepEqual(erase(purge, [id]), [id]); assert.equal(service.get(annotation).kind, "annotation"); @@ -177,39 +178,39 @@ test("purging one paper deletes only its independent copy of an identically impo writeFileSync(path, knownCoordinatePdf()); const a = papers.importFile(path).pageId, b = papers.importFile(path).pageId; const first = papers.externalPath((await papers.resources(a)).files[0].id), second = papers.externalPath((await papers.resources(b)).files[0].id); - confirm(token => service.trash([a, b], "trash", token)); + confirm(token => service.trash([a, b], "trash", workspaceHistory, token)); erase(purge, [a]); assert.equal(existsSync(first), false); assert.equal(existsSync(second), true); erase(purge, [b]); assert.equal(existsSync(second), false); }); -test("purging an annotation's paper removes its PDF and clears every tab's in-memory history", async t => { +test("purging an annotation's paper removes its PDF and removes the highlight history", async t => { const { service, history, purge, papers, info } = fixture(t), path = join(info.path, "plain.pdf"); writeFileSync(path, knownCoordinatePdf()); const page = papers.importFile(path).pageId, fileId = (await papers.resources(page)).files[0].id; - await papers.annotate(page, { fileId, pageNumber: 1, rectangles: [{ x: 50, y: 690, width: 70, height: 30 }], quote: "", context: "", extractorVersion: PDF_EXTRACTOR_VERSION }, "annotations", "yellow"); + await papers.annotate(page, { fileId, pageNumber: 1, rectangles: [{ x: 50, y: 690, width: 70, height: 30 }], quote: "", context: "", extractorVersion: PDF_EXTRACTOR_VERSION }, "annotations", pageHistory(page), "yellow"); const mark = (await papers.resources(page)).annotations[0]; - confirm(token => papers.deleteAnnotation(mark.id, "highlight-tab", token)); - assert.equal(history.state("highlight-tab").canUndo, true); - confirm(token => service.trash([page], "trash", token)); + confirm(token => papers.deleteAnnotation(mark.id, "highlight-tab", pageHistory(mark.id), token)); + assert.equal(history.state(pageHistory(page)).canUndo, true); + confirm(token => service.trash([page], "trash", workspaceHistory, token)); erase(purge, [page]); - assert.equal(history.state("highlight-tab").canUndo, false); + assert.equal(history.state(pageHistory(page)).canUndo, false); assert.equal(service.sql.prepare("SELECT count(*) FROM attachments").pluck().get(), 0); }); -test("a failed permanent deletion rolls back rows and keeps every tab's history", async t => { +test("a failed permanent deletion rolls back rows and keeps every page's history", async t => { const { service, history, purge, id, file } = await annotated(t); const other = service.create("editable", "B"); - service.commitEdit({ pageId: other.id, tabId: "other", batch: 1, blocks: [], attributes: { pinned: true } }); - confirm(token => service.trash([id], "trash", token)); + service.commitEdit({ pageId: other.id, tabId: "other", batch: 1, blocks: [], attributes: { pinned: true } }, pageHistory(other.id)); + confirm(token => service.trash([id], "trash", workspaceHistory, token)); service.sql.prepare("UPDATE attachments SET stored_name='../invalid.pdf'").run(); - const before = history.state("other"), trash = history.state("trash"); + const before = history.state(pageHistory(other.id)), trash = history.state(workspaceHistory); const preview = purge.purge([id], "purge"); assert.equal(preview.status, "confirmation"); if (preview.status !== "confirmation") throw new Error("Expected confirmation"); assert.throws(() => purge.purge([id], "purge", preview.token), hasFailure("attachment-invalid-name")); assert.equal(service.get(id).attributes.deleted, true); assert.equal(existsSync(file), true); - assert.deepEqual(history.state("other"), before); - assert.deepEqual(history.state("trash"), trash); + assert.deepEqual(history.state(pageHistory(other.id)), before); + assert.deepEqual(history.state(workspaceHistory), trash); }); test("menus and shortcut dispatch use the same table, respect editor handling and ignore composing input", () => { const event = (key: string, overrides = {}): Pick => ({ key, ctrlKey: true, altKey: false, shiftKey: false, metaKey: false, isComposing: false, defaultPrevented: false, ...overrides }); diff --git a/tests/retention.test.ts b/tests/retention.test.ts index 284921e..94a4637 100644 --- a/tests/retention.test.ts +++ b/tests/retention.test.ts @@ -1,3 +1,4 @@ +import { pageHistory, workspaceHistory } from "./support/history"; import { knowledgeServices, session, type Knowledge } from "./support/session"; import assert from "node:assert/strict"; import { randomUUID } from "node:crypto"; @@ -64,7 +65,7 @@ function checkEdit(service: Knowledge, graph: Graph, item: GraphPage, change: Ch assert.deepEqual(preview?.recycled.map(p => p.id).sort() ?? [], expected, description); const deleted = service.db.$client.prepare("SELECT page_id FROM page_attrs WHERE attr_id = 'deleted' AND value = 1 ORDER BY page_id").pluck(); assert.deepEqual(deleted.all(), graph.pages.filter(p => p.attributes.deleted).map(p => p.id).sort(), description + " preview wrote data"); - assert.equal(service.commitEdit(edit, preview?.token).status, "saved"); + assert.equal(service.commitEdit(edit, pageHistory(edit.pageId), preview?.token).status, "saved"); for (const p of graph.pages) if (expected.includes(p.id)) p.attributes.deleted = true; assert.deepEqual(deleted.all(), graph.pages.filter(p => p.attributes.deleted).map(p => p.id).sort(), description + " commit"); const sync = service.sql.prepare("SELECT * FROM sync_refs ORDER BY container_kind,container_id,slot,position"); @@ -80,13 +81,13 @@ function checkEdit(service: Knowledge, graph: Graph, item: GraphPage, change: Ch function replaceBody(service: Knowledge, pageId: string, target: Target, inline: boolean): ContentBlock { const page = service.get(pageId); const block = { ...reference(target, inline), id: page.children[0] }; - const result = service.commitEdit({ pageId, tabId: "setup", batch: 1, blocks: [block] }); + const result = service.commitEdit({ pageId, tabId: "setup", batch: 1, blocks: [block] }, pageHistory(pageId)); assert.equal(result.status, "saved"); return block; } function changeAttributes(service: Knowledge, pageId: string, attributes: GraphPage["attributes"]): void { - assert.equal(service.commitEdit({ pageId, tabId: "setup", batch: 1, attributes, blocks: [] }).status, "saved"); + assert.equal(service.commitEdit({ pageId, tabId: "setup", batch: 1, attributes, blocks: [] }, pageHistory(pageId)).status, "saved"); } for (const otherSource of [false, true]) { @@ -97,18 +98,18 @@ for (const otherSource of [false, true]) { replaceBody(service, a.id, { kind: "block", id: paragraph.id }, false); if (otherSource) changeAttributes(service, service.create("editable", "D").id, { links: [c.id] }); changeAttributes(service, c.id, { independent: false }); - const preview = service.trash([b.id], "trash"); + const preview = service.trash([b.id], "trash", workspaceHistory); assert.equal(preview.status, "confirmation"); assert.equal(service.get(b.id).attributes.deleted, false); assert.equal(service.get(c.id).attributes.deleted, false); - assert.equal(service.trash([b.id], "trash", preview.preview.token).status, "saved"); + assert.equal(service.trash([b.id], "trash", workspaceHistory, preview.preview.token).status, "saved"); const edit: EditCommit = { pageId: a.id, tabId: "entry", batch: 2, pageChildren: [], blocks: [] }; const removal = service.previewEdit(edit); t.diagnostic("Trash B, preview = " + JSON.stringify(preview.preview.recycled.map(p => p.title)) + ", C recycled = " + service.get(c.id).attributes.deleted + "; later removing A's entry would recycle " + JSON.stringify(removal?.recycled.map(p => p.title) ?? [])); assert.deepEqual(preview.preview.recycled.map(p => p.id), otherSource ? [] : [c.id]); assert.equal(service.get(c.id).attributes.deleted, !otherSource); assert.equal(removal, null); - assert.equal(service.commitEdit(edit).status, "saved"); + assert.equal(service.commitEdit(edit, pageHistory(edit.pageId)).status, "saved"); assert.deepEqual(service.get(a.id).children, []); assert.equal(service.get(c.id).attributes.deleted, !otherSource); }); @@ -121,10 +122,10 @@ test("automatically recycling the only owner disables its block's outgoing links replaceBody(service, a.id, { kind: "block", id: paragraph.id }, false); changeAttributes(service, c.id, { independent: false }); const edit: EditCommit = { pageId: b.id, tabId: "retention", batch: 1, blocks: [], attributes: { independent: false } }; - const result = service.commitEdit(edit); + const result = service.commitEdit(edit, pageHistory(edit.pageId)); assert.equal(result.status, "confirmation"); assert.deepEqual(result.preview.recycled.map(p => p.id).sort(), [b.id, c.id].sort()); - assert.equal(service.commitEdit(edit, result.preview.token).status, "saved"); + assert.equal(service.commitEdit(edit, pageHistory(edit.pageId), result.preview.token).status, "saved"); assert.equal(service.get(b.id).attributes.deleted, true); assert.equal(service.get(c.id).attributes.deleted, true); }); @@ -136,10 +137,10 @@ test("a block link cannot rescue a rootless page cycle or its outgoing page refe const entry = replaceBody(service, a.id, { kind: "block", id: paragraph.id }, false); changeAttributes(service, c.id, { links: [b.id], independent: false }); const edit: EditCommit = { pageId: b.id, batch: 1, tabId: "cycle", blocks: [], attributes: { independent: false } }; - const preview = service.commitEdit(edit); + const preview = service.commitEdit(edit, pageHistory(edit.pageId)); assert.equal(preview.status, "confirmation"); assert.deepEqual(preview.preview.recycled.map(p => p.id).sort(), [b.id, c.id].sort()); - assert.equal(service.commitEdit(edit, preview.preview.token).status, "saved"); + assert.equal(service.commitEdit(edit, pageHistory(edit.pageId), preview.preview.token).status, "saved"); assert.equal(service.get(b.id).attributes.deleted, true); assert.equal(service.get(c.id).attributes.deleted, true); assert.equal(service.get(a.id).attributes.deleted, false); diff --git a/tests/schedule.test.ts b/tests/schedule.test.ts index 2c589e3..8271c56 100644 --- a/tests/schedule.test.ts +++ b/tests/schedule.test.ts @@ -1,3 +1,4 @@ +import { pageHistory, workspaceHistory } from "./support/history"; import { events } from "./support/session"; import { knowledgeServices, historyServices, session, type Knowledge, type History } from "./support/session"; import assert from "node:assert/strict"; @@ -20,7 +21,7 @@ function fixture(t: TestContext): ReturnType & { clock: delivered.push(notice); bodies.push(body); }); const edit = (pageId: string, attributes: Record): void => { - assert.equal(knowledge.commitEdit({ pageId, tabId: "timers", batch: 0, blocks: [], attributes }).status, "saved"); + assert.equal(knowledge.commitEdit({ pageId, tabId: "timers", batch: 0, blocks: [], attributes }, pageHistory(pageId)).status, "saved"); }; return { ...ws, clock, knowledge, history, delivered, bodies, check, edit }; } @@ -58,9 +59,9 @@ test("time edits and undo reschedule reminders; empty values retain their settin f.edit(page.id, { schedule_start: now + 7200 }); f.clock.now = (now + 3600) * 1000; await f.check(); assert.equal(f.delivered.length, 0); f.clock.now = now * 1000; - assert.equal(f.history.apply("timers", "undo").status, "saved"); + assert.equal(f.history.apply(pageHistory(page.id), "undo").status, "saved"); assert.equal(f.database.prepare("SELECT due_at FROM timers").pluck().get(), now + 3600); - assert.equal(f.history.apply("timers", "redo").status, "saved"); + assert.equal(f.history.apply(pageHistory(page.id), "redo").status, "saved"); assert.equal(f.database.prepare("SELECT due_at FROM timers").pluck().get(), now + 7200); f.edit(page.id, { schedule_start: null }); assert.equal(f.database.prepare("SELECT due_at FROM timers").pluck().get(), null); assert.equal(f.database.prepare("SELECT count(*) FROM timers").pluck().get(), 1); @@ -71,15 +72,15 @@ test("time edits and undo reschedule reminders; empty values retain their settin test("recycle, restore, completed tasks, detached attributes and changed types update timer rows", async t => { const f = fixture(t), now = Math.floor(f.clock.now / 1000), page = f.knowledge.create("task", "A", { schedule_start: now + 1000 }); f.knowledge.timers.set(page.id, "schedule_start", 0, true); - const preview = f.knowledge.trash([page.id], "trash"); if (preview.status !== "confirmation") throw new Error("Expected confirmation"); - f.knowledge.trash([page.id], "trash", preview.preview.token); + const preview = f.knowledge.trash([page.id], "trash", workspaceHistory); if (preview.status !== "confirmation") throw new Error("Expected confirmation"); + f.knowledge.trash([page.id], "trash", workspaceHistory, preview.preview.token); assert.equal(f.database.prepare("SELECT due_at FROM timers").pluck().get(), null); - f.knowledge.restore([page.id], "restore"); assert.equal(f.database.prepare("SELECT due_at FROM timers").pluck().get(), now + 1000); + f.knowledge.restore([page.id], "restore", workspaceHistory); assert.equal(f.database.prepare("SELECT due_at FROM timers").pluck().get(), now + 1000); f.edit(page.id, { task_status: "done" }); f.clock.now = (now + 1000) * 1000; await f.check(); assert.equal(f.delivered.length, 0); const id = "custom:" + randomUUID(), definition = { id, type: "minute" as const, name: "A", metadata: {} }; f.knowledge.setDefinition(id, definition, "types"); f.edit(page.id, { task_status: "todo", [id]: now + 2000 }); f.knowledge.timers.set(page.id, id, 0, true); - f.knowledge.commitEdit({ pageId: page.id, tabId: "timers", batch: 0, blocks: [], detach: [id] }); + f.knowledge.commitEdit({ pageId: page.id, tabId: "timers", batch: 0, blocks: [], detach: [id] }, pageHistory(page.id)); assert.equal(f.database.prepare("SELECT count(*) FROM timers WHERE attr_id=?").pluck().get(id), 0); f.edit(page.id, { [id]: now + 3000 }); f.knowledge.timers.set(page.id, id, 0, true); const next = { ...definition, type: "string" as const }, impact = f.knowledge.setDefinition(id, next, "types"); @@ -107,13 +108,13 @@ test("a scheduled reminder catches up after reopening and subsequent checks do n test("notification identity and title are derived from the current page, with no undo entries for settings or reading", async t => { const f = fixture(t), due = Math.floor(f.clock.now / 1000) + 1000, page = f.knowledge.create("editable", "A"), id = "custom:" + randomUUID(); f.knowledge.setDefinition(id, { id, name: "结束", type: "hour", metadata: {} }, "types"); f.edit(page.id, { [id]: due }); - const history = f.history.state("timers"); f.knowledge.timers.set(page.id, id, 0, true); assert.deepEqual(f.history.state("timers"), history); + const history = f.history.state(pageHistory(page.id)); f.knowledge.timers.set(page.id, id, 0, true); assert.deepEqual(f.history.state(pageHistory(page.id)), history); f.clock.now = due * 1000; await f.check(); const notice = f.knowledge.timers.notices()[0]; assert.equal(notice.seen, false); assert.equal(notice.attrName, "结束"); f.knowledge.timers.read(page.id, id, 0); assert.equal(f.knowledge.timers.notices()[0].seen, true); - const title = page.blocks[page.titleBlockId]; f.knowledge.commitEdit({ pageId: page.id, tabId: "title", batch: 0, blocks: [{ ...title, payload: { ...title.payload, inline: [{ type: "text", text: "B" }] } }] }); + const title = page.blocks[page.titleBlockId]; f.knowledge.commitEdit({ pageId: page.id, tabId: "title", batch: 0, blocks: [{ ...title, payload: { ...title.payload, inline: [{ type: "text", text: "B" }] } }] }, pageHistory(page.id)); assert.equal(f.knowledge.timers.notices()[0].title, "B"); - const preview = f.knowledge.trash([page.id], "trash"); if (preview.status === "confirmation") f.knowledge.trash([page.id], "trash", preview.preview.token); + const preview = f.knowledge.trash([page.id], "trash", workspaceHistory); if (preview.status === "confirmation") f.knowledge.trash([page.id], "trash", workspaceHistory, preview.preview.token); assert.deepEqual(f.knowledge.timers.notices(), []); }); diff --git a/tests/services.test.ts b/tests/services.test.ts index 8a3b440..e094b4f 100644 --- a/tests/services.test.ts +++ b/tests/services.test.ts @@ -1,3 +1,4 @@ +import { pageHistory, workspaceHistory } from "./support/history"; import assert from "node:assert/strict"; import { randomUUID } from "node:crypto"; import { EventEmitter } from "node:events"; @@ -43,7 +44,7 @@ function entry(id: string, pdfURL: string | null = null): FeedEntry { } function edit(page: PageRecord, text: string, tabId = "a"): CommitResult { const block = page.blocks[page.children[0]]; - return edits.commitEdit({ pageId: page.id, tabId, batch: 0, blocks: [{ ...block, payload: payload("paragraph", text) }] }); + return edits.commitEdit({ pageId: page.id, tabId, batch: 0, blocks: [{ ...block, payload: payload("paragraph", text) }] }, pageHistory(page.id)); } function confirm(action: (token?: string) => CommitResult): CommitResult { const preview = action(); @@ -69,14 +70,14 @@ test("opening B drops A history, cached queries, timers and database connection" const first = edits.create("event", "A", { schedule_start: now / 1000 + 60 }); edit(first, "A"); timers.set(first.id, "schedule_start", 0, true); - assert.equal(history.state("a").canUndo, true); + assert.equal(history.state(pageHistory(first.id)).canUndo, true); session.close(); assert.equal(a.database.open, false); assert.equal(a.lock.connection.open, false); const b = open(t, { clock: () => now, timeZone: () => "UTC" }); const second = edits.create("event", "B", { schedule_start: now / 1000 + 60 }); timers.set(second.id, "schedule_start", 0, true); - assert.deepEqual(history.state("a"), { canUndo: false, redo: [] }); + assert.deepEqual(history.state(pageHistory(first.id)), { canUndo: false, redo: [] }); assert.deepEqual(records.list().items.map(page => page.id), [second.id]); assert.throws(() => records.get(first.id), hasFailure("page-unavailable")); now += 60000; @@ -94,11 +95,11 @@ test("every public service operation rejects a closed session before validating () => records.get(page.id), () => records.list(), () => records.listUpdates({}, []), () => records.readObjects(page.id, []), () => records.header(""), () => records.readBatch([]), () => records.sharedUses([]), () => records.backlinks(page.id), () => records.resolve({ kind: "page", id: page.id }), () => attributes.definitions(), () => attributes.definition("tags"), - () => edits.create(), () => edits.commitEdit({} as never), () => edits.previewEdit({} as never), () => edits.syncBlocks("", []), - () => edits.trash([], ""), () => edits.restore([], ""), () => edits.setDefinition("", null, ""), - () => history.state("a"), () => history.apply("a", "undo"), () => history.close("a"), () => history.clear(), + () => edits.create(), () => edits.commitEdit({} as never, workspaceHistory), () => edits.previewEdit({} as never), () => edits.syncBlocks("", []), + () => edits.trash([], "", workspaceHistory), () => edits.restore([], "", workspaceHistory), () => edits.setDefinition("", null, ""), + () => history.state(pageHistory(page.id)), () => history.apply(pageHistory(page.id), "undo"), () => papers.files([]), () => papers.state(page.id), () => papers.read(""), () => papers.get(page.id), - () => papers.resources(page.id), () => papers.annotate(page.id, "", ""), () => papers.getAnnotation(""), + () => papers.resources(page.id), () => papers.annotate(page.id, "", "", pageHistory(page.id)), () => papers.getAnnotation(""), () => papers.unlockPDF("", ""), () => papers.importFile(""), () => papers.position("", "", {} as never), () => purge.purge(null, ""), () => timers.settings(""), () => timers.notices(), () => timers.check(), () => timers.set("", "", -1, false), () => timers.read("", "", -1), () => timers.recalculateAll(), @@ -204,29 +205,29 @@ test("all write paths publish after committing, including direct paper and subsc const page = edits.create("event", "A", { schedule_start: now / 1000 + 60 }); await check("create", () => edits.create("editable", "B")); await check("edit", () => edit(page, "A")); - await check("undo", () => history.apply("a", "undo")); - await check("redo", () => history.apply("a", "redo")); - await check("place", () => edits.place({ position: { pageId: page.id, containerId: page.id, index: 0, blockId: page.children[0] }, action: "duplicate", tabId: "place" })); + await check("undo", () => history.apply(pageHistory(page.id), "undo")); + await check("redo", () => history.apply(pageHistory(page.id), "redo")); + await check("place", () => edits.place({ position: { pageId: page.id, containerId: page.id, index: 0, blockId: page.children[0] }, action: "duplicate", tabId: "place" }, pageHistory(page.id))); const definition = { id: "custom:" + randomUUID(), name: "A", type: "files" as const, metadata: {} }; await check("definition", () => edits.setDefinition(definition.id, definition, "definition")); - await check("files", () => papers.attachFiles([paths.text], page.id, definition.id, "files")); - await check("deleteBlock", () => confirm(token => edits.deleteBlock({ pageId: page.id, blockId: page.children[0], tabId: "delete" }, token))); - await check("trash", () => confirm(token => edits.trash([page.id], "trash", token))); - await check("restore", () => edits.restore([page.id], "restore")); + await check("files", () => papers.attachFiles([paths.text], page.id, definition.id, { tabId: "files", source: pageHistory(page.id) })); + await check("deleteBlock", () => confirm(token => edits.deleteBlock({ pageId: page.id, blockId: page.children[0], tabId: "delete" }, pageHistory(page.id), token))); + await check("trash", () => confirm(token => edits.trash([page.id], "trash", workspaceHistory, token))); + await check("restore", () => edits.restore([page.id], "restore", workspaceHistory)); let paperId = ""; await check("import PDF", () => { paperId = papers.importFile(paths.pdf).pageId; }); - await check("add PDF", () => papers.importFile(paths.pdf, paperId, "files")); + await check("add PDF", () => papers.importFile(paths.pdf, paperId, { tabId: "files", source: pageHistory(paperId) })); const fileId = (await papers.resources(paperId)).files[0].id; let annotation = ""; await check("highlight", async () => { - annotation = await papers.annotate(paperId, selection(fileId), "annotations"); + annotation = await papers.annotate(paperId, selection(fileId), "annotations", pageHistory(paperId)); }); - await check("color", () => papers.changeAnnotation(annotation, "green", "annotations")); + await check("color", () => papers.changeAnnotation(annotation, "green", "annotations", pageHistory(paperId))); await check("reading position", () => papers.position(paperId, fileId, { page: 1, rotation: 0, left: 0, top: 0, scale: 1 }, "reader")); - await check("delete highlight", () => confirm(token => papers.deleteAnnotation(annotation, "annotations", token))); - await check("restore highlight", () => edits.restore([annotation], "restore")); + await check("delete highlight", () => confirm(token => papers.deleteAnnotation(annotation, "annotations", pageHistory(paperId), token))); + await check("restore highlight", () => edits.restore([annotation], "restore", workspaceHistory)); edits.cacheAttributes(annotation, { annotation_extractor: "old" }); await check("source-text cache", () => papers.get(annotation)); await check("reminder setting", () => timers.set(page.id, "schedule_start", 0, true)); @@ -236,10 +237,10 @@ test("all write paths publish after committing, including direct paper and subsc await check("read notice", () => timers.read(page.id, "schedule_start", 0)); await check("time-zone recalculation", () => timers.recalculateAll()); await check("rebuild links", () => edits.rebuildLinks()); - confirm(token => edits.trash([page.id], "trash", token)); + confirm(token => edits.trash([page.id], "trash", workspaceHistory, token)); await check("purge", () => erase([page.id]), true); const recycled = edits.create(); - confirm(token => edits.trash([recycled.id], "trash", token)); + confirm(token => edits.trash([recycled.id], "trash", workspaceHistory, token)); await check("empty recycle bin", () => erase(null), true); let source = ""; await check("save source", async () => { @@ -267,7 +268,7 @@ test("all write paths publish after committing, including direct paper and subsc test("one shared-block change expands summaries for both pages and reaches every subscriber", t => { open(t); const a = edits.create(), b = edits.create(); - edits.commitEdit({ pageId: b.id, tabId: "b", batch: 0, blocks: [], pageChildren: [a.children[0]] }); + edits.commitEdit({ pageId: b.id, tabId: "b", batch: 0, blocks: [], pageChildren: [a.children[0]] }, pageHistory(b.id)); const first: events.Event[] = [], second: events.Event[] = []; t.after(events.subscribe(event => first.push(event))); t.after(events.subscribe(event => second.push(event))); @@ -291,7 +292,7 @@ test("create rules apply to service calls and rolled-back writes publish no even edit(page, "rollback"); throw new Error("rollback"); }), /rollback/); assert.equal(changed.length, 0); - assert.equal(history.state("a").canUndo, false); + assert.equal(history.state(pageHistory(page.id)).canUndo, false); assert.equal(records.get(page.id).blocks[page.children[0]].payload.inline.length, 0); }); @@ -384,7 +385,7 @@ test("service architecture has no singleton classes, connection WeakMaps, Electr test("annotation parsing returning after close leaves B unchanged and reports no stale error", async t => { const a = open(t), paths = files(a.info.path), paper = papers.importFile(paths.pdf).pageId; const file = (await papers.resources(paper)).files[0].id; - const pending = papers.annotate(paper, selection(file), "annotations"); + const pending = papers.annotate(paper, selection(file), "annotations", pageHistory(paper)); session.close(); open(t); assert.equal(await pending, ""); diff --git a/tests/support/history.ts b/tests/support/history.ts new file mode 100644 index 0000000..376dd5e --- /dev/null +++ b/tests/support/history.ts @@ -0,0 +1,4 @@ +import type { HistorySource } from "../../shared/history/ipc"; + +export const workspaceHistory = { kind: "workspace" } as const; +export const pageHistory = (id: string): HistorySource => ({ kind: "page", id }); \ No newline at end of file diff --git a/tests/support/ipc.ts b/tests/support/ipc.ts new file mode 100644 index 0000000..5eb9bcb --- /dev/null +++ b/tests/support/ipc.ts @@ -0,0 +1,34 @@ +import assert from "node:assert/strict"; +import type { TestContext } from "node:test"; +import { EventEmitter } from "node:events"; +import type { BrowserWindow } from "electron"; +import { registerIPCs } from "../../main/register"; +import * as session from "../../main/session"; +import type { IPCReply } from "../../shared/ipc"; + +type Fixture = { + call(channel: string, ...args: unknown[]): Promise; + invoke(channel: string, ...args: unknown[]): Promise>; + send(channel: string, ...args: unknown[]): boolean; + contents: EventEmitter; sent: string[]; devTools: { opened: number }; +}; +export function fixture(t?: TestContext): Fixture { + const frame = {}, sent: string[] = [], messages = new EventEmitter(); + const handlers = new Map Promise>>(); + const devTools = { opened: 0 }; + const contents = Object.assign(new EventEmitter(), { mainFrame: frame, isDestroyed: () => false, send: (channel: string, ...args: unknown[]) => { + sent.push(channel); contents.emit(channel, ...args); + }, openDevTools: () => devTools.opened++, ipc: Object.assign(messages, { handle: handlers.set.bind(handlers) }) }); + registerIPCs({ webContents: contents } as unknown as BrowserWindow, () => { }); + const invoke = (channel: string, ...args: unknown[]): Promise> => handlers.get(channel)!({ senderFrame: frame }, ...args); + async function call(channel: string, ...args: unknown[]): Promise { + const reply = await invoke(channel, ...args); + if (!reply.ok) assert.fail(channel + ": " + JSON.stringify(reply.failure)); + return reply.value as Value; + } + t?.after(() => { + contents.emit("destroyed"); + session.close(); + }); + return { invoke, call, send: (channel: string, ...args: unknown[]) => messages.emit(channel, { senderFrame: frame }, ...args), contents, sent, devTools }; +} \ No newline at end of file diff --git a/tests/time-precision.test.ts b/tests/time-precision.test.ts index 691e14f..4246f56 100644 --- a/tests/time-precision.test.ts +++ b/tests/time-precision.test.ts @@ -1,3 +1,4 @@ +import { pageHistory } from "./support/history"; import { knowledgeServices, historyServices, session, type Knowledge } from "./support/session"; import assert from "node:assert/strict"; import { randomUUID } from "node:crypto"; @@ -130,8 +131,8 @@ test("definition preview and commit share conversion, invalidate undo, and refre const history = historyServices(); const page = service.create("editable", "A"), def = definition("minute"); service.setDefinition(def.id, def, "manager"); - assert.equal(service.commitEdit({ pageId: page.id, tabId: "editor", batch: 1, blocks: [], attributes: { [def.id]: instant } }).status, "saved"); - assert.equal(history.state("editor").canUndo, true); + assert.equal(service.commitEdit({ pageId: page.id, tabId: "editor", batch: 1, blocks: [], attributes: { [def.id]: instant } }, pageHistory(page.id)).status, "saved"); + assert.equal(history.state(pageHistory(page.id)).canUndo, true); const target = { ...def, type: "day" as const }; const preview = service.setDefinition(def.id, target, "manager")!; assert.deepEqual(preview.pages.map(p => p.id), [page.id]); @@ -142,7 +143,7 @@ test("definition preview and commit share conversion, invalidate undo, and refre assert.equal(service.get(page.id).attributes[def.id], instant); assert.equal(service.setDefinition(def.id, target, "manager", updated.token), null); assert.equal(service.get(page.id).attributes[def.id], convertValue(def, target, instant, "UTC")); - assert.equal(history.state("editor").canUndo, false); + assert.equal(history.state(pageHistory(page.id)).canUndo, false); const text = { ...target, type: "string" as const }; const back = service.setDefinition(def.id, text, "manager")!; service.setDefinition(def.id, text, "manager", back.token); diff --git a/tests/timestamps.test.ts b/tests/timestamps.test.ts index 9b3e474..73b700c 100644 --- a/tests/timestamps.test.ts +++ b/tests/timestamps.test.ts @@ -1,3 +1,4 @@ +import { pageHistory } from "./support/history"; import { knowledgeServices, historyServices, feedServices, session } from "./support/session"; import assert from "node:assert/strict"; import { mkdtempSync } from "node:fs"; @@ -18,15 +19,15 @@ test("attribute and timer timestamps use seconds while workspace and published i const first = Date.parse("2026-11-07T17:12:56.210Z"), later = Date.parse("2026-11-07T17:32:56.208Z"), seconds = Math.floor(first / 1000), due = Math.floor(later / 1000); let now = first; const service = knowledgeServices(), history = historyServices(), page = service.create("event", "A"); - service.commitEdit({ pageId: page.id, tabId: "time", batch: 0, blocks: [], attributes: { schedule_start: due } }); + service.commitEdit({ pageId: page.id, tabId: "time", batch: 0, blocks: [], attributes: { schedule_start: due } }, pageHistory(page.id)); service.timers.set(page.id, "schedule_start", 0, true); now = due * 1000 - 1; await service.timers.check(() => assert.fail("too early")); now = later; const notices: string[] = []; await service.timers.check(notice => notices.push(notice.pageId)); assert.deepEqual(notices, [page.id]); assert.equal(sql.prepare("SELECT fired_at FROM timers").pluck().get(), due); assert.equal(service.get(page.id).attributes.schedule_start, due); - history.apply("time", "undo"); assert.equal(service.get(page.id).attributes.schedule_start, null); - history.apply("time", "redo"); assert.equal(service.get(page.id).attributes.schedule_start, due); + history.apply(pageHistory(page.id), "undo"); assert.equal(service.get(page.id).attributes.schedule_start, null); + history.apply(pageHistory(page.id), "redo"); assert.equal(service.get(page.id).attributes.schedule_start, due); const feed = feedServices(); const source = await feed.saveSource({ name: "A", url: "https://example.org/feed" }); assert.equal(feed.getState({}).items[0].publishedAt, first);