Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions dsh-reader/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ const ZH = {
'action.copyDiagnostics': '复制诊断信息',
'label.readerError': '阅读器出错了',
'label.nestLimit': '嵌套最多 3 层',
'label.ancestorRevisit': '这个词本链路上层已有解释,已为你打开原卡片(不重复生成)',
'label.conceptSaved': '已收下',
'label.pinned': '已固定',
'label.openFromSession': '请从会话中打开阅读视图',
Expand Down Expand Up @@ -457,6 +458,7 @@ const EN = {
'action.copyDiagnostics': 'Copy diagnostics',
'label.readerError': 'The reader hit an error',
'label.nestLimit': 'Nesting is limited to 3 levels',
'label.ancestorRevisit': 'This term is already explained one level up; showing that card instead of repeating it',
'label.conceptSaved': 'Saved',
'label.pinned': 'Pinned',
'label.openFromSession': 'Open the reader from a session',
Expand Down Expand Up @@ -4293,6 +4295,13 @@ function ReaderView(props) {
})
const concept = result.concept
if (result.store) mergeStore(result.store)
if (result.ancestor) {
// The reader walked down the chain and asked about a term that raised it:
// show that card with the reason instead of pretending it is new.
setCards((current) => replaceTop(current, { id: concept.id, pinned: true, rect, hint: t('label.ancestorRevisit') }))
flash(t('label.ancestorRevisit'))
return
}
setCards((current) => replaceTop(current, { id: concept.id, pinned: true, rect }))
flash(`${t('label.conceptSaved')}:${concept.term}`)
} catch (e) {
Expand Down Expand Up @@ -6749,6 +6758,7 @@ function ReaderView(props) {
chain.length
? h('div', { className: 'rd-muted', style: { fontSize: '11px', marginBottom: '7px' } }, chain.map((item) => item.term).join(' › '))
: null,
card.hint ? h('div', { className: 'rd-muted', style: { fontSize: '11px', marginBottom: '7px' } }, card.hint) : null,
h('div', { className: 'rd-def' }, concept.definition || ''),
concept.intuition
? h('div', { className: 'rd-sec' }, h('b', null, t('label.intuition') + ' '), concept.intuition)
Expand Down
46 changes: 43 additions & 3 deletions dsh-reader/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,27 @@ async function complete(
return reply
}

const MAX_ANCESTOR_DEPTH = 4

/**
* The cards the reader came through, farthest ancestor first. Parents are only
* ever set to an already-stored concept, but the walk keeps a visited set so a
* hand-edited or migrated store can never spin here.
*/
function ancestorChain(concepts, startId) {
const chain = []
const seen = new Set()
let current = typeof startId === 'string' && startId ? concepts?.[startId] : null
while (current && chain.length < MAX_ANCESTOR_DEPTH) {
const id = typeof current.id === 'string' && current.id ? current.id : null
if (!id || seen.has(id)) break
seen.add(id)
chain.push(current)
current = current.parentId ? concepts?.[current.parentId] : null
}
return chain.reverse()
}

async function explainConcept(ctx, cwd, body) {
const term = String(body?.term || '').trim()
if (!term) throw httpError(400, 'term required')
Expand All @@ -278,10 +299,29 @@ async function explainConcept(ctx, cwd, body) {
return Array.isArray(concept.aliases) && concept.aliases.some((alias) => normalizeTerm(alias) === key)
})
const model = pluginModel(store, ctx)
const ancestors = ancestorChain(store.concepts, body?.parentId)
const depth = body?.depth === 'full' ? 'full' : 'quick'
if (existing) {
// Asking about a concept that is already on the path the reader came down
// would hand back the very card that raised the question. Reuse it as a
// step back up instead of re-explaining it against itself.
if (ancestors.some((item) => item.id === existing.id)) {
return {
concept: existing,
reused: true,
ancestor: true,
route: 'ancestor',
chain: ancestors.map((item) => ({ id: item.id, term: item.term })),
}
}
if (depth === 'full' && existing.depth !== 'full' && existing.source !== 'user') {
const { system, user } = buildExplainPrompt({ term: existing.term, sentence, paragraph, docTitle: body?.docTitle })
const { system, user } = buildExplainPrompt({
term: existing.term,
sentence,
paragraph,
docTitle: body?.docTitle,
ancestors,
})
const parsed = parseExplanation(
await complete(ctx, {
system,
Expand Down Expand Up @@ -365,8 +405,8 @@ async function explainConcept(ctx, cwd, body) {

const quick = depth === 'quick'
const { system, user } = quick
? buildQuickExplainPrompt({ term, sentence, docTitle: body?.docTitle })
: buildExplainPrompt({ term, sentence, paragraph, docTitle: body?.docTitle })
? buildQuickExplainPrompt({ term, sentence, docTitle: body?.docTitle, ancestors })
: buildExplainPrompt({ term, sentence, paragraph, docTitle: body?.docTitle, ancestors })
const quickEffort = quick ? await pickEffort(ctx, model.provider, model.model, 'low') : null
// Single-flight: two readers explaining the same term share one model call.
const inflightKey = `${cwd}|${key}|${depth}`
Expand Down
27 changes: 25 additions & 2 deletions dsh-reader/lib/explain.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,23 @@ function strings(value, limit) {
return Array.isArray(value) ? value.filter((x) => typeof x === 'string' && x.trim()).slice(0, limit) : []
}

const NESTED_RULE =
'如果「词条」本身就是某个上层概念或它的别名,不要重复该概念已有的定义,改为说明它在这段话里具体指什么、与上层概念的差别。'

/** Ancestors of the card the reader is looking at, farthest first. */
function ancestorLines(ancestors) {
const list = (Array.isArray(ancestors) ? ancestors : []).filter((item) => item && text(item.term))
if (list.length === 0) return []
return [
'',
'上层解释(从远到近,读者正在看这些卡片):',
...list.map(
(item, index) =>
`${index + 1}. ${text(item.term)}${text(item.definition) ? ':' + text(item.definition).slice(0, 120) : ''}`,
),
]
}

/** Turn one model reply into concept fields, tolerating fences and prose. */
export function parseExplanation(reply) {
const raw = String(reply ?? '')
Expand Down Expand Up @@ -109,22 +126,26 @@ export function buildAskPrompt({ concept, question, related = [], web = null })
}

/** Compact first-pass explanation: two fields, low latency. */
export function buildQuickExplainPrompt({ term, sentence, docTitle }) {
export function buildQuickExplainPrompt({ term, sentence, docTitle, ancestors = [] }) {
const layered = ancestorLines(ancestors)
const system = [
'你是阅读助手。读者只需要快速理解这个词。',
'只输出一个 JSON 对象:{"definition":"一句话定义,60 字以内","intuition":"一句话直觉或比喻,40 字以内","examples":["一个短例子"]}。',
'不要展开长文;不确定就直说。',
...(layered.length ? [NESTED_RULE] : []),
].join('')
const user = [
`书名:${text(docTitle) || '未知'}`,
`原文:${text(sentence).slice(0, 300)}`,
`词条:${text(term)}`,
...layered,
].join('\n')
return { system, user }
}

/** Build the single-shot explanation prompt; never send more than one paragraph. */
export function buildExplainPrompt({ term, sentence, paragraph, docTitle }) {
export function buildExplainPrompt({ term, sentence, paragraph, docTitle, ancestors = [] }) {
const layered = ancestorLines(ancestors)
const system = [
'你是阅读助手,帮助读者理解正在读的书里的概念。',
'只输出一个 JSON 对象,不要输出其他文字。字段:',
Expand All @@ -133,12 +154,14 @@ export function buildExplainPrompt({ term, sentence, paragraph, docTitle }) {
'context:结合这本书的语境说明为什么这里用它,不超过 80 字;',
'examples:0-3 个短例子;related:0-3 个相关概念名。',
'不确定时用“可能指 A 或 B”表达,禁止编造。',
...(layered.length ? [NESTED_RULE] : []),
].join('')
const user = [
`书名:${text(docTitle) || '未知'}`,
`概念:${text(term)}`,
`所在句:${text(sentence).slice(0, 240)}`,
`所在段落:${text(paragraph).slice(0, 600)}`,
...layered,
'请输出 JSON。',
].join('\n')
return { system, user }
Expand Down
8 changes: 8 additions & 0 deletions dsh-reader/src/client/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -1019,6 +1019,13 @@ export function ReaderView(props) {
})
const concept = result.concept
if (result.store) mergeStore(result.store)
if (result.ancestor) {
// The reader walked down the chain and asked about a term that raised it:
// show that card with the reason instead of pretending it is new.
setCards((current) => replaceTop(current, { id: concept.id, pinned: true, rect, hint: t('label.ancestorRevisit') }))
flash(t('label.ancestorRevisit'))
return
}
setCards((current) => replaceTop(current, { id: concept.id, pinned: true, rect }))
flash(`${t('label.conceptSaved')}:${concept.term}`)
} catch (e) {
Expand Down Expand Up @@ -3475,6 +3482,7 @@ export function ReaderView(props) {
chain.length
? h('div', { className: 'rd-muted', style: { fontSize: '11px', marginBottom: '7px' } }, chain.map((item) => item.term).join(' › '))
: null,
card.hint ? h('div', { className: 'rd-muted', style: { fontSize: '11px', marginBottom: '7px' } }, card.hint) : null,
h('div', { className: 'rd-def' }, concept.definition || ''),
concept.intuition
? h('div', { className: 'rd-sec' }, h('b', null, t('label.intuition') + ' '), concept.intuition)
Expand Down
2 changes: 2 additions & 0 deletions dsh-reader/src/client/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ const ZH = {
'action.copyDiagnostics': '复制诊断信息',
'label.readerError': '阅读器出错了',
'label.nestLimit': '嵌套最多 3 层',
'label.ancestorRevisit': '这个词本链路上层已有解释,已为你打开原卡片(不重复生成)',
'label.conceptSaved': '已收下',
'label.pinned': '已固定',
'label.openFromSession': '请从会话中打开阅读视图',
Expand Down Expand Up @@ -411,6 +412,7 @@ const EN = {
'action.copyDiagnostics': 'Copy diagnostics',
'label.readerError': 'The reader hit an error',
'label.nestLimit': 'Nesting is limited to 3 levels',
'label.ancestorRevisit': 'This term is already explained one level up; showing that card instead of repeating it',
'label.conceptSaved': 'Saved',
'label.pinned': 'Pinned',
'label.openFromSession': 'Open the reader from a session',
Expand Down
Loading
Loading