Skip to content

Commit a0f4399

Browse files
authored
Merge pull request #13998 from logseq/fix/cli-block-reference-updates
fix(cli): align block input with Desktop and label batches
2 parents e057b5b + adb2c6c commit a0f4399

28 files changed

Lines changed: 1655 additions & 636 deletions
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
const fs = require('node:fs');
2+
const path = require('node:path');
3+
const assert = require('node:assert/strict');
4+
const { execFile } = require('node:child_process');
5+
const exec = require('node:util').promisify(execFile);
6+
const os = require('node:os');
7+
const test = require('node:test');
8+
const repo = path.resolve(__dirname, '../..');
9+
const transit = require(path.join(repo, 'cli/node_modules/transit-js'));
10+
11+
test('CLI metadata writes preserve named links, backlinks and recurring journal refs', async t => {
12+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'logseq-cli-metadata-refs-'));
13+
const graph = 'combined-metadata-refs';
14+
const cli = path.join(repo, 'static/logseq-cli.js');
15+
const report = { checks: 0, stages: [], failures: [] };
16+
let server;
17+
async function command(...args) {
18+
try {
19+
const { stdout } = await exec(process.execPath, [cli, '--root-dir', root, '--graph', graph,
20+
'--output', 'json', '--timeout-ms', '120000', ...args], { timeout: 130000 });
21+
const result = JSON.parse(stdout);
22+
assert.equal(result.status, 'ok', stdout);
23+
return result.data;
24+
} catch (error) { throw Error(`${args.join(' ')}\n${error.stdout || ''}\n${error.stderr || error.message}`); }
25+
}
26+
async function query(q) { return (await command('query', '--query', q)).result; }
27+
async function id(title) { return query(`[:find ?e . :where [?e :block/title ${JSON.stringify(title)}]]`); }
28+
async function uuid(eid) { return query(`[:find ?u . :where [${eid} :block/uuid ?u]]`); }
29+
async function titleRefs(eid) { return (await query(`[:find [?title ...] :where [${eid} :block/refs ?r] [?r :block/title ?title]]`)).sort(); }
30+
async function backlinkUUIDs(eid) {
31+
const response = await fetch(server['base-url'] + '/v1/invoke', { method: 'POST',
32+
headers: { 'Content-Type': 'application/json' },
33+
body: JSON.stringify({ method: 'thread-api/get-block-refs',
34+
argsTransit: transit.writer('json').write([server.repo, eid]) }) });
35+
const result = await response.json();
36+
assert.equal(response.status, 200, JSON.stringify(result));
37+
const blocks = transit.reader('json').read(result.resultTransit);
38+
const entries = [];
39+
if (Array.isArray(blocks)) entries.push(...blocks);
40+
else if (blocks && blocks.tag === 'list') entries.push(...blocks.rep);
41+
else if (blocks && typeof blocks.forEach === 'function') blocks.forEach(value => entries.push(value));
42+
else if (blocks) throw Error('Backlink result shape: ' + require('node:util').inspect(blocks, {depth: 3}));
43+
return entries.map(block => String(block.get(transit.keyword('block/uuid'))));
44+
}
45+
function equal(label, actual, expected) {
46+
report.checks++;
47+
if (JSON.stringify(actual) !== JSON.stringify(expected)) report.failures.push({ label, actual, expected });
48+
}
49+
async function checkpoint(label, block, required, absent = []) {
50+
const actual = await titleRefs(block);
51+
report.stages.push({ label, refs: actual });
52+
for (const name of required) {
53+
equal(label + ' refs include ' + name, actual.includes(name), true);
54+
const target = await id(name);
55+
const membership = await query(`[:find ?tag . :where [${block} :block/tags ?tag] [(= ?tag ${target})]]`);
56+
equal(label + (membership ? ' tag membership excluded from linked references on ' : ' UI backlinks include source on ') + name,
57+
(await backlinkUUIDs(target)).includes(await uuid(block)), !membership);
58+
}
59+
for (const name of absent) {
60+
equal(label + ' refs exclude ' + name, actual.includes(name), false);
61+
const target = await id(name);
62+
if (target) equal(label + ' UI backlinks exclude source on ' + name,
63+
(await backlinkUUIDs(target)).includes(await uuid(block)), false);
64+
}
65+
}
66+
async function refreshServer() {
67+
server = (await command('server', 'list')).servers.find(item => item.graph === graph);
68+
equal('worker owned by CLI', server['owner-source'], 'cli');
69+
}
70+
async function main() {
71+
await command('graph', 'create');
72+
for (const name of ['Home', 'Alpha', 'Beta', 'T1', 'T2']) await command('upsert', 'page', '--page', name);
73+
for (const name of ['Topic', 'Topic2']) await command('upsert', 'tag', '--name', name);
74+
for (const name of ['p1', 'p2']) await command('upsert', 'property', '--name', name, '--type', 'node');
75+
await refreshServer();
76+
const created = await command('upsert', 'block', '--target-page', 'Home', '--content', 'initial [[Alpha]]', '--update-tags', '["Topic"]');
77+
const block = created.result[0];
78+
await checkpoint('create with tag', block, ['Alpha', 'Tags', 'Topic']);
79+
await command('upsert', 'block', '--id', String(block), '--content', 'updated [[Beta]] and [[Namespace/Child]]');
80+
await checkpoint('named and namespace update', block, ['Beta', 'Child', 'Tags', 'Topic'], ['Alpha']);
81+
await command('upsert', 'block', '--id', String(block), '--update-tags', '["Topic2"]');
82+
await checkpoint('subsequent tag operation', block, ['Beta', 'Child', 'Tags', 'Topic', 'Topic2'], ['Alpha']);
83+
const p1 = await id('p1'), p2 = await id('p2'), t1 = await id('T1'), t2 = await id('T2');
84+
const legacy = (await command('upsert', 'block', '--target-page', 'Home', '--content', 'legacy [[Alpha]] and [[Namespace/Child]]')).result[0];
85+
report.legacyStoredTitle = await query(`[:find ?title . :where [${legacy} :block/title ?title]]`);
86+
await checkpoint('raw named links before metadata', legacy, ['Alpha', 'Child']);
87+
await command('upsert', 'block', '--id', String(legacy), '--update-tags', '["Topic"]');
88+
await checkpoint('raw named links after separate tag write', legacy, ['Alpha', 'Child', 'Tags', 'Topic']);
89+
await command('upsert', 'block', '--id', String(legacy), '--update-properties', `{${p1} ${t1} ${p2} ${t2}}`);
90+
await checkpoint('raw named links after separate property write', legacy, ['Alpha', 'Child', 'p1', 'p2', 'T1', 'T2']);
91+
await command('upsert', 'block', '--id', String(block), '--update-properties', `{${p1} ${t1} ${p2} ${t2}}`);
92+
await checkpoint('subsequent two-node-property operation', block, ['Beta', 'Child', 'T1', 'T2', 'p1', 'p2']);
93+
await command('upsert', 'block', '--id', String(block), '--content', 'replacement [[Alpha]] and [[Namespace/Other]]',
94+
'--remove-tags', '["Topic"]', '--update-properties', `{${p1} ${t2}}`, '--remove-properties', `[${p2}]`);
95+
await checkpoint('combined title and metadata replacement', block, ['Alpha', 'Other', 'Tags', 'Topic2', 'p1', 'T2'], ['Beta', 'Child', 'Topic', 'p2', 'T1']);
96+
await command('upsert', 'block', '--id', String(block), '--remove-tags', '["Topic2"]', '--remove-properties', `[${p1}]`);
97+
await checkpoint('metadata removed', block, ['Alpha', 'Other'], ['Tags', 'Topic2', 'p1', 'T2']);
98+
const tasks = [];
99+
for (const temporal of ['scheduled', 'deadline']) {
100+
const property = ':logseq.property/' + temporal;
101+
const task = (await command('upsert', 'block', '--target-page', 'Home', '--content', temporal + ' [[Alpha]] and [[Namespace/Child]]')).result[0];
102+
await command('upsert', 'task', '--id', String(task), '--status', 'todo');
103+
const stamp = new Date(2026, 10, 8, 12).getTime();
104+
await command('upsert', 'block', '--id', String(task), '--update-properties',
105+
`{${property} ${stamp} :logseq.property.repeat/repeated? true :logseq.property.repeat/recur-frequency 1 :logseq.property.repeat/recur-unit :logseq.property.repeat/recur-unit.week :logseq.property.repeat/repeat-type :logseq.property.repeat/repeat-type.plus :logseq.property.repeat/temporal-property ${property}}`);
106+
for (const day of [20261115, 20261122]) {
107+
await command('upsert', 'task', '--id', String(task), '--status', 'done');
108+
const actual = await query(`[:find [?day ...] :where [${task} :block/refs ?j] [?j :block/journal-day ?day]]`);
109+
equal(temporal + ' journal refs ' + day, actual, [day]);
110+
const stored = await query(`[:find ?stamp . :where [${task} ${property} ?stamp]]`);
111+
const date = new Date(stored);
112+
equal(temporal + ' stored date ' + day, Number(`${date.getFullYear()}${String(date.getMonth()+1).padStart(2,'0')}${String(date.getDate()).padStart(2,'0')}`), day);
113+
const journal = await query(`[:find ?j . :where [?j :block/journal-day ${day}]]`);
114+
equal(temporal + ' new journal UI backlinks ' + day, (await backlinkUUIDs(journal)).includes(await uuid(task)), true);
115+
const oldDay = day === 20261115 ? 20261108 : 20261115;
116+
const old = await query(`[:find ?j . :where [?j :block/journal-day ${oldDay}]]`);
117+
if (old) equal(temporal + ' old journal UI backlinks removed ' + oldDay, (await backlinkUUIDs(old)).includes(await uuid(task)), false);
118+
await checkpoint(temporal + ' completion ' + day, task, day === 20261115 ? ['Alpha', 'Child', 'Tags', 'Task', 'Status'] : ['Beta', 'Other', 'Tags', 'Task', 'Status'], day === 20261122 ? ['Alpha', 'Child'] : []);
119+
if (day === 20261115) await command('upsert', 'block', '--id', String(task), '--content', temporal + ' replacement [[Beta]] and [[Namespace/Other]]');
120+
}
121+
tasks.push({ task, temporal });
122+
}
123+
await command('server', 'restart');
124+
await refreshServer();
125+
await checkpoint('restart raw named links', legacy, ['Alpha', 'Child', 'Tags', 'Topic', 'p1', 'p2', 'T1', 'T2']);
126+
await checkpoint('restart ordinary block', block, ['Alpha', 'Other'], ['Beta', 'Child', 'Tags', 'Topic', 'Topic2', 'p1', 'p2', 'T1', 'T2']);
127+
for (const {task, temporal} of tasks) {
128+
await checkpoint('restart ' + temporal, task, ['Beta', 'Other', 'Tags', 'Task', 'Status'], ['Alpha', 'Child']);
129+
equal('restart ' + temporal + ' journal refs', await query(`[:find [?day ...] :where [${task} :block/refs ?j] [?j :block/journal-day ?day]]`), [20261122]);
130+
}
131+
const beforeRenameTitle = await query(`[:find ?title . :where [${legacy} :block/title ?title]]`);
132+
const alpha = await id('Alpha'), child = await id('Child');
133+
equal('created named and namespace links use Desktop UUID storage', beforeRenameTitle,
134+
`legacy [[${await uuid(alpha)}]] and [[${await uuid(child)}]]`);
135+
await command('upsert', 'page', '--id', String(alpha), '--rename', 'Renamed Alpha');
136+
await command('upsert', 'page', '--id', String(child), '--rename', 'Renamed Child');
137+
await command('upsert', 'block', '--id', String(legacy), '--update-tags', '["Topic2"]');
138+
await checkpoint('rename then metadata', legacy, ['Renamed Alpha', 'Renamed Child', 'Topic', 'Topic2', 'Tags', 'p1', 'p2', 'T1', 'T2']);
139+
equal('rename preserves stored UUID title', await query(`[:find ?title . :where [${legacy} :block/title ?title]]`), beforeRenameTitle);
140+
await command('server', 'restart');
141+
await refreshServer();
142+
await checkpoint('restart after rename', legacy, ['Renamed Alpha', 'Renamed Child', 'Topic', 'Topic2', 'Tags', 'p1', 'p2', 'T1', 'T2']);
143+
await command('graph', 'validate');
144+
}
145+
t.after(async () => {
146+
let teardownError;
147+
try {
148+
await command('server', 'stop');
149+
const logs = fs.readdirSync(root, { recursive: true }).filter(name => /db-worker-node-.*\.log$/.test(name));
150+
const errors = logs.flatMap(name => fs.readFileSync(path.join(root, name), 'utf8')
151+
.split('\n').filter(line => /ERROR|Exception|invalid-data/.test(line)));
152+
t.diagnostic(`Checked ${logs.length} worker log(s): ${errors.length} error line(s)`);
153+
for (const line of errors) t.diagnostic(line);
154+
} catch (error) {
155+
teardownError = error;
156+
throw error;
157+
} finally {
158+
try {
159+
fs.rmSync(root, { recursive: true, force: true });
160+
} catch (cleanupError) {
161+
if (teardownError) throw new AggregateError([teardownError, cleanupError], 'Teardown and directory cleanup failed', { cause: teardownError });
162+
throw cleanupError;
163+
}
164+
}
165+
});
166+
await main();
167+
t.diagnostic(`${report.stages.length} stages, ${report.checks} reference and backlink checks`);
168+
assert.deepEqual(report.failures, [], JSON.stringify(report, null, 2));
169+
});
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
#!/usr/bin/env python3
2+
3+
import argparse
4+
import json
5+
import subprocess
6+
7+
8+
def main():
9+
parser = argparse.ArgumentParser()
10+
for name in ("cli", "root-dir", "config", "graph"):
11+
parser.add_argument("--" + name, required=True)
12+
args = parser.parse_args()
13+
command = ["node", args.cli, "--root-dir", args.root_dir,
14+
"--config", args.config, "--graph", args.graph, "--output", "json"]
15+
16+
def run(*argv, error=False):
17+
result = subprocess.run(command + list(argv), text=True, capture_output=True)
18+
if error:
19+
assert result.returncode != 0, (argv, result.stdout, result.stderr)
20+
return
21+
assert result.returncode == 0, (argv, result.stdout, result.stderr)
22+
payload = json.loads(result.stdout)
23+
assert payload["status"] == "ok", payload
24+
return payload["data"]
25+
26+
def query(expression):
27+
return run("query", "--query", expression)["result"]
28+
29+
def refs():
30+
return set(query(f"[:find [?title ...] :where [{block_id} :block/refs ?r] "
31+
"[?r :block/title ?title]]"))
32+
33+
def update(content, expected, selector="--id"):
34+
identity = str(block_id) if selector == "--id" else block_uuid
35+
run("upsert", "block", selector, identity, "--content", content)
36+
actual = refs()
37+
assert actual == set(expected), (content, expected, actual)
38+
39+
for page in ("Home", "Alpha", "Beta"):
40+
run("upsert", "page", "--page", page)
41+
block_id = run("upsert", "block", "--target-page", "Home", "--content",
42+
"Note on [[Alpha]] and [[Beta]]")["result"][0]
43+
block_uuid = query(f"[:find ?uuid . :where [{block_id} :block/uuid ?uuid]]")
44+
assert refs() == {"Alpha", "Beta"}
45+
46+
update("Updated note on [[Alpha]] and [[Beta]]", ["Alpha", "Beta"])
47+
update("Updated note on [[Alpha]] and [[Beta]]", ["Alpha", "Beta"])
48+
update("Only [[Alpha]]", ["Alpha"], selector="--uuid")
49+
update("New [[Created from update]] and [[Namespace/Child]]",
50+
["Created from update", "Child"])
51+
assert query('[:find (count ?e) . :where [?e :block/name "created from update"]]') == 1
52+
assert query('[:find (count ?e) . :where [?e :block/name "child"] '
53+
'[?e :block/parent ?p] [?p :block/name "namespace"]]') == 1
54+
update("Again [[Created from update]] and [[Created from update]]",
55+
["Created from update"])
56+
assert query('[:find (count ?e) . :where [?e :block/name "created from update"]]') == 1
57+
update("中文 [[参考页面]] and [[Alpha]]", ["参考页面", "Alpha"])
58+
59+
alpha_uuid = query('[:find ?uuid . :where [?e :block/name "alpha"] [?e :block/uuid ?uuid]]')
60+
update(f"Mixed [[Beta]] and [[{alpha_uuid}]]", ["Alpha", "Beta"])
61+
update(f"Mixed again [[Beta]] and [[{alpha_uuid}]]", ["Alpha", "Beta"])
62+
update(f"UUID only [[{alpha_uuid}]]", ["Alpha"])
63+
update(f"UUID only [[{alpha_uuid}]]", ["Alpha"])
64+
update("Real [[Alpha]] and `[[Ignored code]]`", ["Alpha"])
65+
assert query('[:find ?e . :where [?e :block/name "ignored code"]]') is None
66+
# Deliberately match Desktop's current global conversion, including literals.
67+
update("Case [[aLpHa]] and `[[aLpHa]]` and \\[[aLpHa]]", ["Alpha"])
68+
stored_title = query(f"[:find ?title . :where [{block_id} :block/title ?title]]")
69+
assert stored_title == (f"Case [[{alpha_uuid}]] and `[[{alpha_uuid}]]` "
70+
f"and \\[[{alpha_uuid}]]"), stored_title
71+
update("literal ` then [[Created after unmatched tick]]", ["Created after unmatched tick"])
72+
update("literal `` then [[Created after unmatched pair]]", ["Created after unmatched pair"])
73+
update("literal `\n\n[[Created in next paragraph]]\n\n`", ["Created in next paragraph"])
74+
update("Plain content", [])
75+
update("[[Alpha]]", ["Alpha"])
76+
update("", [])
77+
update("Persisted [[Alpha]] and [[Beta]]", ["Alpha", "Beta"])
78+
run("server", "restart")
79+
assert refs() == {"Alpha", "Beta"}
80+
81+
run("upsert", "block", "--id", "999999999", "--content", "[[Missing source page]]", error=True)
82+
assert query('[:find ?e . :where [?e :block/name "missing source page"]]') is None
83+
run("upsert", "block", "--id", str(block_id), "--content", "[[Rollback page]]",
84+
"--update-properties", '{:logseq.property/description 999999999}', error=True)
85+
assert refs() == {"Alpha", "Beta"}
86+
assert query('[:find ?e . :where [?e :block/name "rollback page"] '
87+
'(not [?e :logseq.property/deleted-at])]') is None
88+
# Fresh blocks avoid carrying an existing display-type into another case.
89+
for markup, raw, display, lang in (
90+
("```clojure\n[[Alpha]]\n```", "[[Alpha]]", "code", "clojure"),
91+
("$$E=mc^2$$", "E=mc^2", "math", None),
92+
):
93+
created = run("upsert", "block", "--target-page", "Home", "--content", markup)["result"][0]
94+
assert query(f"[:find ?title . :where [{created} :block/title ?title]]") == raw
95+
assert query(f"[:find ?type . :where [{created} :logseq.property.node/display-type ?type]]") == display
96+
assert query(f"[:find ?lang . :where [{created} :logseq.property.code/lang ?lang]]") == lang
97+
assert query(f"[:find ?r . :where [{created} :block/refs ?r] [?r :block/name \"alpha\"]]") is None
98+
tagged = run("upsert", "block", "--target-page", "Home", "--content", "note #InlineTag")["result"][0]
99+
tag_uuid = query('[:find ?u . :where [?e :block/name "inlinetag"] [?e :block/uuid ?u]]')
100+
assert query(f"[:find ?title . :where [{tagged} :block/title ?title]]") == f"note #[[{tag_uuid}]]"
101+
assert query(f"[:find ?r . :where [{tagged} :block/tags ?r] [?r :block/name \"inlinetag\"]]") is not None
102+
heading = run("upsert", "block", "--target-page", "Home", "--content", "## Heading [[Alpha]]")["result"][0]
103+
assert query(f"[:find ?title . :where [{heading} :block/title ?title]]") == f"Heading [[{alpha_uuid}]]"
104+
assert query(f"[:find ?level . :where [{heading} :logseq.property/heading ?level]]") == 2
105+
print("block update page refs: passed")
106+
107+
108+
if __name__ == "__main__":
109+
main()

