import { type Decision, FRAME_Y, frame, frameInner, isOpen, isStale, type KeyHint, newestFirst, POINTER, rule, type SessionTasks, type Task, type TaskOp, type TaskStatus, tasksWith, formatCost, GLYPH, LINE, } from "@adeildo/pi-kit"; import type { Theme } from "@earendil-works/pi-coding-agent"; import { type Component, type KeyId, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui"; export const MARKS = { doing: "\u2316", waiting: GLYPH.flag, queued: "\u29d7", deferred: "\u21b7", done: GLYPH.check, dropped: GLYPH.times, decision: GLYPH.diamond, } as const; type Tint = "accent" | "warning" | "success" | "dim" | "muted" | "text" | "mdLink"; const STATUS: Record = { doing: { title: "Doing", tint: "accent", mark: "accent" }, waiting: { title: "Waiting", tint: "warning", mark: "warning" }, queued: { title: "Queued", tint: "text", mark: "muted" }, deferred: { title: "Deferred", tint: "muted", mark: "muted" }, done: { title: "Done", tint: "success", mark: "success" }, dropped: { title: "Dropped", tint: "dim", mark: "dim" }, }; export interface TasksViewOptions { theme: Theme; state: () => SessionTasks; spent: () => { cost: number; calls: number }; rows: () => number; close: () => void; requestRender: () => void; clock?: Clock; act?: (op: TaskOp) => void; } export interface TaskKey { keys: KeyId[]; hint: KeyHint; op: TaskOp; } export function taskKeys(task: Task): TaskKey[] { const { id } = task; const open = isOpen(task); const keys: TaskKey[] = []; if (task.status !== "doing") keys.push({ keys: ["enter"], hint: ["enter", "doing"], op: { op: "continue", id } }); if (open) keys.push({ keys: ["x"], hint: ["x", "done"], op: { op: "done", id } }); if (open && task.status !== "deferred") keys.push({ keys: ["p"], hint: ["p", "later"], op: { op: "defer", id } }); if (task.status !== "dropped") keys.push({ keys: ["backspace", "delete"], hint: ["\u232b", "drop"], op: { op: "drop", id } }); return keys; } function pressed(data: string, key: KeyId): boolean { return key.length === 1 ? data === key : matchesKey(data, key); } type Clock = (at: number) => string; type Pick = { kind: "task"; task: Task } | { kind: "decision"; decision: Decision }; interface Line { text: string; id?: string; } const DETAIL_LINES = 4; const DOT = " \u00b7 "; export class TasksView implements Component { readonly #options: TasksViewOptions; readonly #clock: Clock; #selected: string | undefined; #index = 0; #offset = 0; #dropped = false; #room = 0; #page = 10; constructor(options: TasksViewOptions) { this.#options = options; this.#clock = options.clock ?? localClock; } handleInput(data: string): void { const { close, requestRender } = this.#options; if (matchesKey(data, "escape") || matchesKey(data, "alt+t") || data === "q") return close(); if (matchesKey(data, "up") || data === "k") this.#step(-1); else if (matchesKey(data, "down") || data === "j") this.#step(1); else if (matchesKey(data, "pageUp")) this.#step(-this.#page); else if (matchesKey(data, "pageDown")) this.#step(this.#page); else if (matchesKey(data, "home") || data === "g") this.#step(-Infinity); else if (matchesKey(data, "end") || data === "G") this.#step(Infinity); else if (data === "d") this.#dropped = !this.#dropped; else if (!this.#act(data)) return; requestRender(); } #act(data: string): boolean { const { act, state } = this.#options; const task = state().tasks.find((entry) => entry.id === this.#selected); if (act === undefined || task === undefined) return false; const chosen = taskKeys(task).find((entry) => entry.keys.some((key) => pressed(data, key))); if (chosen === undefined) return false; act(chosen.op); return true; } invalidate(): void {} render(width: number): string[] { const { theme } = this.#options; const state = this.#options.state(); const picks = this.#picks(state); // A task that left the list, like one you dropped, leaves the cursor where it was. const at = picks.findIndex((pick) => idOf(pick) === this.#selected); const selected = this.#select(picks, at === -1 ? this.#index : at); const inner = Math.max(10, frameInner(width)); const body = this.#body(state, picks, inner); // The frame, the rule over the detail, and the detail. const chrome = FRAME_Y + 1 + DETAIL_LINES; const most = Math.max(3, this.#options.rows() - chrome); // The panel never shrinks while open, so moving the cursor never moves the frame. this.#room = Math.min(most, Math.max(this.#room, body.length)); const room = this.#room; this.#page = Math.max(1, room - 2); this.#follow(body, room); const shown = body.slice(this.#offset, this.#offset + room); while (shown.length < room) shown.push({ text: "" }); return frame( theme, width, [ ...shown.map((line) => ({ text: line.text, selected: line.id !== undefined && line.id === this.#selected, })), rule(theme, inner, this.#scrollHint(body.length, room)), ...this.#detail(selected, inner), ], { title: state.title ?? "This session", status: this.#counts(state), keys: this.#keys(selected), footnote: this.#spent(), }, ); } #picks(state: SessionTasks): Pick[] { const tasks = (status: TaskStatus) => { const found = tasksWith(state, status); return status === "done" || status === "dropped" ? newestFirst(found) : found; }; const statuses: TaskStatus[] = ["doing", "waiting", "queued", "deferred", "done"]; if (this.#dropped) statuses.push("dropped"); return [ ...statuses.flatMap((status) => tasks(status).map((task): Pick => ({ kind: "task", task }))), ...state.decisions.toReversed().map((decision): Pick => ({ kind: "decision", decision })), ]; } #body(state: SessionTasks, picks: readonly Pick[], width: number): Line[] { const { theme } = this.#options; if (picks.length === 0) return [ { text: theme.fg("muted", "Nothing tracked yet.") }, { text: theme.fg("dim", "Your next message starts the list.") }, ]; const lines: Line[] = []; const section = (title: string, tint: Tint, rows: Line[]) => { if (rows.length === 0) return; if (lines.length > 0) lines.push({ text: "" }); lines.push({ text: `${theme.bold(theme.fg(tint, title))} ${theme.fg("dim", String(rows.length))}`, }); lines.push(...rows.map((line, index) => this.#branch(line, index === rows.length - 1))); }; for (const status of Object.keys(STATUS) as TaskStatus[]) { const rows = picks.flatMap((pick) => pick.kind === "task" && pick.task.status === status ? [this.#taskRow(pick.task, width)] : [], ); section(STATUS[status].title, STATUS[status].tint, rows); } const decisions = picks.flatMap((pick) => pick.kind === "decision" ? [this.#decisionRow(pick.decision, width)] : [], ); section("Decided", "mdLink", decisions); return lines; } #branch(line: Line, last: boolean): Line { const { theme } = this.#options; const on = line.id === this.#selected; const branch = on ? theme.fg("accent", `${POINTER} `) : theme.fg("border", last ? `\u2514${LINE.h} ` : `${LINE.teeLeft}${LINE.h} `); return { text: `${branch}${line.text}`, id: line.id }; } #taskRow(task: Task, width: number): Line { const { theme } = this.#options; const closed = task.status === "done" || task.status === "dropped"; const faded = task.id !== this.#selected && (closed || isStale(task)); const meta = this.#meta(task); const mark = theme.fg(STATUS[task.status].mark, MARKS[task.status]); const aside = task.status === "done" ? task.result : undefined; const ink = faded ? "muted" : "text"; const picked = task.id === this.#selected; return { text: this.#fit(mark, task.text, ink, meta, width, picked, aside), id: task.id }; } #decisionRow(decision: Decision, width: number): Line { const { theme } = this.#options; const meta = theme.fg("dim", this.#clock(decision.made.at)); return { text: this.#fit( theme.fg("mdLink", MARKS.decision), decision.text, "text", meta, width, decision.id === this.#selected, ), id: decision.id, }; } #fit( mark: string, words: string, ink: Tint, meta: string, width: number, picked: boolean, aside?: string, ): string { const { theme } = this.#options; // The branch takes three columns. const room = width - 3; const metaWidth = meta === "" ? 0 : visibleWidth(meta) + 2; const joined = aside === undefined ? words : `${words}${DOT}${aside}`; const plain = truncateToWidth(joined, Math.max(8, room - 2 - metaWidth), "..."); const rest = plain.slice(words.length); const text = theme.fg(ink, plain.slice(0, words.length)); const head = `${mark} ${picked ? theme.bold(text) : text}${theme.fg("dim", rest)}`; if (meta === "") return head; return `${head}${" ".repeat(Math.max(2, room - visibleWidth(head) - visibleWidth(meta)))}${meta}`; } #meta(task: Task): string { const { theme } = this.#options; switch (task.status) { case "doing": return task.started === undefined ? "" : theme.fg("dim", `since ${this.#clock(task.started.at)}`); case "waiting": return task.waitingOn === "outside" ? theme.fg("dim", "outside") : theme.fg("warning", "on you"); case "queued": if (isStale(task)) return theme.fg("dim", `passed over ${task.idleRuns}${GLYPH.times}`); return task.origin === "agent" ? theme.fg("dim", "agent") : ""; default: return task.finished === undefined ? "" : theme.fg("dim", this.#clock(task.finished.at)); } } #detail(pick: Pick | undefined, width: number): string[] { const { theme } = this.#options; const lines: string[] = []; const add = (text: string | undefined, tint: Tint) => { if (text) lines.push(...wrapTextWithAnsi(theme.fg(tint, text), width)); }; if (pick?.kind === "decision") { add(pick.decision.text, "text"); const by = pick.decision.origin === "you" ? "you decided" : "the agent decided"; add(`${by} ${this.#clock(pick.decision.made.at)}`, "dim"); } else if (pick?.kind === "task") { const { task } = pick; add(task.text, "text"); add(task.result && `${GLYPH.right} ${task.result}`, "success"); add(task.left && `left: ${task.left}`, "warning"); add(task.why && `${reasonLabel(task)}: ${task.why}`, "muted"); add(this.#when(task), "dim"); } const kept = lines.slice(0, DETAIL_LINES); if (lines.length > DETAIL_LINES) kept[DETAIL_LINES - 1] = `${kept[DETAIL_LINES - 1]}...`; while (kept.length < DETAIL_LINES) kept.push(""); return kept; } #when(task: Task): string { const parts = [ `${task.origin === "agent" ? "left by the agent" : "asked"} ${this.#clock(task.created.at)}`, ]; if (task.started !== undefined && task.started.at !== task.created.at) parts.push(`started ${this.#clock(task.started.at)}`); if (task.finished !== undefined) parts.push(`${task.status} ${this.#clock(task.finished.at)}`); if (task.asks.length > 1) parts.push(`${task.asks.length} messages`); return parts.join(DOT); } #step(by: number): void { const picks = this.#picks(this.#options.state()); if (picks.length === 0) return; const at = picks.findIndex((pick) => idOf(pick) === this.#selected); this.#select(picks, Math.max(0, at) + by); } #select(picks: readonly Pick[], index: number): Pick | undefined { this.#index = Math.min(picks.length - 1, Math.max(0, index)); const pick = picks[this.#index]; this.#selected = pick === undefined ? undefined : idOf(pick); return pick; } #follow(body: readonly Line[], room: number): void { const at = body.findIndex((line) => line.id === this.#selected); if (at !== -1) { const top = body[at - 1]?.id === undefined ? at - 1 : at; if (top < this.#offset) this.#offset = Math.max(0, top); if (at >= this.#offset + room) this.#offset = at - room + 1; } this.#offset = Math.min(Math.max(0, this.#offset), Math.max(0, body.length - room)); } #counts(state: SessionTasks): string { const { theme } = this.#options; const counted: TaskStatus[] = ["doing", "waiting", "queued", "done"]; return counted .flatMap((status) => { const size = tasksWith(state, status).length; return size === 0 ? [] : [theme.fg(STATUS[status].mark, `${MARKS[status]} ${size}`)]; }) .join(" "); } #keys(selected: Pick | undefined): KeyHint[] { const actions = this.#options.act !== undefined && selected?.kind === "task" ? taskKeys(selected.task).map((entry) => entry.hint) : []; return [ [`${GLYPH.up}${GLYPH.down}`, "move"], ...actions, ["d", this.#dropped ? "hide dropped" : "dropped"], ["esc", "close"], ]; } #spent(): string { const { cost, calls } = this.#options.spent(); return calls === 0 ? "" : this.#options.theme.fg("dim", `${formatCost(cost)}, ${calls} calls`); } #scrollHint(total: number, room: number): string { if (total <= room) return ""; const below = total - room - this.#offset; return this.#options.theme.fg( "dim", below > 0 ? `${GLYPH.down} ${below} more` : `${GLYPH.up} top`, ); } } function reasonLabel(task: Task): string { if (task.status !== "waiting") return "why"; return task.waitingOn === "outside" ? "on something outside" : "on you"; } function idOf(pick: Pick): string { return pick.kind === "task" ? pick.task.id : pick.decision.id; } function localClock(at: number): string { return new Date(at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); }