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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
permissions:
security-events: write
steps:
Expand Down
8 changes: 5 additions & 3 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@four-bytes/four-opencode-brain",
"version": "1.6.2",
"version": "1.7.0",
"description": "Unified brain plugin — single SQLite DB for RAG search, memory, and knowledge base",
"license": "Apache-2.0",
"type": "module",
Expand All @@ -14,7 +14,7 @@
"four-bytes"
],
"dependencies": {
"@four-bytes/opencode-plugin-lib": "github:four-bytes/four-opencode-plugin-lib#v0.2.0",
"@four-bytes/opencode-plugin-lib": "github:four-bytes/four-opencode-plugin-lib#v0.3.0",
"@opencode-ai/plugin": "1.16.2",
"@opentui/core": "0.3.2",
"@opentui/solid": "0.3.2",
Expand Down
34 changes: 3 additions & 31 deletions src/event-bus.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,12 @@
type Listener<T> = (payload: T) => void;
import { EventBus } from "@four-bytes/opencode-plugin-lib";

class BrainEventBus {
private listeners = new Map<string, Set<Listener<any>>>();
private latest = new Map<string, any>();

on<T>(event: string, listener: Listener<T>): () => void {
if (!this.listeners.has(event)) this.listeners.set(event, new Set());
this.listeners.get(event)!.add(listener);
if (this.latest.has(event)) listener(this.latest.get(event));
return () => this.listeners.get(event)?.delete(listener);
}

emit<T>(event: string, payload: T): void {
this.latest.set(event, payload);
this.listeners.get(event)?.forEach(fn => fn(payload));
}

clear(): void {
this.listeners.clear();
this.latest.clear();
}
}

export const brainBus = new BrainEventBus();
export const brainBus = new EventBus();

export interface BrainStatusEvent {
phase?: "init" | "ingest" | "idle" | "busy";
status?: "init" | "busy" | "ready" | "error";
statusText?: string;
progress?: number;
current?: number;
total?: number;
scanning?: boolean;
searching?: boolean;
ingesting?: boolean;
blocked?: boolean;
busy?: boolean;
version?: string;
error?: string;
}
18 changes: 8 additions & 10 deletions src/four-opencode-brain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ function calculateIngestTimeout(fileCount: number): number {
}

/** Unified status updates — see src/status.ts */
import { updateStatus, initStatus, initVersion, stopStatusServer } from "./status";
import { updateStatus, initStatus, initVersion, stopStatusServer, toast } from "./status";



Expand Down Expand Up @@ -95,20 +95,20 @@ const _serverPlugin = async (input: PluginInput) => {
// Fire-and-forget — don't block plugin readiness
(async () => {
// Signal TUI we're scanning the directory tree
updateStatus("busy", { text: "scanning files", scanning: true, total: 0 });
updateStatus("busy", { text: "scanning files...", total: 0 });

// Quick preliminary file count for toast + timeout calculation
let fileCount = 0;
try {
const walked = await resolveFiles(directory, true);
fileCount = walked.files.length;
updateStatus("busy", { text: "scanning files", scanning: true, total: fileCount });
updateStatus("busy", { text: `scanning files... ${fileCount}`, total: fileCount });
const timeoutS = (calculateIngestTimeout(fileCount) / 1000).toFixed(0);
toast( `Indexing ${fileCount} files… (timeout: ${timeoutS}s)`, "info", "Brain 🧠");
updateStatus("busy", { text: `ingesting... 0/${fileCount}`, progress: 0, current: 0, total: fileCount, ingesting: true });
updateStatus("busy", { text: `ingesting... 0/${fileCount}`, current: 0, total: fileCount });
} catch {
toast( `Indexing ${project?.name ?? "project"}…`, "info", "Brain 🧠");
updateStatus("busy", { text: "ingesting...", progress: 0, ingesting: true });
updateStatus("busy", { text: "ingesting..." });
}

const ingestDb = initBrainDatabase();
Expand All @@ -120,9 +120,8 @@ const _serverPlugin = async (input: PluginInput) => {
reIndex: false,
project: directory,
progressCallback: ({ current, total }) => {
const pct = total > 0 ? Math.round((current / total) * 100) : 0;
// Update status file every tick so TUI spinner stays live
updateStatus("busy", { text: `ingesting... ${current}/${total}`, progress: pct, current, total, ingesting: true });
updateStatus("busy", { text: `ingesting... ${current}/${total}`, current, total });
},
}),
timeoutMs,
Expand Down Expand Up @@ -248,9 +247,8 @@ const _serverPlugin = async (input: PluginInput) => {
reIndex: args.reIndex === true,
project: toolCtx.directory,
progressCallback: ({ current, total }) => {
const pct = total > 0 ? Math.round((current / total) * 100) : 0;
// Update status file every tick so TUI spinner stays live
updateStatus("busy", { text: `ingesting... ${current}/${total}`, progress: pct, current, total, ingesting: true });
updateStatus("busy", { text: `ingesting... ${current}/${total}`, current, total });
},
}),
timeoutMs,
Expand Down Expand Up @@ -295,7 +293,7 @@ const _serverPlugin = async (input: PluginInput) => {
project: s.string().optional().describe("Project name or hash to scope search"),
},
execute: async (args, toolCtx) => {
updateStatus("busy", { text: "searching...", searching: true });
updateStatus("busy", { text: "searching..." });
const db = initBrainDatabase();
try {
const results = await withTimeout(
Expand Down
55 changes: 16 additions & 39 deletions src/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,13 @@ export interface StatusOpts {
/** Toast variant (defaults based on state) */
toastVariant?: "info" | "success" | "warning" | "error";
/** Progress info for busy states */
progress?: number;
current?: number;
total?: number;
scanning?: boolean;
searching?: boolean;
ingesting?: boolean;
}

/** Merged state — published via event bus on every update */
let currentStatus: Record<string, unknown> = { phase: "init", version: "" };
const _state = { current: {} as Record<string, unknown> };
_state.current = { status: "init", statusText: "", version: "" };
let _version = "";

let _client: PluginInput["client"] | null = null;
Expand All @@ -34,7 +31,7 @@ let _port = 0;
/** Initialize with client for toast support */
export function initVersion(v: string): void {
_version = v;
write({ phase: "init", statusText: "initializing..." });
write({ status: "init", statusText: "initializing..." });
}

export function initStatus(client: PluginInput["client"], directory: string): void {
Expand All @@ -51,7 +48,7 @@ export function startStatusServer(directory: string): void {
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/status") {
const payload = { ...currentStatus, version: _version, updated: Date.now() };
const payload = { ..._state.current, version: _version, updated: Date.now() };
return new Response(JSON.stringify(payload), {
headers: { "Content-Type": "application/json" },
});
Expand Down Expand Up @@ -86,8 +83,8 @@ export function stopStatusServer(): void {
}

function write(data: Record<string, unknown>): void {
currentStatus = { ...currentStatus, ...data };
brainBus.emit("status", { ...currentStatus, version: _version } as BrainStatusEvent);
_state.current = { ..._state.current, ...data };
brainBus.emit("status", { ..._state.current, version: _version } as BrainStatusEvent);
}

/**
Expand All @@ -103,74 +100,54 @@ export function updateStatus(state: StatusState, opts?: StatusOpts): void {
switch (state) {
case "busy":
write({
phase: "busy",
status: "busy",
statusText: opts?.text ?? "",
progress: opts?.progress,
current: opts?.current,
total: opts?.total,
scanning: opts?.scanning ?? false,
searching: opts?.searching ?? false,
ingesting: opts?.ingesting ?? false,
blocked: false,
});
break;

case "success":
write({
phase: "idle",
status: "ready",
statusText: opts?.text ?? "",
busy: false,
scanning: false,
searching: false,
ingesting: false,
});
if (opts?.toast && _client) {
_client?.tui.showToast({ body: { title: "Brain 🧠", message: opts.toast, variant: opts.toastVariant ?? "success", duration: 5000 } });
_client?.tui?.showToast({ body: { title: "Brain 🧠", message: opts.toast, variant: opts.toastVariant ?? "success", duration: 5000 } });
}
break;

case "warning":
write({
phase: "idle",
status: "ready",
statusText: opts?.text ?? "",
busy: false,
scanning: false,
searching: false,
ingesting: false,
});
if (opts?.toast && _client) {
_client?.tui.showToast({ body: { title: "Brain 🧠", message: opts.toast, variant: opts.toastVariant ?? "warning", duration: 5000 } });
_client?.tui?.showToast({ body: { title: "Brain 🧠", message: opts.toast, variant: opts.toastVariant ?? "warning", duration: 5000 } });
}
break;

case "error":
write({
phase: "idle",
status: "error",
statusText: opts?.text ?? "error occurred",
busy: false,
scanning: false,
searching: false,
ingesting: false,
error: opts?.text ?? "error occurred",
});
if (opts?.toast && _client) {
_client?.tui.showToast({ body: { title: "Brain 🧠", message: opts.toast, variant: "error", duration: 7000 } });
_client?.tui?.showToast({ body: { title: "Brain 🧠", message: opts.toast, variant: "error", duration: 7000 } });
}
break;

case "ready":
write({
phase: "idle",
status: "ready",
statusText: "",
busy: false,
scanning: false,
searching: false,
ingesting: false,
});
break;
}
}

/** Convenience wrapper for direct toast calls without status file updates */
export function toast(msg: string, variant: "info" | "success" | "warning" | "error" = "info", _title?: string): void {
_client?.tui.showToast({ body: { title: "Brain 🧠", message: msg, variant, duration: variant === "error" ? 7000 : 5000 } });
_client?.tui?.showToast({ body: { title: "Brain 🧠", message: msg, variant, duration: variant === "error" ? 7000 : 5000 } });
}
47 changes: 11 additions & 36 deletions src/tui.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,50 +27,25 @@ function BrainStatusBar(props: { centered?: boolean; api: TuiPluginApi }) {
setVersion(data.version ?? "");
pulse++;

if (data.error) {
if (data.status === "error") {
setBusy(false);
setIndicator("•");
setStatus("error occurred");
setStatus(data.error || data.statusText || "error occurred");
setFg(theme().error);
return;
}

if (data.phase === "init") {
} else if (data.status === "init") {
setBusy(true);
setStatus(data.statusText ?? "initializing...");
setFg(pulse % 2 === 0 ? theme().warning : theme().accent);
} else if (data.scanning) {
setBusy(true);
setStatus("scanning files... " + (data.total ?? 0));
setFg(pulse % 2 === 0 ? theme().warning : theme().accent);
} else if (data.ingesting) {
setBusy(true);
setCurrent(data.current ?? 0);
setTotal(data.total ?? 0);
setPct(data.progress ?? 0);
setStatus("ingesting... " + (data.current ?? 0) + "/" + (data.total ?? 0) + " (" + (data.progress ?? 0).toFixed(1) + "%)");
setFg(pulse % 2 === 0 ? theme().warning : theme().success);
} else if (data.phase === "ingest") {
// fallback for legacy ingest phase
setFg(theme().warning);
} else if (data.status === "busy") {
setBusy(true);
setCurrent(data.current ?? 0);
setTotal(data.total ?? 0);
setPct(data.progress ?? 0);
setStatus("ingesting... " + (data.current ?? 0) + "/" + (data.total ?? 0) + " (" + (data.progress ?? 0).toFixed(1) + "%)");
setFg(pulse % 2 === 0 ? theme().warning : theme().success);
} else if (data.searching) {
setBusy(true);
setStatus("searching...");
setFg(pulse % 2 === 0 ? theme().warning : theme().success);
} else if (data.blocked) {
setBusy(false);
setIndicator("•");
setStatus("ingest excluded");
setFg(theme().warning);
} else if (data.phase === "idle") {
setStatus(data.statusText ?? "working");
setFg(pulse % 2 === 0 ? theme().warning : theme().accent);
} else {
setBusy(false);
setIndicator("•");
setStatus(data.statusText || "ready");
setStatus("ready");
setFg(theme().success);
}
} catch {
Expand Down Expand Up @@ -108,8 +83,8 @@ function BrainStatusBar(props: { centered?: boolean; api: TuiPluginApi }) {
try {
const res = await fetch(statusUrl);
if (!res.ok) return;
const data = await res.json();
handleStatus(data as BrainStatusEvent);
const data = await res.json() as BrainStatusEvent;
handleStatus(data);
} catch { /* server not ready */ }
};

Expand Down
Loading