‎cli-e2e/scripts/created_entity_results.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,12 +114,21 @@ def property_value(created):
114114
"--update-tags", '["ResultTag"]',
115115
"--update-properties", '{"Result Note" 1}', output=output)
116116
ids = result if output == "edn" else result["result"]
117-
expected = [title_id(title) for title in titles]
117+
stored_titles = titles
118+
if refs:
119+
existing_uuid = entity(reference)["block/uuid"]
120+
new_uuid = entity(title_id(new_page))["block/uuid"]
121+
stored_titles = [title.replace("[[ExistingReference]]", f"[[{existing_uuid}]]")
122+
.replace(f"[[{new_page}]]", f"[[{new_uuid}]]") for title in titles]
123+
expected = [query('[:find ?e . :where [?e :block/title ?title] '
124+
f'[(clojure.string/starts-with? ?title {json.dumps(title.split(" [[", 1)[0])})]]')
125+
for title in titles]
118126
print(f"{args.case} {source} {output} refs={refs}: {ids}; expected {expected}", flush=True)
119127
assert all(expected), expected
120128
assert entity(reference) == before, "Command metadata changed the reference page"
121129
for index, entity_id in enumerate(expected):
122130
created = entity(entity_id)
131+
assert created["block/title"] == stored_titles[index], created
123132
is_root = index in (0, 3)
124133
assert (property_value(created) == 1) == is_root, created
125134
assert any(t["db/id"] == tag for t in created.get("block/tags", [])) == is_root, created

‎cli-e2e/scripts/graph_lifecycle_protocol_test.cjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ const os = require('node:os');
55
const path = require('node:path');
66
const { fork } = require('node:child_process');
77
const { once } = require('node:events');
8-
const lifecycle = require('../../deps/graph-lifecycle');
8+
const lifecycle = require('@logseq/graph-lifecycle');
99

1010
function storage(root) { return lifecycle.resolveStorage(root, path.join(root, 'graphs')); }
1111

0 commit comments

Comments
 (0)