Add live LiNA-style side displays, session-aware autocomplete context, and IDE session resume

This commit is contained in:
Homer committed 2026-11-26 19:14:26 +00:00
1 parent b504dfd979
commit f99269151f
17 files changed
+1848 -17

No files matched your search

+8
View File
@@ -813,6 +813,14 @@ The device passes it to the server's `POST /v1/lembas/complete` (*The HTTP API*)
carried that `id`, answered the same way. `id` is **the client's own string for the request, in
its params** — not the JSON-RPC id, which a relay between the two rewrites. Without an `id` a
request is cancelled by the next one only.
- **`_lembas/complete/warm`** — client → agent, a notification `{ cwd?, sessionId?, path?, text? }`:
pre-warms the project's `FileIndex` and direct import summaries for `path` so subsequent
`_lembas/complete` requests send only situation-appropriate context in a stable session order.
- **`_lembas/sessions/list`** — client → agent → result `{ sessions }`: lists recent non-empty
sessions for a project `cwd` (optional `limit`, default 30) for editor session pickers.
- **`_lembas/sessions/resume`** — client → agent → result `{ sessionId, modes, turns, _meta }`:
opens an existing stored session by `sessionId` and returns its replayable `turns` along with
the active modes and model metadata.
- **Refusals** are `-32602` with the server's own sentence where it gave one, and `data.reason`:
`not_logged_in`; `no_model` (nobody has chosen an autocomplete model — the sentence says where);
`not_allowed` (the model is not one allowed for autocomplete); `unknown_model` (not a model of
+4
View File
@@ -80,6 +80,10 @@
"plain"
]
},
"displays": {
"description": "Side display pane showing live agent activity, files read, diffs, and bash output on wide terminals. Default true; Alt+D or /display toggles it.",
"type": "boolean"
},
"personality": {
"description": "How the agent talks: concise, pragmatic, optimistic, funny, formal, socratic, custom (personality_custom's text), or empty for none (the default). The same presets as the LLeMbas web UI; appended last to the system prompt, under \"## Personality\".",
"anyOf": [
+100 -3
View File
@@ -49,6 +49,7 @@ import { jobList, jobOutput, jobSend, jobStop, jobTranscript, storedJobs, teamFi
import { isNote } from "../session/prefix.ts"
import { outstandingReason } from "../session/outstanding.ts"
import { CANCELLED, changeBytes, completeBody, completeOnServer, currentLogin, diffContent, diffItems, editorBlock, editorSettings, loginOrRefuse, modelsForPicker, rewriteModel, rewriteParams, runRewrite, settingsToSet, type Login } from "./editor.ts"
import { CompletionContext } from "./complete_context.ts"
import { DeviceFiles, hashFd } from "./files.ts"
import { clientFor, ModelError, resolveModel } from "../provider/index.ts"
import { ProviderError, type ResolvedModel } from "../provider/types.ts"
@@ -615,6 +616,9 @@ export class AcpAgent {
// Spec 3.11.0: an editor as the client, files that are not text shown, and device files.
peer.handle("_lembas/complete", (p) => this.complete(p))
peer.on("_lembas/complete/cancel", (p) => this.completeCancel(p))
peer.on("_lembas/complete/warm", (p) => this.completeWarm(p))
peer.handle("_lembas/sessions/list", (p) => this.listSessions(p))
peer.handle("_lembas/sessions/resume", (p) => this.resumeSession(p))
peer.handle("_lembas/edit", (p) => this.edit(p))
peer.on("_lembas/edit/cancel", (p) => this.rewriteIds.get(requestId(p?.id) ?? "")?.abort())
peer.handle("_lembas/models", async () => modelsForPicker(loginOrRefuse(currentLogin())))
@@ -813,7 +817,11 @@ export class AcpAgent {
this.adopt(session)
// After the answer that names the session, so the client knows whose commands they are
// (and whose plan, where the session has one).
setTimeout(() => (this.sendCommands(session, true), this.sendPlan(session)), 0)
setTimeout(() => {
this.sendCommands(session, true)
this.sendPlan(session)
if (this.editorClient) this.completionCtx.warm(cwd)
}, 0)
return {
sessionId: id,
modes: { currentModeId: session.app.engine.mode, availableModes: this.modes().map((m) => ({ id: m, name: m })) },
@@ -1068,10 +1076,28 @@ export class AcpAgent {
}
/** `_lembas/complete`: autocomplete. One HTTP request to the server with the login this agent
* holds — no session, no project, nothing read — and a newer request stops the older, which is
* answered as cancelled: a result, since nothing went wrong. */
* holds; when a session or workspace `cwd` is given, gathers only the related context needed
* for the cursor's current situation in a stable session order so KV-cache prefill hits stay
* warm across keystrokes. A newer request stops the older, which is answered as cancelled. */
private async complete(p: any) {
const body = completeBody(p)
const root = this.completionRoot(p)
const open = Array.isArray(p?.open)
? p.open
.filter((x: any) => x && typeof x.path === "string" && typeof x.text === "string")
.slice(0, 12)
.map((x: any) => ({ path: x.path, text: x.text }))
: undefined
const gathered = this.completionCtx.gather({
root,
path: body.path,
language: body.language,
prefix: body.prefix,
suffix: body.suffix,
open,
clientContext: body.context,
})
if (gathered.length) body.context = gathered
const login = loginOrRefuse((this.login ??= currentLogin()))
this.completion?.abort.abort()
const id = requestId(p?.id)
@@ -1089,6 +1115,76 @@ export class AcpAgent {
}
}
private completionRoot(p: any): string | undefined {
const sid = typeof p?.sessionId === "string" ? p.sessionId : ""
if (sid) {
const held = this.sessions.get(sid)
if (held) return held.cwd
}
const raw = typeof p?.cwd === "string" ? p.cwd.trim() : ""
if (raw && isAbsolute(expandHome(raw))) {
const dir = resolve(expandHome(raw))
if (existsSync(dir) && statSync(dir).isDirectory() && !this.refusal(dir)) return dir
}
return undefined
}
/** `_lembas/complete/warm`: pre-warm the workspace FileIndex and direct imports for a file so
* the first completion request is already prefilled. */
private completeWarm(p: any) {
try {
const root = this.completionRoot(p)
if (!root) return
const path = typeof p?.path === "string" ? p.path : undefined
const text = typeof p?.text === "string" ? p.text : undefined
this.completionCtx.warm(root, path, text)
} catch {}
}
/** `_lembas/sessions/list`: list recent sessions for a project directory (for IDE resume). */
private listSessions(p: any) {
const raw = typeof p?.cwd === "string" ? p.cwd.trim() : ""
let root: string | undefined
if (raw && isAbsolute(expandHome(raw))) {
const dir = resolve(expandHome(raw))
const refused = this.refusal(dir)
if (refused) throw new RpcError(INVALID_PARAMS, refused)
root = findProject(dir).root
}
const limit = Math.max(1, Math.min(50, Number(p?.limit) || 25))
const rows = (this.store ??= new Store()).sessions(limit, root, true)
return {
sessions: rows.map((r) => ({
id: r.id,
title: r.title || "Untitled session",
root: r.root,
model: r.model,
updated: r.updated,
created: r.created,
})),
}
}
/** `_lembas/sessions/resume`: load an existing session from the store into memory and return
* its state + history turns so an editor can pick up where it left off. */
private resumeSession(p: any) {
const id = String(p?.sessionId ?? "").trim()
if (!id) throw new RpcError(INVALID_PARAMS, "sessionId is required")
const s = this.sessions.get(id) ?? this.load(id)
if (!s) throw new RpcError(INVALID_PARAMS, "no such session")
const store = (this.store ??= new Store())
const row = store.session(id)
const turns = row ? historyTurns(store.messages(id), s.cwd) : []
return {
sessionId: s.id,
title: row?.title || "",
cwd: s.cwd,
modes: { currentModeId: s.app.engine.mode, availableModes: this.modes().map((m) => ({ id: m, name: m })) },
_meta: { lembas: { model: s.app.engine.model.ref, mode: s.app.engine.mode, effort: s.app.engine.effort, instance: this.isInstance(s.app.engine.model.connectionName) } },
turns,
}
}
private completeCancel(p: any) {
const id = requestId(p?.id)
const running = this.completion
@@ -1284,6 +1380,7 @@ export class AcpAgent {
}
private indexes = new Map<string, FileIndex>()
private completionCtx = new CompletionContext((root) => this.indexFor(root))
private indexFor(root: string): FileIndex {
let i = this.indexes.get(root)
if (!i) {
+478
View File
@@ -0,0 +1,478 @@
// Session-aware, situation-aware autocomplete context gathering with stable KV-cache ordering.
//
// Gathers ONLY what is needed for the cursor's current situation:
// - Inside a comment -> no external context (fast, zero wasted tokens).
// - On an import/include/require line -> compact workspace file list from the warmed FileIndex.
// - Member access (`foo.`) or general code -> resolves local imports and referenced identifiers
// from cached file summaries (preferring unsaved open buffers sent by the editor), returning
// compact declarations/excerpts in a deterministic session order so KV-cache prefill hits
// stay warm across keystrokes.
import { readFileSync, statSync } from "node:fs"
import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path"
import type { FileIndex } from "../project/files.ts"
export interface ContextChunk {
path: string
text: string
}
export interface OpenSnippet {
path: string
text: string
}
export type Situation = "comment" | "import" | "member" | "code"
export interface SituationInfo {
kind: Situation
receiver?: string
partialImport?: string
identifiers: string[]
}
const MAX_CHUNKS = 6
const MAX_TOTAL_BYTES = 24 * 1024
const MAX_CHUNK_BYTES = 5 * 1024
const MAX_READ_BYTES = 128 * 1024
const SUMMARY_MAX_LINES = 80
const MAX_CACHED_FILES = 300
const CODE_EXTS = new Set([
".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
".py", ".pyi", ".rs", ".go", ".lua", ".c", ".h", ".cc", ".cpp", ".hpp",
".java", ".kt", ".cs", ".rb", ".php", ".swift", ".sh", ".bash", ".zsh",
".css", ".scss", ".html", ".json", ".yaml", ".yml", ".toml", ".sql",
])
const KEYWORDS = new Set([
"if", "else", "for", "while", "return", "const", "let", "var", "function", "class",
"import", "from", "export", "default", "async", "await", "try", "catch", "finally",
"throw", "new", "this", "super", "true", "false", "null", "undefined", "void",
"def", "self", "None", "True", "False", "and", "or", "not", "in", "is", "as", "with",
"pub", "fn", "struct", "enum", "impl", "trait", "mod", "use", "match", "mut", "ref",
"local", "end", "then", "elseif", "do", "repeat", "until", "nil", "type", "interface",
"string", "number", "boolean", "object", "any", "unknown", "never", "int", "str", "bool",
"float", "list", "dict", "set", "tuple", "print", "console", "len", "range", "error",
])
interface CachedFile {
mtimeMs: number
size: number
summary: string
symbols: Set<string>
}
const bytes = (s: string) => Buffer.byteLength(s, "utf8")
function clipBytes(text: string, max: number): string {
if (bytes(text) <= max) return text
const b = Buffer.from(text, "utf8")
let at = max
while (at > 0 && (b[at]! & 0xc0) === 0x80) at--
return b.subarray(0, at).toString("utf8")
}
/** Analyze the immediate cursor context to decide what external data is actually needed. */
export function analyzeSituation(prefix: string, suffix: string, language?: string): SituationInfo {
const nl = prefix.lastIndexOf("\n")
const rawLine = nl >= 0 ? prefix.slice(nl + 1) : prefix
const currentLine = rawLine.length > 300 ? rawLine.slice(-300) : rawLine
const trimmed = rawLine.trimStart().slice(0, 300)
// 1. Inside a line comment -> no external file context needed.
if (
trimmed.startsWith("//") ||
trimmed.startsWith("# ") ||
trimmed === "#" ||
trimmed.startsWith("--") ||
trimmed.startsWith("/*") ||
trimmed.startsWith("* ")
) {
// Exception: C/C++ #include or Python `#` is comment unless #include.
if (!/^#\s*include\b/.test(trimmed)) {
return { kind: "comment", identifiers: [] }
}
}
// Unclosed block comment check in recent tail.
const tail = prefix.slice(-1500)
const lastOpen = tail.lastIndexOf("/*")
const lastClose = tail.lastIndexOf("*/")
if (lastOpen >= 0 && lastOpen > lastClose) {
return { kind: "comment", identifiers: [] }
}
// 2. Import / include / require / use line -> needs workspace file paths, not file bodies.
const importMatch =
rawLine.length <= 300
? /(?:^|\s)(?:import\b.*?\bfrom\s+["']([^"']*)|import\s+["']([^"']*)|require\(\s*["']([^"']*)|from\s+([A-Za-z0-9_./]*)|^import\s+([A-Za-z0-9_.,\s]*)|use\s+([A-Za-z0-9_:]*)|#\s*include\s+["<]([^">]*))$/.exec(
trimmed,
)
: null
if (importMatch) {
const partial = (importMatch.slice(1).find((g) => g !== undefined) ?? "").trim()
return { kind: "import", partialImport: partial, identifiers: [] }
}
// Collect nearby identifiers from the bounded window around the cursor.
const recentPrefix = prefix.slice(-2000).split("\n").slice(-15).join("\n")
const recentSuffix = suffix.slice(0, 600).split("\n").slice(0, 5).join("\n")
const recent = recentPrefix + "\n" + recentSuffix
const idSet = new Set<string>()
for (const m of recent.matchAll(/\b([A-Za-z_][A-Za-z0-9_]{2,64})\b/g)) {
const id = m[1]!
if (!KEYWORDS.has(id)) idSet.add(id)
}
// 3. Member access (`receiver.` / `receiver::` / `receiver->`)
const memberMatch = /\b([A-Za-z_][A-Za-z0-9_]{0,64})\s*(?:\.|::|->)\s*[A-Za-z0-9_]{0,64}$/.exec(currentLine)
if (memberMatch) {
const receiver = memberMatch[1]!
if (!KEYWORDS.has(receiver)) idSet.add(receiver)
return { kind: "member", receiver, identifiers: [...idSet].slice(0, 40) }
}
void language
return { kind: "code", identifiers: [...idSet].slice(0, 40) }
}
/** Extract local import specifiers from a source file's text. */
export function extractImports(text: string): string[] {
const out = new Set<string>()
// JS/TS: import ... from "...", export ... from "...", require("...")
for (const m of text.matchAll(/(?:from|import)\s+["']([^"'\n]+)["']|require\(\s*["']([^"'\n]+)["']\s*\)/g)) {
const spec = (m[1] ?? m[2] ?? "").trim()
if (spec) out.add(spec)
}
// Python: from foo.bar import ..., import foo.bar
for (const m of text.matchAll(/^\s*from\s+(\.{0,3}[A-Za-z0-9_.]+)\s+import\b|^\s*import\s+([A-Za-z0-9_.]+)/gm)) {
const spec = (m[1] ?? m[2] ?? "").trim()
if (spec) out.add(spec)
}
// Rust: use crate::foo::bar, mod foo;
for (const m of text.matchAll(/^\s*use\s+(?:crate|super|self)::([A-Za-z0-9_:]+)|^\s*(?:pub\s+)?mod\s+([A-Za-z0-9_]+)\s*;/gm)) {
const spec = (m[1] ?? m[2] ?? "").trim()
if (spec) out.add(spec)
}
// C/C++: #include "foo.h"
for (const m of text.matchAll(/^\s*#\s*include\s+"([^"\n]+)"/gm)) {
const spec = m[1]!.trim()
if (spec) out.add(spec)
}
return [...out].slice(0, 40)
}
/** Extract compact declarations/signatures and symbol names from a source file. */
export function summarizeSource(text: string): { summary: string; symbols: Set<string> } {
const lines = text.split("\n")
const symbols = new Set<string>()
const picked: string[] = []
const declRe =
/^(?:(?:export\s+(?:default\s+)?)?(?:async\s+)?(?:function|class|interface|type|enum|const|let|var|def|fn|pub\s+(?:async\s+)?(?:fn|struct|enum|trait|type|const)|struct|impl|trait|local\s+function|function\s+[A-Za-z0-9_.:]+|func)\b|\s{1,4}(?:async\s+)?(?:def|fn|pub\s+(?:async\s+)?fn|function)\b)/
const symRe =
/\b(?:function|class|interface|type|enum|const|let|var|def|fn|struct|trait|func)\s+([A-Za-z_][A-Za-z0-9_]*)/
if (lines.length <= SUMMARY_MAX_LINES && bytes(text) <= MAX_CHUNK_BYTES) {
for (const line of lines) {
const sm = symRe.exec(line)
if (sm && !KEYWORDS.has(sm[1]!)) symbols.add(sm[1]!)
}
return { summary: text, symbols }
}
for (let i = 0; i < lines.length && picked.length < SUMMARY_MAX_LINES; i++) {
const line = lines[i]!
const sm = symRe.exec(line)
if (sm && !KEYWORDS.has(sm[1]!)) symbols.add(sm[1]!)
if (declRe.test(line)) {
// Include a 1-line doc comment above if present.
const prev = i > 0 ? lines[i - 1]!.trim() : ""
if (
(prev.startsWith("/**") || prev.startsWith("///") || prev.startsWith("--- ") || prev.startsWith("# ")) &&
picked[picked.length - 1] !== lines[i - 1]
) {
picked.push(lines[i - 1]!)
}
picked.push(line)
// For interfaces/structs/type blocks, include up to 8 member lines.
if (/\b(?:interface|struct|enum|type)\b/.test(line) && line.includes("{") && !line.includes("}")) {
for (let k = 1; k <= 8 && i + k < lines.length && picked.length < SUMMARY_MAX_LINES; k++) {
picked.push(lines[i + k]!)
if (lines[i + k]!.includes("}")) break
}
}
}
}
const body = picked.length ? picked.join("\n") : lines.slice(0, 40).join("\n")
return { summary: clipBytes(body, MAX_CHUNK_BYTES), symbols }
}
/** Resolve an import specifier to a relative project path in `allFiles`. */
function resolveImport(spec: string, currentRel: string, fileSet: Set<string>, allFiles: readonly string[]): string | undefined {
const dir = currentRel ? dirname(currentRel).replace(/^\.$/, "") : ""
const candidates: string[] = []
const addWithExts = (base: string) => {
const clean = base.replace(/^\.\//, "").replace(/\/+/g, "/")
candidates.push(clean)
if (!extname(clean)) {
for (const ext of [".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".lua", ".go", ".h", ".hpp"]) {
candidates.push(clean + ext)
}
for (const idx of ["/index.ts", "/index.js", "/__init__.py", "/mod.rs", "/init.lua"]) {
candidates.push(clean + idx)
}
}
}
if (spec.startsWith("./") || spec.startsWith("../")) {
const joined = dir ? join(dir, spec) : spec
addWithExts(joined.replace(/\\/g, "/"))
} else if (spec.includes("::")) {
// Rust crate::a::b -> src/a/b.rs or src/a.rs
const parts = spec.split("::").filter(Boolean)
if (parts.length) {
addWithExts("src/" + parts.join("/"))
if (parts.length > 1) addWithExts("src/" + parts.slice(0, -1).join("/"))
}
} else if (spec.startsWith(".")) {
// Python relative import `.foo` / `..bar`
const dots = /^\.+/.exec(spec)![0].length
const rest = spec.slice(dots).replace(/\./g, "/")
let baseDir = dir
for (let i = 1; i < dots; i++) baseDir = dirname(baseDir).replace(/^\.$/, "")
addWithExts(baseDir ? (rest ? `${baseDir}/${rest}` : baseDir) : rest)
} else {
// Dotted Python/Lua module or workspace-root path (`lembas.services.foo` or `llembas.chat`)
const slash = spec.replace(/\./g, "/")
addWithExts(slash)
addWithExts("src/" + slash)
if (dir) addWithExts(`${dir}/${slash}`)
}
for (const c of candidates) {
if (fileSet.has(c)) return c
}
// Tail match for unique module suffix (e.g. `llembas/chat.lua` in `nvim/lua/llembas/chat.lua`).
const tailSlash = "/" + spec.replace(/\./g, "/")
for (const f of allFiles) {
const noExt = f.replace(/\.[^/.]+$/, "")
if (noExt.endsWith(tailSlash)) return f
}
return undefined
}
/** Session-scoped cache & selective context gatherer for autocomplete. */
export class CompletionContext {
private files = new Map<string, CachedFile>()
/** Stable order in which context files were introduced per workspace (keeps KV-cache prefix stable). */
private order = new Map<string, string[]>()
constructor(private indexFor: (root: string) => FileIndex) {}
private relOf(root: string, filePath?: string): string {
if (!filePath) return ""
if (!isAbsolute(filePath)) return filePath.replace(/\\/g, "/")
const rel = relative(root, resolve(filePath)).replace(/\\/g, "/")
return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : ""
}
private readCached(root: string, rel: string): CachedFile | undefined {
const abs = join(root, rel)
let st: ReturnType<typeof statSync>
try {
st = statSync(abs)
} catch {
return undefined
}
if (!st.isFile() || st.size === 0 || st.size > MAX_READ_BYTES) return undefined
const prev = this.files.get(abs)
if (prev && prev.mtimeMs === st.mtimeMs && prev.size === st.size) return prev
let text: string
try {
text = readFileSync(abs, "utf8")
} catch {
return undefined
}
if (text.includes("\0")) return undefined
const entry: CachedFile = { mtimeMs: st.mtimeMs, size: st.size, ...summarizeSource(text) }
this.files.set(abs, entry)
if (this.files.size > MAX_CACHED_FILES) {
const oldest = this.files.keys().next().value
if (oldest) this.files.delete(oldest)
}
return entry
}
private rankInOrder(root: string, rel: string): number {
let list = this.order.get(root)
if (!list) {
list = []
this.order.set(root, list)
}
let idx = list.indexOf(rel)
if (idx < 0) {
idx = list.length
list.push(rel)
if (list.length > 200) list.shift()
}
return idx
}
/** Pre-warm the file index and direct imports for a file in `root` so the first completion is prefilled. */
warm(root: string, filePath?: string, text?: string): void {
const idx = this.indexFor(root)
const allFiles = idx.allFiles()
const fileSet = new Set(allFiles)
const currentRel = this.relOf(root, filePath)
if (!currentRel) return
let source = text
if (source === undefined) {
try {
const abs = isAbsolute(filePath!) ? filePath! : join(root, currentRel)
const st = statSync(abs)
if (st.isFile() && st.size <= MAX_READ_BYTES) source = readFileSync(abs, "utf8")
} catch {
return
}
}
if (!source) return
for (const spec of extractImports(source).slice(0, 12)) {
const target = resolveImport(spec, currentRel, fileSet, allFiles)
if (target && target !== currentRel) {
this.readCached(root, target)
this.rankInOrder(root, target)
}
}
}
/** Gather only the context needed for the cursor's current situation, in a stable session order. */
gather(o: {
root?: string
path?: string
language?: string
prefix: string
suffix: string
open?: OpenSnippet[]
clientContext?: ContextChunk[]
}): ContextChunk[] {
const sit = analyzeSituation(o.prefix, o.suffix, o.language)
const clientChunks = (o.clientContext ?? []).filter((c) => c && c.path && c.text)
// Comments need no external project context.
if (sit.kind === "comment") return clientChunks.slice(0, MAX_CHUNKS)
if (!o.root) return clientChunks.slice(0, MAX_CHUNKS)
const idx = this.indexFor(o.root)
const allFiles = idx.allFiles()
// Import line: return a compact list of matching project paths from the file index.
if (sit.kind === "import") {
const query = (sit.partialImport ?? "").replace(/^\.+\//, "").replace(/\./g, "/")
const matches = query ? idx.search(query, 30) : allFiles.slice(0, 40)
const list = matches.filter((f) => !f.endsWith("/")).slice(0, 30)
if (!list.length) return clientChunks.slice(0, MAX_CHUNKS)
return [
...clientChunks,
{ path: "<workspace-files>", text: list.join("\n") },
].slice(0, MAX_CHUNKS)
}
const fileSet = new Set(allFiles)
const currentRel = this.relOf(o.root, o.path)
const openMap = new Map<string, { rel: string; summary: string; symbols: Set<string> }>()
for (const s of o.open ?? []) {
if (!s?.path || !s.text) continue
const rel = this.relOf(o.root, s.path) || s.path
if (rel === currentRel) continue
const parsed = summarizeSource(s.text)
openMap.set(rel, { rel, ...parsed })
}
const scores = new Map<string, { score: number; text: string }>()
const idSet = new Set(sit.identifiers)
const imports = extractImports(o.prefix + "\n" + o.suffix)
// 1. Directly imported local files (highest relevance).
for (const spec of imports) {
const target = resolveImport(spec, currentRel, fileSet, allFiles)
if (!target || target === currentRel) continue
const openHit = openMap.get(target)
const entry = openHit ?? this.readCached(o.root, target)
if (!entry) continue
let overlap = 0
for (const sym of entry.symbols) {
if (sit.receiver && sym === sit.receiver) overlap += 5
else if (idSet.has(sym)) overlap += 2
}
const prev = scores.get(target)
const score = 10 + overlap
if (!prev || score > prev.score) scores.set(target, { score, text: entry.summary })
}
// 2. Open editor buffers that share symbols referenced near the cursor (unsaved text included!).
for (const [rel, entry] of openMap) {
if (scores.has(rel)) continue
let overlap = 0
for (const sym of entry.symbols) {
if (sit.receiver && sym === sit.receiver) overlap += 5
else if (idSet.has(sym)) overlap += 2
}
if (overlap > 0) {
scores.set(rel, { score: 4 + overlap, text: entry.summary })
}
}
// 3. If still very sparse and we have specific symbols, check same-directory sibling code files.
if (scores.size < 2 && currentRel && idSet.size > 0) {
const currentDir = dirname(currentRel).replace(/^\.$/, "")
const currentExt = extname(currentRel)
let checked = 0
for (const f of allFiles) {
if (checked >= 8) break
if (f === currentRel || scores.has(f)) continue
if (dirname(f).replace(/^\.$/, "") !== currentDir) continue
const ext = extname(f)
if (!CODE_EXTS.has(ext) || (currentExt && ext !== currentExt)) continue
checked++
const entry = this.readCached(o.root, f)
if (!entry) continue
let overlap = 0
for (const sym of entry.symbols) {
if (sit.receiver && sym === sit.receiver) overlap += 5
else if (idSet.has(sym)) overlap += 2
}
if (overlap > 0) {
scores.set(f, { score: 2 + overlap, text: entry.summary })
}
}
}
// Pick top-K candidates by relevance, then sort by STABLE session order so the KV cache stays hot!
const top = [...scores.entries()]
.sort((a, b) => b[1].score - a[1].score)
.slice(0, MAX_CHUNKS)
for (const [rel] of top) this.rankInOrder(o.root, rel)
top.sort((a, b) => this.rankInOrder(o.root!, a[0]) - this.rankInOrder(o.root!, b[0]))
const seenPaths = new Set<string>()
const result: ContextChunk[] = []
let total = 0
const push = (path: string, text: string) => {
if (!path || !text || seenPaths.has(path) || result.length >= MAX_CHUNKS) return
const clipped = clipBytes(text, MAX_CHUNK_BYTES)
const cost = bytes(clipped)
if (total + cost > MAX_TOTAL_BYTES) return
seenPaths.add(path)
total += cost
result.push({ path, text: clipped })
}
// Client-supplied explicit context first (e.g., pinned/unsaved), then gathered session context.
for (const c of clientChunks) push(c.path, c.text)
for (const [rel, item] of top) push(rel, item.text)
return result
}
}
+27 -1
View File
@@ -74,6 +74,11 @@ export function currentLogin(): Login | undefined {
return soleInstance()
}
export interface CompleteContextChunk {
path: string
text: string
}
export interface CompleteParams {
prefix: string
suffix: string
@@ -81,6 +86,7 @@ export interface CompleteParams {
language?: string
model?: string
max_tokens?: number
context?: CompleteContextChunk[]
}
/** What `_lembas/complete` sends on from its params: the window trimmed, the tokens capped. */
@@ -92,7 +98,27 @@ export function completeBody(p: any): CompleteParams {
const path = str(p.path, 1000)
const language = str(p.language, 100)
const model = str(p.model, 300)
return { ...w, ...(path ? { path } : {}), ...(language ? { language } : {}), ...(model ? { model } : {}), ...(tokens ? { max_tokens: tokens } : {}) }
const rawCtx = Array.isArray(p.context) ? p.context : []
const context: CompleteContextChunk[] = []
let ctxBytes = 0
for (const item of rawCtx) {
if (context.length >= 8) break
if (!item || typeof item !== "object" || typeof item.path !== "string" || typeof item.text !== "string") continue
const cPath = item.path.replace(/[\r\n]/g, "").trim().slice(0, 500)
if (!cPath || !item.text) continue
const size = bytes(item.text)
if (ctxBytes + size > 32 * 1024) continue
ctxBytes += size
context.push({ path: cPath, text: item.text })
}
return {
...w,
...(path ? { path } : {}),
...(language ? { language } : {}),
...(model ? { model } : {}),
...(tokens ? { max_tokens: tokens } : {}),
...(context.length ? { context } : {}),
}
}
/** One autocomplete request to the server (`POST /v1/lembas/complete`, acp.md *The HTTP API*).
+1
View File
@@ -247,6 +247,7 @@ export const Config = z.strictObject({
paste: z.enum(["placeholder", "full"]).optional().describe("A long paste into the prompt box (3 lines or more, or over 150 characters) and a pasted image: placeholder (default) — shown as [Pasted text 40 lines] or [Image 1], sent in full; full — the text itself, and an image as its @path."),
kitty_clipboard: z.boolean().optional().describe("true: over SSH in the kitty terminal, ctrl+v asks the terminal itself for the image on its clipboard (kitty's clipboard protocol, OSC 5522; kitty asks you to allow it). Default false: on a connection that stalls the image may not arrive whole — it is then refused, never saved broken — so it is opt-in."),
icons: z.enum(["emoji", "plain"]).optional().describe("emoji (default), or plain: one-column symbols for a terminal font that has no emoji."),
displays: z.boolean().optional().describe("Side display pane showing live agent activity, files read, diffs, and bash output on wide terminals. Default true; Alt+D or /display toggles it."),
personality: z
.enum(PERSONALITIES)
.or(z.literal(""))
+1
View File
@@ -62,6 +62,7 @@ export const SETTINGS: SettingDef[] = [
{ key: "paste", kind: "enum", values: ["placeholder", "full"], agent: true, scopes: USER, fallback: "placeholder", hint: "a long paste or a pasted image in the prompt box: a placeholder, or shown in full" },
{ key: "kitty_clipboard", kind: "boolean", agent: false, scopes: USER, fallback: "false", hint: "over SSH in kitty, ctrl+v asks the terminal for the image on its clipboard" },
{ key: "icons", kind: "enum", values: ["emoji", "plain"], agent: true, scopes: USER, fallback: "emoji" },
{ key: "displays", kind: "boolean", agent: true, scopes: USER, fallback: "true", hint: "side display pane on wide terminals (Alt+D or /display toggles)" },
{ key: "notify", kind: "boolean", agent: true, scopes: USER, fallback: "true", hint: "bell and desktop notification when a reply finishes or the agent waits for you while the terminal is not focused" },
{ key: "mouse", kind: "boolean", agent: true, scopes: ["global"], reload: true, fallback: "true" },
{ key: "compaction.auto_at", kind: "number", agent: true, scopes: ALL, fallback: "0.85" },
+6
View File
@@ -42,6 +42,12 @@ export class FileIndex {
this.dirs = [...dirs].sort()
}
/** All indexed relative file paths (refreshes at most every few seconds). */
allFiles(): readonly string[] {
this.refresh()
return this.files
}
/** Best matches for what was typed after @. A trailing / lists that directory's children. */
search(query: string, limit = 8): string[] {
this.refresh()
+1 -1
View File
@@ -40,7 +40,7 @@ export const TUI_COMMAND_NAMES = [
"agents", "continue", "help", "model", "effort", "mode", "plan", "plans", "pages", "review", "changelog", "init", "release", "tasks", "decisions", "decide",
"jobs", "sessions", "resume", "remote", "delete", "new", "clear", "copy", "undo", "redo", "diff", "checkpoint", "checkpoints", "branch", "commit", "context",
"compact", "memory", "skills", "skill", "personality", "voice", "speak", "mcp", "login", "logout", "settings", "usage", "kb", "theme", "skin", "terminal",
"icons", "trust", "reload", "restart", "quit", "exit", "q", "team", "rename", "schedule", "schedules", "search", "permissions", "status", "command", "reports",
"icons", "trust", "reload", "restart", "quit", "exit", "q", "team", "rename", "schedule", "schedules", "search", "permissions", "status", "command", "reports", "display", "displays",
] as const
/** The built-ins that work without a screen of their own. Descriptions as the TUI's (a test). */
+91 -11
View File
@@ -8,7 +8,9 @@ import { levelLabel, type Level } from "../provider/effort.ts"
import { teamLabel } from "../session/commands.ts"
import { COMMANDS, findCommand, type CommandCtx } from "./commands.ts"
import { Dialog, type DialogSpec } from "./components/dialog.tsx"
import { DisplayPane } from "./components/display_pane.tsx"
import { Messages } from "./components/messages.tsx"
import { cycleTab, DISPLAY_MIN_WIDTH, effectiveTab, extractBash, extractChanges, extractFiles, initialNav, resetFollow, stepEntry, type DisplayNavState } from "./displays.ts"
import { PermissionPrompt } from "./components/permission.tsx"
import { copiedMessage, copyText, isRemote } from "./clipboard.ts"
import { QuestionCard } from "./components/question.tsx"
@@ -112,20 +114,26 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
icons = e.value as IconSet
setThemeSignal(loadTheme(theme().name, icons).theme)
}
if (e.key === "displays") setDisplaysEnabled(e.value !== false)
refresh()
})
app.settings.checks.set("theme", (v) => {
if (!themeNames().includes(String(v))) throw new Error(`no theme "${v}" — ${themeNames().join(", ")}`)
})
let scroll: ScrollBoxRenderable | undefined
let displayScroll: ScrollBoxRenderable | undefined
let input: TextareaRenderable | undefined
let box: PromptHandle | undefined
const [displaysEnabled, setDisplaysEnabled] = createSignal(app.loaded.config.displays !== false)
const [displayNav, setDisplayNav] = createSignal<DisplayNavState>(initialNav())
/** What is selected, as it is copied: a selection in the prompt box in full (a paste placeholder
* as what it stands for), anything else as it reads. */
const selectedText = (visible: string) => (visible && input?.hasSelection() && input.getSelectedText() === visible ? (box?.expandedSelection() ?? visible) : visible)
let quitArmed = 0
const dims = useTerminalDimensions()
const showDisplays = () => displaysEnabled() && !entered() && dims().width >= DISPLAY_MIN_WIDTH
const displayWidth = () => Math.max(42, Math.min(84, Math.floor(dims().width * 0.44)))
const ctx: Ctx = { app, view, theme, md, thought, dims }
// Background jobs: the view's list is the registry's at the start and on every session change
@@ -295,6 +303,31 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
},
openJob: (id) => setJobPanel(id),
enterJob,
setDisplays(action) {
if (action === "toggle") {
const next = !displaysEnabled()
setDisplaysEnabled(next)
return next
? dims().width < DISPLAY_MIN_WIDTH
? `side display enabled (widen terminal to ${DISPLAY_MIN_WIDTH}+ cols to show it; now ${dims().width})`
: "side display shown (Alt+↑↓ tabs · Alt+←→ entry · Alt+PgUp/Dn scroll · Alt+D hide)"
: "side display hidden (Alt+D or /display on to show)"
}
if (action === "off") {
setDisplaysEnabled(false)
return "side display hidden"
}
setDisplaysEnabled(true)
if (action !== "on") {
setDisplayNav((n) => ({ ...n, tab: action, pinned: action !== "live" }))
return dims().width < DISPLAY_MIN_WIDTH
? `side display tab: ${action} (widen terminal to ${DISPLAY_MIN_WIDTH}+ cols to show it)`
: `side display: ${action}`
}
return dims().width < DISPLAY_MIN_WIDTH
? `side display enabled (widen terminal to ${DISPLAY_MIN_WIDTH}+ cols to show it)`
: "side display shown"
},
copy: (text: string) => copy(text),
renderer,
send: (text: string) => void send(text),
@@ -340,6 +373,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
// its text. Only here: the session's title, the `prompt` event and everything a server
// mirrors get `shown`, which holds the words themselves.
view.user(drawn)
setDisplayNav((n) => resetFollow(n))
if (atts.length) view.info(`attached ${atts.map((a) => (a.image ? `${a.path} (image)` : a.text.includes("not attached") ? `${a.path} (not attached: ${/not attached: ([^)]*)/.exec(a.text)?.[1]})` : a.path)).join(", ")}`)
if (given?.attachments.length) view.info(`attached ${given.attachments.map((a) => a.name).join(", ")}`)
scroll?.scrollTo(scroll.scrollHeight)
@@ -549,6 +583,42 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
if (holdToTalk && voice.state === "recording" && recordKey.released(key)) void voice.toggle()
return
}
// Side display navigation works even while a permission/question/plan card is open so the
// person can scroll diffs or inspect files/bash output before answering.
const alt = Boolean(key.meta || (key as { option?: boolean }).option)
if (alt && !key.ctrl && !dialog() && !jobPanel()) {
if (key.name === "d") {
const next = !displaysEnabled()
setDisplaysEnabled(next)
flash(next ? (dims().width < DISPLAY_MIN_WIDTH ? `display on (needs ${DISPLAY_MIN_WIDTH}+ cols)` : "side display shown") : "side display hidden")
return key.preventDefault()
}
if (showDisplays()) {
if (key.name === "up" || key.name === "down") {
setDisplayNav((n) => cycleTab(n, key.name === "up" ? -1 : 1))
return key.preventDefault()
}
if (key.name === "left" || key.name === "right") {
const tab = effectiveTab(displayNav(), Boolean(view.state.pending?.preview?.diff))
if (tab !== "live") {
const count =
tab === "files"
? extractFiles(view.state.items).length
: tab === "changes"
? extractChanges(view.state.items, view.state.pending).length
: extractBash(view.state.items).length
setDisplayNav((n) => stepEntry(n, tab, key.name === "left" ? -1 : 1, count))
}
return key.preventDefault()
}
if (key.name === "pageup" || key.name === "pagedown" || key.name === "[" || key.name === "]") {
const up = key.name === "pageup" || key.name === "["
const step = Math.max(1, Math.floor((displayScroll?.height || 10) / 2))
displayScroll?.scrollBy(up ? -step : step)
return key.preventDefault()
}
}
}
// A card or dialog owns the keyboard: esc there means that card's own thing.
const overlay = dialog() || jobPanel() || view.state.pending || view.state.question || view.state.plan
if (!overlay && recordKey.matches(key) && (voice.canListen || voiceCfg)) {
@@ -655,17 +725,27 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
when={entered()}
keyed
fallback={
<scrollbox
ref={(r: ScrollBoxRenderable) => (scroll = r)}
flexGrow={1}
stickyScroll
stickyStart="bottom"
viewportOptions={{ paddingRight: 1 }}
verticalScrollbarOptions={{ trackOptions: { backgroundColor: theme().colors.panel, foregroundColor: theme().colors.dim } }}
>
<Welcome />
<Messages />
</scrollbox>
<box flexDirection="row" flexGrow={1}>
<scrollbox
ref={(r: ScrollBoxRenderable) => (scroll = r)}
flexGrow={1}
stickyScroll
stickyStart="bottom"
viewportOptions={{ paddingRight: 1 }}
verticalScrollbarOptions={{ trackOptions: { backgroundColor: theme().colors.panel, foregroundColor: theme().colors.dim } }}
>
<Welcome />
<Messages />
</scrollbox>
<Show when={showDisplays()}>
<DisplayPane
width={displayWidth()}
nav={displayNav}
onSelectTab={(tab) => setDisplayNav((n) => ({ ...n, tab, pinned: tab !== "live" }))}
scrollRef={(r) => (displayScroll = r)}
/>
</Show>
</box>
}
>
{(id: string) => <SubagentView id={id} view={childViews.get(id)!} scrollRef={(r) => (scroll = r)} />}
+18
View File
@@ -73,6 +73,8 @@ export interface CommandCtx extends Ctx {
openJob(id: string): void
/** Enter a subagent job: its transcript in place of the session's, the prompt box sends to it. */
enterJob(id: string): void
/** Control the side display pane (on/off/toggle or select a tab). */
setDisplays?(action: "toggle" | "on" | "off" | "live" | "files" | "changes" | "bash"): string
}
export interface Command {
@@ -88,6 +90,7 @@ const HELP_KEYS = [
"esc stop the model · ctrl+g continue (after a stop, or to keep going) · ctrl+c clear, twice to quit · ctrl+d (empty box) quit",
"/jobs background jobs: enter opens one (a subagent: esc back, type to message it), k stops it · ctrl+b moves the running command to the background",
"shift+tab cycle mode (manual → edit → plan) · ctrl+r show reasoning · ctrl+o expand tool output",
"alt+d toggle side display · alt+↑/↓ switch display tab (live/files/changes/bash) · alt+←/→ entry · alt+pgup/pgdn scroll display",
"pgup/pgdn scroll half a screen · ctrl+↑/↓ three lines · the mouse wheel · ↑ in an empty box takes back a message waiting to go in",
]
@@ -194,6 +197,21 @@ export const COMMANDS: Command[] = [
description: "carry on — after esc stopped it, or when it should keep going (ctrl+g)",
run: (c) => c.continueTask(),
},
{
name: "display",
aliases: ["displays"],
args: "[on|off|live|files|changes|bash]",
description: "toggle or switch the side display pane (live activity, files, changes, bash)",
run(c, arg) {
if (!c.setDisplays) return c.view.info("side displays are not available here", "warn")
const a = arg.trim().toLowerCase()
if (!a) return c.view.info(c.setDisplays("toggle"))
if (a === "on" || a === "off" || a === "live" || a === "files" || a === "changes" || a === "bash") {
return c.view.info(c.setDisplays(a))
}
c.view.info("usage: /display [on|off|live|files|changes|bash]", "warn")
},
},
{
name: "help",
description: "commands and keys",
+443
View File
@@ -0,0 +1,443 @@
import { TextAttributes, type ScrollBoxRenderable } from "@opentui/core"
import { createEffect, createMemo, createSignal, For, Match, onCleanup, Show, Switch } from "solid-js"
import { useTui } from "../context.ts"
import {
buildLiveSnapshot,
DISPLAY_TABS,
effectiveTab,
extractBash,
extractChanges,
extractFiles,
resolveIndex,
type DisplayNavState,
type DisplayTab,
} from "../displays.ts"
import { filetypeOf } from "./messages.tsx"
const TAB_LABEL: Record<DisplayTab, string> = {
live: "Live",
files: "Files",
changes: "Changes",
bash: "Bash",
}
const PLAN_MARK: Record<string, string> = { todo: "☐", doing: "▸", done: "☑", dropped: "✗" }
function toolStatusGlyph(status: string): string {
if (status === "running") return "◐"
if (status === "error") return "✗"
if (status === "denied") return "⊘"
return "✓"
}
export function DisplayPane(p: {
width: number
nav: () => DisplayNavState
onSelectTab: (tab: DisplayTab) => void
scrollRef?: (r: ScrollBoxRenderable) => void
}) {
const { theme, view, app } = useTui()
const c = () => theme().colors
// Tick once per second while busy so elapsed times and live progress stay fresh.
const [now, setNow] = createSignal(Date.now())
createEffect(() => {
if (view.state.phase === "idle" && !view.state.jobs.some((j) => j.state === "running")) return
const t = setInterval(() => setNow(Date.now()), 500)
onCleanup(() => clearInterval(t))
})
const files = createMemo(() => extractFiles(view.state.items))
const changes = createMemo(() => extractChanges(view.state.items, view.state.pending))
const bash = createMemo(() => extractBash(view.state.items))
const hasProposed = createMemo(() => Boolean(view.state.pending?.preview?.diff))
const activeTab = createMemo(() => effectiveTab(p.nav(), hasProposed()))
const live = createMemo(() => buildLiveSnapshot(view.state, now()))
const teamMembers = createMemo(() => {
now()
const tree = app.team.team.tree()
return tree.filter((m) => m.manager !== null)
})
const counts = () => ({
files: files().length,
changes: changes().length,
bash: bash().length,
})
const fileIdx = () => resolveIndex(p.nav(), "files", files().length)
const changeIdx = () => resolveIndex(p.nav(), "changes", changes().length)
const bashIdx = () => resolveIndex(p.nav(), "bash", bash().length)
const currentFile = () => (fileIdx() >= 0 ? files()[fileIdx()] : undefined)
const currentChange = () => (changeIdx() >= 0 ? changes()[changeIdx()] : undefined)
const currentBash = () => (bashIdx() >= 0 ? bash()[bashIdx()] : undefined)
const subHeader = () => {
const tab = activeTab()
if (tab === "live") {
return {
left: live().statusLine,
right: p.nav().pinned ? "pinned" : "auto-follow",
warn: Boolean(live().waiting),
}
}
if (tab === "files") {
const f = currentFile()
if (!f) return { left: "No files read yet", right: "0/0", warn: false }
return {
left: `${f.title}${f.subtitle ? ` · ${f.subtitle}` : ""}`,
right: `${fileIdx() + 1}/${files().length}`,
warn: f.status === "error" || f.status === "denied",
}
}
if (tab === "changes") {
const ch = currentChange()
if (!ch) return { left: "No file changes yet", right: "0/0", warn: false }
return {
left: `${ch.title}${ch.subtitle ? ` · ${ch.subtitle}` : ""}`,
right: `${changeIdx() + 1}/${changes().length}`,
warn: ch.status === "proposed" || ch.status === "error" || ch.status === "denied",
}
}
const b = currentBash()
if (!b) return { left: "No bash commands yet", right: "0/0", warn: false }
return {
left: `$ ${b.title}${b.subtitle ? ` · ${b.subtitle}` : ""}`,
right: `${bashIdx() + 1}/${bash().length}`,
warn: b.status === "error" || b.status === "denied",
}
}
// Diff width inside the pane (minus left border, padding and scrollbar).
const diffWidth = () => Math.max(20, p.width - 5)
return (
<box
width={p.width}
flexShrink={0}
flexDirection="column"
border={["left"]}
borderColor={hasProposed() ? c().warn : c().border}
backgroundColor={c().panel}
>
{/* Tab bar */}
<box
height={1}
flexShrink={0}
flexDirection="row"
justifyContent="space-between"
paddingLeft={1}
paddingRight={1}
backgroundColor={c().menu}
>
<text wrapMode="none" truncate>
<For each={DISPLAY_TABS}>
{(tab, i) => {
const isActive = () => activeTab() === tab
const count = () => (tab === "live" ? 0 : counts()[tab])
const dot = () => (tab === "changes" && hasProposed() ? " ●" : tab === "live" && view.state.phase !== "idle" ? " ◉" : "")
const label = () => `${TAB_LABEL[tab]}${tab !== "live" && count() > 0 ? ` (${count()})` : ""}${dot()}`
return (
<>
<Show when={i() > 0}>
<span style={{ fg: c().dim }}>{" "}</span>
</Show>
<span
style={{
fg: isActive() ? c().panel : tab === "changes" && hasProposed() ? c().warn : c().muted,
bg: isActive() ? (tab === "changes" && hasProposed() ? c().warn : c().accent) : undefined,
attributes: isActive() ? TextAttributes.BOLD : 0,
}}
>
{` ${label()} `}
</span>
</>
)
}}
</For>
</text>
</box>
{/* Sub-header */}
<box
height={1}
flexShrink={0}
flexDirection="row"
justifyContent="space-between"
paddingLeft={1}
paddingRight={1}
border={["bottom"]}
borderColor={c().border}
>
<text wrapMode="none" truncate fg={subHeader().warn ? c().warn : c().title}>
{subHeader().left}
</text>
<text wrapMode="none" fg={c().dim}>
{" "}{subHeader().right}
</text>
</box>
{/* Body */}
<scrollbox
ref={(r: ScrollBoxRenderable) => p.scrollRef?.(r)}
flexGrow={1}
scrollX={false}
stickyScroll={activeTab() === "bash"}
stickyStart={activeTab() === "bash" ? "bottom" : "top"}
viewportOptions={{ paddingLeft: 1, paddingRight: 1 }}
verticalScrollbarOptions={{ trackOptions: { backgroundColor: c().panel, foregroundColor: c().dim } }}
>
<Switch>
<Match when={activeTab() === "live"}>
<box flexDirection="column" gap={1} paddingTop={1}>
{/* Waiting banner */}
<Show when={live().waiting}>
<box border borderStyle="rounded" borderColor={c().warn} paddingLeft={1} paddingRight={1} flexDirection="column">
<text fg={c().warn} attributes={TextAttributes.BOLD} wrapMode="word">
{`Waiting: ${live().waiting!.title}`}
</text>
<text fg={c().text} wrapMode="word">
{live().waiting!.detail}
</text>
</box>
</Show>
{/* Currently running tools */}
<Show when={live().activeTools.length > 0}>
<box flexDirection="column">
<text fg={c().accent} attributes={TextAttributes.BOLD}>
Running now
</text>
<For each={live().activeTools}>
{(t) => (
<box flexDirection="column" paddingLeft={1}>
<text wrapMode="word">
<span style={{ fg: c().accent }}>◐ </span>
<span style={{ fg: c().label }}>{t.name}</span>
<span style={{ fg: c().text }}>{t.title ? ` ${t.title}` : ""}</span>
</text>
<For each={t.children ?? []}>
{(ch) => (
<text wrapMode="none" truncate>
<span style={{ fg: c().dim }}>{" ↳ "}</span>
<span style={{ fg: c().label }}>{ch.name}</span>
<span style={{ fg: ch.isError ? c().error : c().muted }}>{ch.title ? ` ${ch.title}` : ""}</span>
</text>
)}
</For>
</box>
)}
</For>
</box>
</Show>
{/* Live thinking preview */}
<Show when={live().thinkingTail}>
<box flexDirection="column">
<text fg={c().reasoning} attributes={TextAttributes.BOLD}>
{live().thinkingStreaming ? "Thinking live" : "Last thought"}
</text>
<box paddingLeft={1}>
<text fg={c().reasoning} attributes={TextAttributes.ITALIC} wrapMode="word">
{live().thinkingTail}
</text>
</box>
</box>
</Show>
{/* Active plan */}
<Show when={live().plan}>
<box flexDirection="column">
<text fg={c().label} attributes={TextAttributes.BOLD} wrapMode="none" truncate>
{live().plan!.head}
</text>
<For each={live().plan!.lines}>
{(line) => (
<text
wrapMode="word"
fg={line.status === "doing" ? c().accent : line.status === "done" ? c().dim : c().text}
>
{` ${PLAN_MARK[line.status] ?? "•"} ${line.text}`}
</text>
)}
</For>
</box>
</Show>
{/* Subagents & background jobs */}
<Show when={live().jobs.length > 0 || teamMembers().length > 0}>
<box flexDirection="column">
<text fg={c().info} attributes={TextAttributes.BOLD}>
Agents & jobs
</text>
<For each={teamMembers()}>
{(m) => (
<text wrapMode="none" truncate>
<span style={{ fg: m.state === "working" ? c().accent : c().dim }}>{" ● "}</span>
<span style={{ fg: c().label }}>{m.name}</span>
<span style={{ fg: c().muted }}>{` (${m.role}) · ${m.state}`}</span>
</text>
)}
</For>
<For each={live().jobs}>
{(j) => (
<text wrapMode="none" truncate>
<span style={{ fg: j.state === "running" ? c().accent : j.state === "error" ? c().error : c().dim }}>
{" "}
{j.state === "running" ? "◐" : j.state === "error" ? "✗" : "✓"}{" "}
</span>
<span style={{ fg: c().label }}>{j.id}</span>
<span style={{ fg: c().text }}>{` ${j.label}`}</span>
<span style={{ fg: c().dim }}>{` · ${j.detail}`}</span>
</text>
)}
</For>
</box>
</Show>
{/* Recent tool activity */}
<Show when={live().recentTools.length > 0}>
<box flexDirection="column">
<text fg={c().title} attributes={TextAttributes.BOLD}>
Recent activity
</text>
<For each={live().recentTools}>
{(t) => (
<text wrapMode="none" truncate>
<span style={{ fg: t.status === "error" ? c().error : t.status === "denied" ? c().warn : c().statusGood }}>
{` ${toolStatusGlyph(t.status)} `}
</span>
<span style={{ fg: c().label }}>{t.name}</span>
<span style={{ fg: c().text }}>{t.title ? ` ${t.title}` : ""}</span>
<span style={{ fg: c().dim }}>{t.detail ? ` · ${t.detail}` : ""}</span>
</text>
)}
</For>
</box>
</Show>
{/* Latest preview */}
<Show when={live().latestPreview && live().activeTools.length === 0}>
<box flexDirection="column">
<text fg={c().muted} attributes={TextAttributes.BOLD} wrapMode="none" truncate>
{`Latest ${live().latestPreview!.kind}: ${live().latestPreview!.title}`}
</text>
<box paddingLeft={1}>
<text fg={c().muted} wrapMode="char">
{live().latestPreview!.body}
</text>
</box>
</box>
</Show>
<Show
when={
!live().waiting &&
live().activeTools.length === 0 &&
!live().thinkingTail &&
!live().plan &&
live().jobs.length === 0 &&
live().recentTools.length === 0
}
>
<text fg={c().muted} wrapMode="word">
Live agent activity, thinking, files read, diffs, and bash output will appear here as the agent works.
</text>
</Show>
</box>
</Match>
<Match when={activeTab() === "files"}>
<Show
when={currentFile()}
fallback={
<box paddingTop={1}>
<text fg={c().muted}>No files read in this session yet.</text>
</box>
}
>
<box flexDirection="column" paddingTop={1}>
<text fg={c().text} wrapMode="char">
{currentFile()!.body}
</text>
</box>
</Show>
</Match>
<Match when={activeTab() === "changes"}>
<Show
when={currentChange()}
fallback={
<box paddingTop={1}>
<text fg={c().muted}>No file changes in this session yet.</text>
</box>
}
>
<box flexDirection="column" paddingTop={1}>
<Show when={currentChange()!.status === "proposed"}>
<text fg={c().warn} attributes={TextAttributes.BOLD}>
Proposed change — waiting for your answer
</text>
</Show>
<Show
when={currentChange()!.diff.includes("@@") || currentChange()!.diff.includes("--- ")}
fallback={
<text fg={c().text} wrapMode="char">
{currentChange()!.diff}
</text>
}
>
<diff
width={diffWidth()}
diff={currentChange()!.diff}
view="unified"
filetype={filetypeOf(currentChange()!.diff)}
showLineNumbers
wrapMode="char"
fg={c().text}
addedBg={c().diffAddedBg}
removedBg={c().diffRemovedBg}
contextBg={c().diffContextBg}
addedSignColor={c().diffAddedSign}
removedSignColor={c().diffRemovedSign}
lineNumberFg={c().lineNumber}
lineNumberBg={c().diffContextBg}
/>
</Show>
</box>
</Show>
</Match>
<Match when={activeTab() === "bash"}>
<Show
when={currentBash()}
fallback={
<box paddingTop={1}>
<text fg={c().muted}>No bash commands run in this session yet.</text>
</box>
}
>
<box flexDirection="column" paddingTop={1} gap={1}>
<text fg={c().accent} wrapMode="char">
{`$ ${currentBash()!.command}`}
</text>
<text fg={currentBash()!.status === "error" ? c().error : c().text} wrapMode="char">
{currentBash()!.output}
</text>
</box>
</Show>
</Match>
</Switch>
</scrollbox>
{/* Footer key hints */}
<box height={1} flexShrink={0} paddingLeft={1} paddingRight={1} backgroundColor={c().menu}>
<text fg={c().dim} wrapMode="none" truncate>
Alt+↑↓ tabs · Alt+←→ entry · Alt+PgUp/Dn scroll · Alt+D hide
</text>
</box>
</box>
)
}
+348
View File
@@ -0,0 +1,348 @@
// Side display pane state & extractors (inspired by LiNA's displays, extended with a real-time
// "Live" activity view so you can always see what the agent is doing right now).
import { duration } from "../duration.ts"
import { open as planOpen, summary as planSummary } from "../plan/plan.ts"
import { callDuration, callTitle } from "../session/display.ts"
import { progressLine } from "../session/progress.ts"
import { diffStat } from "../tool/write.ts"
import { num } from "./locale.ts"
import type { Item, Pending, ViewState } from "./state.ts"
export const DISPLAY_TABS = ["live", "files", "changes", "bash"] as const
export type DisplayTab = (typeof DISPLAY_TABS)[number]
/** Minimum terminal width to show the side-by-side display pane cleanly. */
export const DISPLAY_MIN_WIDTH = 100
/** Cap displayed text per entry so huge reads/outputs stay snappy in the terminal. */
const MAX_BODY_CHARS = 40_000
export interface FileEntry {
id: string
title: string
subtitle: string
body: string
status: "running" | "done" | "error" | "denied"
}
export interface ChangeEntry {
id: string
title: string
subtitle: string
diff: string
status: "proposed" | "done" | "error" | "denied"
added: number
removed: number
}
export interface BashEntry {
id: string
title: string
command: string
subtitle: string
output: string
status: "running" | "done" | "error" | "denied"
}
export interface ActivityRow {
id: string
name: string
title: string
status: "running" | "done" | "error" | "denied"
detail: string
children?: { name: string; title: string; isError?: boolean }[]
}
export interface LiveSnapshot {
phase: ViewState["phase"]
statusLine: string
waiting?: { kind: "permission" | "question" | "plan"; title: string; detail: string }
thinkingTail?: string
thinkingStreaming: boolean
activeTools: ActivityRow[]
recentTools: ActivityRow[]
latestPreview?: { kind: "diff" | "bash" | "file"; title: string; body: string }
plan?: { head: string; lines: { text: string; status: string }[] }
jobs: { id: string; label: string; state: string; detail: string }[]
}
const CHANGE_TOOLS = new Set(["edit", "write", "multiedit", "apply_patch"])
const FILE_TOOLS = new Set(["read", "show"])
function argStr(args: unknown, key: string): string {
if (!args || typeof args !== "object") return ""
const v = (args as Record<string, unknown>)[key]
return typeof v === "string" ? v : ""
}
function clipHead(text: string, max = MAX_BODY_CHARS): string {
if (text.length <= max) return text
return `${text.slice(0, max)}\n… (truncated ${text.length - max} chars)`
}
function clipTail(text: string, max = MAX_BODY_CHARS): string {
if (text.length <= max) return text
return `… (earlier ${text.length - max} chars omitted)\n${text.slice(-max)}`
}
function tailLines(text: string, maxLines: number): string {
const lines = text.trimEnd().split("\n")
if (lines.length <= maxLines) return lines.join("\n")
return `…\n${lines.slice(-maxLines).join("\n")}`
}
/** Extract files read/shown in the session for the `files` display tab. */
export function extractFiles(items: readonly Item[]): FileEntry[] {
const out: FileEntry[] = []
for (const it of items) {
if (it.kind !== "tool" || !FILE_TOOLS.has(it.name)) continue
const path = argStr(it.args, "path") || argStr(it.args, "file_path") || it.title || it.name
const bits = [...(it.facts ?? []), ...(it.note ? [it.note] : [])]
const dur = callDuration(it.status === "error" ? "failed" : it.status, it.ms)
if (dur) bits.push(dur)
if (it.status === "running") bits.unshift("reading…")
const body = it.output ? clipHead(it.output) : it.status === "running" ? "(reading file…)" : it.note || "(no content)"
out.push({
id: it.id,
title: path,
subtitle: bits.join(" · "),
body,
status: it.status,
})
}
return out
}
/** Extract applied/denied/proposed file changes for the `changes` display tab. */
export function extractChanges(items: readonly Item[], pending?: Pending): ChangeEntry[] {
const out: ChangeEntry[] = []
for (const it of items) {
if (it.kind === "diff" && it.patch) {
const stat = diffStat(it.patch)
out.push({
id: it.id,
title: it.title,
subtitle: `+${stat.added} −${stat.removed}`,
diff: clipHead(it.patch),
status: "done",
added: stat.added,
removed: stat.removed,
})
continue
}
if (it.kind !== "tool") continue
if (!it.diff && !CHANGE_TOOLS.has(it.name)) continue
const path = argStr(it.args, "path") || argStr(it.args, "file_path") || it.title || it.name
const diff = it.diff ?? ""
const stat = diff ? diffStat(diff) : { added: 0, removed: 0 }
const bits: string[] = []
if (diff) bits.push(`+${stat.added} −${stat.removed}`)
if (it.status === "denied") bits.push("denied")
else if (it.status === "error") bits.push(it.note || "error")
else if (it.status === "running") bits.push("applying…")
const dur = callDuration(it.status === "error" ? "failed" : it.status, it.ms)
if (dur) bits.push(dur)
out.push({
id: it.id,
title: path,
subtitle: bits.join(" · "),
diff: diff ? clipHead(diff) : it.note || it.output || "(no diff preview)",
status: it.status === "running" ? "proposed" : it.status,
added: stat.added,
removed: stat.removed,
})
}
if (pending?.preview?.diff) {
const stat = diffStat(pending.preview.diff)
const target = pending.request.patterns[0] || argStr(pending.args, "path") || pending.tool
out.push({
id: "pending-diff",
title: target,
subtitle: `WAITING FOR APPROVAL · +${stat.added} −${stat.removed}`,
diff: clipHead(pending.preview.diff),
status: "proposed",
added: stat.added,
removed: stat.removed,
})
}
return out
}
/** Extract bash commands (running and finished) for the `bash` display tab. */
export function extractBash(items: readonly Item[]): BashEntry[] {
const out: BashEntry[] = []
for (const it of items) {
if (it.kind !== "tool" || it.name !== "bash") continue
const command = argStr(it.args, "command") || it.title || "bash"
const firstLine = command.split("\n")[0] || "bash"
const bits = [...(it.facts ?? []), ...(it.note ? [it.note] : [])]
const dur = callDuration(it.status === "error" ? "failed" : it.status, it.ms)
if (dur) bits.push(dur)
if (it.status === "running") bits.unshift("running…")
const output = it.output ? clipTail(it.output) : it.status === "running" ? "(running…)" : it.status === "denied" ? `denied: ${it.note || ""}` : "(no output)"
out.push({
id: it.id,
title: firstLine,
command,
subtitle: bits.join(" · "),
output,
status: it.status,
})
}
return out
}
function toolDetail(it: Extract<Item, { kind: "tool" }>): string {
if (it.status === "running") return "running…"
const bits = [...(it.facts ?? []), ...(it.note ? [it.note] : [])]
const dur = callDuration(it.status === "error" ? "failed" : it.status, it.ms)
if (dur) bits.push(dur)
return bits.join(" · ")
}
/** Build a live cockpit view of everything the agent is currently doing. */
export function buildLiveSnapshot(state: ViewState, nowMs = Date.now()): LiveSnapshot {
let statusLine = "Idle — ready for your prompt"
if (state.pending) {
statusLine = `Waiting for approval: ${state.pending.tool}`
} else if (state.question) {
statusLine = "Waiting for your answer"
} else if (state.plan) {
statusLine = "Waiting for plan approval"
} else if (state.now) {
statusLine = progressLine(state.now, nowMs, num)
} else if (state.preparing) {
statusLine = `Preparing tool call: ${state.preparing}`
} else if (state.phase === "waiting" && state.progress) {
const pct = state.progress.total ? Math.floor((state.progress.done / state.progress.total) * 100) : 0
statusLine = `Reading prompt ${pct}% (${num(state.progress.done)} / ${num(state.progress.total)})`
} else if (state.phase === "thinking") {
statusLine = "Thinking…"
} else if (state.phase === "tools") {
statusLine = "Running tools…"
} else if (state.phase === "writing") {
statusLine = "Writing reply…"
} else if (state.phase === "waiting") {
statusLine = "Waiting for model…"
}
let waiting: LiveSnapshot["waiting"]
if (state.pending) {
const detail = state.pending.purpose || state.pending.request.command || state.pending.request.patterns.join(", ") || state.pending.decision.reason
waiting = { kind: "permission", title: state.pending.tool, detail }
} else if (state.question) {
waiting = { kind: "question", title: "Question", detail: state.question.req.why || state.question.req.questions[0]?.question || "Answer in the prompt area" }
} else if (state.plan) {
waiting = { kind: "plan", title: state.plan.plan?.title || "Plan ready", detail: "Approve or revise the plan below" }
}
const activeTools: ActivityRow[] = []
const doneTools: ActivityRow[] = []
let latestReasoning: Extract<Item, { kind: "reasoning" }> | undefined
let latestPreview: LiveSnapshot["latestPreview"]
for (const it of state.items) {
if (it.kind === "reasoning") {
latestReasoning = it
} else if (it.kind === "tool") {
const title = it.title ?? callTitle(it.args) ?? ""
const row: ActivityRow = {
id: it.id,
name: it.name,
title,
status: it.status,
detail: toolDetail(it),
...(it.children?.length ? { children: it.children.slice(-6) } : {}),
}
if (it.status === "running") activeTools.push(row)
else doneTools.push(row)
if (it.diff) {
latestPreview = { kind: "diff", title: title || it.name, body: tailLines(it.diff, 14) }
} else if (it.name === "bash" && it.output) {
latestPreview = { kind: "bash", title: title || "bash", body: tailLines(it.output, 10) }
} else if (FILE_TOOLS.has(it.name) && it.output) {
latestPreview = { kind: "file", title: title || it.name, body: it.output.split("\n").slice(0, 10).join("\n") }
}
}
}
const thinkingTail = latestReasoning?.text.trim() ? tailLines(latestReasoning.text.trim(), 10) : undefined
const plan = state.livePlan && planOpen(state.livePlan) ? planSummary(state.livePlan) : undefined
const jobs = state.jobs.slice(0, 8).map((j) => {
const elapsed = duration((j.ended ?? nowMs) - j.started, true)
const detail = j.state === "running" ? `running · ${elapsed}` : `${j.state} · ${elapsed}`
return {
id: j.id,
label: j.agent ? `${j.agent}: ${j.description}` : j.description,
state: j.state,
detail,
}
})
return {
phase: state.phase,
statusLine,
waiting,
thinkingTail,
thinkingStreaming: Boolean(latestReasoning?.streaming),
activeTools,
recentTools: doneTools.slice(-10).reverse(),
latestPreview,
plan,
jobs,
}
}
export interface DisplayNavState {
tab: DisplayTab
/** True when the user manually navigated tabs or older entries; pauses auto-switching until reset. */
pinned: boolean
/** 0-based selected index per list tab; -1 means "follow newest". */
index: Record<Exclude<DisplayTab, "live">, number>
}
export function initialNav(): DisplayNavState {
return { tab: "live", pinned: false, index: { files: -1, changes: -1, bash: -1 } }
}
/** Resolve which tab is active right now: auto-jumps to `changes` when a proposed diff awaits approval (unless pinned). */
export function effectiveTab(nav: DisplayNavState, hasProposedDiff: boolean): DisplayTab {
if (!nav.pinned && hasProposedDiff) return "changes"
return nav.tab
}
/** Resolve the 0-based entry index for a list tab (clamped, defaulting to newest when -1). */
export function resolveIndex(nav: DisplayNavState, tab: Exclude<DisplayTab, "live">, count: number): number {
if (count <= 0) return -1
const raw = nav.index[tab]
if (raw < 0 || raw >= count) return count - 1
return raw
}
/** Move between display tabs (`dir`: -1 for Alt+Up, +1 for Alt+Down). */
export function cycleTab(nav: DisplayNavState, dir: -1 | 1): DisplayNavState {
const i = DISPLAY_TABS.indexOf(nav.tab)
const next = DISPLAY_TABS[(i + dir + DISPLAY_TABS.length) % DISPLAY_TABS.length]!
return { ...nav, tab: next, pinned: next !== "live" }
}
/** Move between entries in the active list tab (`dir`: -1 for Alt+Left, +1 for Alt+Right). */
export function stepEntry(nav: DisplayNavState, tab: Exclude<DisplayTab, "live">, dir: -1 | 1, count: number): DisplayNavState {
if (count <= 0) return nav
const cur = resolveIndex(nav, tab, count)
const next = Math.max(0, Math.min(count - 1, cur + dir))
const atEnd = next === count - 1
return {
...nav,
tab,
pinned: true,
index: { ...nav.index, [tab]: atEnd ? -1 : next },
}
}
/** Return to live auto-follow (called when a new user prompt starts). */
export function resetFollow(nav: DisplayNavState): DisplayNavState {
return { tab: "live", pinned: false, index: { ...nav.index, files: -1, changes: -1, bash: -1 } }
}
+163
View File
@@ -0,0 +1,163 @@
import { afterEach, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, realpathSync, rmSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { analyzeSituation, CompletionContext, extractImports, summarizeSource } from "../src/acp/complete_context.ts"
import { FileIndex } from "../src/project/files.ts"
const dirs: string[] = []
afterEach(() => {
while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true })
})
function makeProject(files: Record<string, string>): string {
const dir = realpathSync(mkdtempSync(join(tmpdir(), "lmb-ctx-")))
dirs.push(dir)
for (const [rel, body] of Object.entries(files)) {
const abs = join(dir, rel)
mkdirSync(join(abs, ".."), { recursive: true })
writeFileSync(abs, body)
}
return dir
}
test("analyzeSituation distinguishes comment, import, member, and code", () => {
expect(analyzeSituation("const x = 1\n// writing a note ", "", "typescript").kind).toBe("comment")
expect(analyzeSituation("/* block comment\nstill inside ", "", "typescript").kind).toBe("comment")
expect(analyzeSituation("# python comment ", "", "python").kind).toBe("comment")
const imp = analyzeSituation('import { foo } from "./uti', "", "typescript")
expect(imp.kind).toBe("import")
expect(imp.partialImport).toBe("./uti")
const pyImp = analyzeSituation("from services.au", "", "python")
expect(pyImp.kind).toBe("import")
expect(pyImp.partialImport).toBe("services.au")
const mem = analyzeSituation("const u = loadUser(id)\nu.", "\nreturn u", "typescript")
expect(mem.kind).toBe("member")
expect(mem.receiver).toBe("u")
expect(mem.identifiers).toContain("loadUser")
const code = analyzeSituation("export function greet(profile: UserProfile) {\n return ", "\n}", "typescript")
expect(code.kind).toBe("code")
expect(code.identifiers).toContain("UserProfile")
})
test("extractImports parses TS/JS, Python, Rust, and C/C++ imports", () => {
expect(extractImports('import { a } from "./alpha"\nconst b = require("../beta")')).toEqual(["./alpha", "../beta"])
expect(extractImports("from pkg.mod import helper\nimport pkg.other")).toEqual(["pkg.mod", "pkg.other"])
expect(extractImports("use crate::net::client;\nmod parser;")).toEqual(["net::client", "parser"])
expect(extractImports('#include "config.h"\n#include <stdio.h>')).toEqual(["config.h"])
})
test("summarizeSource keeps short files whole and condenses long files to declarations", () => {
const short = "export function add(a: number, b: number) { return a + b }\n"
const s1 = summarizeSource(short)
expect(s1.summary).toBe(short)
expect(s1.symbols.has("add")).toBe(true)
const longLines = [
"/** User record */",
"export interface UserRecord {",
" id: string",
" name: string",
"}",
...Array.from({ length: 120 }, (_, i) => ` const filler_${i} = ${i}`),
"export function formatUser(u: UserRecord): string {",
" return u.name",
"}",
].join("\n")
const s2 = summarizeSource(longLines)
expect(s2.summary).toContain("export interface UserRecord")
expect(s2.summary).toContain("export function formatUser")
expect(s2.summary).not.toContain("filler_90")
expect(s2.symbols.has("UserRecord")).toBe(true)
expect(s2.symbols.has("formatUser")).toBe(true)
})
test("CompletionContext gathers situation-appropriate chunks, prefers unsaved buffers, and keeps KV-cache order stable", () => {
const root = makeProject({
"src/types.ts": "export interface WidgetConfig {\n retries: number\n timeoutMs: number\n}\n",
"src/helper.ts": "export function buildWidget(name: string) {\n return { name }\n}\n",
"src/app.ts": 'import { WidgetConfig } from "./types"\nimport { buildWidget } from "./helper"\n',
})
const indices = new Map<string, FileIndex>()
const ctx = new CompletionContext((r) => {
let idx = indices.get(r)
if (!idx) {
idx = new FileIndex(r)
indices.set(r, idx)
}
return idx
})
// Comment line -> no project chunks fetched.
const commentChunks = ctx.gather({
root,
path: join(root, "src/app.ts"),
language: "typescript",
prefix: 'import { WidgetConfig } from "./types"\n// explain ',
suffix: "",
})
expect(commentChunks).toEqual([])
// Import line -> workspace file paths only.
const importChunks = ctx.gather({
root,
path: join(root, "src/app.ts"),
language: "typescript",
prefix: 'import { x } from "./hel',
suffix: "",
})
expect(importChunks.length).toBe(1)
expect(importChunks[0]!.path).toBe("<workspace-files>")
expect(importChunks[0]!.text).toContain("src/helper.ts")
// Pre-warm establishes stable session order: types.ts before helper.ts.
ctx.warm(root, join(root, "src/app.ts"))
// First completion emphasizes helper.ts (`buildWidget`), second emphasizes types.ts (`WidgetConfig`):
// both return chunks in the SAME stable session order so KV-cache prefixes stay warm!
const first = ctx.gather({
root,
path: join(root, "src/app.ts"),
language: "typescript",
prefix: 'import { WidgetConfig } from "./types"\nimport { buildWidget } from "./helper"\nconst w = buildWidget(',
suffix: "",
})
const second = ctx.gather({
root,
path: join(root, "src/app.ts"),
language: "typescript",
prefix: 'import { WidgetConfig } from "./types"\nimport { buildWidget } from "./helper"\nconst c: WidgetConfig = { ',
suffix: "",
})
expect(first.map((c) => c.path)).toEqual(["src/types.ts", "src/helper.ts"])
expect(second.map((c) => c.path)).toEqual(["src/types.ts", "src/helper.ts"])
// Unsaved editor buffer overrides disk contents immediately.
const withUnsaved = ctx.gather({
root,
path: join(root, "src/app.ts"),
language: "typescript",
prefix: 'import { WidgetConfig } from "./types"\nconst c: WidgetConfig = { ',
suffix: "",
open: [{ path: join(root, "src/types.ts"), text: "export interface WidgetConfig {\n unsavedFlag: boolean\n}\n" }],
})
expect(withUnsaved.find((c) => c.path === "src/types.ts")?.text).toContain("unsavedFlag")
// Disk cache invalidates when mtime/size change.
const helperPath = join(root, "src/helper.ts")
writeFileSync(helperPath, "export function buildWidget(name: string, strict: boolean) { return { name, strict } }\n")
const future = new Date(Date.now() + 5000)
utimesSync(helperPath, future, future)
const afterEdit = ctx.gather({
root,
path: join(root, "src/app.ts"),
language: "typescript",
prefix: 'import { buildWidget } from "./helper"\nbuildWidget(',
suffix: "",
})
expect(afterEdit.find((c) => c.path === "src/helper.ts")?.text).toContain("strict: boolean")
})
+120
View File
@@ -0,0 +1,120 @@
import { expect, test } from "bun:test"
import {
buildLiveSnapshot,
cycleTab,
effectiveTab,
extractBash,
extractChanges,
extractFiles,
initialNav,
resetFollow,
resolveIndex,
stepEntry,
} from "../src/tui/displays.ts"
import type { Item, Pending, ViewState } from "../src/tui/state.ts"
function baseState(overrides: Partial<ViewState> = {}): ViewState {
return {
items: [],
phase: "idle",
busySince: 0,
showReasoning: false,
expandTools: false,
queued: { texts: [], mode: "steer" },
jobs: [],
...overrides,
}
}
test("extractFiles, extractChanges, and extractBash derive entries cleanly from items and pending diffs", () => {
const diff = "--- a/src/a.ts\n+++ b/src/a.ts\n@@ -1,1 +1,2 @@\n-old\n+new\n+more\n"
const pendingDiff = "--- a/src/b.ts\n+++ b/src/b.ts\n@@ -1,1 +1,1 @@\n-x\n+y\n"
const items: Item[] = [
{ kind: "tool", id: "t1", name: "read", args: { path: "src/a.ts" }, status: "done", output: "1: old\n", facts: ["1 line"], ms: 12 },
{ kind: "tool", id: "t2", name: "edit", args: { path: "src/a.ts" }, status: "done", diff, ms: 40 },
{ kind: "tool", id: "t3", name: "bash", args: { command: "bun test\n" }, status: "running", title: "bun test" },
]
const pending: Pending = {
tool: "edit",
args: { path: "src/b.ts" },
request: { permission: "edit", class: "write", patterns: ["src/b.ts"] },
decision: { action: "ask", reason: "edit needs approval", always: [] },
preview: { diff: pendingDiff },
resolve: () => {},
}
const files = extractFiles(items)
expect(files.length).toBe(1)
expect(files[0]!.title).toBe("src/a.ts")
expect(files[0]!.body).toContain("1: old")
const changes = extractChanges(items, pending)
expect(changes.length).toBe(2)
expect(changes[0]!.status).toBe("done")
expect(changes[0]!.added).toBe(2)
expect(changes[0]!.removed).toBe(1)
expect(changes[1]!.status).toBe("proposed")
expect(changes[1]!.title).toBe("src/b.ts")
expect(changes[1]!.subtitle).toContain("WAITING FOR APPROVAL")
const bash = extractBash(items)
expect(bash.length).toBe(1)
expect(bash[0]!.status).toBe("running")
expect(bash[0]!.output).toContain("running")
})
test("buildLiveSnapshot surfaces active tools, live thinking, plan, jobs, and waiting state", () => {
const state = baseState({
phase: "tools",
items: [
{ kind: "reasoning", id: "r1", text: "Checking imports\nEditing parser.ts next", streaming: true, started: 1000 },
{ kind: "tool", id: "t1", name: "read", args: { path: "src/parser.ts" }, status: "done", output: "line1\nline2", ms: 20 },
{
kind: "tool",
id: "t2",
name: "task",
args: { description: "inspect tests" },
status: "running",
title: "inspect tests",
children: [{ name: "grep", title: "parseExpr" }],
},
],
jobs: [{ id: "job1", kind: "command", description: "run suite", state: "running", started: 1000, unread: 0 }],
})
const snap = buildLiveSnapshot(state, 4000)
expect(snap.thinkingStreaming).toBe(true)
expect(snap.thinkingTail).toContain("Editing parser.ts next")
expect(snap.activeTools.length).toBe(1)
expect(snap.activeTools[0]!.children?.[0]?.name).toBe("grep")
expect(snap.recentTools.length).toBe(1)
expect(snap.recentTools[0]!.name).toBe("read")
expect(snap.jobs.length).toBe(1)
expect(snap.jobs[0]!.detail).toContain("running")
})
test("DisplayNav auto-jumps to changes on proposed diff, respects pinning, and resets on new prompt", () => {
let nav = initialNav()
expect(effectiveTab(nav, false)).toBe("live")
expect(effectiveTab(nav, true)).toBe("changes")
// Alt+Down cycles live -> files and pins.
nav = cycleTab(nav, 1)
expect(nav.tab).toBe("files")
expect(nav.pinned).toBe(true)
// Pinned stays on files even if proposed diff appears.
expect(effectiveTab(nav, true)).toBe("files")
// Stepping entries back and forward.
expect(resolveIndex(nav, "files", 3)).toBe(2)
nav = stepEntry(nav, "files", -1, 3)
expect(resolveIndex(nav, "files", 3)).toBe(1)
nav = stepEntry(nav, "files", 1, 3)
expect(resolveIndex(nav, "files", 3)).toBe(2)
// New prompt resets follow back to live.
nav = resetFollow(nav)
expect(nav.tab).toBe("live")
expect(nav.pinned).toBe(false)
expect(effectiveTab(nav, true)).toBe("changes")
})
+37
View File
@@ -0,0 +1,37 @@
import { afterEach, expect, test } from "bun:test"
import { delta, toolCall } from "../fake-provider.ts"
import { tui } from "./harness.tsx"
let t: Awaited<ReturnType<typeof tui>> | undefined
afterEach(() => t?.stop())
test("side display shows live activity, files, changes, and toggles with /display", async () => {
t = await tui(
[
{ chunks: [toolCall(0, "r1", "read", JSON.stringify({ path: "hello.txt" }))] },
{ chunks: [delta({ content: "Read hello.txt." }, "stop")] },
],
{ width: 120, height: 35 },
"displays: true\n",
)
expect(t.frame()).toContain("Live")
expect(t.frame()).toContain("Files")
expect(t.frame()).toContain("Changes")
expect(t.frame()).toContain("Bash")
await t.input.typeText("read hello.txt")
t.input.pressEnter()
expect(await t.until("Read hello.txt.")).toBe(true)
expect(t.frame()).toContain("Files (1)")
// Switch to Files tab via /display files
await t.input.typeText("/display files")
t.input.pressEnter()
expect(await t.until("hello world")).toBe(true)
// Hide side display via /display off
await t.input.typeText("/display off")
t.input.pressEnter()
expect(await t.until("side display hidden")).toBe(true)
expect(t.frame()).not.toContain("Alt+↑↓ tabs")
})
+2 -1
View File
@@ -19,7 +19,8 @@ export async function tui(script: Scripted[], size = { width: 100, height: 30 },
`connections:\n fake:\n type: webui\n url: ${fake.url}\n models:\n fake/coder: { context: 32768, efforts: [low, high], effort: low }\n fake/other: { context: 8192 }\n`,
{ mode: 0o600 },
)
writeFileSync(join(paths.config, "config.yaml"), `model: fake/coder\n${extraConfig}`)
const disp = /^\s*displays:/m.test(extraConfig) ? "" : "displays: false\n"
writeFileSync(join(paths.config, "config.yaml"), `model: fake/coder\n${disp}${extraConfig}`)
const cwd = mkdtempSync(join(tmpdir(), "lembas-tui-"))
Bun.spawnSync(["git", "init", "-q", cwd])
writeFileSync(join(cwd, "hello.txt"), "hello world\n")