mirror of
https://github.com/fancive/obsidian-parallel-reader.git
synced 2026-07-22 06:53:43 +00:00
Compare commits
27 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6519633459 | ||
|
|
2278129f03 | ||
|
|
7986f1c308 | ||
|
|
5f36b1218b | ||
|
|
c45f7987e3 | ||
|
|
2faf1729f2 | ||
|
|
68bfed7f56 | ||
|
|
052aa13547 | ||
|
|
606593e39b | ||
|
|
de66de5b5c | ||
|
|
955a86e2c5 | ||
|
|
9473ff8434 | ||
|
|
5a5baf0910 | ||
|
|
617cc9b668 | ||
|
|
50c76f528e | ||
|
|
714b6a368b | ||
|
|
d00075779e | ||
|
|
04428950de | ||
|
|
07faeddab5 | ||
|
|
a57743e7e2 | ||
|
|
d738fc120a | ||
|
|
89464608aa | ||
|
|
65cb81730a | ||
|
|
7d5bfffecf | ||
|
|
33371cadd6 | ||
|
|
83dc9b2874 | ||
|
|
e4b2ae3e22 |
57 changed files with 9264 additions and 534 deletions
21
.c8rc.json
Normal file
21
.c8rc.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"all": false,
|
||||
"src": ["src"],
|
||||
"include": ["src/**/*.ts", "main.ts"],
|
||||
"exclude": [
|
||||
"src/test-exports.ts",
|
||||
"tests/**",
|
||||
"scripts/**",
|
||||
".e2e/**",
|
||||
"**/node_modules/**"
|
||||
],
|
||||
"excludeAfterRemap": true,
|
||||
"reporter": ["text-summary", "text", "html", "json-summary"],
|
||||
"reportsDirectory": "coverage",
|
||||
"tempDirectory": "coverage/.tmp",
|
||||
"check-coverage": true,
|
||||
"branches": 100,
|
||||
"statements": 0,
|
||||
"lines": 0,
|
||||
"functions": 0
|
||||
}
|
||||
|
|
@ -98,6 +98,10 @@ class FakeElement {
|
|||
return this.createEl('div', options);
|
||||
}
|
||||
|
||||
createSpan(options = {}) {
|
||||
return this.createEl('span', options);
|
||||
}
|
||||
|
||||
addEventListener(type, handler) {
|
||||
if (typeof handler !== 'function') return;
|
||||
if (!this._listeners.has(type)) this._listeners.set(type, []);
|
||||
|
|
|
|||
9
.github/workflows/ci.yml
vendored
9
.github/workflows/ci.yml
vendored
|
|
@ -24,6 +24,15 @@ jobs:
|
|||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
- name: Lint (Obsidian review rules)
|
||||
run: npm run lint:obsidian
|
||||
|
||||
- name: Lint (Obsidian strict review)
|
||||
run: npm run lint:obsidian:review:all
|
||||
|
||||
- name: Coverage (branch threshold)
|
||||
run: npm run coverage
|
||||
|
||||
- name: E2E gate
|
||||
run: timeout 600 npm run e2e
|
||||
|
||||
|
|
|
|||
12
.github/workflows/release.yml
vendored
12
.github/workflows/release.yml
vendored
|
|
@ -44,7 +44,11 @@ jobs:
|
|||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
tag="${GITHUB_REF#refs/tags/}"
|
||||
gh release create "$tag" \
|
||||
--title "$tag" \
|
||||
--generate-notes \
|
||||
main.js main.js.map manifest.json styles.css
|
||||
if gh release view "$tag" >/dev/null 2>&1; then
|
||||
gh release upload "$tag" --clobber main.js main.js.map manifest.json styles.css
|
||||
else
|
||||
gh release create "$tag" \
|
||||
--title "$tag" \
|
||||
--generate-notes \
|
||||
main.js main.js.map manifest.json styles.css
|
||||
fi
|
||||
|
|
|
|||
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -18,6 +18,10 @@ dist/
|
|||
main.js
|
||||
main.js.map
|
||||
|
||||
# Coverage
|
||||
coverage/
|
||||
.test-bundles/
|
||||
|
||||
# Agent state
|
||||
.agent/
|
||||
.claude/
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
<a href="https://github.com/fancive/obsidian-parallel-reader/releases"><img src="https://img.shields.io/github/downloads/fancive/obsidian-parallel-reader/total?style=flat-square&color=4c1" alt="Total downloads"></a>
|
||||
<a href="https://github.com/fancive/obsidian-parallel-reader/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/fancive/obsidian-parallel-reader/ci.yml?style=flat-square&label=CI" alt="CI status"></a>
|
||||
<a href="./LICENSE"><img src="https://img.shields.io/github/license/fancive/obsidian-parallel-reader?style=flat-square" alt="License"></a>
|
||||
<img src="https://img.shields.io/badge/Obsidian-%E2%89%A5%201.4.0-7c3aed?style=flat-square&logo=obsidian&logoColor=white" alt="Obsidian 1.4+">
|
||||
<img src="https://img.shields.io/badge/Obsidian-%E2%89%A5%201.8.7-7c3aed?style=flat-square&logo=obsidian&logoColor=white" alt="Obsidian 1.8.7+">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
|
@ -39,7 +39,7 @@ Inspired by [this reading workflow demo](https://www.bilibili.com/video/BV1FxoGB
|
|||
- **Rich rendering** — cards render through Obsidian's `MarkdownRenderer`, so tables, bold, code, and wikilinks all work natively.
|
||||
- **Card editing** — right-click any card to copy, edit, delete, or jump to source.
|
||||
- **Export** — save cards as a Markdown note in your vault, or copy to clipboard.
|
||||
- **Bilingual UI** — full Chinese and English support for commands, settings, and notices.
|
||||
- **Multi-language UI and output** — UI supports Auto, Chinese, English, Japanese, Korean, French, German, and Spanish; generated titles, gists, and bullets can use the same fixed languages or follow the source document.
|
||||
|
||||
## Quick Start
|
||||
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
<a href="https://github.com/fancive/obsidian-parallel-reader/releases"><img src="https://img.shields.io/github/downloads/fancive/obsidian-parallel-reader/total?style=flat-square&color=4c1" alt="累计下载"></a>
|
||||
<a href="https://github.com/fancive/obsidian-parallel-reader/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/fancive/obsidian-parallel-reader/ci.yml?style=flat-square&label=CI" alt="CI 状态"></a>
|
||||
<a href="./LICENSE"><img src="https://img.shields.io/github/license/fancive/obsidian-parallel-reader?style=flat-square" alt="开源协议"></a>
|
||||
<img src="https://img.shields.io/badge/Obsidian-%E2%89%A5%201.4.0-7c3aed?style=flat-square&logo=obsidian&logoColor=white" alt="Obsidian 1.4+">
|
||||
<img src="https://img.shields.io/badge/Obsidian-%E2%89%A5%201.8.7-7c3aed?style=flat-square&logo=obsidian&logoColor=white" alt="Obsidian 1.8.7+">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
|
@ -39,7 +39,7 @@
|
|||
- **Markdown 渲染** — 通过 Obsidian 的 `MarkdownRenderer` 渲染,表格、加粗、代码、wikilink 均正常显示。
|
||||
- **卡片编辑** — 右键任意卡片:复制、编辑、删除、跳转原文。
|
||||
- **导出** — 保存为 Vault 中的 Markdown 文件,或复制到剪贴板。
|
||||
- **中英双语 UI** — 命令、设置、面板文案全部支持中文和英文。
|
||||
- **多语言 UI 与输出** — UI 支持 Auto、中文、英文、日文、韩文、法文、德文、西班牙文;生成的 title/gist/bullets 也可选择这些固定语言,或跟随原文语言。
|
||||
|
||||
## 快速开始
|
||||
|
||||
|
|
|
|||
|
|
@ -4,12 +4,7 @@ import { builtinModules } from 'module';
|
|||
const production = process.argv[2] === 'production';
|
||||
const watch = process.argv[2] === 'watch';
|
||||
|
||||
const external = [
|
||||
'obsidian',
|
||||
'electron',
|
||||
...builtinModules,
|
||||
...builtinModules.map(m => `node:${m}`),
|
||||
];
|
||||
const external = ['obsidian', 'electron', ...builtinModules, ...builtinModules.map((m) => `node:${m}`)];
|
||||
|
||||
const context = await esbuild.context({
|
||||
entryPoints: ['main.ts'],
|
||||
|
|
|
|||
36
eslint.config.mjs
Normal file
36
eslint.config.mjs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import tsparser from "@typescript-eslint/parser";
|
||||
import { defineConfig } from "eslint/config";
|
||||
import obsidianmd from "eslint-plugin-obsidianmd";
|
||||
|
||||
export default defineConfig([
|
||||
...obsidianmd.configs.recommended,
|
||||
{
|
||||
files: ["main.ts", "src/**/*.ts"],
|
||||
languageOptions: {
|
||||
parser: tsparser,
|
||||
parserOptions: { project: "./tsconfig.json" },
|
||||
},
|
||||
rules: {
|
||||
// Out-of-scope for an Obsidian plugin lint pass: TS-strict noise
|
||||
// from JSON.parse / dynamic i18n keys. Biome + tsc cover type safety.
|
||||
"@typescript-eslint/no-unsafe-assignment": "off",
|
||||
"@typescript-eslint/no-unsafe-member-access": "off",
|
||||
"@typescript-eslint/no-unsafe-argument": "off",
|
||||
"@typescript-eslint/no-unsafe-call": "off",
|
||||
"@typescript-eslint/no-unsafe-return": "off",
|
||||
},
|
||||
},
|
||||
{
|
||||
ignores: [
|
||||
"node_modules/",
|
||||
"main.js",
|
||||
"main.js.map",
|
||||
"tests/",
|
||||
"scripts/",
|
||||
".e2e/",
|
||||
".orchestration/",
|
||||
".agent/",
|
||||
".codex-tmp/",
|
||||
],
|
||||
},
|
||||
]);
|
||||
47
eslint.obsidian-review.config.mjs
Normal file
47
eslint.obsidian-review.config.mjs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import tsparser from "@typescript-eslint/parser";
|
||||
import { defineConfig } from "eslint/config";
|
||||
import obsidianmd from "eslint-plugin-obsidianmd";
|
||||
|
||||
export default defineConfig([
|
||||
...obsidianmd.configs.recommended,
|
||||
{
|
||||
files: ["main.ts", "src/**/*.ts"],
|
||||
languageOptions: {
|
||||
parser: tsparser,
|
||||
parserOptions: { project: "./tsconfig.json" },
|
||||
},
|
||||
rules: {
|
||||
// Keep this review check close to Obsidian policy rules while avoiding
|
||||
// project-specific dynamic-type noise that the ReviewBot did not report.
|
||||
"@typescript-eslint/no-unsafe-assignment": "off",
|
||||
"@typescript-eslint/no-unsafe-member-access": "off",
|
||||
"@typescript-eslint/no-unsafe-argument": "off",
|
||||
"@typescript-eslint/no-unsafe-call": "off",
|
||||
"@typescript-eslint/no-unsafe-return": "off",
|
||||
|
||||
// The ReviewBot currently reports underscore-only unused bindings as
|
||||
// Optional findings, while the published recommended config ignores them.
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"warn",
|
||||
{
|
||||
args: "all",
|
||||
caughtErrors: "all",
|
||||
ignoreRestSiblings: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
ignores: [
|
||||
"node_modules/",
|
||||
"main.js",
|
||||
"main.js.map",
|
||||
"tests/",
|
||||
"scripts/",
|
||||
".e2e/",
|
||||
".orchestration/",
|
||||
".agent/",
|
||||
".codex-tmp/",
|
||||
],
|
||||
},
|
||||
]);
|
||||
76
main.ts
76
main.ts
|
|
@ -18,6 +18,7 @@ import {
|
|||
import { shouldConfirmRegenerate } from './src/cache';
|
||||
import { CacheManager } from './src/cache-manager';
|
||||
import { resolveCardAnchors } from './src/cards';
|
||||
import { showGenerationError } from './src/error-ui';
|
||||
import { cancellationNoticeKey, summarizeDocument } from './src/generation';
|
||||
import {
|
||||
classifyGenerationError,
|
||||
|
|
@ -29,7 +30,14 @@ import { translate } from './src/i18n';
|
|||
import { cardsToMarkdown } from './src/markdown';
|
||||
import { confirmRegenerateEditedCards } from './src/modal';
|
||||
import { createRafThrottledHandler, visibleTopProbeY } from './src/scroll';
|
||||
import { cacheEntryMatches, DEFAULT_SETTINGS, normalizeSettings } from './src/settings';
|
||||
import {
|
||||
cacheEntryMatches,
|
||||
DEFAULT_SETTINGS,
|
||||
getApiAuthType,
|
||||
getApiKey,
|
||||
isApiBackend,
|
||||
normalizeSettings,
|
||||
} from './src/settings';
|
||||
import { ParallelReaderSettingTab } from './src/settings-tab';
|
||||
import type { StreamProgress } from './src/streaming';
|
||||
import type {
|
||||
|
|
@ -53,7 +61,7 @@ class ParallelReaderPlugin extends Plugin {
|
|||
jobs!: GenerationJobManager;
|
||||
activeBatch: BatchRunState | null = null;
|
||||
_scrollDispose: (() => void) | null = null;
|
||||
_settingsSaveTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
_settingsSaveTimer: number | null = null;
|
||||
|
||||
get cache(): Record<string, CacheEntry> {
|
||||
return this.cacheManager.cache;
|
||||
|
|
@ -176,7 +184,7 @@ class ParallelReaderPlugin extends Plugin {
|
|||
}
|
||||
|
||||
onunload() {
|
||||
if (this.jobs) this.jobs.cancelAllWaiters();
|
||||
if (this.jobs) this.jobs.cancelAll();
|
||||
this.flushSettingsSave().catch((e: unknown) => console.error('[parallel-reader] flush settings on unload', e));
|
||||
this.flushCacheSave().catch((e: unknown) => console.error('[parallel-reader] flush cache on unload', e));
|
||||
}
|
||||
|
|
@ -198,15 +206,15 @@ class ParallelReaderPlugin extends Plugin {
|
|||
|
||||
async saveSettings() {
|
||||
if (this._settingsSaveTimer) {
|
||||
clearTimeout(this._settingsSaveTimer);
|
||||
activeWindow.clearTimeout(this._settingsSaveTimer);
|
||||
this._settingsSaveTimer = null;
|
||||
}
|
||||
await this.saveData({ settings: this.settings });
|
||||
}
|
||||
|
||||
saveSettingsDebounced(delayMs = 400) {
|
||||
if (this._settingsSaveTimer) clearTimeout(this._settingsSaveTimer);
|
||||
this._settingsSaveTimer = setTimeout(() => {
|
||||
if (this._settingsSaveTimer) activeWindow.clearTimeout(this._settingsSaveTimer);
|
||||
this._settingsSaveTimer = activeWindow.setTimeout(() => {
|
||||
this._settingsSaveTimer = null;
|
||||
this.saveSettings().catch((e: unknown) => console.error('[parallel-reader] failed to save settings', e));
|
||||
}, delayMs);
|
||||
|
|
@ -214,7 +222,7 @@ class ParallelReaderPlugin extends Plugin {
|
|||
|
||||
async flushSettingsSave() {
|
||||
if (!this._settingsSaveTimer) return;
|
||||
clearTimeout(this._settingsSaveTimer);
|
||||
activeWindow.clearTimeout(this._settingsSaveTimer);
|
||||
this._settingsSaveTimer = null;
|
||||
await this.saveSettings();
|
||||
}
|
||||
|
|
@ -554,6 +562,9 @@ class ParallelReaderPlugin extends Plugin {
|
|||
}
|
||||
const rawCards = sections.map((s) => ({ title: s.title, anchor: s.anchor, gist: s.gist, bullets: s.bullets }));
|
||||
job.setPhase('saving');
|
||||
// Check BEFORE persisting: a job cancelled during the generate→disk window must not
|
||||
// poison the cache (a later force=false run would otherwise serve the cancelled output).
|
||||
job.throwIfCancelled();
|
||||
await this.cacheManager.put(file.path, content, rawCards, this.settings);
|
||||
job.throwIfCancelled();
|
||||
if (view && shouldRender) view.loadFor(file, sections, false);
|
||||
|
|
@ -567,7 +578,7 @@ class ParallelReaderPlugin extends Plugin {
|
|||
outcome = 'generated';
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
this.handleGenerationError(e, file, view);
|
||||
this.handleGenerationError(e, file, view, force);
|
||||
if (e instanceof GenerationJobAlreadyRunningError) outcome = 'already-running';
|
||||
else if (e instanceof GenerationJobCancelledError) outcome = 'cancelled';
|
||||
else outcome = 'error';
|
||||
|
|
@ -589,7 +600,7 @@ class ParallelReaderPlugin extends Plugin {
|
|||
};
|
||||
}
|
||||
|
||||
private handleGenerationError(e: unknown, file: TFile, view: ParallelReaderView | null) {
|
||||
private handleGenerationError(e: unknown, file: TFile, view: ParallelReaderView | null, force = false) {
|
||||
if (e instanceof GenerationJobAlreadyRunningError) {
|
||||
new Notice(this.t('generationAlreadyRunning'));
|
||||
return;
|
||||
|
|
@ -603,7 +614,48 @@ class ParallelReaderPlugin extends Plugin {
|
|||
const msg = e instanceof Error ? e.message : String(e);
|
||||
console.error(e);
|
||||
if (view && this.viewIsShowingFile(view, file)) view.renderError(file, msg);
|
||||
new Notice(this.t('generationFailed', { kind: kind === 'unknown' ? '' : ` (${kind})`, error: msg }));
|
||||
showGenerationError(
|
||||
{
|
||||
app: this.app,
|
||||
settings: this.settings,
|
||||
openSettings: () => this.openSettings(),
|
||||
onRetry: () => void this.runForFile(file, force),
|
||||
},
|
||||
kind,
|
||||
e,
|
||||
msg,
|
||||
);
|
||||
}
|
||||
|
||||
openSettings(): void {
|
||||
// Obsidian doesn't expose a typed API for opening a specific plugin tab; use the documented
|
||||
// (but technically internal) setting/openTabById path with safe fallbacks.
|
||||
const setting = (this.app as unknown as { setting?: { open: () => void; openTabById: (id: string) => void } })
|
||||
.setting;
|
||||
if (!setting) return;
|
||||
try {
|
||||
setting.open();
|
||||
setting.openTabById(this.manifest.id);
|
||||
} catch (err: unknown) {
|
||||
console.warn('[parallel-reader] failed to open settings tab', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the active backend has a usable credential: an API key (direct or via
|
||||
* env var) for API backends, or any keyless/local provider (auth type 'none').
|
||||
* CLI backends authenticate out-of-band (claude/codex login), so they are treated
|
||||
* as configured. Used to show a first-run setup nudge instead of a dead-end.
|
||||
*/
|
||||
isCredentialConfigured(): boolean {
|
||||
if (!isApiBackend(this.settings.backend)) return true;
|
||||
try {
|
||||
if (getApiAuthType(this.settings) === 'none') return true;
|
||||
return !!getApiKey(this.settings);
|
||||
} catch {
|
||||
// Settings resolution can throw for half-configured custom providers — treat as not configured.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async runBatchForFolder() {
|
||||
|
|
@ -732,7 +784,7 @@ class ParallelReaderPlugin extends Plugin {
|
|||
try {
|
||||
const pos = cm.posAtCoords({ x: rect.left + 20, y: topY });
|
||||
if (pos != null) topLine = cm.state.doc.lineAt(pos).number - 1;
|
||||
} catch (_: unknown) {
|
||||
} catch {
|
||||
/* posAtCoords/lineAt can throw during editor state transitions — safe to ignore */
|
||||
return;
|
||||
}
|
||||
|
|
@ -777,7 +829,7 @@ class ParallelReaderPlugin extends Plugin {
|
|||
try {
|
||||
mdView.editor.setCursor({ line, ch: 0 });
|
||||
mdView.editor.scrollIntoView({ from: { line, ch: 0 }, to: { line, ch: 0 } }, true);
|
||||
} catch (_: unknown) {
|
||||
} catch {
|
||||
/* setCursor/scrollIntoView can throw during view transitions — safe to ignore */
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
{
|
||||
"id": "parallel-reader",
|
||||
"name": "Parallel Reader",
|
||||
"version": "1.0.14",
|
||||
"minAppVersion": "1.4.0",
|
||||
"version": "1.0.24",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "AI-powered split-view reading: source note on the left, LLM-generated summary cards on the right with scroll-sync highlighting.",
|
||||
"author": "lancivez",
|
||||
"fundingUrl": "https://github.com/fancive",
|
||||
|
|
|
|||
5297
package-lock.json
generated
5297
package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -7,8 +7,12 @@
|
|||
"build": "node esbuild.config.mjs production",
|
||||
"dev": "node esbuild.config.mjs watch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"coverage": "c8 node scripts/run-tests.mjs --all; status=$?; rm -rf .test-bundles; exit $status",
|
||||
"lint": "biome check main.ts src/ tests/ scripts/ .e2e/scripts/",
|
||||
"lint:fix": "biome check --write main.ts src/ tests/ scripts/ .e2e/scripts/",
|
||||
"lint:obsidian": "eslint main.ts src/",
|
||||
"lint:obsidian:review": "eslint --config eslint.obsidian-review.config.mjs --no-config-lookup main.ts src/",
|
||||
"lint:obsidian:review:all": "npm run lint:obsidian:review -- --max-warnings=0",
|
||||
"version": "node scripts/bump-version.mjs",
|
||||
"test": "npm run build && npm run typecheck && node scripts/run-tests.mjs",
|
||||
"test:only": "node scripts/run-tests.mjs",
|
||||
|
|
@ -22,7 +26,11 @@
|
|||
"devDependencies": {
|
||||
"@biomejs/biome": "^2.4.13",
|
||||
"@types/node": "^22.10.2",
|
||||
"@typescript-eslint/parser": "^8.59.1",
|
||||
"c8": "^10.1.3",
|
||||
"esbuild": "^0.24.2",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-plugin-obsidianmd": "^0.2.9",
|
||||
"obsidian": "^1.7.2",
|
||||
"typescript": "^5.7.2"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,33 @@
|
|||
'use strict';
|
||||
|
||||
export function findLineForAnchor(content: string, anchor: string): number {
|
||||
// Precompute the byte offset where each line starts (offsets[k] = start of
|
||||
// line k). Built once per document so callers resolving many anchors over the
|
||||
// same content avoid an O(n) newline rescan per anchor.
|
||||
export function buildLineOffsets(content: string): number[] {
|
||||
const offsets = [0];
|
||||
for (let i = 0; i < content.length; i++) {
|
||||
if (content.charCodeAt(i) === 10) offsets.push(i + 1);
|
||||
}
|
||||
return offsets;
|
||||
}
|
||||
|
||||
// Largest line index whose start offset is <= charOffset, i.e. the 0-based
|
||||
// line containing charOffset. Equivalent to counting '\n' before charOffset
|
||||
// but O(log n) instead of O(n).
|
||||
function offsetToLine(offsets: number[], charOffset: number): number {
|
||||
let lo = 0;
|
||||
let hi = offsets.length - 1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi + 1) >> 1;
|
||||
if (offsets[mid] <= charOffset) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
export function findLineForAnchor(content: string, anchor: string, lineOffsets?: number[]): number {
|
||||
if (!anchor) return -1;
|
||||
const offsets = lineOffsets ?? buildLineOffsets(content);
|
||||
const normalize = (s: string) => s.replace(/\s+/g, ' ').trim();
|
||||
const normalizeWithMap = (s: string) => {
|
||||
const chars: string[] = [];
|
||||
|
|
@ -9,7 +35,18 @@ export function findLineForAnchor(content: string, anchor: string): number {
|
|||
let pendingWhitespace = false;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const c = s[i];
|
||||
if (/\s/.test(c)) {
|
||||
const code = s.charCodeAt(i);
|
||||
// ASCII whitespace fast path; defer to /\s/ only for rare non-ASCII
|
||||
// code points so the exact RegExp semantics are preserved.
|
||||
const isWhitespace =
|
||||
code === 32 ||
|
||||
code === 9 ||
|
||||
code === 10 ||
|
||||
code === 13 ||
|
||||
code === 12 ||
|
||||
code === 11 ||
|
||||
(code > 127 && /\s/.test(c));
|
||||
if (isWhitespace) {
|
||||
pendingWhitespace = chars.length > 0;
|
||||
continue;
|
||||
}
|
||||
|
|
@ -27,9 +64,7 @@ export function findLineForAnchor(content: string, anchor: string): number {
|
|||
if (!needle) return -1;
|
||||
const idx = content.indexOf(needle);
|
||||
if (idx === -1) return -1;
|
||||
let line = 0;
|
||||
for (let i = 0; i < idx; i++) if (content[i] === '\n') line++;
|
||||
return line;
|
||||
return offsetToLine(offsets, idx);
|
||||
};
|
||||
|
||||
let line = tryAt(anchor);
|
||||
|
|
@ -51,7 +86,5 @@ export function findLineForAnchor(content: string, anchor: string): number {
|
|||
if (normIdx === -1) return -1;
|
||||
const originalIdx = normDoc.map[normIdx];
|
||||
if (originalIdx == null) return -1;
|
||||
let l = 0;
|
||||
for (let j = 0; j < originalIdx; j++) if (content[j] === '\n') l++;
|
||||
return l;
|
||||
return offsetToLine(offsets, originalIdx);
|
||||
}
|
||||
|
|
|
|||
60
src/backend-test.ts
Normal file
60
src/backend-test.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
'use strict';
|
||||
|
||||
import { requestUrl } from 'obsidian';
|
||||
import { resolveCliPath, runCli, summarizeViaClaudeCode, summarizeViaCodex } from './cli';
|
||||
import type { RequestUrlFunction } from './provider-request';
|
||||
import { testApiBackend } from './providers';
|
||||
import { normalizeCliTimeoutMs } from './settings';
|
||||
import type { PluginSettings } from './types';
|
||||
|
||||
const CLI_TEST_SYSTEM =
|
||||
'Return only valid JSON with exactly one card: {"cards":[{"title":"CLI smoke","anchor":"parallel reader smoke anchor","gist":"ok","bullets":["ok"]}]}';
|
||||
const CLI_TEST_USER = 'parallel reader smoke anchor';
|
||||
const CLI_TEST_TIMEOUT_MS = 60000;
|
||||
|
||||
type SpawnImpl = Parameters<typeof runCli>[5];
|
||||
|
||||
interface BackendTestDeps {
|
||||
requestUrlImpl?: RequestUrlFunction;
|
||||
spawnImpl?: SpawnImpl;
|
||||
}
|
||||
|
||||
function cliSmokeSettings(settings: PluginSettings): PluginSettings {
|
||||
return {
|
||||
...settings,
|
||||
cliTimeoutMs: Math.min(normalizeCliTimeoutMs(settings.cliTimeoutMs), CLI_TEST_TIMEOUT_MS),
|
||||
minCards: 1,
|
||||
maxCards: 1,
|
||||
maxDocChars: 1000,
|
||||
};
|
||||
}
|
||||
|
||||
export async function testBackend(settings: PluginSettings, deps: BackendTestDeps = {}): Promise<string> {
|
||||
if (settings.backend === 'claude-code') {
|
||||
const cmd = resolveCliPath('claude', settings.cliPath);
|
||||
const version = await runCli(cmd, ['--version'], '', 10000, undefined, deps.spawnImpl);
|
||||
const cards = await summarizeViaClaudeCode(
|
||||
CLI_TEST_SYSTEM,
|
||||
CLI_TEST_USER,
|
||||
cliSmokeSettings(settings),
|
||||
undefined,
|
||||
deps.spawnImpl,
|
||||
);
|
||||
return `claude @ ${cmd}\n${version.stdout.trim()}\nsmoke: ${cards.length} card`;
|
||||
}
|
||||
|
||||
if (settings.backend === 'codex') {
|
||||
const cmd = resolveCliPath('codex', settings.cliPath);
|
||||
const version = await runCli(cmd, ['--version'], '', 10000, undefined, deps.spawnImpl);
|
||||
const cards = await summarizeViaCodex(
|
||||
CLI_TEST_SYSTEM,
|
||||
CLI_TEST_USER,
|
||||
cliSmokeSettings(settings),
|
||||
undefined,
|
||||
deps.spawnImpl,
|
||||
);
|
||||
return `codex @ ${cmd}\n${version.stdout.trim()}\nsmoke: ${cards.length} card`;
|
||||
}
|
||||
|
||||
return testApiBackend(deps.requestUrlImpl || requestUrl, settings);
|
||||
}
|
||||
|
|
@ -34,7 +34,7 @@ function isValidCacheEntry(entry: unknown): entry is CacheEntry {
|
|||
|
||||
export class CacheManager {
|
||||
cache: Record<string, CacheEntry> = {};
|
||||
private _timer: ReturnType<typeof setTimeout> | null = null;
|
||||
private _timer: number | null = null;
|
||||
private _dirty = false;
|
||||
|
||||
constructor(
|
||||
|
|
@ -53,7 +53,7 @@ export class CacheManager {
|
|||
try {
|
||||
if (typeof this.adapter.exists === 'function' && (await this.adapter.exists(dir))) return;
|
||||
await this.adapter.mkdir(dir);
|
||||
} catch (_) {
|
||||
} catch {
|
||||
/* ignore race */
|
||||
}
|
||||
}
|
||||
|
|
@ -104,7 +104,7 @@ export class CacheManager {
|
|||
|
||||
async save(): Promise<void> {
|
||||
if (this._timer) {
|
||||
clearTimeout(this._timer);
|
||||
activeWindow.clearTimeout(this._timer);
|
||||
this._timer = null;
|
||||
}
|
||||
this.prune();
|
||||
|
|
@ -115,7 +115,7 @@ export class CacheManager {
|
|||
scheduleSave(delayMs = 5000): void {
|
||||
this._dirty = true;
|
||||
if (this._timer) return;
|
||||
this._timer = setTimeout(() => {
|
||||
this._timer = activeWindow.setTimeout(() => {
|
||||
this._timer = null;
|
||||
if (!this._dirty) return;
|
||||
this.save().catch((e: unknown) => console.error('[parallel-reader] failed to save cache', e));
|
||||
|
|
@ -124,7 +124,7 @@ export class CacheManager {
|
|||
|
||||
async flush(): Promise<void> {
|
||||
if (this._timer) {
|
||||
clearTimeout(this._timer);
|
||||
activeWindow.clearTimeout(this._timer);
|
||||
this._timer = null;
|
||||
}
|
||||
if (!this._dirty) return;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
'use strict';
|
||||
|
||||
import { findLineForAnchor } from './anchor';
|
||||
import { buildLineOffsets, findLineForAnchor } from './anchor';
|
||||
import type { CardPatch, RawCard, ResolvedCard } from './types';
|
||||
|
||||
export function removeCardAt<T extends RawCard>(cards: T[], index: number): T[] {
|
||||
|
|
@ -29,12 +29,15 @@ export function updateCardAt<T extends RawCard>(cards: T[], index: number, patch
|
|||
}
|
||||
|
||||
export function resolveCardAnchors(content: string, rawCards: RawCard[]): ResolvedCard[] {
|
||||
// Build the line-offset index once and reuse it for every card instead of
|
||||
// rescanning the whole document per anchor.
|
||||
const lineOffsets = buildLineOffsets(content);
|
||||
const resolved: ResolvedCard[] = (rawCards || []).map((c: RawCard) => ({
|
||||
title: c.title,
|
||||
level: 2,
|
||||
anchor: c.anchor,
|
||||
gist: c.gist,
|
||||
startLine: findLineForAnchor(content, c.anchor),
|
||||
startLine: findLineForAnchor(content, c.anchor, lineOffsets),
|
||||
bullets: c.bullets || [],
|
||||
}));
|
||||
resolved.sort((a, b) => {
|
||||
|
|
|
|||
244
src/cli.ts
244
src/cli.ts
|
|
@ -44,7 +44,7 @@ export function resolveCliPath(name: string, override: string): string {
|
|||
const p = path.join(dir, name + ext);
|
||||
try {
|
||||
if (fs.existsSync(p)) return p;
|
||||
} catch (_) {
|
||||
} catch {
|
||||
// Ignore unreadable candidate paths and keep searching.
|
||||
}
|
||||
}
|
||||
|
|
@ -52,6 +52,90 @@ export function resolveCliPath(name: string, override: string): string {
|
|||
return name;
|
||||
}
|
||||
|
||||
type CliFailureReason = 'wall-timeout' | 'exit-nonzero' | 'streams-unavailable' | 'spawn-failure' | 'startup-error';
|
||||
|
||||
export interface CliErrorDetails {
|
||||
reason: CliFailureReason;
|
||||
cmd: string;
|
||||
pid: number | null;
|
||||
elapsedMs: number;
|
||||
/** ms since the last byte of stdout/stderr — useful to tell hung-mid-call from hung-from-start. */
|
||||
idleMs: number | null;
|
||||
stdoutBytes: number;
|
||||
stderrBytes: number;
|
||||
/** Already secret-redacted, capped to DIAG_STDERR_TAIL_CHARS. */
|
||||
stderrTail: string;
|
||||
/** Already secret-redacted, capped to DIAG_STDOUT_TAIL_CHARS. */
|
||||
stdoutTail: string;
|
||||
exitCode: number | null;
|
||||
signal: NodeJS.Signals | null;
|
||||
timeoutMs: number;
|
||||
}
|
||||
|
||||
export class CliProcessError extends Error {
|
||||
readonly name = 'CliProcessError';
|
||||
readonly details: CliErrorDetails;
|
||||
|
||||
constructor(message: string, details: CliErrorDetails) {
|
||||
super(message);
|
||||
this.details = details;
|
||||
}
|
||||
}
|
||||
|
||||
const DIAG_STDERR_TAIL_CHARS = 1500;
|
||||
const DIAG_STDOUT_TAIL_CHARS = 1500;
|
||||
const EMPTY_MCP_CONFIG = '{"mcpServers":{}}';
|
||||
|
||||
function tail(text: string, max: number): string {
|
||||
if (text.length <= max) return text;
|
||||
return text.slice(-max);
|
||||
}
|
||||
|
||||
const REDACT = '[REDACTED]';
|
||||
function redactSecrets(text: string): string {
|
||||
if (!text) return text;
|
||||
return text
|
||||
.replace(/\b(Bearer)\s+[\w.\-+/=]{6,}/gi, `$1 ${REDACT}`)
|
||||
.replace(/\b(x-api-key|x-goog-api-key|api[_-]?key|authorization)\s*[:=]\s*[\w.\-+/=]{6,}/gi, `$1: ${REDACT}`)
|
||||
.replace(/\b(sk-[A-Za-z0-9_-]{12,})/g, REDACT);
|
||||
}
|
||||
|
||||
function utf8ByteLength(text: string): number {
|
||||
return Buffer.byteLength(text, 'utf8');
|
||||
}
|
||||
|
||||
function claudeResultText(stdout: string): string {
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
try {
|
||||
const parsed = JSON.parse(stdout);
|
||||
if (Array.isArray(parsed)) {
|
||||
events.push(...(parsed.filter((e) => e && typeof e === 'object') as Array<Record<string, unknown>>));
|
||||
} else if (parsed && typeof parsed === 'object') {
|
||||
events.push(parsed as Record<string, unknown>);
|
||||
}
|
||||
} catch {
|
||||
for (const line of stdout.split(/\r?\n/)) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (parsed && typeof parsed === 'object') events.push(parsed as Record<string, unknown>);
|
||||
} catch {
|
||||
// Ignore non-JSON progress lines and keep scanning for result events.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = events.length - 1; i >= 0; i--) {
|
||||
const event = events[i];
|
||||
if (event.type === 'result' && typeof event.result === 'string') return event.result;
|
||||
}
|
||||
const single = events[0];
|
||||
if (single && typeof single.result === 'string') return single.result;
|
||||
if (single && typeof single.content === 'string') return single.content;
|
||||
return '';
|
||||
}
|
||||
|
||||
export function runCli(
|
||||
cmd: string,
|
||||
args: string[],
|
||||
|
|
@ -63,21 +147,48 @@ export function runCli(
|
|||
return new Promise<{ stdout: string; stderr: string }>((resolve, reject) => {
|
||||
let child: ReturnType<typeof spawn>;
|
||||
let settled = false;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let timer: number | null = null;
|
||||
const startedAt = Date.now();
|
||||
let lastActivityAt = startedAt;
|
||||
const clearTimers = () => {
|
||||
if (timer) {
|
||||
activeWindow.clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
};
|
||||
const fail = (err: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
clearTimers();
|
||||
console.warn('[parallel-reader] cli failed', {
|
||||
cmd,
|
||||
pid: child?.pid,
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
error: err.message,
|
||||
});
|
||||
reject(err);
|
||||
};
|
||||
const succeed = (value: { stdout: string; stderr: string }) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
clearTimers();
|
||||
console.debug('[parallel-reader] cli ok', {
|
||||
cmd,
|
||||
pid: child?.pid,
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
stdoutBytes: utf8ByteLength(value.stdout),
|
||||
stderrBytes: utf8ByteLength(value.stderr),
|
||||
});
|
||||
resolve(value);
|
||||
};
|
||||
try {
|
||||
child = spawnImpl(cmd, args, {
|
||||
// Lock cwd to the user's home dir. Inheriting Obsidian's cwd (often the Vault path)
|
||||
// can break Claude CLI's per-project memory writes — iCloud-synced Vault paths
|
||||
// contain characters like `~md~` that produce malformed `~/.claude/projects/...`
|
||||
// slugs and an immediate exit-1 with empty modelUsage. Home dir is stable and
|
||||
// writable; the LLM call itself is independent of cwd.
|
||||
cwd: os.homedir(),
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env: {
|
||||
...process.env,
|
||||
|
|
@ -93,19 +204,75 @@ export function runCli(
|
|||
},
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
return reject(new Error(`Failed to start ${cmd}: ${e instanceof Error ? e.message : String(e)}`));
|
||||
const message = `Failed to start ${cmd}: ${e instanceof Error ? e.message : String(e)}`;
|
||||
console.warn('[parallel-reader] cli spawn failed', { cmd, error: message });
|
||||
return reject(
|
||||
new CliProcessError(message, {
|
||||
reason: 'spawn-failure',
|
||||
cmd,
|
||||
pid: null,
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
idleMs: null,
|
||||
stdoutBytes: 0,
|
||||
stderrBytes: 0,
|
||||
stdoutTail: '',
|
||||
stderrTail: '',
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
timeoutMs,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
console.debug('[parallel-reader] cli spawn', {
|
||||
cmd,
|
||||
argCount: args.length,
|
||||
pid: child?.pid,
|
||||
timeoutMs,
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
timer = setTimeout(() => {
|
||||
|
||||
const collectDetails = (
|
||||
reason: CliFailureReason,
|
||||
idleMs: number,
|
||||
extras: { exitCode?: number | null; signal?: NodeJS.Signals | null } = {},
|
||||
): CliErrorDetails => ({
|
||||
reason,
|
||||
cmd,
|
||||
pid: child?.pid ?? null,
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
idleMs,
|
||||
stdoutBytes: utf8ByteLength(stdout),
|
||||
stderrBytes: utf8ByteLength(stderr),
|
||||
stdoutTail: redactSecrets(tail(stdout, DIAG_STDOUT_TAIL_CHARS)),
|
||||
stderrTail: redactSecrets(tail(stderr, DIAG_STDERR_TAIL_CHARS)),
|
||||
exitCode: extras.exitCode ?? null,
|
||||
signal: extras.signal ?? null,
|
||||
timeoutMs,
|
||||
});
|
||||
|
||||
const buildDiagSuffix = (details: CliErrorDetails): string => {
|
||||
let suffix =
|
||||
` [pid=${details.pid ?? 'unknown'} elapsed=${details.elapsedMs}ms idle=${details.idleMs ?? 0}ms ` +
|
||||
`stdout=${details.stdoutBytes}B stderr=${details.stderrBytes}B]`;
|
||||
if (details.stderrTail) suffix += `\n--- stderr tail ---\n${details.stderrTail}`;
|
||||
if (details.stdoutTail) suffix += `\n--- stdout tail ---\n${details.stdoutTail}`;
|
||||
return suffix;
|
||||
};
|
||||
|
||||
timer = activeWindow.setTimeout(() => {
|
||||
try {
|
||||
child.kill('SIGKILL');
|
||||
} catch (e: unknown) {
|
||||
console.warn('[parallel-reader] failed to kill timed-out CLI process', e);
|
||||
}
|
||||
fail(new Error(`CLI timed out (${timeoutMs}ms)`));
|
||||
const idleMs = Date.now() - lastActivityAt;
|
||||
const details = collectDetails('wall-timeout', idleMs, { signal: 'SIGKILL' });
|
||||
fail(new CliProcessError(`CLI timed out (${timeoutMs}ms)${buildDiagSuffix(details)}`, details));
|
||||
}, timeoutMs);
|
||||
|
||||
if (job) {
|
||||
job.onCancel(() => {
|
||||
try {
|
||||
|
|
@ -118,7 +285,7 @@ export function runCli(
|
|||
}
|
||||
|
||||
if (!child.stdout || !child.stderr || !child.stdin) {
|
||||
fail(new Error('CLI process streams are unavailable'));
|
||||
fail(new CliProcessError('CLI process streams are unavailable', collectDetails('streams-unavailable', 0)));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -126,19 +293,41 @@ export function runCli(
|
|||
const childStderr = child.stderr;
|
||||
const childStdin = child.stdin;
|
||||
|
||||
const noteActivity = () => {
|
||||
if (settled) return;
|
||||
lastActivityAt = Date.now();
|
||||
};
|
||||
|
||||
childStdout.on('data', (d) => {
|
||||
stdout += d.toString('utf8');
|
||||
noteActivity();
|
||||
});
|
||||
childStderr.on('data', (d) => {
|
||||
stderr += d.toString('utf8');
|
||||
noteActivity();
|
||||
});
|
||||
child.on('error', (e) => {
|
||||
fail(new Error(`CLI startup error: ${e.message}. Try setting an absolute CLI path.`));
|
||||
const idleMs = Date.now() - lastActivityAt;
|
||||
fail(
|
||||
new CliProcessError(
|
||||
`CLI startup error: ${e.message}. Try setting an absolute CLI path.`,
|
||||
collectDetails('startup-error', idleMs),
|
||||
),
|
||||
);
|
||||
});
|
||||
child.on('close', (code) => {
|
||||
child.on('close', (code, signal) => {
|
||||
if (settled) return;
|
||||
if (code !== 0) {
|
||||
return fail(new Error(`CLI exited with code ${code}\nstderr:\n${stderr.slice(0, 1000)}`));
|
||||
const idleMs = Date.now() - lastActivityAt;
|
||||
const details = collectDetails('exit-nonzero', idleMs, { exitCode: code, signal });
|
||||
// Some CLIs (notably `claude --output-format json`) emit error events to stdout
|
||||
// instead of stderr. Always include both tails so the failure mode is debuggable
|
||||
// even when stderr is empty.
|
||||
let suffix = '';
|
||||
if (details.stderrTail) suffix += `\nstderr:\n${details.stderrTail}`;
|
||||
if (details.stdoutTail) suffix += `\nstdout:\n${details.stdoutTail}`;
|
||||
if (!suffix) suffix = '\n(no output on either stream)';
|
||||
return fail(new CliProcessError(`CLI exited with code ${code} (signal=${signal ?? 'none'})${suffix}`, details));
|
||||
}
|
||||
succeed({ stdout, stderr });
|
||||
});
|
||||
|
|
@ -147,7 +336,7 @@ export function runCli(
|
|||
try {
|
||||
childStdin.write(stdinText);
|
||||
childStdin.end();
|
||||
} catch (_e) {
|
||||
} catch {
|
||||
// Child may have exited before stdin was written.
|
||||
}
|
||||
} else {
|
||||
|
|
@ -171,38 +360,33 @@ export async function summarizeViaClaudeCode(
|
|||
const args = [
|
||||
'-p',
|
||||
'--output-format',
|
||||
'json',
|
||||
'stream-json',
|
||||
'--verbose',
|
||||
'--append-system-prompt',
|
||||
system,
|
||||
'--tools',
|
||||
'',
|
||||
'--disallowed-tools',
|
||||
'Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch,TodoWrite,Task',
|
||||
'Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch,TodoWrite,Task,LSP,NotebookEdit',
|
||||
'--no-session-persistence',
|
||||
'--disable-slash-commands',
|
||||
'--no-chrome',
|
||||
'--strict-mcp-config',
|
||||
'--mcp-config',
|
||||
EMPTY_MCP_CONFIG,
|
||||
];
|
||||
const claudeModel = (settings.model || '').trim();
|
||||
if (claudeModel) args.push('--model', claudeModel);
|
||||
const { stdout } = await runCli(cmd, args, user, settings.cliTimeoutMs, job, spawnImpl);
|
||||
|
||||
// --output-format json produces a JSON array of event objects.
|
||||
// Find the "result" entry and extract its .result text field.
|
||||
let resultText = '';
|
||||
try {
|
||||
const events = JSON.parse(stdout);
|
||||
if (Array.isArray(events)) {
|
||||
const resultEvent = events.find((e: Record<string, unknown>) => e.type === 'result');
|
||||
if (resultEvent && typeof resultEvent.result === 'string') {
|
||||
resultText = resultEvent.result;
|
||||
}
|
||||
} else if (events && typeof events === 'object') {
|
||||
// Older CLI versions return a single object
|
||||
resultText = events.result || events.content || '';
|
||||
}
|
||||
} catch (_) {
|
||||
const resultText = claudeResultText(stdout);
|
||||
if (!resultText && stdout.trim()) {
|
||||
console.warn(
|
||||
'[parallel-reader] claude CLI returned unexpected output. length=',
|
||||
stdout.length,
|
||||
'head=',
|
||||
stdout.slice(0, 80),
|
||||
);
|
||||
throw new Error(translate(settings, 'errorClaudeCliBadJson', { length: String(stdout.length) }));
|
||||
}
|
||||
|
||||
if (!resultText) {
|
||||
|
|
|
|||
242
src/error-ui.ts
Normal file
242
src/error-ui.ts
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
'use strict';
|
||||
|
||||
import { type App, Modal, Notice, Setting } from 'obsidian';
|
||||
import type { CliErrorDetails } from './cli';
|
||||
import { translate } from './i18n';
|
||||
import type { ErrorKind, PluginSettings } from './types';
|
||||
import { copyToClipboard } from './ui-helpers';
|
||||
|
||||
interface GenerationErrorContext {
|
||||
app: App;
|
||||
settings: PluginSettings;
|
||||
/** Open the plugin settings tab (best-effort; falls back to no-op if unavailable). */
|
||||
openSettings: () => void;
|
||||
/** Re-run the generation that failed (used by retryable error kinds such as network). */
|
||||
onRetry?: () => void;
|
||||
}
|
||||
|
||||
interface ActionableNoticeAction {
|
||||
label: string;
|
||||
primary?: boolean;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
function showActionableNotice(message: string, actions: ActionableNoticeAction[], durationMs = 12000): Notice {
|
||||
const notice = new Notice('', durationMs);
|
||||
const root = notice.messageEl;
|
||||
root.addClass('parallel-reader-error-notice');
|
||||
root.createDiv({ cls: 'parallel-reader-error-notice-message', text: message });
|
||||
if (actions.length > 0) {
|
||||
const buttonRow = root.createDiv({ cls: 'parallel-reader-error-notice-actions' });
|
||||
for (const action of actions) {
|
||||
const btn = buttonRow.createEl('button', {
|
||||
cls: action.primary ? 'parallel-reader-error-notice-button mod-cta' : 'parallel-reader-error-notice-button',
|
||||
text: action.label,
|
||||
attr: { type: 'button' },
|
||||
});
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
try {
|
||||
action.onClick();
|
||||
} catch (err: unknown) {
|
||||
console.error('[parallel-reader] error notice action failed', err);
|
||||
} finally {
|
||||
notice.hide();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
return notice;
|
||||
}
|
||||
|
||||
function reasonCopyKeys(reason: CliErrorDetails['reason']): { titleKey: string; reasonKey: string } {
|
||||
switch (reason) {
|
||||
case 'wall-timeout':
|
||||
return { titleKey: 'errorModalTimeoutTitle', reasonKey: 'errorModalReasonWall' };
|
||||
case 'exit-nonzero':
|
||||
return { titleKey: 'errorModalExitTitle', reasonKey: 'errorModalReasonExit' };
|
||||
case 'spawn-failure':
|
||||
case 'startup-error':
|
||||
return { titleKey: 'errorModalStartupTitle', reasonKey: 'errorModalReasonStartup' };
|
||||
default:
|
||||
return { titleKey: 'errorModalTimeoutTitle', reasonKey: 'errorModalReasonWall' };
|
||||
}
|
||||
}
|
||||
|
||||
class CliDiagnosticsModal extends Modal {
|
||||
private readonly settings: PluginSettings;
|
||||
private readonly details: CliErrorDetails;
|
||||
private readonly fullMessage: string;
|
||||
private readonly onOpenSettings: () => void;
|
||||
|
||||
constructor(
|
||||
app: App,
|
||||
settings: PluginSettings,
|
||||
details: CliErrorDetails,
|
||||
fullMessage: string,
|
||||
onOpenSettings: () => void,
|
||||
) {
|
||||
super(app);
|
||||
this.settings = settings;
|
||||
this.details = details;
|
||||
this.fullMessage = fullMessage;
|
||||
this.onOpenSettings = onOpenSettings;
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
const { contentEl } = this;
|
||||
contentEl.empty();
|
||||
contentEl.addClass('parallel-reader-error-modal');
|
||||
const { titleKey, reasonKey } = reasonCopyKeys(this.details.reason);
|
||||
contentEl.createEl('h2', { text: translate(this.settings, titleKey) });
|
||||
contentEl.createEl('p', { text: translate(this.settings, reasonKey) });
|
||||
if (this.details.exitCode != null) {
|
||||
contentEl.createEl('p', {
|
||||
cls: 'parallel-reader-error-modal-exit',
|
||||
text: translate(this.settings, 'errorModalFieldExit', {
|
||||
code: String(this.details.exitCode),
|
||||
signal: this.details.signal ?? 'none',
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const grid = contentEl.createDiv({ cls: 'parallel-reader-error-modal-grid' });
|
||||
const addRow = (label: string, value: string) => {
|
||||
const row = grid.createDiv({ cls: 'parallel-reader-error-modal-row' });
|
||||
row.createSpan({ cls: 'parallel-reader-error-modal-label', text: label });
|
||||
row.createSpan({ cls: 'parallel-reader-error-modal-value', text: value });
|
||||
};
|
||||
addRow(translate(this.settings, 'errorModalFieldCmd'), this.details.cmd);
|
||||
addRow(translate(this.settings, 'errorModalFieldPid'), String(this.details.pid ?? '—'));
|
||||
addRow(translate(this.settings, 'errorModalFieldElapsed'), `${this.details.elapsedMs}ms`);
|
||||
addRow(
|
||||
translate(this.settings, 'errorModalFieldIdle'),
|
||||
this.details.idleMs == null ? '—' : `${this.details.idleMs}ms`,
|
||||
);
|
||||
addRow(
|
||||
translate(this.settings, 'errorModalFieldBytes'),
|
||||
`stdout ${this.details.stdoutBytes}B / stderr ${this.details.stderrBytes}B`,
|
||||
);
|
||||
|
||||
let hasOutput = false;
|
||||
if (this.details.stderrTail) {
|
||||
contentEl.createEl('h3', { text: translate(this.settings, 'errorModalStderrTail') });
|
||||
contentEl.createEl('pre', { cls: 'parallel-reader-error-modal-tail', text: this.details.stderrTail });
|
||||
hasOutput = true;
|
||||
}
|
||||
if (this.details.stdoutTail) {
|
||||
contentEl.createEl('h3', { text: translate(this.settings, 'errorModalStdoutTail') });
|
||||
contentEl.createEl('pre', { cls: 'parallel-reader-error-modal-tail', text: this.details.stdoutTail });
|
||||
hasOutput = true;
|
||||
}
|
||||
if (!hasOutput) {
|
||||
contentEl.createEl('p', {
|
||||
cls: 'parallel-reader-error-modal-empty',
|
||||
text: translate(this.settings, 'errorModalNoOutput'),
|
||||
});
|
||||
}
|
||||
|
||||
new Setting(contentEl)
|
||||
.addButton((b) =>
|
||||
b.setButtonText(translate(this.settings, 'errorModalActionCopy')).onClick(() => {
|
||||
void copyToClipboard(this.fullMessage, translate(this.settings, 'errorModalCopySuccess'));
|
||||
}),
|
||||
)
|
||||
.addButton((b) =>
|
||||
b
|
||||
.setButtonText(translate(this.settings, 'errorModalActionOpenSettings'))
|
||||
.setCta()
|
||||
.onClick(() => {
|
||||
this.onOpenSettings();
|
||||
this.close();
|
||||
}),
|
||||
)
|
||||
.addButton((b) => b.setButtonText(translate(this.settings, 'errorModalActionClose')).onClick(() => this.close()));
|
||||
}
|
||||
|
||||
onClose(): void {
|
||||
this.contentEl.empty();
|
||||
}
|
||||
}
|
||||
|
||||
export function showGenerationError(
|
||||
ctx: GenerationErrorContext,
|
||||
kind: ErrorKind,
|
||||
error: unknown,
|
||||
message: string,
|
||||
): void {
|
||||
const tr = (k: string, vars?: Record<string, string | number>) => translate(ctx.settings, k, vars);
|
||||
|
||||
// Any structured CLI error opens the diagnostics modal — even when classify falls
|
||||
// through to 'unknown' (e.g. exit-nonzero with empty stderr) we want the stdout tail
|
||||
// surfaced so the failure is debuggable.
|
||||
const cliDetails = (error as { details?: CliErrorDetails }).details;
|
||||
const isStructuredCliError = !!cliDetails && typeof cliDetails.reason === 'string';
|
||||
if (isStructuredCliError) {
|
||||
new CliDiagnosticsModal(ctx.app, ctx.settings, cliDetails, message, ctx.openSettings).open();
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind === 'timeout') {
|
||||
// API streaming timeout: no structured details, show actionable notice with raw message tail.
|
||||
showActionableNotice(tr('errorNoticeTimeout'), [
|
||||
{
|
||||
label: tr('errorActionCopyDetails'),
|
||||
onClick: () => void copyToClipboard(message, tr('errorModalCopySuccess')),
|
||||
},
|
||||
{ label: tr('errorActionOpenSettings'), primary: true, onClick: ctx.openSettings },
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind === 'auth') {
|
||||
showActionableNotice(tr('errorNoticeAuth'), [
|
||||
{ label: tr('errorActionOpenSettings'), primary: true, onClick: ctx.openSettings },
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind === 'rate-limit') {
|
||||
showActionableNotice(tr('errorNoticeRateLimit', { error: message }), [
|
||||
{
|
||||
label: tr('errorActionCopyDetails'),
|
||||
onClick: () => void copyToClipboard(message, tr('errorModalCopySuccess')),
|
||||
},
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind === 'network') {
|
||||
const actions: ActionableNoticeAction[] = [];
|
||||
if (ctx.onRetry) actions.push({ label: tr('errorActionRetry'), primary: true, onClick: ctx.onRetry });
|
||||
actions.push({
|
||||
label: tr('errorActionCopyDetails'),
|
||||
onClick: () => void copyToClipboard(message, tr('errorModalCopySuccess')),
|
||||
});
|
||||
showActionableNotice(tr('errorNoticeNetwork'), actions);
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind === 'schema') {
|
||||
showActionableNotice(tr('errorNoticeSchema'), [
|
||||
{
|
||||
label: tr('errorActionCopyRaw'),
|
||||
primary: true,
|
||||
onClick: () => void copyToClipboard(message, tr('errorModalCopySuccess')),
|
||||
},
|
||||
{ label: tr('errorActionOpenSettings'), onClick: ctx.openSettings },
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind === 'config') {
|
||||
showActionableNotice(tr('errorNoticeConfig', { error: message }), [
|
||||
{ label: tr('errorActionOpenSettings'), primary: true, onClick: ctx.openSettings },
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
// Unknown / fallback: keep the legacy short Notice with kind tag, no buttons.
|
||||
new Notice(tr('generationFailed', { kind: kind === 'unknown' ? '' : ` (${kind})`, error: message }));
|
||||
}
|
||||
|
|
@ -155,13 +155,9 @@ export class GenerationJobManager {
|
|||
if (this.isPending(key)) throw new GenerationJobAlreadyRunningError(key);
|
||||
const wait = this.waitSlot(key);
|
||||
if (wait) {
|
||||
try {
|
||||
await wait;
|
||||
} catch (err) {
|
||||
// Cancelled while queued (cancelAllWaiters) — slot was never reserved
|
||||
// for this caller, so no releaseSlot is needed.
|
||||
throw err;
|
||||
}
|
||||
// If cancelled while queued (cancelAllWaiters), the slot was never reserved
|
||||
// for this caller, so no releaseSlot is needed — propagation is enough.
|
||||
await wait;
|
||||
if (this.jobs.has(key)) {
|
||||
// Same-key racily inserted while we waited; release the slot we got.
|
||||
this.reserved--;
|
||||
|
|
@ -193,16 +189,53 @@ export class GenerationJobManager {
|
|||
if (!job) return false;
|
||||
return job.cancel();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel every in-flight job — firing each job's cancel handlers, which abort the
|
||||
* streaming HTTP request and SIGKILL any CLI child process — and reject all queued
|
||||
* waiters. Used on plugin unload so nothing keeps running after teardown. Returns
|
||||
* the total number of jobs and waiters cancelled.
|
||||
*/
|
||||
cancelAll(): number {
|
||||
let cancelled = 0;
|
||||
for (const job of this.jobs.values()) {
|
||||
if (job.cancel()) cancelled++;
|
||||
}
|
||||
return cancelled + this.cancelAllWaiters();
|
||||
}
|
||||
}
|
||||
|
||||
export function classifyGenerationError(error: unknown): ErrorKind {
|
||||
if (error instanceof GenerationJobCancelledError) return 'cancelled';
|
||||
const errObj = error as { code?: string; message?: string } | null;
|
||||
if (errObj?.code === 'cancelled') return 'cancelled';
|
||||
|
||||
// Structured CLI error short-circuits message-regex matching for the deterministic cases.
|
||||
// Duck-typed to avoid circular import with ./cli.
|
||||
const details = (error as { details?: { reason?: string } } | null)?.details;
|
||||
if (details && typeof details.reason === 'string') {
|
||||
switch (details.reason) {
|
||||
case 'wall-timeout':
|
||||
return 'timeout';
|
||||
case 'spawn-failure':
|
||||
case 'startup-error':
|
||||
return 'config';
|
||||
case 'streams-unavailable':
|
||||
return 'unknown';
|
||||
// exit-nonzero falls through: stderr might carry auth/rate-limit/schema info.
|
||||
}
|
||||
}
|
||||
|
||||
const message = String(errObj?.message || error);
|
||||
if (/api key|unauthorized|401|403|认证|权限/i.test(message)) return 'auth';
|
||||
if (/timeout|超时|timed out/i.test(message)) return 'timeout';
|
||||
if (/429|rate limit|too many requests/i.test(message)) return 'rate-limit';
|
||||
if (
|
||||
/ECONNREFUSED|ENOTFOUND|ENETUNREACH|EAI_AGAIN|ECONNRESET|EHOSTUNREACH|Failed to fetch|NetworkError|net::ERR_|fetch failed/i.test(
|
||||
message,
|
||||
)
|
||||
)
|
||||
return 'network';
|
||||
if (
|
||||
/非 JSON|非预期输出|没有返回结果|non-JSON|unexpected output|no result|json_schema|schema|structured/i.test(message)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
import { requestUrl } from 'obsidian';
|
||||
import { findLineForAnchor } from './anchor';
|
||||
import { buildLineOffsets, findLineForAnchor } from './anchor';
|
||||
import { summarizeViaClaudeCode, summarizeViaCodex } from './cli';
|
||||
import type { GenerationJob } from './generation-job-manager';
|
||||
import { buildPrompts } from './prompt';
|
||||
|
|
@ -30,19 +30,27 @@ export async function summarizeDocument(
|
|||
if (useStreaming) {
|
||||
const abortController = new AbortController();
|
||||
job.onCancel(() => abortController.abort());
|
||||
cards = await summarizeViaApiStreaming(system, user, settings, onStreamProgress, abortController.signal);
|
||||
cards = await summarizeViaApiStreaming(
|
||||
requestUrl,
|
||||
system,
|
||||
user,
|
||||
settings,
|
||||
onStreamProgress,
|
||||
abortController.signal,
|
||||
);
|
||||
} else {
|
||||
cards = await summarizeViaApi(requestUrl, system, user, settings);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
const lineOffsets = buildLineOffsets(content);
|
||||
const resolved: ResolvedCard[] = cards.map((c) => ({
|
||||
title: c.title,
|
||||
level: 2,
|
||||
anchor: c.anchor,
|
||||
gist: c.gist,
|
||||
startLine: findLineForAnchor(content, c.anchor),
|
||||
startLine: findLineForAnchor(content, c.anchor, lineOffsets),
|
||||
bullets: c.bullets,
|
||||
}));
|
||||
resolved.sort((a, b) => {
|
||||
|
|
|
|||
1282
src/i18n-strings.ts
1282
src/i18n-strings.ts
File diff suppressed because it is too large
Load diff
17
src/i18n.ts
17
src/i18n.ts
|
|
@ -3,14 +3,23 @@
|
|||
import { STRINGS } from './i18n-strings';
|
||||
import type { PluginSettings } from './types';
|
||||
|
||||
export { STRINGS } from './i18n-strings';
|
||||
export { LOCALE_OVERRIDES, STRINGS } from './i18n-strings';
|
||||
|
||||
function supportedBaseLanguage(value: unknown): string | null {
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const base = value.trim().toLowerCase().split(/[-_]/)[0];
|
||||
return base && STRINGS[base] ? base : null;
|
||||
}
|
||||
|
||||
export function resolveUiLanguage(settings: Pick<PluginSettings, 'uiLanguage'> | null): string {
|
||||
const configured = settings?.uiLanguage;
|
||||
if (configured === 'zh' || configured === 'en') return configured;
|
||||
if (configured && configured !== 'auto') {
|
||||
return supportedBaseLanguage(configured) || 'en';
|
||||
}
|
||||
const nav = typeof navigator !== 'undefined' ? navigator : null;
|
||||
const language = String(nav?.language || '').toLowerCase();
|
||||
return language.startsWith('zh') ? 'zh' : 'en';
|
||||
return supportedBaseLanguage(nav?.language) || 'en';
|
||||
}
|
||||
|
||||
export function translate(
|
||||
|
|
|
|||
|
|
@ -3,21 +3,51 @@
|
|||
import { DEFAULT_SETTINGS, MAX_DOC_CHARS, normalizeCardCount, PROMPT_LANGUAGES } from './settings';
|
||||
import type { PluginSettings, PromptPair } from './types';
|
||||
|
||||
const PROMPT_LANGUAGE_INSTRUCTIONS: Record<string, string> = {
|
||||
auto: 'Write title, gist, and bullets in the main language of the source document.',
|
||||
zh: '用中文输出 title、gist 和 bullets。',
|
||||
en: 'Write title, gist, and bullets in English.',
|
||||
ja: 'Write title, gist, and bullets in Japanese.',
|
||||
ko: 'Write title, gist, and bullets in Korean.',
|
||||
fr: 'Write title, gist, and bullets in French.',
|
||||
de: 'Write title, gist, and bullets in German.',
|
||||
es: 'Write title, gist, and bullets in Spanish.',
|
||||
};
|
||||
|
||||
const PROMPT_SCHEMA_EXAMPLES: Record<string, string> = {
|
||||
zh: `{"cards":[
|
||||
{"title":"U 型收益曲线","anchor":"那谁又会被 AI 所受益?整体来看,它把整个分数变成了一分到七分","gist":"AI 生产力收益呈 U 型,两端受益最大、中间层塌陷","bullets":["最高薪岗位(软件管理)通过加速既有工作受益最大","最低薪岗位(外卖员、园艺工)用 AI 开副业创造新收入","中间层科学家、律师收益最少,部分因对 prompt 精度信任不足","全体均分 5.1/7,42% 报告收益模糊"]}
|
||||
]}`,
|
||||
en: `{"cards":[
|
||||
{"title":"U-shaped gains","anchor":"Who benefits from AI? Overall, it shifts the score from one to seven","gist":"AI productivity gains form a U shape, with both ends benefiting most","bullets":["Top-paid software managers benefit by accelerating existing work","Low-paid workers use AI to create new side income","Middle-layer specialists gain less because prompt precision is hard to trust","Average reported benefit is 5.1/7, with 42% describing gains as unclear"]}
|
||||
]}`,
|
||||
ja: `{"cards":[
|
||||
{"title":"U字型の利益","anchor":"Who benefits from AI? Overall, it shifts the score from one to seven","gist":"AIによる生産性向上はU字型になり、両端の層がもっとも大きな恩恵を受ける","bullets":["高所得のソフトウェア管理職は既存業務を加速できるため大きく恩恵を受ける","低所得の労働者はAIを使って新しい副収入を作り出せる","中間層の専門職は、プロンプト精度への信頼が難しいため利益が小さい","平均利益は5.1/7で、42%が効果は不明確だと報告している"]}
|
||||
]}`,
|
||||
ko: `{"cards":[
|
||||
{"title":"U자형 이득","anchor":"Who benefits from AI? Overall, it shifts the score from one to seven","gist":"AI 생산성 향상은 U자형을 보이며 양끝 집단이 가장 큰 혜택을 얻는다","bullets":["고소득 소프트웨어 관리자는 기존 업무를 더 빠르게 처리해 큰 이득을 얻는다","저소득 노동자는 AI로 새로운 부수입 기회를 만들 수 있다","중간층 전문가는 프롬프트 정확도를 신뢰하기 어려워 상대적으로 이득이 작다","평균 체감 이득은 5.1/7이며 42%는 효과가 불명확하다고 답했다"]}
|
||||
]}`,
|
||||
fr: `{"cards":[
|
||||
{"title":"Gains en U","anchor":"Who benefits from AI? Overall, it shifts the score from one to seven","gist":"Les gains de productivité liés à l'AI forment une courbe en U, les deux extrémités en profitant le plus","bullets":["Les managers logiciels très rémunérés gagnent surtout en accélérant leur travail existant","Les travailleurs peu rémunérés utilisent l'AI pour créer de nouveaux revenus complémentaires","Les spécialistes intermédiaires gagnent moins, car la précision des prompts reste difficile à fiabiliser","Le bénéfice moyen déclaré est de 5,1/7, avec 42% de gains jugés peu clairs"]}
|
||||
]}`,
|
||||
de: `{"cards":[
|
||||
{"title":"U-förmige Gewinne","anchor":"Who benefits from AI? Overall, it shifts the score from one to seven","gist":"AI-Produktivitätsgewinne bilden eine U-Form, bei der beide Enden am stärksten profitieren","bullets":["Hochbezahlte Softwaremanager profitieren, weil sie bestehende Arbeit beschleunigen","Geringverdienende nutzen AI, um neue Nebeneinnahmen zu schaffen","Spezialisten in der Mitte gewinnen weniger, weil präzise Prompts schwer zu vertrauen sind","Der gemeldete Durchschnittsnutzen liegt bei 5,1/7; 42% beschreiben die Gewinne als unklar"]}
|
||||
]}`,
|
||||
es: `{"cards":[
|
||||
{"title":"Ganancias en forma de U","anchor":"Who benefits from AI? Overall, it shifts the score from one to seven","gist":"Las mejoras de productividad con AI forman una U: los extremos son quienes más se benefician","bullets":["Los gerentes de software mejor pagados se benefician al acelerar su trabajo existente","Los trabajadores con menores ingresos usan AI para crear nuevas fuentes de ingreso","Los especialistas intermedios ganan menos porque es difícil confiar en la precisión del prompt","El beneficio medio reportado es 5,1/7, con un 42% que describe las ganancias como poco claras"]}
|
||||
]}`,
|
||||
};
|
||||
|
||||
function usesEnglishPromptShell(language: string): boolean {
|
||||
return language !== 'zh' && language !== 'auto';
|
||||
}
|
||||
|
||||
export function promptLanguageInstruction(language: string): string {
|
||||
if (language === 'en') return 'Write title, gist, and bullets in English.';
|
||||
if (language === 'auto') return 'Write title, gist, and bullets in the main language of the source document.';
|
||||
return '用中文输出 title、gist 和 bullets。';
|
||||
return PROMPT_LANGUAGE_INSTRUCTIONS[language] || PROMPT_LANGUAGE_INSTRUCTIONS.zh;
|
||||
}
|
||||
|
||||
export function promptSchemaExample(language: string): string {
|
||||
if (language === 'en') {
|
||||
return `{"cards":[
|
||||
{"title":"U-shaped gains","anchor":"Who benefits from AI? Overall, it shifts the score from one to seven","gist":"AI productivity gains form a U shape, with both ends benefiting most","bullets":["Top-paid software managers benefit by accelerating existing work","Low-paid workers use AI to create new side income","Middle-layer specialists gain less because prompt precision is hard to trust","Average reported benefit is 5.1/7, with 42% describing gains as unclear"]}
|
||||
]}`;
|
||||
}
|
||||
return `{"cards":[
|
||||
{"title":"U 型收益曲线","anchor":"那谁又会被 AI 所受益?整体来看,它把整个分数变成了一分到七分","gist":"AI 生产力收益呈 U 型,两端受益最大、中间层塌陷","bullets":["最高薪岗位(软件管理)通过加速既有工作受益最大","最低薪岗位(外卖员、园艺工)用 AI 开副业创造新收入","中间层科学家、律师收益最少,部分因对 prompt 精度信任不足","全体均分 5.1/7,42% 报告收益模糊"]}
|
||||
]}`;
|
||||
return PROMPT_SCHEMA_EXAMPLES[language] || PROMPT_SCHEMA_EXAMPLES.zh;
|
||||
}
|
||||
|
||||
export function renderPromptTemplate(template: string, vars: Record<string, string | number>): string {
|
||||
|
|
@ -34,7 +64,7 @@ function defaultSystemPrompt(
|
|||
schema: string,
|
||||
example: string,
|
||||
): string {
|
||||
if (language === 'en') {
|
||||
if (usesEnglishPromptShell(language)) {
|
||||
return `You are a long-form reading summary assistant. After reading the full document, split it into ${minCards}-${maxCards} natural topic units. They do not need to match markdown headings; use a complete argument or topic as the unit, merging short sections and splitting long ones when needed.
|
||||
|
||||
Each card has one guiding sentence plus several bullets. Bullets carry details; gist is the lead-in.
|
||||
|
|
@ -98,7 +128,7 @@ function systemPromptContract(
|
|||
languageInstruction: string,
|
||||
schema: string,
|
||||
): string {
|
||||
if (language === 'en') {
|
||||
if (usesEnglishPromptShell(language)) {
|
||||
return `Non-overridable output contract:
|
||||
- Must output ${minCards}-${maxCards} cards.
|
||||
- ${languageInstruction}
|
||||
|
|
@ -125,7 +155,7 @@ export function buildPrompts(content: string, settings: PluginSettings): PromptP
|
|||
const doc =
|
||||
content.length > maxDocChars
|
||||
? content.slice(0, maxDocChars) +
|
||||
(promptLanguage === 'en' ? '\n\n[Document truncated]' : '\n\n[文档过长,已截断]')
|
||||
(usesEnglishPromptShell(promptLanguage) ? '\n\n[Document truncated]' : '\n\n[文档过长,已截断]')
|
||||
: content;
|
||||
|
||||
const schema = '{"cards":[{"title":"...","anchor":"...","gist":"...","bullets":["...","..."]}]}';
|
||||
|
|
@ -141,6 +171,8 @@ export function buildPrompts(content: string, settings: PluginSettings): PromptP
|
|||
${contract}`
|
||||
: defaultSystem;
|
||||
|
||||
const user = promptLanguage === 'en' ? `Source document:\n\n${doc}` : `以下是需要处理的文档全文:\n\n${doc}`;
|
||||
const user = usesEnglishPromptShell(promptLanguage)
|
||||
? `Source document:\n\n${doc}`
|
||||
: `以下是需要处理的文档全文:\n\n${doc}`;
|
||||
return { system, user };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import type { PluginSettings } from './types';
|
|||
|
||||
/* ---------- Body type interfaces ---------- */
|
||||
|
||||
export interface AnthropicMessagesBody {
|
||||
interface AnthropicMessagesBody {
|
||||
model: string;
|
||||
max_tokens: number;
|
||||
system: string;
|
||||
|
|
@ -22,7 +22,7 @@ export interface AnthropicMessagesBody {
|
|||
stream?: boolean;
|
||||
}
|
||||
|
||||
export interface OpenAiChatBody {
|
||||
interface OpenAiChatBody {
|
||||
model: string;
|
||||
messages: Array<{ role: string; content: string }>;
|
||||
response_format?: unknown;
|
||||
|
|
@ -30,7 +30,7 @@ export interface OpenAiChatBody {
|
|||
[tokenField: string]: unknown;
|
||||
}
|
||||
|
||||
export interface OpenAiResponsesBody {
|
||||
interface OpenAiResponsesBody {
|
||||
model: string;
|
||||
instructions: string;
|
||||
input: string;
|
||||
|
|
@ -46,7 +46,7 @@ interface GeminiGenerationConfig {
|
|||
responseJsonSchema?: unknown;
|
||||
}
|
||||
|
||||
export interface GeminiBody {
|
||||
interface GeminiBody {
|
||||
systemInstruction: { parts: Array<{ text: string }> };
|
||||
contents: Array<{ role: string; parts: Array<{ text: string }> }>;
|
||||
generationConfig: GeminiGenerationConfig;
|
||||
|
|
|
|||
|
|
@ -11,6 +11,22 @@ export type RequestUrlFunction = (params: {
|
|||
throw?: boolean;
|
||||
}) => Promise<{ status: number; json: unknown; text: string }>;
|
||||
|
||||
/**
|
||||
* Thrown when a provider responds with HTTP >= 400. Carries the raw status code
|
||||
* and response body so callers can make locale-independent decisions (e.g. the
|
||||
* structured-output fallback) instead of pattern-matching a translated message.
|
||||
*/
|
||||
export class ProviderApiError extends Error {
|
||||
readonly status: number;
|
||||
readonly body: string;
|
||||
constructor(message: string, status: number, body: string) {
|
||||
super(message);
|
||||
this.name = 'ProviderApiError';
|
||||
this.status = status;
|
||||
this.body = body;
|
||||
}
|
||||
}
|
||||
|
||||
export function endpointUrl(baseUrl: string, suffixes: string[]) {
|
||||
const base = baseUrl.replace(/\/+$/, '');
|
||||
for (const suffix of suffixes) {
|
||||
|
|
@ -65,24 +81,43 @@ export async function requestJsonBody(
|
|||
}
|
||||
|
||||
if (resp.status >= 400) {
|
||||
throw new Error(
|
||||
throw new ProviderApiError(
|
||||
translate(settings || null, 'errorProviderApiStatus', {
|
||||
label,
|
||||
status: resp.status,
|
||||
excerpt: (resp.text || '').slice(0, 500),
|
||||
}),
|
||||
resp.status,
|
||||
resp.text || '',
|
||||
);
|
||||
}
|
||||
return responseJson(resp, label, settings);
|
||||
}
|
||||
|
||||
// Bare `unknown`/`unrecognized` were intentionally dropped: they false-positive on
|
||||
// model-name errors ("unknown model", "unrecognized model ID") and trigger a wasted
|
||||
// fallback retry. The specific feature tokens + bare `schema` cover real structured-
|
||||
// output rejections (e.g. "Unknown field: responseSchema" still matches `schema`).
|
||||
const STRUCTURED_OUTPUT_REJECTION_KEYWORDS =
|
||||
/response_format|json_schema|responseJsonSchema|responseMimeType|tools?|tool_choice|unsupported|schema/i;
|
||||
const STRUCTURED_OUTPUT_FALLBACK_STATUSES = new Set([400, 404, 422]);
|
||||
|
||||
export function shouldRetryWithoutStructuredOutput(error: unknown): boolean {
|
||||
// Preferred path: decide on the locale-independent HTTP status + raw provider body.
|
||||
// The error message is i18n-translated, so matching it would only work for the two
|
||||
// languages whose templates happen to contain the English/Chinese status phrasing.
|
||||
if (error instanceof ProviderApiError) {
|
||||
if (!STRUCTURED_OUTPUT_FALLBACK_STATUSES.has(error.status)) return false;
|
||||
return (
|
||||
STRUCTURED_OUTPUT_REJECTION_KEYWORDS.test(error.body) || STRUCTURED_OUTPUT_REJECTION_KEYWORDS.test(error.message)
|
||||
);
|
||||
}
|
||||
// Fallback for errors without a status (e.g. wrapped transport failures): keep the
|
||||
// legacy English/Chinese template match so existing behavior is preserved.
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (!/(?:API (?:400|404|422):|API returned HTTP (?:400|404|422)|API 返回 HTTP (?:400|404|422))/.test(message))
|
||||
return false;
|
||||
return /response_format|json_schema|responseJsonSchema|responseMimeType|tools?|tool_choice|unsupported|unrecognized|unknown|schema/i.test(
|
||||
message,
|
||||
);
|
||||
return STRUCTURED_OUTPUT_REJECTION_KEYWORDS.test(message);
|
||||
}
|
||||
|
||||
export async function requestJsonBodyWithStructuredFallback(
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ import {
|
|||
getApiPreset,
|
||||
modelForApi,
|
||||
} from './settings';
|
||||
import { deltaExtractorForFormat, type StreamProgress, streamingFetch } from './streaming';
|
||||
import { deltaExtractorForFormat, type StreamProgress, streamingRequestUrl } from './streaming';
|
||||
import type { PluginSettings, RawCard } from './types';
|
||||
|
||||
export {
|
||||
|
|
@ -193,7 +193,7 @@ async function summarizeViaGoogleGenerativeAi(
|
|||
return parseCardsJson(textFromGoogleGenerativeAiResponse(json), settings);
|
||||
}
|
||||
|
||||
// Obsidian's requestUrl is not directly compatible with fetch — we accept it as a typed callback
|
||||
// Accept Obsidian's requestUrl as a typed callback so tests can inject the transport.
|
||||
export async function summarizeViaApi(
|
||||
requestUrlImpl: RequestUrlFunction,
|
||||
system: string,
|
||||
|
|
@ -220,6 +220,7 @@ export function supportsStreaming(settings: PluginSettings): boolean {
|
|||
}
|
||||
|
||||
async function streamSummarizeViaOpenAiChat(
|
||||
requestUrlImpl: RequestUrlFunction,
|
||||
system: string,
|
||||
user: string,
|
||||
settings: PluginSettings,
|
||||
|
|
@ -231,11 +232,12 @@ async function streamSummarizeViaOpenAiChat(
|
|||
const body = buildOpenAiChatBody(system, user, settings, { structured: false });
|
||||
body.stream = true;
|
||||
const extractor = requiredDeltaExtractor('openai-chat');
|
||||
const text = await streamingFetch(url, headers, body, extractor, onProgress, signal, settings);
|
||||
const text = await streamingRequestUrl(requestUrlImpl, url, headers, body, extractor, onProgress, signal, settings);
|
||||
return parseCardsJson(text.trim(), settings);
|
||||
}
|
||||
|
||||
async function streamSummarizeViaAnthropicMessages(
|
||||
requestUrlImpl: RequestUrlFunction,
|
||||
system: string,
|
||||
user: string,
|
||||
settings: PluginSettings,
|
||||
|
|
@ -247,11 +249,12 @@ async function streamSummarizeViaAnthropicMessages(
|
|||
const body = buildAnthropicMessagesBody(system, user, settings, { structured: false });
|
||||
body.stream = true;
|
||||
const extractor = requiredDeltaExtractor('anthropic-messages');
|
||||
const text = await streamingFetch(url, headers, body, extractor, onProgress, signal, settings);
|
||||
const text = await streamingRequestUrl(requestUrlImpl, url, headers, body, extractor, onProgress, signal, settings);
|
||||
return parseCardsJson(text.trim(), settings);
|
||||
}
|
||||
|
||||
export async function summarizeViaApiStreaming(
|
||||
requestUrlImpl: RequestUrlFunction,
|
||||
system: string,
|
||||
user: string,
|
||||
settings: PluginSettings,
|
||||
|
|
@ -261,15 +264,15 @@ export async function summarizeViaApiStreaming(
|
|||
const format = getApiFormat(settings);
|
||||
switch (format) {
|
||||
case 'openai-chat':
|
||||
return streamSummarizeViaOpenAiChat(system, user, settings, onProgress, signal);
|
||||
return streamSummarizeViaOpenAiChat(requestUrlImpl, system, user, settings, onProgress, signal);
|
||||
case 'anthropic-messages':
|
||||
return streamSummarizeViaAnthropicMessages(system, user, settings, onProgress, signal);
|
||||
return streamSummarizeViaAnthropicMessages(requestUrlImpl, system, user, settings, onProgress, signal);
|
||||
default:
|
||||
throw new Error(`Streaming not supported for format: ${format}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Obsidian's requestUrl is not directly compatible with fetch — we accept it as a typed callback
|
||||
// Accept Obsidian's requestUrl as a typed callback so tests can inject the transport.
|
||||
export async function testApiBackend(requestUrlImpl: RequestUrlFunction, settings: PluginSettings): Promise<string> {
|
||||
await summarizeViaApi(requestUrlImpl, '只输出 JSON:{"cards":[]}', '连通性测试:请原样输出 {"cards":[]}', settings);
|
||||
const format = getApiFormat(settings);
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ export function extractJson(text: string): string {
|
|||
try {
|
||||
JSON.parse(raw);
|
||||
return raw;
|
||||
} catch (_) {
|
||||
} catch {
|
||||
/* continue */
|
||||
}
|
||||
|
||||
|
|
@ -58,7 +58,7 @@ export function extractJson(text: string): string {
|
|||
try {
|
||||
JSON.parse(fenced);
|
||||
return fenced;
|
||||
} catch (_) {
|
||||
} catch {
|
||||
/* continue */
|
||||
}
|
||||
}
|
||||
|
|
@ -69,7 +69,7 @@ export function extractJson(text: string): string {
|
|||
try {
|
||||
JSON.parse(c);
|
||||
return c;
|
||||
} catch (_) {
|
||||
} catch {
|
||||
/* skip */
|
||||
}
|
||||
}
|
||||
|
|
@ -94,7 +94,7 @@ export function repairTruncatedCardsJson(text: string): string | null {
|
|||
try {
|
||||
JSON.parse(c);
|
||||
validCards.push(c);
|
||||
} catch (_) {
|
||||
} catch {
|
||||
/* skip malformed card */
|
||||
}
|
||||
}
|
||||
|
|
@ -107,7 +107,7 @@ export function parseCardsJson(text: string, settings?: PluginSettings | null):
|
|||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(jsonText);
|
||||
} catch (_e) {
|
||||
} catch {
|
||||
// Attempt to salvage complete cards from truncated output
|
||||
const repaired = repairTruncatedCardsJson(text);
|
||||
if (repaired) {
|
||||
|
|
@ -119,7 +119,7 @@ export function parseCardsJson(text: string, settings?: PluginSettings | null):
|
|||
'complete cards. Consider increasing max tokens.',
|
||||
);
|
||||
return normalizeCardsPayload(parsed, settings);
|
||||
} catch (_) {
|
||||
} catch {
|
||||
/* repair failed, fall through to error */
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,12 +29,12 @@ export function visibleTopProbeY(
|
|||
type ScheduleId = { readonly __brand: 'ScheduleId'; readonly raw: number | ReturnType<typeof setTimeout> };
|
||||
|
||||
function wrapId(raw: number | ReturnType<typeof setTimeout>): ScheduleId {
|
||||
return { __brand: 'ScheduleId', raw } as ScheduleId;
|
||||
return { __brand: 'ScheduleId', raw };
|
||||
}
|
||||
|
||||
function defaultSchedule(callback: FrameRequestCallback): ScheduleId {
|
||||
if (typeof requestAnimationFrame === 'function') return wrapId(requestAnimationFrame(callback));
|
||||
return wrapId(setTimeout(() => callback(Date.now()), FALLBACK_FRAME_MS));
|
||||
return wrapId(activeWindow.setTimeout(() => callback(Date.now()), FALLBACK_FRAME_MS));
|
||||
}
|
||||
|
||||
function defaultCancel(id: ScheduleId) {
|
||||
|
|
@ -42,7 +42,7 @@ function defaultCancel(id: ScheduleId) {
|
|||
cancelAnimationFrame(id.raw as number);
|
||||
return;
|
||||
}
|
||||
clearTimeout(id.raw as ReturnType<typeof setTimeout>);
|
||||
activeWindow.clearTimeout(id.raw as number);
|
||||
}
|
||||
|
||||
export function createRafThrottledHandler(
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
import { type App, Notice, type Plugin, PluginSettingTab, requestUrl, Setting } from 'obsidian';
|
||||
import { resolveCliPath, runCli } from './cli';
|
||||
import { testApiBackend } from './providers';
|
||||
import { type App, Notice, type Plugin, PluginSettingTab, Setting } from 'obsidian';
|
||||
import { testBackend } from './backend-test';
|
||||
import {
|
||||
API_AUTH_TYPES,
|
||||
API_FORMATS,
|
||||
|
|
@ -20,18 +19,19 @@ import {
|
|||
} from './settings';
|
||||
import type { PluginHost, PluginSettings } from './types';
|
||||
|
||||
async function testBackend(settings: PluginSettings) {
|
||||
if (settings.backend === 'claude-code') {
|
||||
const cmd = resolveCliPath('claude', settings.cliPath);
|
||||
const { stdout } = await runCli(cmd, ['--version'], '', 10000);
|
||||
return `claude @ ${cmd}\n${stdout.trim()}`;
|
||||
}
|
||||
if (settings.backend === 'codex') {
|
||||
const cmd = resolveCliPath('codex', settings.cliPath);
|
||||
const { stdout } = await runCli(cmd, ['--version'], '', 10000);
|
||||
return `codex @ ${cmd}\n${stdout.trim()}`;
|
||||
}
|
||||
return testApiBackend(requestUrl, settings);
|
||||
/** Detect whether the user has departed from preset defaults. If so we keep the
|
||||
* Advanced connection section open so they can find what they configured. */
|
||||
function shouldOpenAdvancedConnection(settings: PluginSettings): boolean {
|
||||
if ((settings.apiProvider || '').startsWith('custom-')) return true;
|
||||
if ((settings.apiHeaders || '').trim()) return true;
|
||||
const preset = getApiPreset(settings);
|
||||
const baseUrl = (settings.apiBaseUrl || '').trim();
|
||||
if (baseUrl && preset.baseUrl && baseUrl.replace(/\/+$/, '') !== preset.baseUrl.replace(/\/+$/, '')) return true;
|
||||
if (settings.apiAuthType && settings.apiAuthType !== 'auto') return true;
|
||||
if (settings.streaming === false) return true;
|
||||
if (settings.apiMaxTokens && settings.apiMaxTokens !== DEFAULT_SETTINGS.apiMaxTokens) return true;
|
||||
if (settings.apiFormat && preset.format && settings.apiFormat !== preset.format) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export class ParallelReaderSettingTab extends PluginSettingTab {
|
||||
|
|
@ -49,31 +49,27 @@ export class ParallelReaderSettingTab extends PluginSettingTab {
|
|||
display() {
|
||||
const { containerEl } = this;
|
||||
containerEl.empty();
|
||||
new Setting(containerEl).setName(this.tr('settingsTitle')).setHeading();
|
||||
|
||||
this.renderGeneralSection(containerEl);
|
||||
containerEl.addClass('parallel-reader-settings');
|
||||
|
||||
const isCliBacked = this.plugin.settings.backend === 'claude-code' || this.plugin.settings.backend === 'codex';
|
||||
this.renderBackendSection(containerEl, isCliBacked);
|
||||
this.renderPromptSection(containerEl, isCliBacked);
|
||||
this.renderActionsSection(containerEl, isCliBacked);
|
||||
this.renderCacheSection(containerEl);
|
||||
|
||||
this.renderQuickSetup(containerEl, isCliBacked);
|
||||
this.renderReadingOutput(containerEl);
|
||||
|
||||
if (!isCliBacked) {
|
||||
this.renderAdvancedConnection(containerEl);
|
||||
} else {
|
||||
this.renderAdvancedConnectionCli(containerEl);
|
||||
}
|
||||
|
||||
this.renderAdvancedPrompt(containerEl);
|
||||
this.renderCacheMaintenance(containerEl);
|
||||
}
|
||||
|
||||
private renderGeneralSection(containerEl: HTMLElement) {
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingUiLanguageName'))
|
||||
.setDesc(this.tr('settingUiLanguageDesc'))
|
||||
.addDropdown((d) => {
|
||||
for (const [id, label] of Object.entries(UI_LANGUAGES)) {
|
||||
d.addOption(id, label);
|
||||
}
|
||||
return d.setValue(this.plugin.settings.uiLanguage || DEFAULT_SETTINGS.uiLanguage).onChange(async (v) => {
|
||||
this.plugin.settings.uiLanguage = v;
|
||||
await this.plugin.saveSettings();
|
||||
this.display();
|
||||
});
|
||||
});
|
||||
/* ---------- 1. Quick setup (always expanded) ---------- */
|
||||
|
||||
private renderQuickSetup(containerEl: HTMLElement, isCliBacked: boolean) {
|
||||
new Setting(containerEl).setName(this.tr('sectionQuickSetup')).setHeading();
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingBackendName'))
|
||||
|
|
@ -96,175 +92,103 @@ export class ParallelReaderSettingTab extends PluginSettingTab {
|
|||
this.display();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private renderBackendSection(containerEl: HTMLElement, isCliBacked: boolean) {
|
||||
if (isCliBacked) {
|
||||
this.renderCliBackendSettings(containerEl);
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingCliPathName'))
|
||||
.setDesc(this.tr('settingCliPathDesc'))
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder(this.tr('settingCliPathPlaceholder'))
|
||||
.setValue(this.plugin.settings.cliPath)
|
||||
.onChange((v) => {
|
||||
this.plugin.settings.cliPath = v.trim();
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
this.renderApiBackendSettings(containerEl);
|
||||
this.renderProviderPresetWithSummary(containerEl);
|
||||
this.renderCredentialRow(containerEl);
|
||||
}
|
||||
|
||||
this.renderModelRow(containerEl, isCliBacked);
|
||||
this.renderTestButton(containerEl, isCliBacked);
|
||||
}
|
||||
|
||||
private renderCliBackendSettings(containerEl: HTMLElement) {
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingCliPathName'))
|
||||
.setDesc(this.tr('settingCliPathDesc'))
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder(this.tr('settingCliPathPlaceholder'))
|
||||
.setValue(this.plugin.settings.cliPath)
|
||||
.onChange((v) => {
|
||||
this.plugin.settings.cliPath = v.trim();
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}),
|
||||
);
|
||||
private renderProviderPresetWithSummary(containerEl: HTMLElement) {
|
||||
const settings = this.plugin.settings;
|
||||
const preset = getApiPreset(settings);
|
||||
const format = getApiFormat(settings);
|
||||
const baseUrl = (settings.apiBaseUrl || preset.baseUrl || API_FORMATS[format]?.defaultBaseUrl || '').replace(
|
||||
/\/+$/,
|
||||
'',
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingCliTimeoutName'))
|
||||
.setDesc(this.tr('settingCliTimeoutDesc'))
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder(String(DEFAULT_SETTINGS.cliTimeoutMs))
|
||||
.setValue(String(this.plugin.settings.cliTimeoutMs || DEFAULT_SETTINGS.cliTimeoutMs))
|
||||
.onChange((v) => {
|
||||
this.plugin.settings.cliTimeoutMs = normalizeCliTimeoutMs(v);
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private renderApiBackendSettings(containerEl: HTMLElement) {
|
||||
const preset = getApiPreset(this.plugin.settings);
|
||||
new Setting(containerEl).setName(this.tr('apiProviderHeader')).setHeading();
|
||||
|
||||
new Setting(containerEl)
|
||||
const setting = new Setting(containerEl)
|
||||
.setName(this.tr('settingProviderPresetName'))
|
||||
.setDesc(this.tr('settingProviderPresetDesc'))
|
||||
.addDropdown((d) => {
|
||||
for (const [id, entry] of Object.entries(API_PROVIDER_PRESETS)) {
|
||||
d.addOption(id, entry.label);
|
||||
}
|
||||
return d.setValue(this.plugin.settings.apiProvider).onChange(async (v) => {
|
||||
return d.setValue(settings.apiProvider).onChange(async (v) => {
|
||||
this.plugin.settings = applyApiProviderPreset(this.plugin.settings, v);
|
||||
await this.plugin.saveSettings();
|
||||
this.display();
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingApiFormatName'))
|
||||
.setDesc(this.tr('settingApiFormatDesc'))
|
||||
.addDropdown((d) => {
|
||||
for (const [id, entry] of Object.entries(API_FORMATS)) {
|
||||
d.addOption(id, entry.label);
|
||||
}
|
||||
return d.setValue(getApiFormat(this.plugin.settings)).onChange(async (v) => {
|
||||
this.plugin.settings.apiFormat = v;
|
||||
await this.plugin.saveSettings();
|
||||
this.display();
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingBaseUrlName'))
|
||||
.setDesc(this.tr('settingBaseUrlDesc'))
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder(
|
||||
(this.plugin.settings.apiProvider || '').startsWith('custom-')
|
||||
? 'https://your-provider.example/v1'
|
||||
: preset.baseUrl || API_FORMATS[getApiFormat(this.plugin.settings)].defaultBaseUrl,
|
||||
)
|
||||
.setValue(this.plugin.settings.apiBaseUrl)
|
||||
.onChange((v) => {
|
||||
this.plugin.settings.apiBaseUrl = v.trim();
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingApiKeyName'))
|
||||
.setDesc(this.tr('settingApiKeyDesc'))
|
||||
.addText((t) => {
|
||||
t.inputEl.type = 'password';
|
||||
return t.setValue(this.plugin.settings.apiKey).onChange((v) => {
|
||||
this.plugin.settings.apiKey = v.trim();
|
||||
this.plugin.saveSettingsDebounced();
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingApiKeyEnvName'))
|
||||
.setDesc(this.tr('settingApiKeyEnvDesc'))
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder(preset.envVar || 'OPENAI_API_KEY')
|
||||
.setValue(this.plugin.settings.apiKeyEnvVar)
|
||||
.onChange((v) => {
|
||||
this.plugin.settings.apiKeyEnvVar = v.trim();
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingAuthTypeName'))
|
||||
.setDesc(this.tr('settingAuthTypeDesc'))
|
||||
.addDropdown((d) => {
|
||||
for (const [id, label] of Object.entries(API_AUTH_TYPES)) {
|
||||
d.addOption(id, label);
|
||||
}
|
||||
return d.setValue(this.plugin.settings.apiAuthType || 'auto').onChange(async (v) => {
|
||||
this.plugin.settings.apiAuthType = v;
|
||||
await this.plugin.saveSettings();
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingHeadersName'))
|
||||
.setDesc(this.tr('settingHeadersDesc'))
|
||||
.addTextArea((t) =>
|
||||
t.setValue(this.plugin.settings.apiHeaders).onChange((v) => {
|
||||
this.plugin.settings.apiHeaders = v;
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(containerEl).setName(this.tr('settingMaxTokensName')).addText((t) =>
|
||||
t.setValue(String(this.plugin.settings.apiMaxTokens)).onChange((v) => {
|
||||
const n = parseInt(v, 10);
|
||||
if (!Number.isNaN(n) && n > 0) {
|
||||
this.plugin.settings.apiMaxTokens = n;
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingStreamingName'))
|
||||
.setDesc(this.tr('settingStreamingDesc'))
|
||||
.addToggle((toggle) =>
|
||||
toggle.setValue(this.plugin.settings.streaming ?? true).onChange(async (v) => {
|
||||
this.plugin.settings.streaming = v;
|
||||
await this.plugin.saveSettings();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingStreamingTimeoutName'))
|
||||
.setDesc(this.tr('settingStreamingTimeoutDesc'))
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder(String(DEFAULT_SETTINGS.streamingTimeoutMs))
|
||||
.setValue(String(this.plugin.settings.streamingTimeoutMs || DEFAULT_SETTINGS.streamingTimeoutMs))
|
||||
.onChange((v) => {
|
||||
this.plugin.settings.streamingTimeoutMs = normalizeStreamingTimeoutMs(v);
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}),
|
||||
);
|
||||
// Read-only summary of derived format + baseUrl, replacing the standalone rows.
|
||||
const summary = setting.descEl.createDiv({ cls: 'parallel-reader-preset-summary' });
|
||||
summary.createEl('code', {
|
||||
text: `${API_FORMATS[format]?.label || format} · ${baseUrl || this.tr('settingProviderPresetSummaryEmpty')}`,
|
||||
});
|
||||
}
|
||||
|
||||
private renderPromptSection(containerEl: HTMLElement, isCliBacked: boolean) {
|
||||
private renderCredentialRow(containerEl: HTMLElement) {
|
||||
const settings = this.plugin.settings;
|
||||
const preset = getApiPreset(settings);
|
||||
const setting = new Setting(containerEl)
|
||||
.setName(this.tr('settingApiKeyName'))
|
||||
.setDesc(this.tr('settingApiKeyDesc'));
|
||||
|
||||
setting.addText((t) => {
|
||||
t.inputEl.type = 'password';
|
||||
t.inputEl.autocomplete = 'off';
|
||||
return t.setValue(settings.apiKey).onChange((v) => {
|
||||
this.plugin.settings.apiKey = v.trim();
|
||||
this.plugin.saveSettingsDebounced();
|
||||
});
|
||||
});
|
||||
|
||||
// Env-var fallback: render manually (without `new Setting`) to avoid
|
||||
// nesting Obsidian .setting-item inside another controlEl, which causes
|
||||
// theme CSS conflicts (extra borders/padding from `.setting-item:first-child`).
|
||||
const envWrap = setting.controlEl.createDiv({ cls: 'parallel-reader-env-wrap' });
|
||||
const envDetails = envWrap.createEl('details');
|
||||
envDetails.createEl('summary', { text: this.tr('settingApiKeyEnvSummary') });
|
||||
const row = envDetails.createDiv({ cls: 'parallel-reader-env-row' });
|
||||
row.createEl('label', {
|
||||
text: this.tr('settingApiKeyEnvName'),
|
||||
cls: 'parallel-reader-env-label',
|
||||
});
|
||||
const envInput = row.createEl('input', {
|
||||
type: 'text',
|
||||
cls: 'parallel-reader-env-input',
|
||||
});
|
||||
envInput.placeholder = preset.envVar || 'OPENAI_API_KEY';
|
||||
envInput.value = settings.apiKeyEnvVar || '';
|
||||
envInput.addEventListener('input', () => {
|
||||
this.plugin.settings.apiKeyEnvVar = envInput.value.trim();
|
||||
this.plugin.saveSettingsDebounced();
|
||||
});
|
||||
envDetails.createDiv({
|
||||
text: this.tr('settingApiKeyEnvDesc'),
|
||||
cls: 'parallel-reader-env-desc',
|
||||
});
|
||||
}
|
||||
|
||||
private renderModelRow(containerEl: HTMLElement, isCliBacked: boolean) {
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingModelName'))
|
||||
.setDesc(isCliBacked ? this.tr('settingModelDescCli') : this.tr('settingModelDescApi'))
|
||||
|
|
@ -277,21 +201,33 @@ export class ParallelReaderSettingTab extends PluginSettingTab {
|
|||
this.plugin.saveSettingsDebounced();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private renderTestButton(containerEl: HTMLElement, isCliBacked: boolean) {
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingMaxInputName'))
|
||||
.setDesc(this.tr('settingMaxInputDesc'))
|
||||
.addText((t) =>
|
||||
t.setValue(String(this.plugin.settings.maxDocChars || DEFAULT_SETTINGS.maxDocChars)).onChange((v) => {
|
||||
const n = parseInt(v, 10);
|
||||
if (!Number.isNaN(n) && n >= 1000) {
|
||||
this.plugin.settings.maxDocChars = n;
|
||||
this.plugin.saveSettingsDebounced();
|
||||
.setName(this.tr('settingTestBackendName'))
|
||||
.setDesc(isCliBacked ? this.tr('settingTestBackendDescCli') : this.tr('settingTestBackendDescApi'))
|
||||
.addButton((b) =>
|
||||
b.setButtonText(this.tr('settingTestBackendButton')).onClick(async () => {
|
||||
b.setDisabled(true);
|
||||
b.setButtonText(this.tr('settingTestBackendButtonRunning'));
|
||||
try {
|
||||
const result = await testBackend(this.plugin.settings);
|
||||
new Notice(`✓ ${result.slice(0, 180)}`, 8000);
|
||||
} catch (e: unknown) {
|
||||
new Notice(this.tr('backendTestFailed', { error: e instanceof Error ? e.message : String(e) }), 10000);
|
||||
} finally {
|
||||
b.setButtonText(this.tr('settingTestBackendButton'));
|
||||
b.setDisabled(false);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
new Setting(containerEl).setName(this.tr('promptHeader')).setHeading();
|
||||
/* ---------- 2. Reading output (always expanded) ---------- */
|
||||
|
||||
private renderReadingOutput(containerEl: HTMLElement) {
|
||||
new Setting(containerEl).setName(this.tr('sectionReadingOutput')).setHeading();
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingPromptLanguageName'))
|
||||
|
|
@ -344,36 +280,6 @@ export class ParallelReaderSettingTab extends PluginSettingTab {
|
|||
}),
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingCustomPromptName'))
|
||||
.setDesc(this.tr('settingCustomPromptDesc'))
|
||||
.addTextArea((t) => {
|
||||
t.inputEl.rows = 8;
|
||||
return t
|
||||
.setPlaceholder(this.tr('settingCustomPromptPlaceholder'))
|
||||
.setValue(this.plugin.settings.customSystemPrompt || '')
|
||||
.onChange((v) => {
|
||||
this.plugin.settings.customSystemPrompt = v;
|
||||
this.plugin.saveSettingsDebounced();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private renderActionsSection(containerEl: HTMLElement, isCliBacked: boolean) {
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingTestBackendName'))
|
||||
.setDesc(isCliBacked ? this.tr('settingTestBackendDescCli') : this.tr('settingTestBackendDescApi'))
|
||||
.addButton((b) =>
|
||||
b.setButtonText(this.tr('settingTestBackendButton')).onClick(async () => {
|
||||
try {
|
||||
const result = await testBackend(this.plugin.settings);
|
||||
new Notice(`✓ ${result.slice(0, 180)}`, 8000);
|
||||
} catch (e: unknown) {
|
||||
new Notice(this.tr('backendTestFailed', { error: e instanceof Error ? e.message : String(e) }), 10000);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingExportFolderName'))
|
||||
.setDesc(this.tr('settingExportFolderDesc'))
|
||||
|
|
@ -383,12 +289,192 @@ export class ParallelReaderSettingTab extends PluginSettingTab {
|
|||
this.plugin.saveSettingsDebounced();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private renderCacheSection(containerEl: HTMLElement) {
|
||||
new Setting(containerEl).setName(this.tr('cacheHeader')).setHeading();
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(this.tr('settingUiLanguageName'))
|
||||
.setDesc(this.tr('settingUiLanguageDesc'))
|
||||
.addDropdown((d) => {
|
||||
for (const [id, label] of Object.entries(UI_LANGUAGES)) {
|
||||
d.addOption(id, label);
|
||||
}
|
||||
return d.setValue(this.plugin.settings.uiLanguage || DEFAULT_SETTINGS.uiLanguage).onChange(async (v) => {
|
||||
this.plugin.settings.uiLanguage = v;
|
||||
await this.plugin.saveSettings();
|
||||
this.display();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- 3. Advanced connection (collapsed by default) ---------- */
|
||||
|
||||
private renderAdvancedConnection(containerEl: HTMLElement) {
|
||||
const settings = this.plugin.settings;
|
||||
const details = this.openCollapsibleSection(
|
||||
containerEl,
|
||||
'sectionAdvancedConnection',
|
||||
shouldOpenAdvancedConnection(settings),
|
||||
);
|
||||
|
||||
new Setting(details)
|
||||
.setName(this.tr('settingApiFormatName'))
|
||||
.setDesc(this.tr('settingApiFormatDesc'))
|
||||
.addDropdown((d) => {
|
||||
for (const [id, entry] of Object.entries(API_FORMATS)) {
|
||||
d.addOption(id, entry.label);
|
||||
}
|
||||
return d.setValue(getApiFormat(settings)).onChange(async (v) => {
|
||||
this.plugin.settings.apiFormat = v;
|
||||
await this.plugin.saveSettings();
|
||||
this.display();
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(details)
|
||||
.setName(this.tr('settingBaseUrlName'))
|
||||
.setDesc(this.tr('settingBaseUrlDesc'))
|
||||
.addText((t) => {
|
||||
const preset = getApiPreset(settings);
|
||||
t.setPlaceholder(
|
||||
(settings.apiProvider || '').startsWith('custom-')
|
||||
? 'https://your-provider.example/v1'
|
||||
: preset.baseUrl || API_FORMATS[getApiFormat(settings)].defaultBaseUrl,
|
||||
)
|
||||
.setValue(settings.apiBaseUrl)
|
||||
.onChange((v) => {
|
||||
this.plugin.settings.apiBaseUrl = v.trim();
|
||||
this.plugin.saveSettingsDebounced();
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(details)
|
||||
.setName(this.tr('settingAuthTypeName'))
|
||||
.setDesc(this.tr('settingAuthTypeDesc'))
|
||||
.addDropdown((d) => {
|
||||
for (const [id, label] of Object.entries(API_AUTH_TYPES)) {
|
||||
d.addOption(id, label);
|
||||
}
|
||||
return d.setValue(settings.apiAuthType || 'auto').onChange(async (v) => {
|
||||
this.plugin.settings.apiAuthType = v;
|
||||
await this.plugin.saveSettings();
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(details)
|
||||
.setName(this.tr('settingHeadersName'))
|
||||
.setDesc(this.tr('settingHeadersDesc'))
|
||||
.addTextArea((t) =>
|
||||
t.setValue(settings.apiHeaders).onChange((v) => {
|
||||
this.plugin.settings.apiHeaders = v;
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(details).setName(this.tr('settingMaxTokensName')).addText((t) =>
|
||||
t.setValue(String(settings.apiMaxTokens)).onChange((v) => {
|
||||
const n = parseInt(v, 10);
|
||||
if (!Number.isNaN(n) && n > 0) {
|
||||
this.plugin.settings.apiMaxTokens = n;
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// Streaming + timeout merged. We build the timeout in a dedicated wrapper
|
||||
// and toggle that wrapper's visibility so we never accidentally hide the
|
||||
// shared controlEl (which would also hide the toggle itself).
|
||||
const streamingSetting = new Setting(details)
|
||||
.setName(this.tr('settingStreamingName'))
|
||||
.setDesc(this.tr('settingStreamingDesc'));
|
||||
|
||||
let timeoutWrap: HTMLElement | null = null;
|
||||
|
||||
streamingSetting.addToggle((toggle) =>
|
||||
toggle.setValue(settings.streaming ?? true).onChange(async (v) => {
|
||||
this.plugin.settings.streaming = v;
|
||||
await this.plugin.saveSettings();
|
||||
if (timeoutWrap) timeoutWrap.toggleClass('parallel-reader-hidden', !v);
|
||||
}),
|
||||
);
|
||||
|
||||
timeoutWrap = streamingSetting.controlEl.createDiv({ cls: 'parallel-reader-timeout-wrap' });
|
||||
const timeoutInput = timeoutWrap.createEl('input', {
|
||||
type: 'text',
|
||||
cls: 'parallel-reader-timeout-input',
|
||||
});
|
||||
timeoutInput.placeholder = String(DEFAULT_SETTINGS.streamingTimeoutMs);
|
||||
timeoutInput.title = this.tr('settingStreamingTimeoutName');
|
||||
timeoutInput.value = String(settings.streamingTimeoutMs || DEFAULT_SETTINGS.streamingTimeoutMs);
|
||||
timeoutInput.addEventListener('input', () => {
|
||||
this.plugin.settings.streamingTimeoutMs = normalizeStreamingTimeoutMs(timeoutInput.value);
|
||||
this.plugin.saveSettingsDebounced();
|
||||
});
|
||||
timeoutWrap.toggleClass('parallel-reader-hidden', !(settings.streaming ?? true));
|
||||
}
|
||||
|
||||
private renderAdvancedConnectionCli(containerEl: HTMLElement) {
|
||||
const settings = this.plugin.settings;
|
||||
const userChangedTimeout = !!(settings.cliTimeoutMs && settings.cliTimeoutMs !== DEFAULT_SETTINGS.cliTimeoutMs);
|
||||
const details = this.openCollapsibleSection(containerEl, 'sectionAdvancedConnection', userChangedTimeout);
|
||||
new Setting(details)
|
||||
.setName(this.tr('settingCliTimeoutName'))
|
||||
.setDesc(this.tr('settingCliTimeoutDesc'))
|
||||
.addText((t) =>
|
||||
t
|
||||
.setPlaceholder(String(DEFAULT_SETTINGS.cliTimeoutMs))
|
||||
.setValue(String(this.plugin.settings.cliTimeoutMs || DEFAULT_SETTINGS.cliTimeoutMs))
|
||||
.onChange((v) => {
|
||||
this.plugin.settings.cliTimeoutMs = normalizeCliTimeoutMs(v);
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- 4. Advanced prompt (collapsed by default) ---------- */
|
||||
|
||||
private renderAdvancedPrompt(containerEl: HTMLElement) {
|
||||
const settings = this.plugin.settings;
|
||||
const userHasCustomPrompt = !!(settings.customSystemPrompt || '').trim();
|
||||
const userHasCustomMaxInput = settings.maxDocChars && settings.maxDocChars !== DEFAULT_SETTINGS.maxDocChars;
|
||||
const details = this.openCollapsibleSection(
|
||||
containerEl,
|
||||
'sectionAdvancedPrompt',
|
||||
!!(userHasCustomPrompt || userHasCustomMaxInput),
|
||||
);
|
||||
|
||||
new Setting(details)
|
||||
.setName(this.tr('settingMaxInputName'))
|
||||
.setDesc(this.tr('settingMaxInputDesc'))
|
||||
.addText((t) =>
|
||||
t.setValue(String(settings.maxDocChars || DEFAULT_SETTINGS.maxDocChars)).onChange((v) => {
|
||||
const n = parseInt(v, 10);
|
||||
if (!Number.isNaN(n) && n >= 1000) {
|
||||
this.plugin.settings.maxDocChars = n;
|
||||
this.plugin.saveSettingsDebounced();
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(details)
|
||||
.setName(this.tr('settingCustomPromptName'))
|
||||
.setDesc(this.tr('settingCustomPromptDesc'))
|
||||
.addTextArea((t) => {
|
||||
t.inputEl.rows = 8;
|
||||
return t
|
||||
.setPlaceholder(this.tr('settingCustomPromptPlaceholder'))
|
||||
.setValue(settings.customSystemPrompt || '')
|
||||
.onChange((v) => {
|
||||
this.plugin.settings.customSystemPrompt = v;
|
||||
this.plugin.saveSettingsDebounced();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- 5. Cache & maintenance (collapsed by default) ---------- */
|
||||
|
||||
private renderCacheMaintenance(containerEl: HTMLElement) {
|
||||
const details = this.openCollapsibleSection(containerEl, 'sectionCacheMaintenance', false);
|
||||
|
||||
new Setting(details)
|
||||
.setName(this.tr('settingMaxCacheName'))
|
||||
.setDesc(this.tr('settingMaxCacheDesc'))
|
||||
.addText((t) => {
|
||||
|
|
@ -413,7 +499,7 @@ export class ParallelReaderSettingTab extends PluginSettingTab {
|
|||
});
|
||||
|
||||
const cacheCount = Object.keys(this.plugin.cache).length;
|
||||
new Setting(containerEl)
|
||||
new Setting(details)
|
||||
.setName(this.tr('cachedNotesName', { count: cacheCount }))
|
||||
.setDesc(this.tr('cachedNotesDesc'))
|
||||
.addButton((b) =>
|
||||
|
|
@ -428,4 +514,15 @@ export class ParallelReaderSettingTab extends PluginSettingTab {
|
|||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- helpers ---------- */
|
||||
|
||||
/** Create a `<details>` collapsible section with translated `<summary>` and
|
||||
* return the inner element to render Settings into. */
|
||||
private openCollapsibleSection(parent: HTMLElement, summaryKey: string, openByDefault: boolean): HTMLElement {
|
||||
const details = parent.createEl('details', { cls: 'parallel-reader-section' });
|
||||
if (openByDefault) details.setAttr('open', '');
|
||||
details.createEl('summary', { text: this.tr(summaryKey), cls: 'parallel-reader-section-summary' });
|
||||
return details;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,20 +8,31 @@ import type { ApiFormat, ApiProviderPreset, CacheEntry, PluginSettings } from '.
|
|||
export { API_PROVIDER_PRESETS } from './provider-presets';
|
||||
|
||||
export const MAX_DOC_CHARS = 100000;
|
||||
export const PROMPT_VERSION = 2;
|
||||
const PROMPT_VERSION = 2;
|
||||
export const CACHE_SCHEMA_VERSION = 2;
|
||||
export const DEFAULT_MAX_CACHE_ENTRIES = 100;
|
||||
export const MIN_STREAMING_TIMEOUT_MS = 1000;
|
||||
export const MIN_CLI_TIMEOUT_MS = 1000;
|
||||
const DEFAULT_CLI_TIMEOUT_MS = 300000;
|
||||
const MIN_STREAMING_TIMEOUT_MS = 1000;
|
||||
const MIN_CLI_TIMEOUT_MS = 1000;
|
||||
export const PROMPT_LANGUAGES = {
|
||||
auto: 'Auto-detect',
|
||||
zh: '中文',
|
||||
en: 'English',
|
||||
auto: 'Auto-detect',
|
||||
ja: '日本語',
|
||||
ko: '한국어',
|
||||
fr: 'Français',
|
||||
de: 'Deutsch',
|
||||
es: 'Español',
|
||||
};
|
||||
export const UI_LANGUAGES = {
|
||||
auto: 'Auto',
|
||||
zh: '中文',
|
||||
en: 'English',
|
||||
ja: '日本語',
|
||||
ko: '한국어',
|
||||
fr: 'Français',
|
||||
de: 'Deutsch',
|
||||
es: 'Español',
|
||||
};
|
||||
|
||||
export const DEFAULT_SETTINGS: PluginSettings = {
|
||||
|
|
@ -38,13 +49,16 @@ export const DEFAULT_SETTINGS: PluginSettings = {
|
|||
apiMaxTokens: 4096,
|
||||
maxDocChars: MAX_DOC_CHARS,
|
||||
maxCacheEntries: DEFAULT_MAX_CACHE_ENTRIES,
|
||||
promptLanguage: 'zh',
|
||||
// 'auto' = match the source document's main language, so a new user reading an
|
||||
// English (or any non-Chinese) note gets summaries in that language by default
|
||||
// instead of forced Chinese. Existing users keep whatever they have persisted.
|
||||
promptLanguage: 'auto',
|
||||
minCards: 5,
|
||||
maxCards: 15,
|
||||
customSystemPrompt: '',
|
||||
model: 'claude-sonnet-4-6',
|
||||
exportFolder: 'Reading/Articles',
|
||||
cliTimeoutMs: 120000,
|
||||
cliTimeoutMs: DEFAULT_CLI_TIMEOUT_MS,
|
||||
streaming: true,
|
||||
streamingTimeoutMs: 120000,
|
||||
};
|
||||
|
|
@ -267,7 +281,24 @@ export function pruneCacheEntries(cache: Record<string, CacheEntry>, maxEntries:
|
|||
return removed;
|
||||
}
|
||||
|
||||
// Memoize by settings object identity. The plugin replaces this.settings with
|
||||
// a fresh object only on load/save, so the same reference always yields the
|
||||
// same fingerprint — this collapses the SHA-1 + stableStringify work done on
|
||||
// every file-open / cache check down to once per settings change.
|
||||
const fingerprintCache = new WeakMap<object, string>();
|
||||
|
||||
export function generationFingerprint(settings: PluginSettings): string {
|
||||
const cacheKey = settings as unknown as object;
|
||||
if (cacheKey) {
|
||||
const cached = fingerprintCache.get(cacheKey);
|
||||
if (cached !== undefined) return cached;
|
||||
}
|
||||
const result = computeGenerationFingerprint(settings);
|
||||
if (cacheKey) fingerprintCache.set(cacheKey, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function computeGenerationFingerprint(settings: PluginSettings): string {
|
||||
const normalized = normalizeSettings(Object.assign({}, DEFAULT_SETTINGS, settings || {}));
|
||||
const apiBackend = isApiBackend(normalized.backend);
|
||||
const preset = getApiPreset(normalized);
|
||||
|
|
|
|||
174
src/streaming.ts
174
src/streaming.ts
|
|
@ -1,6 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
import { translate } from './i18n';
|
||||
import type { RequestUrlFunction } from './provider-request';
|
||||
import type { PluginSettings } from './types';
|
||||
|
||||
/**
|
||||
|
|
@ -25,6 +26,32 @@ function anthropicDelta(json: Record<string, unknown>): string {
|
|||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect a provider error delivered as an SSE payload inside an HTTP 200 stream.
|
||||
* These bypass the `response.status >= 400` guard, so without this they would be
|
||||
* extracted as empty deltas and later misreported as "non-JSON LLM output".
|
||||
* Anthropic: { type: 'error', error: { type, message } }
|
||||
* OpenAI-compatible: { error: { message, type, code } }
|
||||
* Returns a human-readable error message for an error payload, or null otherwise.
|
||||
*/
|
||||
export function streamErrorMessage(json: Record<string, unknown>): string | null {
|
||||
const messageFromError = (value: unknown): string | null => {
|
||||
if (!value || typeof value !== 'object') return null;
|
||||
const err = value as { message?: unknown; type?: unknown };
|
||||
if (typeof err.message === 'string' && err.message) return err.message;
|
||||
if (typeof err.type === 'string' && err.type) return err.type;
|
||||
return null;
|
||||
};
|
||||
// Anthropic: an explicit error event is an error even if its details are sparse.
|
||||
if (json.type === 'error') {
|
||||
return messageFromError(json.error) ?? 'Provider returned a streaming error';
|
||||
}
|
||||
// OpenAI-compatible: { error: { message, type, code } }. Only treat it as an error
|
||||
// when it actually carries a message/type, so a stray empty `error: {}` (or a
|
||||
// code-only object) in an otherwise-normal chunk does not abort the stream.
|
||||
return messageFromError(json.error);
|
||||
}
|
||||
|
||||
export type DeltaExtractor = (json: Record<string, unknown>) => string;
|
||||
|
||||
export function deltaExtractorForFormat(format: string): DeltaExtractor | null {
|
||||
|
|
@ -60,13 +87,18 @@ export function parseSseBuffer(buffer: string, extractDelta: DeltaExtractor): {
|
|||
|
||||
const data = dataLines.join('\n');
|
||||
if (data.trim() === '[DONE]') continue;
|
||||
let json: Record<string, unknown>;
|
||||
try {
|
||||
const json = JSON.parse(data) as Record<string, unknown>;
|
||||
const delta = extractDelta(json);
|
||||
if (delta) deltas.push(delta);
|
||||
} catch (_) {
|
||||
// skip non-JSON SSE lines
|
||||
json = JSON.parse(data) as Record<string, unknown>;
|
||||
} catch {
|
||||
continue; // skip non-JSON SSE lines (keep-alives, partial frames)
|
||||
}
|
||||
// Provider errors arrive as a 200-status SSE payload — surface them instead of
|
||||
// swallowing them, so a transient overload/quota error is not misreported downstream.
|
||||
const errorMessage = streamErrorMessage(json);
|
||||
if (errorMessage) throw new Error(errorMessage);
|
||||
const delta = extractDelta(json);
|
||||
if (delta) deltas.push(delta);
|
||||
}
|
||||
return { deltas, rest };
|
||||
}
|
||||
|
|
@ -76,68 +108,52 @@ export interface StreamProgress {
|
|||
done: boolean;
|
||||
}
|
||||
|
||||
async function doStreamingFetch(
|
||||
async function doStreamingRequestUrl(
|
||||
requestUrlImpl: RequestUrlFunction,
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
body: unknown,
|
||||
extractDelta: DeltaExtractor,
|
||||
onProgress: ((progress: StreamProgress) => void) | undefined,
|
||||
signal: AbortSignal,
|
||||
settings: PluginSettings | null | undefined,
|
||||
): Promise<string> {
|
||||
const response = await globalThis.fetch(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
let response: Awaited<ReturnType<RequestUrlFunction>>;
|
||||
try {
|
||||
response = await requestUrlImpl({
|
||||
url,
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
throw: false,
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
throw new Error(
|
||||
translate(settings || null, 'errorProviderApiStatus', {
|
||||
translate(settings || null, 'errorProviderRequestFailed', {
|
||||
label: 'Streaming',
|
||||
status: response.status,
|
||||
excerpt: text.slice(0, 500),
|
||||
error: e instanceof Error ? e.message : String(e),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error('Response has no body for streaming');
|
||||
if (response.status >= 400) {
|
||||
throw new Error(
|
||||
translate(settings || null, 'errorProviderApiStatus', {
|
||||
label: 'Streaming',
|
||||
status: response.status,
|
||||
excerpt: (response.text || '').slice(0, 500),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let accumulated = '';
|
||||
let buffer = '';
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const result = parseSseBuffer(buffer, extractDelta);
|
||||
buffer = result.rest;
|
||||
|
||||
for (const delta of result.deltas) {
|
||||
accumulated += delta;
|
||||
}
|
||||
if (result.deltas.length > 0) {
|
||||
onProgress?.({ accumulated, done: false });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
const text = response.text || '';
|
||||
const buffer = text.endsWith('\n\n') ? text : `${text}\n\n`;
|
||||
const result = parseSseBuffer(buffer, extractDelta);
|
||||
for (const delta of result.deltas) {
|
||||
accumulated += delta;
|
||||
}
|
||||
|
||||
// Flush any unterminated final SSE event (some providers close the stream
|
||||
// without a trailing \n\n, leaving the last delta in `buffer`).
|
||||
if (buffer.length > 0) {
|
||||
const tailBuffer = buffer.endsWith('\n\n') ? buffer : `${buffer}\n\n`;
|
||||
const tail = parseSseBuffer(tailBuffer, extractDelta);
|
||||
for (const delta of tail.deltas) accumulated += delta;
|
||||
if (result.deltas.length > 0) {
|
||||
onProgress?.({ accumulated, done: false });
|
||||
}
|
||||
|
||||
onProgress?.({ accumulated, done: true });
|
||||
|
|
@ -145,11 +161,12 @@ async function doStreamingFetch(
|
|||
}
|
||||
|
||||
/**
|
||||
* Perform a streaming fetch with SSE parsing and configurable timeout.
|
||||
* Uses the native Fetch API (available in Electron/Obsidian).
|
||||
* Returns the full accumulated text when done.
|
||||
* Perform an Obsidian requestUrl call that asks providers for SSE output and parses
|
||||
* the complete response text. requestUrl is one-shot, so progress arrives after
|
||||
* the HTTP request completes rather than per network chunk.
|
||||
*/
|
||||
export async function streamingFetch(
|
||||
export async function streamingRequestUrl(
|
||||
requestUrlImpl: RequestUrlFunction,
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
body: unknown,
|
||||
|
|
@ -158,35 +175,44 @@ export async function streamingFetch(
|
|||
signal?: AbortSignal,
|
||||
settings?: PluginSettings | null,
|
||||
): Promise<string> {
|
||||
if (typeof globalThis.fetch !== 'function') {
|
||||
throw new Error('Streaming requires fetch API');
|
||||
}
|
||||
|
||||
const timeoutMs = settings?.streamingTimeoutMs ?? 120000;
|
||||
const timeoutController = new AbortController();
|
||||
let abortListener: (() => void) | null = null;
|
||||
let abortPromise: Promise<never> | null = null;
|
||||
|
||||
if (signal) {
|
||||
abortListener = () => timeoutController.abort();
|
||||
signal.addEventListener('abort', abortListener, { once: true });
|
||||
if (signal.aborted) timeoutController.abort();
|
||||
if (signal.aborted) throw new Error('Streaming request aborted');
|
||||
abortPromise = (async () => {
|
||||
await new Promise<void>((resolve) => {
|
||||
abortListener = resolve;
|
||||
signal.addEventListener('abort', abortListener, { once: true });
|
||||
});
|
||||
throw new Error('Streaming request aborted');
|
||||
})();
|
||||
}
|
||||
|
||||
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutId = setTimeout(() => {
|
||||
timeoutController.abort();
|
||||
reject(new Error(`Streaming timed out after ${timeoutMs}ms`));
|
||||
}, timeoutMs);
|
||||
});
|
||||
let timeoutId: number | null = null;
|
||||
const timeoutPromise = (async () => {
|
||||
await new Promise<void>((resolve) => {
|
||||
timeoutId = activeWindow.setTimeout(resolve, timeoutMs);
|
||||
});
|
||||
throw new Error(`Streaming timed out after ${timeoutMs}ms`);
|
||||
})();
|
||||
|
||||
try {
|
||||
return await Promise.race([
|
||||
doStreamingFetch(url, headers, body, extractDelta, onProgress, timeoutController.signal, settings),
|
||||
timeoutPromise,
|
||||
]);
|
||||
const requestPromise = doStreamingRequestUrl(
|
||||
requestUrlImpl,
|
||||
url,
|
||||
headers,
|
||||
body,
|
||||
extractDelta,
|
||||
onProgress,
|
||||
settings,
|
||||
);
|
||||
return await Promise.race(
|
||||
abortPromise ? [requestPromise, timeoutPromise, abortPromise] : [requestPromise, timeoutPromise],
|
||||
);
|
||||
} finally {
|
||||
if (timeoutId !== null) clearTimeout(timeoutId);
|
||||
if (timeoutId !== null) activeWindow.clearTimeout(timeoutId);
|
||||
if (signal && abortListener) signal.removeEventListener('abort', abortListener);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
'use strict';
|
||||
|
||||
export { default as ParallelReaderPlugin } from '../main';
|
||||
export { findLineForAnchor } from './anchor';
|
||||
export { buildLineOffsets, findLineForAnchor } from './anchor';
|
||||
export { testBackend } from './backend-test';
|
||||
export {
|
||||
batchProgressVars,
|
||||
createBatchRunState,
|
||||
|
|
@ -20,7 +21,7 @@ export {
|
|||
export { serializeCacheFile, shouldConfirmRegenerate, touchCacheEntry } from './cache';
|
||||
export { CacheManager } from './cache-manager';
|
||||
export { activeIndexAfterCardDelete, removeCardAt, updateCardAt } from './cards';
|
||||
export { resolveCliPath, runCli, summarizeViaClaudeCode, summarizeViaCodex } from './cli';
|
||||
export { CliProcessError, resolveCliPath, runCli, summarizeViaClaudeCode, summarizeViaCodex } from './cli';
|
||||
export { cancellationNoticeKey, summarizeDocument } from './generation';
|
||||
export {
|
||||
classifyGenerationError,
|
||||
|
|
@ -32,6 +33,14 @@ export { translate } from './i18n';
|
|||
export { cardsToMarkdown } from './markdown';
|
||||
export { activeSectionLine, nextCardIndex } from './navigation';
|
||||
export { buildPrompts } from './prompt';
|
||||
export {
|
||||
endpointUrl,
|
||||
ProviderApiError,
|
||||
requestJsonBody,
|
||||
requestJsonBodyWithStructuredFallback,
|
||||
responseJson,
|
||||
shouldRetryWithoutStructuredOutput,
|
||||
} from './provider-request';
|
||||
export {
|
||||
buildAnthropicMessagesBody,
|
||||
buildGeminiBody,
|
||||
|
|
@ -57,7 +66,7 @@ export {
|
|||
normalizeStreamingTimeoutMs,
|
||||
pruneCacheEntries,
|
||||
} from './settings';
|
||||
export { deltaExtractorForFormat, parseSseBuffer } from './streaming';
|
||||
export { deltaExtractorForFormat, parseSseBuffer, streamErrorMessage } from './streaming';
|
||||
export { addIconButton, addTextButton, copyToClipboard } from './ui-helpers';
|
||||
export { folderPathsForTarget } from './vault';
|
||||
export { ParallelReaderView } from './view';
|
||||
|
|
|
|||
13
src/types.ts
13
src/types.ts
|
|
@ -37,11 +37,6 @@ export interface CacheEntry {
|
|||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface CacheFile {
|
||||
version: number;
|
||||
entries: Record<string, CacheEntry>;
|
||||
}
|
||||
|
||||
/* ---------- Settings types ---------- */
|
||||
|
||||
export interface PluginSettings {
|
||||
|
|
@ -101,7 +96,7 @@ export type GenerationPhase =
|
|||
| 'done'
|
||||
| 'cancelled';
|
||||
|
||||
export type ErrorKind = 'auth' | 'timeout' | 'rate-limit' | 'schema' | 'config' | 'cancelled' | 'unknown';
|
||||
export type ErrorKind = 'auth' | 'timeout' | 'rate-limit' | 'network' | 'schema' | 'config' | 'cancelled' | 'unknown';
|
||||
|
||||
export interface RunForFileOptions {
|
||||
rethrowErrors?: boolean;
|
||||
|
|
@ -164,6 +159,10 @@ export interface PluginHost {
|
|||
cache: Record<string, CacheEntry>;
|
||||
manifest: PluginManifest;
|
||||
t(key: string, vars?: Record<string, string | number>): string;
|
||||
/** Open the plugin's settings tab (best-effort; no-op if the API is unavailable). */
|
||||
openSettings(): void;
|
||||
/** True if a usable credential is configured for the current backend (API key, env var, or keyless local provider). */
|
||||
isCredentialConfigured(): boolean;
|
||||
isGeneratingFile(file: TFile | null): boolean;
|
||||
cancelGenerationForFile(file: TFile | null): boolean;
|
||||
runForFile(
|
||||
|
|
@ -171,7 +170,7 @@ export interface PluginHost {
|
|||
force: boolean,
|
||||
options?: RunForFileOptions,
|
||||
preloadedContent?: string,
|
||||
): Promise<RunForFileResult | void>;
|
||||
): Promise<RunForFileResult>;
|
||||
copyCurrentViewMarkdown(): Promise<void>;
|
||||
scrollEditorToLine(line: number, file: TFile | null): Promise<void>;
|
||||
cacheReplaceCards(filePath: string, cards: ResolvedCard[]): Promise<boolean>;
|
||||
|
|
|
|||
|
|
@ -14,7 +14,11 @@ export function folderPathsForTarget(folderPath: string): string[] {
|
|||
const normalized = normalizeVaultPath(folderPath);
|
||||
if (!normalized) return [];
|
||||
const parts = normalized.split('/');
|
||||
return parts.map((_, idx) => parts.slice(0, idx + 1).join('/'));
|
||||
const folders: string[] = [];
|
||||
for (let idx = 0; idx < parts.length; idx++) {
|
||||
folders.push(parts.slice(0, idx + 1).join('/'));
|
||||
}
|
||||
return folders;
|
||||
}
|
||||
|
||||
export async function ensureVaultFolder(app: App, folderPath: string) {
|
||||
|
|
|
|||
48
src/view.ts
48
src/view.ts
|
|
@ -20,6 +20,8 @@ export class ParallelReaderView extends ItemView {
|
|||
stale = false;
|
||||
loadingMessage = '';
|
||||
errorMessage = '';
|
||||
private keydownHandler: ((e: KeyboardEvent) => void) | null = null;
|
||||
private keydownTarget: Element | null = null;
|
||||
|
||||
constructor(leaf: WorkspaceLeaf, plugin: PluginHost) {
|
||||
super(leaf);
|
||||
|
|
@ -45,13 +47,20 @@ export class ParallelReaderView extends ItemView {
|
|||
container.empty();
|
||||
container.addClass('parallel-reader-container');
|
||||
container.setAttr('tabindex', '0');
|
||||
container.addEventListener('keydown', (e) => this.handleKeydown(e as KeyboardEvent));
|
||||
this.keydownHandler = (e) => this.handleKeydown(e);
|
||||
this.keydownTarget = container;
|
||||
container.addEventListener('keydown', this.keydownHandler as EventListener);
|
||||
this.renderEmpty();
|
||||
this.focusSummaryPane();
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
onClose() {
|
||||
if (this.keydownHandler && this.keydownTarget) {
|
||||
this.keydownTarget.removeEventListener('keydown', this.keydownHandler as EventListener);
|
||||
}
|
||||
this.keydownHandler = null;
|
||||
this.keydownTarget = null;
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
|
|
@ -67,6 +76,18 @@ export class ParallelReaderView extends ItemView {
|
|||
hint.createEl('h3', { text: this.plugin.t('appTitle') });
|
||||
hint.createEl('p', { text: this.plugin.t('emptyOpenNote') });
|
||||
hint.createEl('code', { text: this.plugin.t('commandGenerate') });
|
||||
this.appendSetupNudge(hint);
|
||||
}
|
||||
|
||||
/**
|
||||
* When no credential is configured, append a "set up your AI provider" call-to-action
|
||||
* so a first-run user does not hit a dead-end (Generate → immediate API-key error).
|
||||
*/
|
||||
private appendSetupNudge(parent: HTMLElement): boolean {
|
||||
if (this.plugin.isCredentialConfigured()) return false;
|
||||
parent.createEl('p', { cls: 'parallel-reader-setup-hint', text: this.plugin.t('emptyNeedsSetup') });
|
||||
addTextButton(parent, 'settings', this.plugin.t('actionSetupProvider'), () => this.plugin.openSettings());
|
||||
return true;
|
||||
}
|
||||
|
||||
focusSummaryPane() {
|
||||
|
|
@ -110,7 +131,7 @@ export class ParallelReaderView extends ItemView {
|
|||
container.empty();
|
||||
const header = container.createDiv({ cls: 'parallel-reader-header' });
|
||||
const headerRow = header.createDiv({ cls: 'parallel-reader-header-row' });
|
||||
headerRow.createEl('div', { text: file.basename, cls: 'parallel-reader-title' });
|
||||
headerRow.createDiv({ text: file.basename, cls: 'parallel-reader-title' });
|
||||
const actions = headerRow.createDiv({ cls: 'parallel-reader-actions' });
|
||||
addIconButton(actions, 'square', this.plugin.t('actionCancel'), () => {
|
||||
this.plugin.cancelGenerationForFile(file);
|
||||
|
|
@ -120,7 +141,7 @@ export class ParallelReaderView extends ItemView {
|
|||
cls: 'parallel-reader-state parallel-reader-loading parallel-reader-streaming-preview',
|
||||
});
|
||||
state.createDiv({ cls: 'parallel-reader-spinner' });
|
||||
const titleEl = state.createEl('div', { cls: 'parallel-reader-state-title' });
|
||||
const titleEl = state.createDiv({ cls: 'parallel-reader-state-title' });
|
||||
titleEl.createSpan({ text: this.plugin.t('loadingGenerating') + ' ' });
|
||||
titleEl.createSpan({ cls: 'parallel-reader-stream-counter', text: `${text.length} chars` });
|
||||
const pre = state.createEl('pre', { cls: 'parallel-reader-stream-text' });
|
||||
|
|
@ -148,6 +169,7 @@ export class ParallelReaderView extends ItemView {
|
|||
hint.createEl('h3', { text: file.basename });
|
||||
hint.createEl('p', { text: this.plugin.t('emptyNoCache') });
|
||||
hint.createEl('code', { text: this.plugin.t('commandGenerate') });
|
||||
this.appendSetupNudge(hint);
|
||||
addTextButton(hint, null, this.plugin.t('actionGenerate'), () => {
|
||||
if (this.plugin.isGeneratingFile(file)) return;
|
||||
void this.plugin.runForFile(file, false);
|
||||
|
|
@ -174,7 +196,7 @@ export class ParallelReaderView extends ItemView {
|
|||
private renderHeader(container: Element) {
|
||||
const header = container.createDiv({ cls: 'parallel-reader-header' });
|
||||
const headerRow = header.createDiv({ cls: 'parallel-reader-header-row' });
|
||||
headerRow.createEl('div', { text: this.sourceFile?.basename || '', cls: 'parallel-reader-title' });
|
||||
headerRow.createDiv({ text: this.sourceFile?.basename || '', cls: 'parallel-reader-title' });
|
||||
const actions = headerRow.createDiv({ cls: 'parallel-reader-actions' });
|
||||
if (this.sourceFile) {
|
||||
if (this.plugin.isGeneratingFile(this.sourceFile)) {
|
||||
|
|
@ -209,14 +231,14 @@ export class ParallelReaderView extends ItemView {
|
|||
private renderLoadingState(container: Element) {
|
||||
const state = container.createDiv({ cls: 'parallel-reader-state parallel-reader-loading' });
|
||||
state.createDiv({ cls: 'parallel-reader-spinner' });
|
||||
state.createEl('div', { text: this.loadingMessage, cls: 'parallel-reader-state-title' });
|
||||
state.createEl('div', { text: this.plugin.t('loadingSubtitle'), cls: 'parallel-reader-state-subtitle' });
|
||||
state.createDiv({ text: this.loadingMessage, cls: 'parallel-reader-state-title' });
|
||||
state.createDiv({ text: this.plugin.t('loadingSubtitle'), cls: 'parallel-reader-state-subtitle' });
|
||||
}
|
||||
|
||||
private renderErrorState(container: Element) {
|
||||
const state = container.createDiv({ cls: 'parallel-reader-state parallel-reader-error' });
|
||||
state.createEl('div', { text: this.plugin.t('errorTitle'), cls: 'parallel-reader-state-title' });
|
||||
state.createEl('div', {
|
||||
state.createDiv({ text: this.plugin.t('errorTitle'), cls: 'parallel-reader-state-title' });
|
||||
state.createDiv({
|
||||
text: this.errorMessage,
|
||||
cls: 'parallel-reader-state-subtitle parallel-reader-selectable',
|
||||
});
|
||||
|
|
@ -254,14 +276,14 @@ export class ParallelReaderView extends ItemView {
|
|||
card.dataset.idx = String(i);
|
||||
if (s.startLine < 0) card.addClass('parallel-reader-card-unanchored');
|
||||
|
||||
const title = card.createEl('div', { cls: 'parallel-reader-card-title' });
|
||||
const title = card.createDiv({ cls: 'parallel-reader-card-title' });
|
||||
title.createSpan({ text: s.title });
|
||||
if (s.startLine < 0) {
|
||||
title.createEl('span', { text: ' ⚠', cls: 'parallel-reader-warn', title: this.plugin.t('anchorMismatch') });
|
||||
title.createSpan({ text: ' ⚠', cls: 'parallel-reader-warn', title: this.plugin.t('anchorMismatch') });
|
||||
}
|
||||
|
||||
if (s.gist) {
|
||||
const gistEl = card.createEl('div', { cls: 'parallel-reader-gist' });
|
||||
const gistEl = card.createDiv({ cls: 'parallel-reader-gist' });
|
||||
MarkdownRenderer.render(this.app, s.gist, gistEl, sourcePath, this).catch(() => {
|
||||
gistEl.setText(s.gist);
|
||||
});
|
||||
|
|
@ -269,13 +291,13 @@ export class ParallelReaderView extends ItemView {
|
|||
|
||||
const bs = s.bullets || [];
|
||||
if (bs.length > 0) {
|
||||
const bulletsEl = card.createEl('div', { cls: 'parallel-reader-bullets-md' });
|
||||
const bulletsEl = card.createDiv({ cls: 'parallel-reader-bullets-md' });
|
||||
const md = bs.map((b) => `- ${b}`).join('\n');
|
||||
MarkdownRenderer.render(this.app, md, bulletsEl, sourcePath, this).catch(() => {
|
||||
bulletsEl.setText(md);
|
||||
});
|
||||
} else if (!s.gist) {
|
||||
card.createEl('div', { cls: 'parallel-reader-empty-li', text: this.plugin.t('emptyCard') });
|
||||
card.createDiv({ cls: 'parallel-reader-empty-li', text: this.plugin.t('emptyCard') });
|
||||
}
|
||||
|
||||
card.addEventListener('click', (e) => {
|
||||
|
|
|
|||
143
styles.css
143
styles.css
|
|
@ -1,3 +1,89 @@
|
|||
/* ---- Settings tab: collapsible sections ---- */
|
||||
|
||||
.parallel-reader-settings details.parallel-reader-section {
|
||||
margin: 0.6em 0 0.4em;
|
||||
border-top: 1px solid var(--background-modifier-border);
|
||||
padding-top: 0.4em;
|
||||
}
|
||||
|
||||
.parallel-reader-settings details.parallel-reader-section > summary.parallel-reader-section-summary {
|
||||
cursor: pointer;
|
||||
list-style: revert;
|
||||
font-weight: 600;
|
||||
font-size: 0.95em;
|
||||
color: var(--text-muted);
|
||||
padding: 0.4em 0;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.parallel-reader-settings details.parallel-reader-section[open] > summary.parallel-reader-section-summary {
|
||||
color: var(--text-normal);
|
||||
margin-bottom: 0.4em;
|
||||
}
|
||||
|
||||
.parallel-reader-settings .parallel-reader-preset-summary {
|
||||
margin-top: 0.3em;
|
||||
font-size: 0.82em;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
.parallel-reader-settings .parallel-reader-preset-summary code {
|
||||
font-size: 0.95em;
|
||||
background: var(--background-secondary);
|
||||
padding: 0.1em 0.4em;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.parallel-reader-settings .parallel-reader-env-wrap {
|
||||
width: 100%;
|
||||
margin-top: 0.4em;
|
||||
}
|
||||
|
||||
.parallel-reader-settings .parallel-reader-env-wrap details summary {
|
||||
cursor: pointer;
|
||||
font-size: 0.85em;
|
||||
color: var(--text-muted);
|
||||
padding: 0.2em 0;
|
||||
}
|
||||
|
||||
.parallel-reader-settings .parallel-reader-env-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6em;
|
||||
margin: 0.4em 0;
|
||||
}
|
||||
|
||||
.parallel-reader-settings .parallel-reader-env-label {
|
||||
font-size: 0.85em;
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.parallel-reader-settings .parallel-reader-env-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.parallel-reader-settings .parallel-reader-env-desc {
|
||||
font-size: 0.8em;
|
||||
color: var(--text-faint);
|
||||
margin-top: 0.2em;
|
||||
}
|
||||
|
||||
.parallel-reader-settings .parallel-reader-timeout-wrap {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin-left: 0.6em;
|
||||
}
|
||||
|
||||
.parallel-reader-settings .parallel-reader-timeout-input {
|
||||
width: 90px;
|
||||
}
|
||||
|
||||
.parallel-reader-settings .parallel-reader-hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.parallel-reader-container {
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
|
|
@ -387,3 +473,60 @@
|
|||
color: var(--text-faint);
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
/* ---- Generation error UI: actionable notice + diagnostics modal ---- */
|
||||
|
||||
.parallel-reader-error-notice .parallel-reader-error-notice-message {
|
||||
white-space: pre-wrap;
|
||||
margin-bottom: 0.6em;
|
||||
}
|
||||
|
||||
.parallel-reader-error-notice .parallel-reader-error-notice-actions {
|
||||
display: flex;
|
||||
gap: 0.4em;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.parallel-reader-error-notice .parallel-reader-error-notice-button {
|
||||
padding: 0.25em 0.7em;
|
||||
font-size: 0.85em;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.parallel-reader-error-modal .parallel-reader-error-modal-grid {
|
||||
display: grid;
|
||||
grid-template-columns: max-content 1fr;
|
||||
column-gap: 0.8em;
|
||||
row-gap: 0.2em;
|
||||
font-size: 0.85em;
|
||||
margin: 0.6em 0;
|
||||
}
|
||||
|
||||
.parallel-reader-error-modal .parallel-reader-error-modal-row {
|
||||
display: contents;
|
||||
}
|
||||
|
||||
.parallel-reader-error-modal .parallel-reader-error-modal-label {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.parallel-reader-error-modal .parallel-reader-error-modal-value {
|
||||
font-family: var(--font-monospace);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.parallel-reader-error-modal .parallel-reader-error-modal-tail {
|
||||
background: var(--background-secondary);
|
||||
padding: 0.6em 0.8em;
|
||||
border-radius: 4px;
|
||||
font-size: 0.8em;
|
||||
max-height: 240px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.parallel-reader-error-modal .parallel-reader-error-modal-empty {
|
||||
color: var(--text-muted);
|
||||
font-style: italic;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,4 +22,22 @@ assert.strictEqual(
|
|||
'unicode anchor match',
|
||||
);
|
||||
|
||||
// ── perf: precomputed line-offset index must yield identical results ──
|
||||
const doc = 'l0\nl1\nl2 needle here\nl3\n\nl5 tail';
|
||||
const offsets = t.buildLineOffsets(doc);
|
||||
assert.deepStrictEqual(offsets, [0, 3, 6, 21, 24, 25], 'buildLineOffsets marks each line start');
|
||||
assert.strictEqual(
|
||||
t.findLineForAnchor(doc, 'needle here', offsets),
|
||||
t.findLineForAnchor(doc, 'needle here'),
|
||||
'threaded offsets match self-computed result (exact path)',
|
||||
);
|
||||
assert.strictEqual(t.findLineForAnchor(doc, 'tail', offsets), 5, 'threaded offsets resolve trailing line');
|
||||
// Non-ASCII whitespace (NBSP ) must still normalize like /\s/ did.
|
||||
assert.strictEqual(
|
||||
t.findLineForAnchor('x\ny\nAlpha beta gamma\nz', 'Alpha beta gamma'),
|
||||
2,
|
||||
'NBSP collapses to single space in normalized fallback match',
|
||||
);
|
||||
assert.strictEqual(t.buildLineOffsets('')[0], 0, 'empty content still has line 0');
|
||||
|
||||
console.log('anchor tests passed');
|
||||
|
|
|
|||
221
tests/backend-test.test.js
Normal file
221
tests/backend-test.test.js
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
const { assert, baseSettings, EventEmitter, openAiCardsResponse, t } = require('./test-setup');
|
||||
|
||||
function createFakeChild(stdoutText, stderrText = '', code = 0) {
|
||||
const child = new EventEmitter();
|
||||
child.stdout = new EventEmitter();
|
||||
child.stderr = new EventEmitter();
|
||||
child.stdin = {
|
||||
written: '',
|
||||
ended: false,
|
||||
write(value) {
|
||||
this.written += value;
|
||||
},
|
||||
end() {
|
||||
this.ended = true;
|
||||
},
|
||||
};
|
||||
child.pid = 1234;
|
||||
child.kill = () => true;
|
||||
|
||||
process.nextTick(() => {
|
||||
if (stdoutText) child.stdout.emit('data', Buffer.from(stdoutText));
|
||||
if (stderrText) child.stderr.emit('data', Buffer.from(stderrText));
|
||||
child.emit('close', code, null);
|
||||
});
|
||||
|
||||
return child;
|
||||
}
|
||||
|
||||
async function testClaudeBackendRunsVersionAndSmoke() {
|
||||
const calls = [];
|
||||
const streamJson = [
|
||||
JSON.stringify({ type: 'system', subtype: 'init', tools: ['LSP'] }),
|
||||
JSON.stringify({
|
||||
type: 'result',
|
||||
result: '{"cards":[{"title":"CLI smoke","anchor":"parallel reader smoke anchor","gist":"ok","bullets":["ok"]}]}',
|
||||
}),
|
||||
'',
|
||||
].join('\n');
|
||||
const spawnImpl = (cmd, args) => {
|
||||
calls.push({ cmd, args });
|
||||
if (args.includes('--version')) return createFakeChild('2.1.133 (Claude Code)\n');
|
||||
return createFakeChild(streamJson);
|
||||
};
|
||||
|
||||
const result = await t.testBackend(
|
||||
{
|
||||
...baseSettings,
|
||||
backend: 'claude-code',
|
||||
cliPath: '/usr/bin/claude',
|
||||
cliTimeoutMs: 300000,
|
||||
model: 'claude-sonnet-4-6',
|
||||
promptLanguage: 'zh',
|
||||
minCards: 5,
|
||||
maxCards: 15,
|
||||
maxDocChars: 100000,
|
||||
},
|
||||
{ spawnImpl },
|
||||
);
|
||||
|
||||
assert.match(result, /claude @ \/usr\/bin\/claude/, 'result shows resolved Claude command');
|
||||
assert.match(result, /2\.1\.133/, 'result includes CLI version output');
|
||||
assert.match(result, /smoke: 1 card/, 'result includes parsed smoke-card count');
|
||||
assert.deepStrictEqual(calls[0].args, ['--version'], 'first Claude call checks version');
|
||||
|
||||
const smokeArgs = calls[1].args;
|
||||
assert.strictEqual(smokeArgs[0], '-p', 'Claude smoke uses print mode');
|
||||
assert.strictEqual(
|
||||
smokeArgs[smokeArgs.indexOf('--output-format') + 1],
|
||||
'stream-json',
|
||||
'Claude smoke uses stream-json for incremental output',
|
||||
);
|
||||
assert.ok(
|
||||
smokeArgs.includes('--verbose'),
|
||||
'Claude smoke must include --verbose (required alongside stream-json on CLI 2.1.131+)',
|
||||
);
|
||||
assert.strictEqual(smokeArgs[smokeArgs.indexOf('--tools') + 1], '', 'Claude smoke disables tools');
|
||||
assert.ok(smokeArgs.includes('--strict-mcp-config'), 'Claude smoke ignores user/project MCP servers');
|
||||
assert.strictEqual(
|
||||
smokeArgs[smokeArgs.indexOf('--mcp-config') + 1],
|
||||
'{"mcpServers":{}}',
|
||||
'Claude smoke passes an empty MCP config',
|
||||
);
|
||||
}
|
||||
|
||||
async function testCodexBackendRunsVersionAndSmoke() {
|
||||
const calls = [];
|
||||
const resultJson =
|
||||
'{"cards":[{"title":"CLI smoke","anchor":"parallel reader smoke anchor","gist":"ok","bullets":["ok"]}]}';
|
||||
const spawnImpl = (cmd, args) => {
|
||||
calls.push({ cmd, args });
|
||||
if (args.includes('--version')) return createFakeChild('codex-cli 1.2.3\n');
|
||||
return createFakeChild(resultJson);
|
||||
};
|
||||
|
||||
const result = await t.testBackend(
|
||||
{
|
||||
...baseSettings,
|
||||
backend: 'codex',
|
||||
cliPath: '/usr/bin/codex',
|
||||
cliTimeoutMs: 300000,
|
||||
promptLanguage: 'zh',
|
||||
minCards: 5,
|
||||
maxCards: 15,
|
||||
maxDocChars: 100000,
|
||||
},
|
||||
{ spawnImpl },
|
||||
);
|
||||
|
||||
assert.match(result, /codex @ \/usr\/bin\/codex/, 'result shows resolved Codex command');
|
||||
assert.match(result, /codex-cli 1\.2\.3/, 'result includes CLI version output');
|
||||
assert.match(result, /smoke: 1 card/, 'result includes parsed smoke-card count');
|
||||
assert.deepStrictEqual(calls[0].args, ['--version'], 'first Codex call checks version');
|
||||
assert.strictEqual(calls[1].args[0], 'exec', 'Codex smoke runs through codex exec');
|
||||
assert.strictEqual(calls[1].args[calls[1].args.indexOf('--sandbox') + 1], 'read-only', 'Codex smoke is read-only');
|
||||
}
|
||||
|
||||
async function testApiBackendUsesInjectedRequestUrl() {
|
||||
let called = false;
|
||||
const result = await t.testBackend(
|
||||
{
|
||||
...baseSettings,
|
||||
apiHeaders: '',
|
||||
maxDocChars: 100000,
|
||||
promptLanguage: 'zh',
|
||||
minCards: 5,
|
||||
maxCards: 15,
|
||||
},
|
||||
{
|
||||
requestUrlImpl: async () => {
|
||||
called = true;
|
||||
return openAiCardsResponse([]);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
assert.strictEqual(called, true, 'API backend test should use injected requestUrl');
|
||||
assert.strictEqual(result, 'OpenAI / OpenAI Chat Completions', 'API backend test reports provider and format');
|
||||
}
|
||||
|
||||
// Regression: smoke flow must propagate the canary stderr that real Claude CLI
|
||||
// emits when --output-format=stream-json is passed without --verbose.
|
||||
async function testClaudeBackendSurfacesVerboseError() {
|
||||
const spawnImpl = (_cmd, args) => {
|
||||
if (args.includes('--version')) return createFakeChild('2.1.133 (Claude Code)\n');
|
||||
// smoke call: simulate the exact stderr the real CLI emits when --verbose is missing
|
||||
return createFakeChild('', 'Error: When using --print, --output-format=stream-json requires --verbose', 1);
|
||||
};
|
||||
|
||||
await assert.rejects(
|
||||
() =>
|
||||
t.testBackend(
|
||||
{
|
||||
...baseSettings,
|
||||
backend: 'claude-code',
|
||||
cliPath: '/usr/bin/claude',
|
||||
cliTimeoutMs: 300000,
|
||||
model: 'claude-sonnet-4-6',
|
||||
promptLanguage: 'zh',
|
||||
minCards: 5,
|
||||
maxCards: 15,
|
||||
maxDocChars: 100000,
|
||||
},
|
||||
{ spawnImpl },
|
||||
),
|
||||
(err) => {
|
||||
assert.ok(err instanceof t.CliProcessError, 'verbose-regression smoke surfaces CliProcessError');
|
||||
assert.match(err.details.stderrTail, /requires --verbose/, 'stderr tail preserves the verbose-flag hint');
|
||||
assert.strictEqual(err.details.exitCode, 1, 'preserves CLI exit code so UI can classify');
|
||||
return true;
|
||||
},
|
||||
'testBackend must propagate Claude smoke failures (including verbose-flag regression) as structured errors',
|
||||
);
|
||||
}
|
||||
|
||||
// Regression: if `<cli> --version` itself fails, testBackend must throw before reaching smoke,
|
||||
// not silently report success with garbage version output.
|
||||
async function testCodexBackendPropagatesVersionFailure() {
|
||||
const calls = [];
|
||||
const spawnImpl = (_cmd, args) => {
|
||||
calls.push(args);
|
||||
if (args.includes('--version')) return createFakeChild('', 'codex: command not found', 127);
|
||||
return createFakeChild('{"cards":[]}');
|
||||
};
|
||||
|
||||
await assert.rejects(
|
||||
() =>
|
||||
t.testBackend(
|
||||
{
|
||||
...baseSettings,
|
||||
backend: 'codex',
|
||||
cliPath: '/usr/bin/codex',
|
||||
cliTimeoutMs: 300000,
|
||||
promptLanguage: 'zh',
|
||||
minCards: 5,
|
||||
maxCards: 15,
|
||||
maxDocChars: 100000,
|
||||
},
|
||||
{ spawnImpl },
|
||||
),
|
||||
(err) => {
|
||||
assert.ok(err instanceof t.CliProcessError, 'version failure surfaces structured CliProcessError');
|
||||
assert.strictEqual(err.details.exitCode, 127, 'preserves shell command-not-found exit code');
|
||||
return true;
|
||||
},
|
||||
'testBackend must not swallow version-probe failures',
|
||||
);
|
||||
assert.strictEqual(calls.length, 1, 'smoke call must NOT run after version probe fails');
|
||||
assert.deepStrictEqual(calls[0], ['--version'], 'only the version probe should have been spawned');
|
||||
}
|
||||
|
||||
(async () => {
|
||||
await testClaudeBackendRunsVersionAndSmoke();
|
||||
await testClaudeBackendSurfacesVerboseError();
|
||||
await testCodexBackendRunsVersionAndSmoke();
|
||||
await testCodexBackendPropagatesVersionFailure();
|
||||
await testApiBackendUsesInjectedRequestUrl();
|
||||
console.log('backend-test tests passed');
|
||||
})().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
|
@ -38,6 +38,7 @@
|
|||
"description": "Tests for provider protocols, CLI command contracts, exported test surfaces, and architecture invariants.",
|
||||
"files": [
|
||||
"architecture.test.js",
|
||||
"backend-test.test.js",
|
||||
"cli.test.js",
|
||||
"direct-providers.test.js",
|
||||
"providers.test.js",
|
||||
|
|
|
|||
|
|
@ -51,10 +51,31 @@ function createFakeChild() {
|
|||
|
||||
async function testRunCliEdgeCases() {
|
||||
const timeoutChild = createFakeChild();
|
||||
timeoutChild.pid = 4242;
|
||||
await assert.rejects(
|
||||
() => t.runCli('fake', [], '', 5, undefined, () => timeoutChild),
|
||||
/CLI timed out \(5ms\)/,
|
||||
'runCli rejects on timeout',
|
||||
() => {
|
||||
// emit some bytes before timeout so we can verify the diagnostic suffix carries them
|
||||
setImmediate(() => {
|
||||
timeoutChild.stderr.emit('data', Buffer.from('boom: connection reset'));
|
||||
});
|
||||
return t.runCli('fake', [], '', 20, undefined, () => timeoutChild);
|
||||
},
|
||||
(err) => {
|
||||
assert.match(err.message, /CLI timed out \(20ms\)/, 'wall-clock timeout keeps original prefix');
|
||||
assert.match(err.message, /pid=4242/, 'timeout error carries pid');
|
||||
assert.match(err.message, /stderr=\d+B/, 'timeout error carries stderr byte count');
|
||||
assert.match(err.message, /stderr tail/, 'timeout error includes stderr tail');
|
||||
assert.match(err.message, /boom: connection reset/, 'timeout error preserves last stderr line');
|
||||
// Structured CliProcessError details (P0 #2: error UI dispatch needs typed access).
|
||||
assert.ok(err instanceof t.CliProcessError, 'wall-timeout throws CliProcessError');
|
||||
assert.strictEqual(err.details.reason, 'wall-timeout', 'wall-timeout reason set');
|
||||
assert.strictEqual(err.details.pid, 4242, 'details.pid populated');
|
||||
assert.ok(err.details.stderrBytes >= 'boom: connection reset'.length, 'details.stderrBytes utf-8 byte count');
|
||||
assert.match(err.details.stderrTail, /boom: connection reset/, 'details.stderrTail preserved');
|
||||
assert.strictEqual(err.details.timeoutMs, 20, 'details.timeoutMs reflects wall timeout');
|
||||
return true;
|
||||
},
|
||||
'runCli rejects on timeout with rich diagnostics',
|
||||
);
|
||||
assert.strictEqual(timeoutChild.killedWith, 'SIGKILL', 'runCli kills timed out processes');
|
||||
|
||||
|
|
@ -83,9 +104,56 @@ async function testRunCliEdgeCases() {
|
|||
|
||||
await assert.rejects(
|
||||
() => t.runCli('fake', [], '', 100, undefined, () => ({ stdout: null, stderr: null, stdin: null })),
|
||||
/CLI process streams are unavailable/,
|
||||
(err) => {
|
||||
assert.match(err.message, /CLI process streams are unavailable/, 'streams-unavailable message preserved');
|
||||
assert.ok(err instanceof t.CliProcessError, 'streams-unavailable throws CliProcessError');
|
||||
assert.strictEqual(err.details.reason, 'streams-unavailable', 'streams-unavailable reason set');
|
||||
return true;
|
||||
},
|
||||
'runCli reports unavailable stdio streams',
|
||||
);
|
||||
|
||||
// Non-zero exit still throws a typed CliProcessError so dispatcher can inspect stderr.
|
||||
const exitChild = createFakeChild();
|
||||
exitChild.pid = 7373;
|
||||
const exitPromise = t.runCli('fake', [], '', 1000, undefined, () => exitChild);
|
||||
setImmediate(() => {
|
||||
exitChild.stderr.emit('data', Buffer.from('error: invalid api key'));
|
||||
exitChild.emit('close', 2, null);
|
||||
});
|
||||
await assert.rejects(
|
||||
() => exitPromise,
|
||||
(err) => {
|
||||
assert.ok(err instanceof t.CliProcessError, 'exit-nonzero throws CliProcessError');
|
||||
assert.strictEqual(err.details.reason, 'exit-nonzero', 'exit-nonzero reason set');
|
||||
assert.strictEqual(err.details.exitCode, 2, 'details.exitCode populated');
|
||||
assert.match(err.details.stderrTail, /invalid api key/, 'details.stderrTail captures auth hint');
|
||||
return true;
|
||||
},
|
||||
'runCli exposes non-zero exit code in structured details',
|
||||
);
|
||||
|
||||
// Diagnostic suffix must redact secrets that show up in stderr (Bearer tokens, sk- keys, etc.)
|
||||
const secretChild = createFakeChild();
|
||||
secretChild.pid = 6363;
|
||||
await assert.rejects(
|
||||
() => {
|
||||
setImmediate(() => {
|
||||
secretChild.stderr.emit(
|
||||
'data',
|
||||
Buffer.from('Authorization: Bearer sk-ant-supersecrettoken-xyz123 failed handshake'),
|
||||
);
|
||||
});
|
||||
return t.runCli('fake', [], '', 20, undefined, () => secretChild);
|
||||
},
|
||||
(err) => {
|
||||
assert.doesNotMatch(err.message, /sk-ant-supersecrettoken-xyz123/, 'token must not appear verbatim');
|
||||
assert.match(err.message, /\[REDACTED\]/, 'redaction marker present');
|
||||
assert.match(err.message, /failed handshake/, 'non-secret context preserved');
|
||||
return true;
|
||||
},
|
||||
'runCli timeout suffix redacts secrets',
|
||||
);
|
||||
}
|
||||
|
||||
// ── summarizeViaClaudeCode args validation ──
|
||||
|
|
@ -190,13 +258,79 @@ async function testClaudeCodeArgs() {
|
|||
// Verify key expected flags are present
|
||||
assert.ok(capturedArgs.includes('-p'), 'should include -p (print mode)');
|
||||
assert.ok(capturedArgs.includes('--output-format'), 'should include --output-format');
|
||||
assert.strictEqual(
|
||||
capturedArgs[capturedArgs.indexOf('--output-format') + 1],
|
||||
'stream-json',
|
||||
'claude output should stream JSON events',
|
||||
);
|
||||
assert.ok(capturedArgs.includes('--verbose'), 'stream-json requires --verbose in Claude CLI 2.1.131+');
|
||||
assert.ok(capturedArgs.includes('--append-system-prompt'), 'should include --append-system-prompt');
|
||||
assert.ok(capturedArgs.includes('--tools'), 'should explicitly restrict Claude tools');
|
||||
assert.strictEqual(capturedArgs[capturedArgs.indexOf('--tools') + 1], '', 'Claude tools should be disabled');
|
||||
assert.ok(capturedArgs.includes('--disallowed-tools'), 'should include --disallowed-tools');
|
||||
assert.ok(capturedArgs.includes('--no-session-persistence'), 'should avoid session persistence for plugin calls');
|
||||
assert.ok(capturedArgs.includes('--disable-slash-commands'), 'should disable slash commands for plugin calls');
|
||||
assert.ok(capturedArgs.includes('--no-chrome'), 'should suppress Claude TUI chrome');
|
||||
assert.ok(capturedArgs.includes('--strict-mcp-config'), 'should ignore user/project MCP servers');
|
||||
assert.strictEqual(
|
||||
capturedArgs[capturedArgs.indexOf('--mcp-config') + 1],
|
||||
'{"mcpServers":{}}',
|
||||
'--mcp-config must pair with an empty MCP server map',
|
||||
);
|
||||
assert.strictEqual(
|
||||
capturedArgs[capturedArgs.indexOf('--disallowed-tools') + 1],
|
||||
'Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch,TodoWrite,Task,LSP,NotebookEdit',
|
||||
'--disallowed-tools must list every tool that could exfiltrate or mutate',
|
||||
);
|
||||
// Ordering: -p must come before --output-format so Claude treats the run as print-mode.
|
||||
assert.ok(
|
||||
capturedArgs.indexOf('-p') < capturedArgs.indexOf('--output-format'),
|
||||
'-p must appear before --output-format',
|
||||
);
|
||||
// --verbose must accompany --output-format stream-json (Claude CLI 2.1.131+ requirement).
|
||||
// The CLI does not constrain position; we only check that --verbose is not consumed as the value of
|
||||
// another flag — i.e. it must not appear at index `--output-format` + 1 (where 'stream-json' belongs).
|
||||
const outputFmtIdx = capturedArgs.indexOf('--output-format');
|
||||
const verboseIdx = capturedArgs.indexOf('--verbose');
|
||||
assert.notStrictEqual(verboseIdx, outputFmtIdx + 1, '--verbose must not be parsed as the --output-format value');
|
||||
|
||||
// Verify --max-tokens is NOT present (it's not a valid claude CLI flag)
|
||||
assert.ok(!capturedArgs.includes('--max-tokens'), 'should NOT include --max-tokens');
|
||||
}
|
||||
|
||||
async function testClaudeCodeStreamJsonOutput() {
|
||||
const streamJson = [
|
||||
JSON.stringify({ type: 'system', subtype: 'init', tools: ['LSP'] }),
|
||||
JSON.stringify({
|
||||
type: 'result',
|
||||
result: '{"cards":[{"title":"T","anchor":"hello world test anchor","gist":"G","bullets":["B"]}]}',
|
||||
}),
|
||||
'',
|
||||
].join('\n');
|
||||
const fakeSpawn = () => {
|
||||
const child = createFakeChild();
|
||||
process.nextTick(() => {
|
||||
child.stdout.emit('data', Buffer.from(streamJson));
|
||||
child.emit('close', 0);
|
||||
});
|
||||
return child;
|
||||
};
|
||||
|
||||
const settings = {
|
||||
backend: 'claude-code',
|
||||
cliPath: '/usr/bin/claude',
|
||||
cliTimeoutMs: 5000,
|
||||
promptLanguage: 'zh',
|
||||
minCards: 5,
|
||||
maxCards: 15,
|
||||
maxDocChars: 100000,
|
||||
};
|
||||
|
||||
const cards = await t.summarizeViaClaudeCode('system prompt', 'user content', settings, undefined, fakeSpawn);
|
||||
assert.strictEqual(cards.length, 1, 'claude stream-json result event is parsed');
|
||||
assert.strictEqual(cards[0].title, 'T', 'parsed card title preserved');
|
||||
}
|
||||
|
||||
// ── summarizeViaCodex args validation ──
|
||||
|
||||
// Known flags/subcommands supported by `codex exec` (from `codex exec --help`).
|
||||
|
|
@ -356,12 +490,254 @@ async function testClaudeCodeArgsWithModel() {
|
|||
assert.strictEqual(capturedArgs[modelIdx + 1], 'claude-opus-4-7', 'claude --model value matches settings.model');
|
||||
}
|
||||
|
||||
// ── Claude stream-json parse resilience ──
|
||||
|
||||
async function runClaudeCodeWithStdout(stdoutText) {
|
||||
const fakeSpawn = () => {
|
||||
const child = createFakeChild();
|
||||
process.nextTick(() => {
|
||||
if (stdoutText) child.stdout.emit('data', Buffer.from(stdoutText));
|
||||
child.emit('close', 0);
|
||||
});
|
||||
return child;
|
||||
};
|
||||
const settings = {
|
||||
backend: 'claude-code',
|
||||
cliPath: '/usr/bin/claude',
|
||||
cliTimeoutMs: 5000,
|
||||
promptLanguage: 'zh',
|
||||
minCards: 1,
|
||||
maxCards: 15,
|
||||
maxDocChars: 100000,
|
||||
};
|
||||
return t.summarizeViaClaudeCode('system', 'user', settings, undefined, fakeSpawn);
|
||||
}
|
||||
|
||||
async function testClaudeCodeStreamJsonResilience() {
|
||||
// B1: NDJSON with non-JSON banner line — must skip banner and still parse the result event.
|
||||
const withBanner = [
|
||||
'Claude Code 2.1.131',
|
||||
JSON.stringify({ type: 'system', subtype: 'init', tools: ['LSP'] }),
|
||||
JSON.stringify({
|
||||
type: 'result',
|
||||
result: '{"cards":[{"title":"B1","anchor":"hello world test anchor","gist":"G","bullets":["B"]}]}',
|
||||
}),
|
||||
].join('\n');
|
||||
const b1 = await runClaudeCodeWithStdout(withBanner);
|
||||
assert.strictEqual(b1.length, 1, 'B1: banner line is skipped and result parsed');
|
||||
assert.strictEqual(b1[0].title, 'B1', 'B1: card title preserved');
|
||||
|
||||
// B2: Missing result event — must throw a recognizable "no result" error (not a crash inside parser).
|
||||
// Match both zh ("没有返回结果") and en ("returned no result") so the assertion survives translate() fallback differences.
|
||||
const noResultRegex = /没有返回结果|returned no result/i;
|
||||
const onlyInit = JSON.stringify({ type: 'system', subtype: 'init', tools: [] }) + '\n';
|
||||
await assert.rejects(
|
||||
() => runClaudeCodeWithStdout(onlyInit),
|
||||
(err) => noResultRegex.test(err.message),
|
||||
'B2: missing result event throws a descriptive "no result" error',
|
||||
);
|
||||
|
||||
// B3: Empty stdout — same behavior: must throw, not crash on undefined / silent success.
|
||||
await assert.rejects(
|
||||
() => runClaudeCodeWithStdout(''),
|
||||
(err) => noResultRegex.test(err.message),
|
||||
'B3: empty stdout throws a descriptive "no result" error',
|
||||
);
|
||||
|
||||
// B4: Multiple result events — last one wins (claudeResultText scans in reverse).
|
||||
const twoResults = [
|
||||
JSON.stringify({
|
||||
type: 'result',
|
||||
result: '{"cards":[{"title":"FIRST","anchor":"hello world test anchor","gist":"G","bullets":["B"]}]}',
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: 'result',
|
||||
result: '{"cards":[{"title":"LAST","anchor":"hello world test anchor","gist":"G","bullets":["B"]}]}',
|
||||
}),
|
||||
].join('\n');
|
||||
const b4 = await runClaudeCodeWithStdout(twoResults);
|
||||
assert.strictEqual(b4.length, 1, 'B4: latest result event is used');
|
||||
assert.strictEqual(b4[0].title, 'LAST', 'B4: last result wins over earlier ones');
|
||||
|
||||
// B5: Single-event object with `content` (not `result`) — covers the legacy fallback path
|
||||
// where claudeResultText reads `events[0].content` when no `type: result` event exists.
|
||||
const contentFallback = JSON.stringify({
|
||||
content: '{"cards":[{"title":"B5","anchor":"hello world test anchor","gist":"G","bullets":["B"]}]}',
|
||||
});
|
||||
const b5 = await runClaudeCodeWithStdout(contentFallback);
|
||||
assert.strictEqual(b5.length, 1, 'B5: events[0].content fallback parses card');
|
||||
assert.strictEqual(b5[0].title, 'B5', 'B5: content-fallback card title preserved');
|
||||
}
|
||||
|
||||
// ── Claude verbose-missing error-path plumbing ──
|
||||
// This does NOT guard the --verbose flag itself (that is locked by
|
||||
// `testClaudeCodeArgs`'s `capturedArgs.includes('--verbose')` assertion, which fails
|
||||
// in fake-spawn before any stderr is even simulated).
|
||||
// Instead, this test simulates the *real* stderr that Claude CLI emits when
|
||||
// --verbose is missing, and asserts that the error-propagation pipeline preserves
|
||||
// exit code + stderr tail so the UI can render a useful diagnostic. If we ever
|
||||
// rework error handling and accidentally swallow CLI stderr, this catches it.
|
||||
|
||||
async function testClaudeCodeVerboseRegressionCanary() {
|
||||
const fakeSpawn = () => {
|
||||
const child = createFakeChild();
|
||||
process.nextTick(() => {
|
||||
child.stderr.emit(
|
||||
'data',
|
||||
Buffer.from('Error: When using --print, --output-format=stream-json requires --verbose'),
|
||||
);
|
||||
child.emit('close', 1, null);
|
||||
});
|
||||
return child;
|
||||
};
|
||||
const settings = {
|
||||
backend: 'claude-code',
|
||||
cliPath: '/usr/bin/claude',
|
||||
cliTimeoutMs: 5000,
|
||||
promptLanguage: 'zh',
|
||||
minCards: 1,
|
||||
maxCards: 15,
|
||||
maxDocChars: 100000,
|
||||
};
|
||||
await assert.rejects(
|
||||
() => t.summarizeViaClaudeCode('system', 'user', settings, undefined, fakeSpawn),
|
||||
(err) => {
|
||||
assert.ok(err instanceof t.CliProcessError, 'canary: throws CliProcessError on exit-nonzero');
|
||||
assert.strictEqual(err.details.reason, 'exit-nonzero', 'canary: exit-nonzero reason');
|
||||
assert.strictEqual(err.details.exitCode, 1, 'canary: surfaces CLI exit code');
|
||||
assert.match(err.details.stderrTail, /requires --verbose/, 'canary: preserves verbose-flag hint in stderr');
|
||||
return true;
|
||||
},
|
||||
'Claude CLI verbose-missing stderr surfaces as a structured CliProcessError',
|
||||
);
|
||||
}
|
||||
|
||||
// ── Codex error path ──
|
||||
|
||||
async function testCodexErrorPath() {
|
||||
const fakeSpawn = () => {
|
||||
const child = createFakeChild();
|
||||
process.nextTick(() => {
|
||||
child.stderr.emit('data', Buffer.from('error: not authenticated, please run codex login'));
|
||||
child.emit('close', 2, null);
|
||||
});
|
||||
return child;
|
||||
};
|
||||
const settings = {
|
||||
backend: 'codex',
|
||||
cliPath: '/usr/bin/codex',
|
||||
cliTimeoutMs: 5000,
|
||||
promptLanguage: 'zh',
|
||||
minCards: 1,
|
||||
maxCards: 15,
|
||||
maxDocChars: 100000,
|
||||
};
|
||||
await assert.rejects(
|
||||
() => t.summarizeViaCodex('system', 'user', settings, undefined, fakeSpawn),
|
||||
(err) => {
|
||||
assert.ok(err instanceof t.CliProcessError, 'codex: throws CliProcessError on exit-nonzero');
|
||||
assert.strictEqual(err.details.exitCode, 2, 'codex: exit code preserved');
|
||||
assert.match(err.details.stderrTail, /not authenticated/, 'codex: stderr tail preserves auth hint');
|
||||
return true;
|
||||
},
|
||||
'codex non-zero exit propagates structured error',
|
||||
);
|
||||
}
|
||||
|
||||
// ── Codex args minimal contract ──
|
||||
// Lock in the exact minimal arg shape: any drift means we are leaking new flags
|
||||
// into a CLI that is intentionally kept minimal (no --model, no --cd, no -c).
|
||||
|
||||
async function testCodexArgsMinimalContract() {
|
||||
let capturedArgs = null;
|
||||
const resultJson = '{"cards":[{"title":"T","anchor":"hello world test anchor","gist":"G","bullets":["B"]}]}';
|
||||
const fakeSpawn = (_cmd, args) => {
|
||||
capturedArgs = args;
|
||||
const child = createFakeChild();
|
||||
process.nextTick(() => {
|
||||
child.stdout.emit('data', Buffer.from(resultJson));
|
||||
child.emit('close', 0);
|
||||
});
|
||||
return child;
|
||||
};
|
||||
const settings = {
|
||||
backend: 'codex',
|
||||
cliPath: '/usr/bin/codex',
|
||||
cliTimeoutMs: 5000,
|
||||
promptLanguage: 'zh',
|
||||
minCards: 1,
|
||||
maxCards: 15,
|
||||
maxDocChars: 100000,
|
||||
};
|
||||
await t.summarizeViaCodex('system', 'user', settings, undefined, fakeSpawn);
|
||||
|
||||
// Exact list lock: changes here are intentional and require updating the test.
|
||||
assert.deepStrictEqual(
|
||||
capturedArgs,
|
||||
['exec', '--skip-git-repo-check', '--sandbox', 'read-only', '-'],
|
||||
'codex exec args must remain minimal (exec + skip-git + read-only sandbox + stdin marker)',
|
||||
);
|
||||
}
|
||||
|
||||
// ── classifyGenerationError ──
|
||||
|
||||
assert.strictEqual(t.classifyGenerationError(new Error('API key 未设置')), 'auth');
|
||||
assert.strictEqual(t.classifyGenerationError(new Error('API key is not set')), 'auth');
|
||||
assert.strictEqual(t.classifyGenerationError(new Error('CLI timed out (120000ms)')), 'timeout');
|
||||
assert.strictEqual(t.classifyGenerationError(new Error('CLI 超时 (120000ms)')), 'timeout');
|
||||
|
||||
// Structured CliProcessError short-circuits message-regex matching for deterministic reasons.
|
||||
const wallTimeout = new t.CliProcessError('whatever message text', {
|
||||
reason: 'wall-timeout',
|
||||
cmd: 'claude',
|
||||
pid: 1,
|
||||
elapsedMs: 0,
|
||||
idleMs: 0,
|
||||
stdoutBytes: 0,
|
||||
stderrBytes: 0,
|
||||
stdoutTail: '',
|
||||
stderrTail: '',
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
timeoutMs: 0,
|
||||
});
|
||||
assert.strictEqual(t.classifyGenerationError(wallTimeout), 'timeout', 'wall-timeout details → timeout kind');
|
||||
const spawnFailure = new t.CliProcessError('Failed to start claude', {
|
||||
reason: 'spawn-failure',
|
||||
cmd: 'claude',
|
||||
pid: null,
|
||||
elapsedMs: 0,
|
||||
idleMs: null,
|
||||
stdoutBytes: 0,
|
||||
stderrBytes: 0,
|
||||
stdoutTail: '',
|
||||
stderrTail: '',
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
timeoutMs: 0,
|
||||
});
|
||||
assert.strictEqual(t.classifyGenerationError(spawnFailure), 'config', 'spawn-failure details → config kind');
|
||||
// exit-nonzero falls through so stderr-derived auth/rate-limit messages can still classify.
|
||||
const exitWithAuthStderr = new t.CliProcessError('CLI exited with code 1\nstderr:\nerror: API key invalid', {
|
||||
reason: 'exit-nonzero',
|
||||
cmd: 'claude',
|
||||
pid: 1,
|
||||
elapsedMs: 0,
|
||||
idleMs: 0,
|
||||
stdoutBytes: 0,
|
||||
stderrBytes: 0,
|
||||
stdoutTail: '',
|
||||
stderrTail: '',
|
||||
exitCode: 1,
|
||||
signal: null,
|
||||
timeoutMs: 0,
|
||||
});
|
||||
assert.strictEqual(
|
||||
t.classifyGenerationError(exitWithAuthStderr),
|
||||
'auth',
|
||||
'exit-nonzero falls through so message-regex still detects auth',
|
||||
);
|
||||
|
||||
assert.strictEqual(t.classifyGenerationError(new Error('API returned HTTP 429')), 'rate-limit');
|
||||
assert.strictEqual(t.classifyGenerationError(new Error('json_schema validation failed')), 'schema');
|
||||
assert.strictEqual(t.classifyGenerationError(new Error('LLM 返回非 JSON')), 'schema');
|
||||
|
|
@ -398,9 +774,14 @@ assert.strictEqual(t.classifyGenerationError('string error'), 'unknown', 'string
|
|||
(async () => {
|
||||
await testRunCliEdgeCases();
|
||||
await testClaudeCodeArgs();
|
||||
await testClaudeCodeStreamJsonOutput();
|
||||
await testClaudeCodeStreamJsonResilience();
|
||||
await testClaudeCodeVerboseRegressionCanary();
|
||||
await testClaudeCodeArgsWithModel();
|
||||
await testCodexArgs();
|
||||
await testCodexArgsIgnoresClaudeDefaultModel();
|
||||
await testCodexArgsMinimalContract();
|
||||
await testCodexErrorPath();
|
||||
console.log('cli tests passed');
|
||||
})().catch((e) => {
|
||||
console.error(e);
|
||||
|
|
|
|||
42
tests/coverage-sourcemap.js
Normal file
42
tests/coverage-sourcemap.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
'use strict';
|
||||
|
||||
// esbuild emits inline source maps whose `sources` are relative to the bundle
|
||||
// file (deep under .test-bundles/) with a `sourceRoot`. v8-to-istanbul / the
|
||||
// source-map library resolve those inconsistently and produce wrong paths like
|
||||
// `/Users/.../github.com/src/batch.ts`, so c8 finds nothing to report.
|
||||
//
|
||||
// This rewrites the inline map in-place so every `source` is an absolute path
|
||||
// to the real repo file and `sourceRoot` is cleared — making the remap exact.
|
||||
// No-op when coverage is not active.
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const MARKER = '//# sourceMappingURL=data:application/json;base64,';
|
||||
|
||||
function fixInlineSourceMap(outfile, repoRoot) {
|
||||
if (!process.env.NODE_V8_COVERAGE) return;
|
||||
const code = fs.readFileSync(outfile, 'utf8');
|
||||
const idx = code.lastIndexOf(MARKER);
|
||||
if (idx === -1) return;
|
||||
const b64 = code.slice(idx + MARKER.length).trim();
|
||||
const map = JSON.parse(Buffer.from(b64, 'base64').toString('utf8'));
|
||||
// esbuild keeps `sources` relative to the bundle file's directory regardless
|
||||
// of `sourceRoot`; resolving against sourceRoot double-counts and corrupts
|
||||
// the path. Always resolve against the bundle directory.
|
||||
const base = path.dirname(outfile);
|
||||
|
||||
map.sources = map.sources.map((src) => {
|
||||
if (src.startsWith('stub:') || src.includes('obsidian-stub')) return src;
|
||||
const abs = path.resolve(base, src);
|
||||
// Strip any leftover climbing artifacts; keep the real repo path.
|
||||
const i = abs.indexOf(repoRoot);
|
||||
return i === -1 ? abs : abs.slice(i);
|
||||
});
|
||||
delete map.sourceRoot;
|
||||
|
||||
const fixed = Buffer.from(JSON.stringify(map), 'utf8').toString('base64');
|
||||
fs.writeFileSync(outfile, code.slice(0, idx) + MARKER + fixed);
|
||||
}
|
||||
|
||||
module.exports = { fixInlineSourceMap };
|
||||
|
|
@ -35,6 +35,31 @@ function createFakeAdapter() {
|
|||
assert.strictEqual(cacheEntry.lastAccessedAt, undefined, 'direct cache import keeps cache entries immutable');
|
||||
assert.strictEqual(JSON.parse(cache.serializeCacheFile({ 'a.md': { cards: [] } })).version, 1);
|
||||
|
||||
// touchCacheEntry: null entry short-circuits to null
|
||||
assert.strictEqual(cache.touchCacheEntry(null), null, 'touchCacheEntry returns null for null entry');
|
||||
// touchCacheEntry: omitted `now` falls back to a generated ISO timestamp
|
||||
const touchedDefault = cache.touchCacheEntry({ generatedAt: '2024-01-01T00:00:00.000Z' });
|
||||
assert.ok(
|
||||
/^\d{4}-\d{2}-\d{2}T/.test(touchedDefault.lastAccessedAt),
|
||||
'touchCacheEntry defaults lastAccessedAt to current ISO time',
|
||||
);
|
||||
// serializeCacheFile: falsy entries map serializes to an empty object
|
||||
assert.deepStrictEqual(
|
||||
JSON.parse(cache.serializeCacheFile(null)).entries,
|
||||
{},
|
||||
'serializeCacheFile coerces falsy entries to {}',
|
||||
);
|
||||
// shouldConfirmRegenerate: every guard branch
|
||||
assert.strictEqual(cache.shouldConfirmRegenerate(null, true), false, 'no entry → false');
|
||||
assert.strictEqual(cache.shouldConfirmRegenerate({ updatedAt: 'x' }, false), false, 'force=false → false');
|
||||
assert.strictEqual(cache.shouldConfirmRegenerate({}, true), false, 'missing updatedAt → false');
|
||||
assert.strictEqual(cache.shouldConfirmRegenerate({ updatedAt: ' ' }, true), false, 'blank updatedAt → false');
|
||||
assert.strictEqual(
|
||||
cache.shouldConfirmRegenerate({ updatedAt: '2024-01-01' }, true),
|
||||
true,
|
||||
'force + non-blank updatedAt → true',
|
||||
);
|
||||
|
||||
// ── CacheManager: load + prune ──
|
||||
const adapter = createFakeAdapter();
|
||||
const manager = new cacheManagerModule.CacheManager(adapter, '.obsidian', 'parallel-reader', () => ({
|
||||
|
|
|
|||
|
|
@ -28,16 +28,65 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'en' }), 'en');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'zh' }), 'zh');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'ja' }), 'ja');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'ko' }), 'ko');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'fr' }), 'fr');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'de' }), 'de');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'es' }), 'es');
|
||||
assert.strictEqual(i18n.resolveUiLanguage(null), 'en');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'auto' }), 'en');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: { toString: () => 'ja' } }), 'en');
|
||||
|
||||
const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator');
|
||||
const setNavigatorLanguage = (language) => {
|
||||
Object.defineProperty(globalThis, 'navigator', {
|
||||
value: { language },
|
||||
configurable: true,
|
||||
});
|
||||
};
|
||||
try {
|
||||
setNavigatorLanguage('ja-JP');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'auto' }), 'ja');
|
||||
setNavigatorLanguage('ko-KR');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'auto' }), 'ko');
|
||||
setNavigatorLanguage('fr-CA');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'auto' }), 'fr');
|
||||
setNavigatorLanguage('de_DE');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'auto' }), 'de');
|
||||
setNavigatorLanguage('es-MX');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'auto' }), 'es');
|
||||
setNavigatorLanguage('it-IT');
|
||||
assert.strictEqual(i18n.resolveUiLanguage({ uiLanguage: 'auto' }), 'en');
|
||||
} finally {
|
||||
if (originalNavigator) {
|
||||
Object.defineProperty(globalThis, 'navigator', originalNavigator);
|
||||
} else {
|
||||
delete globalThis.navigator;
|
||||
}
|
||||
}
|
||||
|
||||
assert.ok(i18n.STRINGS.zh);
|
||||
assert.ok(i18n.STRINGS.en);
|
||||
const zhKeys = Object.keys(i18n.STRINGS.zh);
|
||||
const enKeys = Object.keys(i18n.STRINGS.en);
|
||||
assert.strictEqual(zhKeys.length, enKeys.length);
|
||||
for (const key of zhKeys) {
|
||||
assert.ok(i18n.STRINGS.en[key], `en missing key: ${key}`);
|
||||
assert.ok(i18n.STRINGS.ja);
|
||||
assert.ok(i18n.STRINGS.ko);
|
||||
assert.ok(i18n.STRINGS.fr);
|
||||
assert.ok(i18n.STRINGS.de);
|
||||
assert.ok(i18n.STRINGS.es);
|
||||
const supportedLocales = ['zh', 'en', 'ja', 'ko', 'fr', 'de', 'es'];
|
||||
const enKeys = Object.keys(i18n.STRINGS.en).sort();
|
||||
for (const locale of supportedLocales) {
|
||||
const keys = Object.keys(i18n.STRINGS[locale]).sort();
|
||||
assert.deepStrictEqual(keys, enKeys, `${locale} keys must match en`);
|
||||
for (const key of enKeys) {
|
||||
assert.ok(i18n.STRINGS[locale][key], `${locale} empty key: ${key}`);
|
||||
}
|
||||
}
|
||||
for (const locale of ['ja', 'ko', 'fr', 'de', 'es']) {
|
||||
const overrideKeys = Object.keys(i18n.LOCALE_OVERRIDES[locale]).sort();
|
||||
assert.deepStrictEqual(overrideKeys, enKeys, `${locale} raw override keys must match en`);
|
||||
for (const key of enKeys) {
|
||||
assert.ok(i18n.LOCALE_OVERRIDES[locale][key], `${locale} empty raw override: ${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('direct i18n tests passed');
|
||||
|
|
|
|||
|
|
@ -60,6 +60,9 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
const plainMinimal = md.cardToPlain({ title: 'T', anchor: '', gist: '', bullets: [] });
|
||||
assert.strictEqual(plainMinimal, 'T', 'title only when gist and bullets empty');
|
||||
|
||||
const plainNullBullets = md.cardToPlain({ title: 'T', anchor: '', gist: 'G' });
|
||||
assert.strictEqual(plainNullBullets, 'T\nG', 'undefined bullets coerced to [] (no crash)');
|
||||
|
||||
// ── cardsToMarkdown ──
|
||||
const multi = md.cardsToMarkdown('My Title', [
|
||||
{ title: 'A', anchor: 'q', gist: 'g', bullets: ['b'] },
|
||||
|
|
|
|||
|
|
@ -13,8 +13,13 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
prompt.promptLanguageInstruction('auto'),
|
||||
'Write title, gist, and bullets in the main language of the source document.',
|
||||
);
|
||||
assert.strictEqual(prompt.promptLanguageInstruction('ja'), 'Write title, gist, and bullets in Japanese.');
|
||||
assert.strictEqual(prompt.promptLanguageInstruction('ko'), 'Write title, gist, and bullets in Korean.');
|
||||
assert.strictEqual(prompt.promptLanguageInstruction('fr'), 'Write title, gist, and bullets in French.');
|
||||
assert.strictEqual(prompt.promptLanguageInstruction('de'), 'Write title, gist, and bullets in German.');
|
||||
assert.strictEqual(prompt.promptLanguageInstruction('es'), 'Write title, gist, and bullets in Spanish.');
|
||||
assert.strictEqual(
|
||||
prompt.promptLanguageInstruction('fr'),
|
||||
prompt.promptLanguageInstruction('xx'),
|
||||
'用中文输出 title、gist 和 bullets。',
|
||||
'unknown language falls to zh',
|
||||
);
|
||||
|
|
@ -29,6 +34,11 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
assert.ok(zhExample.includes('"cards"'), 'zh example is JSON-like');
|
||||
|
||||
assert.ok(prompt.promptSchemaExample('auto').includes('U 型收益曲线'), 'auto falls to zh example');
|
||||
assert.ok(prompt.promptSchemaExample('ja').includes('U字型の利益'), 'ja example has expected title');
|
||||
assert.ok(prompt.promptSchemaExample('ko').includes('U자형 이득'), 'ko example has expected title');
|
||||
assert.ok(prompt.promptSchemaExample('fr').includes('Gains en U'), 'fr example has expected title');
|
||||
assert.ok(prompt.promptSchemaExample('de').includes('U-förmige Gewinne'), 'de example has expected title');
|
||||
assert.ok(prompt.promptSchemaExample('es').includes('Ganancias en forma de U'), 'es example has expected title');
|
||||
|
||||
// ── renderPromptTemplate ──
|
||||
assert.strictEqual(prompt.renderPromptTemplate('Hello {name}!', { name: 'World' }), 'Hello World!');
|
||||
|
|
@ -55,6 +65,19 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
const autoResult = prompt.buildPrompts('content', { ...base, promptLanguage: 'auto' });
|
||||
assert.ok(autoResult.system.includes('main language'), 'auto language instruction');
|
||||
|
||||
// ── buildPrompts: expanded output languages ──
|
||||
for (const [language, expected] of [
|
||||
['ja', 'Japanese'],
|
||||
['ko', 'Korean'],
|
||||
['fr', 'French'],
|
||||
['de', 'German'],
|
||||
['es', 'Spanish'],
|
||||
]) {
|
||||
const result = prompt.buildPrompts('content', { ...base, promptLanguage: language });
|
||||
assert.ok(result.system.includes(expected), `${language} language instruction`);
|
||||
assert.ok(result.user.includes('Source document:'), `${language} uses provider-facing source prefix`);
|
||||
}
|
||||
|
||||
// ── buildPrompts: truncation ──
|
||||
const longDoc = 'x'.repeat(25000);
|
||||
const truncResult = prompt.buildPrompts(longDoc, { ...base, maxDocChars: 20000 });
|
||||
|
|
@ -81,9 +104,11 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
const wsCustom = prompt.buildPrompts('doc', { ...base, customSystemPrompt: ' ' });
|
||||
assert.ok(wsCustom.system.includes('long-form reading'), 'default prompt used when custom is whitespace-only');
|
||||
|
||||
// ── buildPrompts: invalid promptLanguage falls back ──
|
||||
// ── buildPrompts: invalid promptLanguage falls back to the default ('auto') ──
|
||||
const badLang = prompt.buildPrompts('doc', { ...base, promptLanguage: 'xyz' });
|
||||
assert.ok(badLang.system.includes('中文'), 'invalid promptLanguage falls back to zh default');
|
||||
const autoFallback = prompt.buildPrompts('doc', { ...base, promptLanguage: 'auto' });
|
||||
assert.strictEqual(badLang.system, autoFallback.system, 'invalid promptLanguage falls back to the default (auto)');
|
||||
assert.ok(badLang.system.includes('main language'), 'fallback uses the auto language instruction');
|
||||
|
||||
// ── buildPrompts: card count normalization ──
|
||||
// 0 is falsy so || picks DEFAULT (5), then Math.max(1, 5) = 5
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
try {
|
||||
const generation = await requireBundledModule('src/generation.ts');
|
||||
const providerParsers = await requireBundledModule('src/provider-parsers.ts');
|
||||
const providerRequest = await requireBundledModule('src/provider-request.ts');
|
||||
|
||||
// ── generation.ts ──
|
||||
assert.strictEqual(
|
||||
|
|
@ -88,6 +89,76 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
);
|
||||
assert.strictEqual(providerParsers.cardsFromAnthropicToolUse({}), null);
|
||||
|
||||
// ── provider-request: structured-output fallback keyed on HTTP status, not localized text ──
|
||||
const { ProviderApiError, shouldRetryWithoutStructuredOutput, requestJsonBodyWithStructuredFallback } =
|
||||
providerRequest;
|
||||
|
||||
// 400 + body keyword ⇒ retry, regardless of the (i18n-translated) message language.
|
||||
assert.strictEqual(
|
||||
shouldRetryWithoutStructuredOutput(
|
||||
new ProviderApiError('英語以外のエラーメッセージ', 400, 'response_format is not supported'),
|
||||
),
|
||||
true,
|
||||
'status-400 + body keyword ⇒ retry even when message is non-English/Chinese',
|
||||
);
|
||||
assert.strictEqual(
|
||||
shouldRetryWithoutStructuredOutput(
|
||||
new ProviderApiError("L'API a renvoyé une erreur", 422, 'json_schema unsupported'),
|
||||
),
|
||||
true,
|
||||
'status-422 + body keyword ⇒ retry for a French-localized message',
|
||||
);
|
||||
// 5xx is a server error, never a structured-output problem ⇒ do not retry.
|
||||
assert.strictEqual(
|
||||
shouldRetryWithoutStructuredOutput(new ProviderApiError('server error', 500, 'response_format')),
|
||||
false,
|
||||
);
|
||||
// 400 without any schema-related keyword ⇒ do not retry.
|
||||
assert.strictEqual(
|
||||
shouldRetryWithoutStructuredOutput(new ProviderApiError('bad request', 400, 'missing required field: model')),
|
||||
false,
|
||||
);
|
||||
// Model-name errors ("unknown model" / "unrecognized model ID") must NOT trigger a
|
||||
// wasted fallback retry — bare unknown/unrecognized keywords were dropped for this.
|
||||
assert.strictEqual(
|
||||
shouldRetryWithoutStructuredOutput(new ProviderApiError('bad request', 400, 'unknown model: gpt-5')),
|
||||
false,
|
||||
);
|
||||
assert.strictEqual(
|
||||
shouldRetryWithoutStructuredOutput(new ProviderApiError('bad request', 400, 'unrecognized model ID: x')),
|
||||
false,
|
||||
);
|
||||
// Legacy path: a plain Error carrying the English template still works (back-compat).
|
||||
assert.strictEqual(
|
||||
shouldRetryWithoutStructuredOutput(new Error('OpenAI API returned HTTP 400: response_format not supported')),
|
||||
true,
|
||||
);
|
||||
assert.strictEqual(shouldRetryWithoutStructuredOutput(new Error('some unrelated error')), false);
|
||||
|
||||
// End-to-end: a 400 returned alongside a NON-English locale still triggers the fallback body.
|
||||
{
|
||||
const calls = [];
|
||||
const fakeRequestUrl = async ({ body }) => {
|
||||
calls.push(JSON.parse(body));
|
||||
if (calls.length === 1) {
|
||||
return { status: 400, json: null, text: 'response_format is not supported by this model' };
|
||||
}
|
||||
return { status: 200, json: { ok: true }, text: '' };
|
||||
};
|
||||
const result = await requestJsonBodyWithStructuredFallback(
|
||||
fakeRequestUrl,
|
||||
'OpenAI-compatible Chat',
|
||||
'https://example.test',
|
||||
{},
|
||||
{ model: 'x', response_format: { type: 'json_schema' } },
|
||||
{ model: 'x' },
|
||||
{ uiLanguage: 'fr' }, // localized error message must NOT block the fallback
|
||||
);
|
||||
assert.deepStrictEqual(result, { ok: true });
|
||||
assert.strictEqual(calls.length, 2, 'should retry exactly once without structured output');
|
||||
assert.ok(!('response_format' in calls[1]), 'fallback body omits response_format');
|
||||
}
|
||||
|
||||
console.log('direct providers tests passed');
|
||||
} finally {
|
||||
cleanup();
|
||||
|
|
|
|||
|
|
@ -4,6 +4,10 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
try {
|
||||
const settings = await requireBundledModule('src/settings.ts');
|
||||
const base = settings.DEFAULT_SETTINGS;
|
||||
const supportedLanguageIds = ['auto', 'zh', 'en', 'ja', 'ko', 'fr', 'de', 'es'];
|
||||
|
||||
assert.deepStrictEqual(Object.keys(settings.PROMPT_LANGUAGES), supportedLanguageIds, 'prompt language order');
|
||||
assert.deepStrictEqual(Object.keys(settings.UI_LANGUAGES), supportedLanguageIds, 'ui language order');
|
||||
|
||||
// ── stableStringify ──
|
||||
assert.strictEqual(settings.stableStringify(42), '42', 'number');
|
||||
|
|
@ -99,6 +103,19 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
assert.strictEqual(normed.maxDocChars, base.maxDocChars, 'maxDocChars <1000 → default');
|
||||
assert.strictEqual(normed.customSystemPrompt, '', 'non-string customSystemPrompt → empty string');
|
||||
|
||||
for (const language of supportedLanguageIds) {
|
||||
assert.strictEqual(
|
||||
settings.normalizeSettings({ ...base, uiLanguage: language }).uiLanguage,
|
||||
language,
|
||||
`normalizeSettings preserves uiLanguage ${language}`,
|
||||
);
|
||||
assert.strictEqual(
|
||||
settings.normalizeSettings({ ...base, promptLanguage: language }).promptLanguage,
|
||||
language,
|
||||
`normalizeSettings preserves promptLanguage ${language}`,
|
||||
);
|
||||
}
|
||||
|
||||
// ── pruneCacheEntries edge cases ──
|
||||
assert.deepStrictEqual(settings.pruneCacheEntries(null, 10), [], 'null cache');
|
||||
assert.deepStrictEqual(settings.pruneCacheEntries({}, 10), [], 'empty cache');
|
||||
|
|
|
|||
|
|
@ -74,7 +74,48 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
const empty = streaming.parseSseBuffer('', openAiExtractor);
|
||||
assert.deepStrictEqual(empty.deltas, []);
|
||||
|
||||
// ── streamingFetch ──
|
||||
// ── streamErrorMessage: provider errors delivered as a 200-status SSE payload ──
|
||||
assert.strictEqual(
|
||||
streaming.streamErrorMessage({ type: 'error', error: { type: 'overloaded_error', message: 'Overloaded' } }),
|
||||
'Overloaded',
|
||||
);
|
||||
assert.strictEqual(
|
||||
streaming.streamErrorMessage({ type: 'error', error: { type: 'overloaded_error' } }),
|
||||
'overloaded_error',
|
||||
);
|
||||
assert.strictEqual(streaming.streamErrorMessage({ type: 'error' }), 'Provider returned a streaming error');
|
||||
assert.strictEqual(streaming.streamErrorMessage({ error: { message: 'Quota exceeded' } }), 'Quota exceeded');
|
||||
// OpenAI-style error object without a message/type is NOT treated as an error
|
||||
// (avoids aborting a normal chunk that carries a stray empty/code-only `error`).
|
||||
assert.strictEqual(streaming.streamErrorMessage({ error: { code: 'insufficient_quota' } }), null);
|
||||
assert.strictEqual(streaming.streamErrorMessage({ error: {} }), null);
|
||||
assert.strictEqual(streaming.streamErrorMessage({ choices: [{ delta: { content: 'hi' } }] }), null);
|
||||
assert.strictEqual(streaming.streamErrorMessage({ type: 'content_block_delta', delta: { text: 'x' } }), null);
|
||||
assert.strictEqual(streaming.streamErrorMessage({ error: null }), null);
|
||||
|
||||
// ── parseSseBuffer: surface in-stream provider errors instead of swallowing them ──
|
||||
assert.throws(
|
||||
() =>
|
||||
streaming.parseSseBuffer(
|
||||
'data: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}\n\n',
|
||||
anthropicExtractor,
|
||||
),
|
||||
/Overloaded/,
|
||||
'anthropic in-stream error must throw, not be swallowed as a non-JSON line',
|
||||
);
|
||||
assert.throws(
|
||||
() => streaming.parseSseBuffer('data: {"error":{"message":"Rate limit reached"}}\n\n', openAiExtractor),
|
||||
/Rate limit reached/,
|
||||
'openai-compatible in-stream error must throw',
|
||||
);
|
||||
// Normal deltas through the same parse path still work.
|
||||
const okAfterError = streaming.parseSseBuffer(
|
||||
'data: {"choices":[{"delta":{"content":"fine"}}]}\n\n',
|
||||
openAiExtractor,
|
||||
);
|
||||
assert.deepStrictEqual(okAfterError.deltas, ['fine']);
|
||||
|
||||
// ── streamingRequestUrl ──
|
||||
function trackedSignal() {
|
||||
const controller = new AbortController();
|
||||
const signal = controller.signal;
|
||||
|
|
@ -92,41 +133,42 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
return { controller, signal, activeListeners: () => activeListeners };
|
||||
}
|
||||
|
||||
function streamingBody(text) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(c) {
|
||||
c.enqueue(encoder.encode(text));
|
||||
c.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
try {
|
||||
{
|
||||
const success = trackedSignal();
|
||||
globalThis.fetch = async () => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
body: streamingBody('data: {"choices":[{"delta":{"content":"ok"}}]}\n\n'),
|
||||
text: async () => '',
|
||||
});
|
||||
await streaming.streamingFetch(
|
||||
const progress = [];
|
||||
const text = await streaming.streamingRequestUrl(
|
||||
async (params) => {
|
||||
assert.strictEqual(params.method, 'POST');
|
||||
assert.strictEqual(params.url, 'https://example.test');
|
||||
assert.strictEqual(params.body, '{"stream":true}');
|
||||
return {
|
||||
status: 200,
|
||||
json: null,
|
||||
text: 'data: {"choices":[{"delta":{"content":"ok"}}]}\n\n',
|
||||
};
|
||||
},
|
||||
'https://example.test',
|
||||
{},
|
||||
{},
|
||||
{ stream: true },
|
||||
streaming.deltaExtractorForFormat('openai-chat'),
|
||||
undefined,
|
||||
(p) => progress.push(p),
|
||||
success.signal,
|
||||
{ streamingTimeoutMs: 1000 },
|
||||
);
|
||||
assert.strictEqual(text, 'ok');
|
||||
assert.deepStrictEqual(progress, [
|
||||
{ accumulated: 'ok', done: false },
|
||||
{ accumulated: 'ok', done: true },
|
||||
]);
|
||||
assert.strictEqual(success.activeListeners(), 0, 'cleanup after success');
|
||||
}
|
||||
|
||||
{
|
||||
const httpError = trackedSignal();
|
||||
globalThis.fetch = async () => ({ ok: false, status: 500, body: null, text: async () => 'bad' });
|
||||
await assert.rejects(
|
||||
() =>
|
||||
streaming.streamingFetch(
|
||||
streaming.streamingRequestUrl(
|
||||
async () => ({ status: 500, json: null, text: 'bad' }),
|
||||
'https://example.test',
|
||||
{},
|
||||
{},
|
||||
|
|
@ -138,12 +180,14 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
/HTTP 500|API returned HTTP 500/,
|
||||
);
|
||||
assert.strictEqual(httpError.activeListeners(), 0, 'cleanup after HTTP error');
|
||||
}
|
||||
|
||||
{
|
||||
const timeout = trackedSignal();
|
||||
globalThis.fetch = async () => new Promise(() => {});
|
||||
await assert.rejects(
|
||||
() =>
|
||||
streaming.streamingFetch(
|
||||
streaming.streamingRequestUrl(
|
||||
async () => new Promise(() => {}),
|
||||
'https://example.test',
|
||||
{},
|
||||
{},
|
||||
|
|
@ -155,16 +199,19 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
/Streaming timed out/,
|
||||
);
|
||||
assert.strictEqual(timeout.activeListeners(), 0, 'cleanup after timeout');
|
||||
}
|
||||
|
||||
{
|
||||
const preAborted = trackedSignal();
|
||||
preAborted.controller.abort();
|
||||
globalThis.fetch = async (_url, opts) => {
|
||||
if (opts?.signal?.aborted) throw new DOMException('The operation was aborted.', 'AbortError');
|
||||
throw new Error('should not reach');
|
||||
};
|
||||
let called = false;
|
||||
await assert.rejects(
|
||||
() =>
|
||||
streaming.streamingFetch(
|
||||
streaming.streamingRequestUrl(
|
||||
async () => {
|
||||
called = true;
|
||||
return { status: 200, json: null, text: '' };
|
||||
},
|
||||
'https://example.test',
|
||||
{},
|
||||
{},
|
||||
|
|
@ -175,41 +222,52 @@ const { assert, requireBundledModule, cleanup } = require('./direct-test-setup')
|
|||
),
|
||||
/abort/i,
|
||||
);
|
||||
assert.strictEqual(called, false, 'pre-aborted request is not started');
|
||||
assert.strictEqual(preAborted.activeListeners(), 0, 'cleanup on pre-aborted');
|
||||
}
|
||||
|
||||
const abortDuringRead = trackedSignal();
|
||||
globalThis.fetch = async (_url, opts) => {
|
||||
const fetchSignal = opts?.signal;
|
||||
const stream = new ReadableStream({
|
||||
async pull(ctrl) {
|
||||
ctrl.enqueue(new TextEncoder().encode('data: {"choices":[{"delta":{"content":"first"}}]}\n\n'));
|
||||
abortDuringRead.controller.abort();
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
if (fetchSignal?.aborted) {
|
||||
ctrl.error(new DOMException('The operation was aborted.', 'AbortError'));
|
||||
return;
|
||||
}
|
||||
ctrl.close();
|
||||
},
|
||||
});
|
||||
return { ok: true, status: 200, body: stream, text: async () => '' };
|
||||
};
|
||||
{
|
||||
const abortDuringRequest = trackedSignal();
|
||||
await assert.rejects(
|
||||
() =>
|
||||
streaming.streamingFetch(
|
||||
streaming.streamingRequestUrl(
|
||||
async () =>
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => abortDuringRequest.controller.abort(), 1);
|
||||
setTimeout(() => resolve({ status: 200, json: null, text: '' }), 20);
|
||||
}),
|
||||
'https://example.test',
|
||||
{},
|
||||
{},
|
||||
streaming.deltaExtractorForFormat('openai-chat'),
|
||||
undefined,
|
||||
abortDuringRead.signal,
|
||||
abortDuringRequest.signal,
|
||||
{ streamingTimeoutMs: 5000 },
|
||||
),
|
||||
/abort/i,
|
||||
);
|
||||
assert.strictEqual(abortDuringRead.activeListeners(), 0, 'cleanup after mid-read abort');
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
assert.strictEqual(abortDuringRequest.activeListeners(), 0, 'cleanup after mid-request abort');
|
||||
}
|
||||
|
||||
{
|
||||
const requestFailure = trackedSignal();
|
||||
await assert.rejects(
|
||||
() =>
|
||||
streaming.streamingRequestUrl(
|
||||
async () => {
|
||||
throw new Error('network down');
|
||||
},
|
||||
'https://example.test',
|
||||
{},
|
||||
{},
|
||||
streaming.deltaExtractorForFormat('openai-chat'),
|
||||
undefined,
|
||||
requestFailure.signal,
|
||||
{ streamingTimeoutMs: 1000 },
|
||||
),
|
||||
/network down/,
|
||||
);
|
||||
assert.strictEqual(requestFailure.activeListeners(), 0, 'cleanup after transport failure');
|
||||
}
|
||||
|
||||
console.log('direct streaming tests passed');
|
||||
|
|
|
|||
|
|
@ -4,8 +4,18 @@ const fs = require('fs');
|
|||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
// Polyfill Obsidian's `activeWindow` global for Node test runtime.
|
||||
if (typeof globalThis.activeWindow === 'undefined') {
|
||||
globalThis.activeWindow = globalThis;
|
||||
}
|
||||
|
||||
const repoRoot = path.join(__dirname, '..');
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'parallel-reader-tests-'));
|
||||
// Under c8, bundles must live inside the repo so c8 processes their coverage
|
||||
// (it ignores scripts outside cwd before source-map remap). Otherwise /tmp.
|
||||
const bundleParent = process.env.NODE_V8_COVERAGE
|
||||
? fs.mkdirSync(path.join(repoRoot, '.test-bundles'), { recursive: true }) || path.join(repoRoot, '.test-bundles')
|
||||
: os.tmpdir();
|
||||
const tempDir = fs.mkdtempSync(path.join(bundleParent, 'parallel-reader-tests-'));
|
||||
|
||||
async function requireBundledModule(relativePath) {
|
||||
const entry = path.join(repoRoot, relativePath);
|
||||
|
|
@ -16,6 +26,9 @@ async function requireBundledModule(relativePath) {
|
|||
platform: 'node',
|
||||
format: 'cjs',
|
||||
outfile,
|
||||
sourcemap: 'inline',
|
||||
sourcesContent: true,
|
||||
sourceRoot: repoRoot,
|
||||
plugins: [
|
||||
{
|
||||
name: 'obsidian-stub',
|
||||
|
|
@ -30,10 +43,14 @@ async function requireBundledModule(relativePath) {
|
|||
},
|
||||
],
|
||||
});
|
||||
require('./coverage-sourcemap').fixInlineSourceMap(outfile, repoRoot);
|
||||
return require(outfile);
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
// Skipped under c8 coverage: c8 reads V8 coverage at exit and needs the
|
||||
// bundled file (with its inline source map) still on disk to remap to src/.
|
||||
if (process.env.NODE_V8_COVERAGE) return;
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -166,6 +166,38 @@ async function testCancelAllWaiters() {
|
|||
assert.strictEqual(manager.waitingCount(), 0);
|
||||
}
|
||||
|
||||
async function testCancelAll() {
|
||||
const manager = new GenerationJobManager(1);
|
||||
let release;
|
||||
const blocker = new Promise((r) => {
|
||||
release = r;
|
||||
});
|
||||
let runningCancelHook = false;
|
||||
|
||||
const running = manager.start('run.md', async (job) => {
|
||||
job.onCancel(() => {
|
||||
runningCancelHook = true;
|
||||
});
|
||||
await blocker;
|
||||
job.throwIfCancelled();
|
||||
return 'run';
|
||||
});
|
||||
const queued = manager.start('q.md', async () => 'q');
|
||||
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
assert.strictEqual(manager.isRunning('run.md'), true, 'one running');
|
||||
assert.strictEqual(manager.waitingCount(), 1, 'one queued');
|
||||
|
||||
const cancelled = manager.cancelAll();
|
||||
assert.strictEqual(cancelled, 2, 'cancelAll cancels the running job and drains the queued waiter');
|
||||
assert.strictEqual(runningCancelHook, true, 'running job cancel handler fired (aborts in-flight HTTP/CLI)');
|
||||
|
||||
release();
|
||||
await assert.rejects(running, GenerationJobCancelledError, 'cancelled running job rejects');
|
||||
await assert.rejects(queued, GenerationJobCancelledError, 'queued job rejects');
|
||||
assert.strictEqual(manager.waitingCount(), 0);
|
||||
}
|
||||
|
||||
async function testCancelSignalsRunnerAndCleansUp() {
|
||||
const manager = new GenerationJobManager();
|
||||
let cancelHookCalled = false;
|
||||
|
|
@ -190,6 +222,12 @@ function testErrorClassification() {
|
|||
assert.strictEqual(classifyGenerationError(new Error('API key 未设置')), 'auth');
|
||||
assert.strictEqual(classifyGenerationError(new Error('CLI 超时 (120000ms)')), 'timeout');
|
||||
assert.strictEqual(classifyGenerationError(new Error('OpenAI API 429: rate limit')), 'rate-limit');
|
||||
assert.strictEqual(
|
||||
classifyGenerationError(new Error('request to https://api failed, reason: ECONNREFUSED')),
|
||||
'network',
|
||||
);
|
||||
assert.strictEqual(classifyGenerationError(new Error('Failed to fetch')), 'network');
|
||||
assert.strictEqual(classifyGenerationError(new Error('getaddrinfo ENOTFOUND api.openai.com')), 'network');
|
||||
assert.strictEqual(classifyGenerationError(new Error('LLM 返回非 JSON')), 'schema');
|
||||
assert.strictEqual(classifyGenerationError(new Error('Model 未设置')), 'config');
|
||||
assert.strictEqual(classifyGenerationError(new Error('something else')), 'unknown');
|
||||
|
|
@ -200,6 +238,7 @@ function testErrorClassification() {
|
|||
await testGlobalConcurrencyLimit();
|
||||
await testNoOverbookingDuringRelease();
|
||||
await testCancelAllWaiters();
|
||||
await testCancelAll();
|
||||
await testCancelSignalsRunnerAndCleansUp();
|
||||
testErrorClassification();
|
||||
console.log('generation job manager tests passed');
|
||||
|
|
|
|||
|
|
@ -2,12 +2,22 @@ const { assert, t } = require('./test-setup');
|
|||
|
||||
assert.strictEqual(t.translate({ uiLanguage: 'zh' }, 'appTitle'), '对照阅读笔记', 'zh translation');
|
||||
assert.strictEqual(t.translate({ uiLanguage: 'en' }, 'appTitle'), 'Parallel Reader', 'en translation');
|
||||
assert.strictEqual(t.translate({ uiLanguage: 'ja' }, 'settingTestBackendButton'), 'テスト');
|
||||
assert.strictEqual(t.translate({ uiLanguage: 'ko' }, 'settingTestBackendButton'), '테스트');
|
||||
assert.strictEqual(t.translate({ uiLanguage: 'fr' }, 'settingTestBackendButton'), 'Tester');
|
||||
assert.strictEqual(t.translate({ uiLanguage: 'de' }, 'settingTestBackendButton'), 'Testen');
|
||||
assert.strictEqual(t.translate({ uiLanguage: 'es' }, 'settingTestBackendButton'), 'Probar');
|
||||
assert.strictEqual(t.translate({ uiLanguage: 'en' }, 'nonexistent_key'), 'nonexistent_key', 'missing key returns key');
|
||||
assert.strictEqual(
|
||||
t.translate({ uiLanguage: 'en' }, 'cacheClearedAll', { count: 5 }),
|
||||
'Cleared 5 cache entries',
|
||||
'variable interpolation',
|
||||
);
|
||||
assert.strictEqual(
|
||||
t.translate({ uiLanguage: 'fr' }, 'cacheClearedAll', { count: 5 }),
|
||||
'5 entrées de cache effacées',
|
||||
'new locale interpolation',
|
||||
);
|
||||
assert.strictEqual(
|
||||
t.translate({ uiLanguage: 'en' }, 'exported', { path: 'foo/bar.md' }),
|
||||
'Exported → foo/bar.md',
|
||||
|
|
|
|||
|
|
@ -103,11 +103,11 @@ assert.strictEqual(t.normalizeCardCount('15', 5), 15, 'numeric string accepted')
|
|||
|
||||
// normalizeCliTimeoutMs (mirrors normalizeStreamingTimeoutMs)
|
||||
assert.strictEqual(t.normalizeCliTimeoutMs('60000'), 60000, 'cli timeout accepts numeric strings');
|
||||
assert.strictEqual(t.normalizeCliTimeoutMs(999), 120000, 'cli timeout below minimum falls back to default');
|
||||
assert.strictEqual(t.normalizeCliTimeoutMs('bad'), 120000, 'cli timeout rejects non-numeric values');
|
||||
assert.strictEqual(t.normalizeCliTimeoutMs(999), 300000, 'cli timeout below minimum falls back to default');
|
||||
assert.strictEqual(t.normalizeCliTimeoutMs('bad'), 300000, 'cli timeout rejects non-numeric values');
|
||||
assert.strictEqual(
|
||||
t.normalizeSettings({ ...baseSettings, cliTimeoutMs: 500 }).cliTimeoutMs,
|
||||
120000,
|
||||
300000,
|
||||
'normalizeSettings protects invalid cli timeout values',
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ const expectedExports = [
|
|||
'runCli',
|
||||
'buildPrompts',
|
||||
'buildOpenAiChatBody',
|
||||
'buildLineOffsets',
|
||||
'extractJson',
|
||||
'findLineForAnchor',
|
||||
'folderPathsForTarget',
|
||||
|
|
|
|||
|
|
@ -5,6 +5,11 @@ const os = require('os');
|
|||
const path = require('path');
|
||||
const { EventEmitter } = require('events');
|
||||
|
||||
// Polyfill Obsidian's `activeWindow` global for Node test runtime.
|
||||
if (typeof globalThis.activeWindow === 'undefined') {
|
||||
globalThis.activeWindow = globalThis;
|
||||
}
|
||||
|
||||
// Load obsidian mock first — hooks Module._load so that require('obsidian')
|
||||
// returns the mock for both us and the esbuild-bundled test-exports module.
|
||||
const { getRequestUrlMock, setRequestUrlMock } = require('./obsidian-mock');
|
||||
|
|
@ -12,7 +17,12 @@ const { getRequestUrlMock, setRequestUrlMock } = require('./obsidian-mock');
|
|||
// Bundle test-exports.ts synchronously with obsidian marked as external.
|
||||
// The bundled code will require('obsidian') at runtime, hitting our mock.
|
||||
const repoRoot = path.join(__dirname, '..');
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'parallel-reader-test-setup-'));
|
||||
// Under c8, bundles must live inside the repo so c8 processes their coverage
|
||||
// (it ignores scripts outside cwd before source-map remap). Otherwise /tmp.
|
||||
const bundleParent = process.env.NODE_V8_COVERAGE
|
||||
? fs.mkdirSync(path.join(repoRoot, '.test-bundles'), { recursive: true }) || path.join(repoRoot, '.test-bundles')
|
||||
: os.tmpdir();
|
||||
const tempDir = fs.mkdtempSync(path.join(bundleParent, 'parallel-reader-test-setup-'));
|
||||
const outfile = path.join(tempDir, 'test-exports.cjs');
|
||||
|
||||
esbuild.buildSync({
|
||||
|
|
@ -22,12 +32,20 @@ esbuild.buildSync({
|
|||
format: 'cjs',
|
||||
outfile,
|
||||
external: ['obsidian'],
|
||||
sourcemap: 'inline',
|
||||
sourcesContent: true,
|
||||
sourceRoot: repoRoot,
|
||||
});
|
||||
|
||||
require('./coverage-sourcemap').fixInlineSourceMap(outfile, repoRoot);
|
||||
|
||||
const t = require(outfile);
|
||||
|
||||
// Clean up temp bundle on process exit.
|
||||
// Clean up temp bundle on process exit. Skipped under c8 coverage:
|
||||
// c8 reads V8 coverage at exit and needs the bundled file (with its
|
||||
// inline source map) still on disk to remap back to src/*.ts.
|
||||
process.on('exit', () => {
|
||||
if (process.env.NODE_V8_COVERAGE) return;
|
||||
try {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
} catch (_) {
|
||||
|
|
|
|||
|
|
@ -13,5 +13,15 @@
|
|||
"1.0.11": "1.4.0",
|
||||
"1.0.12": "1.4.0",
|
||||
"1.0.13": "1.4.0",
|
||||
"1.0.14": "1.4.0"
|
||||
"1.0.14": "1.4.0",
|
||||
"1.0.15": "1.7.2",
|
||||
"1.0.16": "1.7.2",
|
||||
"1.0.17": "1.7.2",
|
||||
"1.0.18": "1.8.7",
|
||||
"1.0.19": "1.8.7",
|
||||
"1.0.20": "1.8.7",
|
||||
"1.0.21": "1.8.7",
|
||||
"1.0.22": "1.8.7",
|
||||
"1.0.23": "1.8.7",
|
||||
"1.0.24": "1.8.7"
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue