Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 | 1x 8x 8x 8x 8x 8x 8x 8x 8x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 114x 114x 114x 114x 114x 114x 114x 114x 1x 1x 1x 1x 1x 114x 114x 114x 32x 114x 82x 82x 82x 82x 114x 4x 4x 114x 117x 37x 36x 36x 36x 36x 36x 36x 37x 7x 7x 7x 36x 36x 36x 36x 6x 6x 3x 2x 1x 3x 3x 2x 1x 1x 2x 2x 36x 37x 37x 5x 5x 5x 37x 36x 36x 37x 5x 5x 5x 5x 5x 5x 31x 31x 31x 31x 31x 31x 31x 31x 31x 3x 2x 1x 1x 3x 3x 31x 31x 31x 31x 26x 26x 37x 5x 5x 37x 36x 36x 37x 117x 2x 2x 1x 1x 1x 2x 117x 3x 3x 2x 2x 3x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 3x 3x 117x 10x 10x 10x 10x 10x 1x 9x 10x 10x 10x 10x 10x 117x 9x 9x 3x 3x 3x 3x 3x 3x 9x 2x 2x 2x 9x 2x 2x 2x 9x 2x 2x 2x 9x 9x 117x 39x 39x 39x 117x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 3x 3x 3x 2x 3x 114x 114x 114x 114x 114x 3x 3x 3x 1x 1x 3x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 2x 2x 1x 1x 1x 1x 1x 1x 2x 114x 114x 117x 3x 1x 1x 3x 3x 117x 116x 116x 116x 117x 8x 8x 8x 8x 2x 1x 1x 1x 1x 1x 1x 8x 6x 1x 1x 1x 1x 6x 6x 8x 8x 8x 117x 210x 210x 210x 210x 117x 237x 236x 236x 236x 236x 236x 236x 237x 237x 117x 116x 116x 116x 116x 117x 110x 1x 1x 1x 110x 110x 117x 19x 2x 2x 19x 117x 9x 7x 9x 9x 9x 9x 117x 13x 12x 11x 11x 13x 13x 13x 117x 53x 53x 117x 2x 2x 2x 117x 17x 17x 17x 17x 17x 17x 7x 7x 1x 1x 1x 7x 7x 17x 6x 6x 6x 6x 17x 6x 2x 6x 4x 4x 4x 4x 17x 17x 17x 17x 17x 17x 117x 8x 1x 8x 1x 1x 8x 117x 1x 4x 4x 1x 1x 117x 3x 3x 1x 1x 1x 2x 3x 1x 1x 1x 3x 117x 5x 5x 5x 5x 5x 5x 5x 5x 5x 20x 20x 20x 5x 117x 4x 1x 1x 4x 2x 4x 4x 117x 14x 13x 13x 13x 13x 13x 14x 8x 8x 2x 2x 2x 8x 8x 14x 2x 2x 2x 2x 14x 3x 2x 3x 1x 1x 1x 14x 13x 13x 13x 13x 14x 117x | import { type Menu, type MenuItem, Notice, Plugin, type TAbstractFile } from "obsidian";
import { LilbeeClient, OllamaClient } from "./api";
import { BinaryManager, getLatestRelease, checkForUpdate } from "./binary-manager";
import type { ReleaseInfo } from "./binary-manager";
import { ServerManager } from "./server-manager";
import { LilbeeSettingTab } from "./settings";
import { DEFAULT_SETTINGS, NOTICE, SERVER_MODE, SSE_EVENT, type LilbeeSettings, type ServerMode, type ServerState, type SSEEvent, type SyncDone } from "./types";
import { ChatView, VIEW_TYPE_CHAT } from "./views/chat-view";
import { SearchModal } from "./views/search-modal";
function summarizeSyncResult(done: SyncDone): string {
const parts: string[] = [];
if (done.added.length > 0) parts.push(`${done.added.length} added`);
if (done.updated.length > 0) parts.push(`${done.updated.length} updated`);
if (done.removed.length > 0) parts.push(`${done.removed.length} removed`);
if (done.failed.length > 0) parts.push(`${done.failed.length} failed`);
return parts.join(", ");
}
export default class LilbeePlugin extends Plugin {
settings: LilbeeSettings = { ...DEFAULT_SETTINGS };
api: LilbeeClient = new LilbeeClient(DEFAULT_SETTINGS.serverUrl);
ollama: OllamaClient = new OllamaClient(DEFAULT_SETTINGS.ollamaUrl);
activeModel = "";
activeVisionModel = "";
statusBarEl: HTMLElement | null = null;
onProgress: ((event: SSEEvent) => void) | null = null;
binaryManager: BinaryManager | null = null;
serverManager: ServerManager | null = null;
syncController: AbortController | null = null;
private syncTimeout: ReturnType<typeof setTimeout> | null = null;
private autoSyncRefs: { id: string }[] = [];
private previousServerMode: ServerMode = SERVER_MODE.MANAGED;
private startingServer = false;
private serverStartFailed = false;
async onload(): Promise<void> {
await this.loadSettings();
this.ollama = new OllamaClient(this.settings.ollamaUrl);
this.statusBarEl = this.addStatusBarItem();
this.registerView(VIEW_TYPE_CHAT, (leaf) => new ChatView(leaf, this));
this.addSettingTab(new LilbeeSettingTab(this.app, this));
this.registerCommands();
this.registerEvent(
this.app.workspace.on("file-menu" as any, (menu: Menu, file: TAbstractFile) => {
menu.addItem((item: MenuItem) => {
item.setTitle("Add to lilbee")
.setIcon("plus-circle")
.onClick(() => this.addToLilbee(file));
});
}),
);
if (this.settings.serverMode === SERVER_MODE.MANAGED) {
void this.startManagedServer();
} else {
this.api = new LilbeeClient(this.settings.serverUrl);
this.setStatusReady();
this.fetchActiveModel();
}
if (this.settings.syncMode === "auto") {
this.registerAutoSync();
}
}
async startManagedServer(): Promise<void> {
if (this.startingServer) return;
this.startingServer = true;
this.serverStartFailed = false;
try {
const pluginDir = this.getPluginDir();
this.binaryManager = new BinaryManager(pluginDir);
const needsDownload = !this.binaryManager.binaryExists();
if (needsDownload) {
this.updateStatusBar("lilbee: downloading...");
this.setStatusClass("lilbee-status-downloading");
}
let binaryPath: string;
let downloadNotice: Notice | null = null;
try {
binaryPath = await this.binaryManager.ensureBinary((msg, url) => {
this.updateStatusBar(`lilbee: ${msg}`);
if (!downloadNotice && needsDownload) {
const text = url
? `lilbee: ${msg}\n${url}`
: `lilbee: ${msg}`;
downloadNotice = new Notice(text, 0);
} else if (downloadNotice) {
const text = url
? `lilbee: ${msg}\n${url}`
: `lilbee: ${msg}`;
downloadNotice.setMessage(text);
}
});
downloadNotice?.hide();
} catch (err) {
downloadNotice?.hide();
this.showError("failed to download server", err);
return;
} finally {
this.setStatusClass(null);
}
if (needsDownload && !this.settings.lilbeeVersion) {
try {
const release = await getLatestRelease();
this.settings.lilbeeVersion = release.tag;
await this.saveData(this.settings);
} catch { /* version tracking is best-effort */ }
}
try {
this.serverManager = new ServerManager({
binaryPath,
dataDir: `${pluginDir}/server-data`,
port: this.settings.serverPort,
ollamaUrl: this.settings.ollamaUrl,
systemPrompt: this.settings.systemPrompt,
onStateChange: (state) => this.handleServerStateChange(state),
onRestartsExhausted: (stderr: string) => {
if (this.serverStartFailed) return;
const detail = stderr
? `\n${stderr.split("\n").slice(-5).join("\n")}`
: "";
new Notice(`lilbee: server crashed after multiple restarts${detail}`, 0);
},
});
this.updateStatusBar("lilbee: starting...");
this.setStatusClass("lilbee-status-starting");
await this.serverManager.start();
this.api = new LilbeeClient(this.serverManager.serverUrl);
this.fetchActiveModel();
} catch (err) {
this.showError("failed to start server", err);
}
} finally {
this.startingServer = false;
}
}
async checkForUpdate(): Promise<{ available: boolean; release?: ReleaseInfo }> {
const release = await getLatestRelease();
if (checkForUpdate(this.settings.lilbeeVersion, release.tag)) {
return { available: true, release };
}
return { available: false };
}
async updateServer(release: ReleaseInfo, onProgress?: (msg: string) => void): Promise<void> {
const pluginDir = this.getPluginDir();
if (!this.binaryManager) {
this.binaryManager = new BinaryManager(pluginDir);
}
// Stop the running server first
if (this.serverManager) {
onProgress?.("Stopping server...");
await this.serverManager.stop();
this.serverManager = null;
}
// Download the new binary (overwrites the old one)
onProgress?.("Downloading...");
await this.binaryManager.download(release.assetUrl, onProgress);
// Save the new version
this.settings.lilbeeVersion = release.tag;
await this.saveData(this.settings);
// Restart if in managed mode
if (this.settings.serverMode === SERVER_MODE.MANAGED) {
onProgress?.("Starting server...");
await this.startManagedServer();
}
onProgress?.("Update complete.");
}
private showError(label: string, err: unknown): void {
console.error(`[lilbee] ${label}:`, err);
const stderr = this.serverManager?.lastStderr;
if (stderr) console.error(`[lilbee] server stderr:\n${stderr}`);
const detail = err instanceof Error ? err.message : String(err);
const stderrTail = stderr
? `\n${stderr.split("\n").slice(-5).join("\n")}`
: "";
new Notice(`lilbee: ${label} — ${detail}${stderrTail}`, 8000);
this.updateStatusBar("lilbee: error");
this.setStatusClass(null);
this.serverStartFailed = true;
}
private handleServerStateChange(state: ServerState): void {
switch (state) {
case "ready":
if (this.serverManager) {
this.api = new LilbeeClient(this.serverManager.serverUrl);
}
this.setStatusReady();
new Notice("lilbee: server ready", 3000);
break;
case "starting":
this.updateStatusBar("lilbee: starting...");
this.setStatusClass("lilbee-status-starting");
break;
case "error":
this.updateStatusBar("lilbee: error");
this.setStatusClass(null);
break;
case "stopped":
this.updateStatusBar("lilbee: stopped");
this.setStatusClass(null);
break;
}
}
private getPluginDir(): string {
const adapter = this.app.vault.adapter as unknown as { getBasePath(): string };
return `${adapter.getBasePath()}/.obsidian/plugins/lilbee`;
}
private registerCommands(): void {
this.addCommand({
id: "lilbee:search",
name: "Search knowledge base",
callback: () => new SearchModal(this.app, this).open(),
});
this.addCommand({
id: "lilbee:ask",
name: "Ask a question",
callback: () => new SearchModal(this.app, this, "ask").open(),
});
this.addCommand({
id: "lilbee:chat",
name: "Open chat",
callback: () => this.activateChatView(),
});
this.addCommand({
id: "lilbee:add-file",
name: "Add current file to lilbee",
checkCallback: (checking) => {
const file = this.app.workspace.getActiveFile();
if (!file) return false;
if (!checking) void this.addToLilbee(file);
return true;
},
});
this.addCommand({
id: "lilbee:add-folder",
name: "Add current folder to lilbee",
checkCallback: (checking) => {
const file = this.app.workspace.getActiveFile();
const folder = file?.parent;
if (!folder) return false;
if (!checking) void this.addToLilbee(folder);
return true;
},
});
this.addCommand({
id: "lilbee:sync",
name: "Sync vault",
callback: () => this.triggerSync(),
});
this.addCommand({
id: "lilbee:status",
name: "Show status",
callback: async () => {
try {
const status = await this.api.status();
new Notice(
`lilbee: ${status.sources.length} documents, ${status.total_chunks} chunks`,
);
} catch {
new Notice("lilbee: cannot connect to server");
}
},
});
}
onunload(): void {
if (this.syncTimeout) {
clearTimeout(this.syncTimeout);
}
void this.serverManager?.stop();
}
async loadSettings(): Promise<void> {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.previousServerMode = this.settings.serverMode;
}
async saveSettings(): Promise<void> {
const previousMode = this.previousServerMode;
this.previousServerMode = this.settings.serverMode;
await this.saveData(this.settings);
if (this.settings.serverMode === SERVER_MODE.MANAGED) {
if (previousMode !== SERVER_MODE.MANAGED) {
void this.startManagedServer();
} else if (this.serverManager) {
this.serverManager.updateOllamaUrl(this.settings.ollamaUrl);
this.serverManager.updatePort(this.settings.serverPort);
this.api = new LilbeeClient(this.serverManager.serverUrl);
}
} else {
if (previousMode === SERVER_MODE.MANAGED) {
void this.serverManager?.stop();
this.serverManager = null;
this.binaryManager = null;
}
this.api = new LilbeeClient(this.settings.serverUrl);
}
this.ollama = new OllamaClient(this.settings.ollamaUrl);
this.updateAutoSync();
}
private updateStatusBar(text: string): void {
if (!this.statusBarEl) return;
const model = this.activeModel ? ` (${this.activeModel})` : "";
this.statusBarEl.setText(`${text}${model}`);
}
private setStatusClass(cls: string | null): void {
if (!this.statusBarEl) return;
this.statusBarEl.classList.remove(
"lilbee-status-downloading",
"lilbee-status-starting",
"lilbee-status-ready",
"lilbee-status-adding",
);
if (cls) this.statusBarEl.classList.add(cls);
}
private setStatusReady(): void {
const suffix = this.settings.serverMode === SERVER_MODE.EXTERNAL ? " [external]" : "";
this.updateStatusBar(`lilbee: ready${suffix}`);
this.setStatusClass("lilbee-status-ready");
}
fetchActiveModel(): void {
this.api.listModels().then((models) => {
this.activeModel = models.chat.active;
this.activeVisionModel = models.vision.active;
this.setStatusReady();
}).catch(() => {});
}
private assertActiveModel(): boolean {
if (this.activeModel) return true;
new Notice(NOTICE.NO_CHAT_MODEL);
return false;
}
async addExternalFiles(paths: string[]): Promise<void> {
if (!this.statusBarEl || paths.length === 0) return;
if (!this.assertActiveModel()) return;
const label = paths.length === 1 ? paths[0].split("/").pop() : `${paths.length} files`;
new Notice(`lilbee: adding ${label}...`);
await this.runAdd(paths);
}
async addToLilbee(file: TAbstractFile): Promise<void> {
if (!this.statusBarEl) return;
if (!this.assertActiveModel()) return;
const adapter = this.app.vault.adapter as unknown as { getBasePath(): string };
const absolutePath = `${adapter.getBasePath()}/${file.path}`;
new Notice(`lilbee: adding ${file.name ?? file.path}...`);
await this.runAdd([absolutePath]);
}
private emitProgress(event: SSEEvent): void {
if (this.onProgress) this.onProgress(event);
}
cancelSync(): void {
this.syncController?.abort();
this.syncController = null;
}
private async runAdd(paths: string[]): Promise<void> {
this.updateStatusBar("lilbee: adding...");
this.setStatusClass("lilbee-status-adding");
this.syncController = new AbortController();
try {
let lastEvent: SSEEvent | null = null;
for await (const event of this.api.addFiles(paths, false, this.activeVisionModel || undefined, this.syncController.signal)) {
this.emitProgress(event);
if (event.event === SSE_EVENT.FILE_START) {
const d = event.data as { current_file: number; total_files: number };
this.updateStatusBar(`lilbee: adding ${d.current_file}/${d.total_files}`);
}
lastEvent = event;
}
if (lastEvent?.event === SSE_EVENT.DONE) {
this.emitProgress(lastEvent);
const summary = summarizeSyncResult(lastEvent.data as SyncDone);
new Notice(summary ? `lilbee: ${summary}` : "lilbee: nothing new to add");
}
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
new Notice("lilbee: add cancelled");
} else {
console.error("[lilbee] add failed:", err);
const msg = err instanceof Error ? err.message : "cannot connect to server";
new Notice(`lilbee: add failed — ${msg}`);
}
} finally {
this.syncController = null;
this.setStatusReady();
this.emitProgress({ event: SSE_EVENT.DONE, data: null });
}
}
private updateAutoSync(): void {
if (this.settings.syncMode === "auto" && this.autoSyncRefs.length === 0) {
this.registerAutoSync();
} else if (this.settings.syncMode === "manual" && this.autoSyncRefs.length > 0) {
this.unregisterAutoSync();
}
}
private unregisterAutoSync(): void {
for (const ref of this.autoSyncRefs) {
this.app.vault.offref(ref as any);
}
this.autoSyncRefs = [];
}
private async activateChatView(): Promise<void> {
const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT);
if (existing.length > 0) {
this.app.workspace.revealLeaf(existing[0]);
return;
}
const leaf = this.app.workspace.getRightLeaf(false);
if (leaf) {
await leaf.setViewState({ type: VIEW_TYPE_CHAT, active: true });
this.app.workspace.revealLeaf(leaf);
}
}
private registerAutoSync(): void {
const handler = () => this.debouncedSync();
const vault = this.app.vault;
const refs = [
vault.on("create", handler),
vault.on("modify", handler),
vault.on("delete", handler),
vault.on("rename", handler),
];
for (const ref of refs) {
this.autoSyncRefs.push(ref as { id: string });
this.registerEvent(ref);
}
}
private debouncedSync(): void {
if (this.syncTimeout) {
clearTimeout(this.syncTimeout);
}
this.syncTimeout = setTimeout(() => {
this.triggerSync();
}, this.settings.syncDebounceMs);
}
async triggerSync(): Promise<void> {
if (!this.statusBarEl) return;
this.updateStatusBar("lilbee: syncing...");
this.setStatusClass("lilbee-status-adding");
this.syncController = new AbortController();
try {
let lastEvent: SSEEvent | null = null;
for await (const event of this.api.syncStream(!!this.activeVisionModel, this.syncController.signal)) {
this.emitProgress(event);
if (event.event === SSE_EVENT.FILE_START) {
const d = event.data as { current_file: number; total_files: number };
this.updateStatusBar(`lilbee: syncing ${d.current_file}/${d.total_files}`);
}
lastEvent = event;
}
if (lastEvent?.event === SSE_EVENT.DONE) {
this.emitProgress(lastEvent);
const summary = summarizeSyncResult(lastEvent.data as SyncDone);
if (summary) new Notice(`lilbee: synced — ${summary}`);
}
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
new Notice("lilbee: sync cancelled");
} else {
console.error("[lilbee] sync failed:", err);
new Notice("lilbee: sync failed — cannot connect to server");
}
} finally {
this.syncController = null;
this.setStatusReady();
this.emitProgress({ event: SSE_EVENT.DONE, data: null });
}
}
}
|