{"version":3,"file":"ui.d.ts","sourceRoot":"","sources":["../../../src/core/llama/ui.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAK9E,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAIzD,MAAM,MAAM,kBAAkB,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,cAAc,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC;AAErH,UAAU,aAAc,SAAQ,aAAa;IAC5C,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACd;AA+CD,MAAM,WAAW,OAAO;IACvB,UAAU,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACrF,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACtE,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1D,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,CAAC;IAChF,YAAY,CACX,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,gBAAgB,EAAE,CAAC,GACzE,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAC/B,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACjD,QAAQ,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI,CAAC;CAC3C;AAwYD,wBAAsB,WAAW,CAAC,GAAG,EAAE,uBAAuB,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAYlH;AAED,wBAAsB,eAAe,CAAC,CAAC,EACtC,EAAE,EAAE,OAAO,EACX,OAAO,EAAE;IACR,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;IACtB,GAAG,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IAChF,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB,GACC,OAAO,CAAC;IAAE,SAAS,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,SAAS,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAAC,CAqC/D","sourcesContent":["import {\n\ttype Component,\n\tContainer,\n\ttype Focusable,\n\tfuzzyFilter,\n\tInput,\n\ttype SelectItem,\n\tSelectList,\n\tSpacer,\n\tText,\n\ttype TUI,\n\ttruncateToWidth,\n\tvisibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport type { ExtensionCommandContext } from \"../../core/extensions/types.ts\";\nimport type { KeybindingsManager } from \"../../core/keybindings.ts\";\nimport { DynamicBorder } from \"../../modes/interactive/components/dynamic-border.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { LlamaModelInfo, LlamaProgress } from \"./client.ts\";\nimport type { HuggingFaceModel } from \"./huggingface.ts\";\n\nconst DOWNLOAD_VALUE = \"\\0download\";\n\nexport type LlamaManagerAction = { type: \"model\"; model: LlamaModelInfo } | { type: \"download\" } | { type: \"close\" };\n\ninterface ProgressState extends LlamaProgress {\n\ttitle: string;\n\tmodel: string;\n}\n\nfunction contextLabel(model: LlamaModelInfo): string | undefined {\n\tconst context = model.meta?.n_ctx ?? model.meta?.n_ctx_train;\n\tif (context) return context >= 1000 ? `${Math.round(context / 1000)}k` : String(context);\n\tconst args = model.status.args ?? [];\n\tfor (let index = 0; index < args.length - 1; index++) {\n\t\tif (args[index] !== \"--ctx-size\" && args[index] !== \"-c\" && args[index] !== \"-ctx\") continue;\n\t\tconst value = Number(args[index + 1]);\n\t\tif (Number.isFinite(value) && value > 0) return value >= 1000 ? `${Math.round(value / 1000)}k` : String(value);\n\t}\n\treturn undefined;\n}\n\nfunction modelDescription(model: LlamaModelInfo): string {\n\tconst details: string[] = [];\n\tconst loaded = model.status.value === \"loaded\" || model.status.value === \"sleeping\";\n\tif (loaded) details.push(\"loaded\");\n\telse if (model.status.value !== \"unloaded\") details.push(model.status.value);\n\tconst context = loaded ? contextLabel(model) : undefined;\n\tif (context) details.push(`${context} context`);\n\treturn details.join(\" · \");\n}\n\nfunction selectTheme(theme: Theme) {\n\treturn {\n\t\tselectedPrefix: (text: string) => theme.fg(\"accent\", text),\n\t\tselectedText: (text: string) => theme.fg(\"accent\", text),\n\t\tdescription: (text: string) => theme.fg(\"muted\", text),\n\t\tscrollInfo: (text: string) => theme.fg(\"dim\", text),\n\t\tnoMatch: (text: string) => theme.fg(\"warning\", text),\n\t};\n}\n\nfunction frame(theme: Theme, title: string, body: Component[], footer?: string): Container {\n\tconst container = new Container();\n\tcontainer.addChild(new DynamicBorder((text: string) => theme.fg(\"accent\", text)));\n\tcontainer.addChild(new Text(theme.fg(\"accent\", theme.bold(title)), 1, 0));\n\tfor (const child of body) container.addChild(child);\n\tif (footer) {\n\t\tcontainer.addChild(new Spacer(1));\n\t\tcontainer.addChild(new Text(theme.fg(\"dim\", footer), 1, 0));\n\t}\n\tcontainer.addChild(new DynamicBorder((text: string) => theme.fg(\"accent\", text)));\n\treturn container;\n}\n\nexport interface LlamaUi {\n\tshowModels(serverUrl: string, models: LlamaModelInfo[]): Promise<LlamaManagerAction>;\n\tselect(title: string, options: string[]): Promise<string | undefined>;\n\tconfirm(title: string, message: string): Promise<boolean>;\n\tconnectionError(serverUrl: string, message: string): Promise<\"retry\" | \"close\">;\n\tsearchModels(\n\t\tsearch: (query: string, signal: AbortSignal) => Promise<HuggingFaceModel[]>,\n\t): Promise<string | undefined>;\n\tshowStatus(title: string, message: string): void;\n\tprogress(state: ProgressState): Promise<void>;\n\tupdateProgress(state: ProgressState): void;\n}\n\nfunction compactCount(value: number): string {\n\tif (value >= 1_000_000) return `${(value / 1_000_000).toFixed(value >= 10_000_000 ? 0 : 1)}M`;\n\tif (value >= 1_000) return `${(value / 1_000).toFixed(value >= 100_000 ? 0 : 1)}k`;\n\treturn String(value);\n}\n\nclass HuggingFaceSearch extends Container implements Focusable {\n\tprivate readonly tui: TUI;\n\tprivate readonly theme: Theme;\n\tprivate readonly keybindings: KeybindingsManager;\n\tprivate readonly search: (query: string, signal: AbortSignal) => Promise<HuggingFaceModel[]>;\n\tprivate readonly cache: Map<string, HuggingFaceModel[]>;\n\tprivate readonly onSelectModel: (model: string | undefined) => void;\n\tprivate readonly input = new Input();\n\tprivate readonly resultsContainer = new Container();\n\tprivate results: HuggingFaceModel[] = [];\n\tprivate filteredResults: HuggingFaceModel[] = [];\n\tprivate selectedIndex = 0;\n\tprivate query = \"\";\n\tprivate status = \"Type at least 2 characters\";\n\tprivate debounce: ReturnType<typeof setTimeout> | undefined;\n\tprivate request: AbortController | undefined;\n\tprivate closed = false;\n\tprivate _focused = false;\n\n\tconstructor(\n\t\ttui: TUI,\n\t\ttheme: Theme,\n\t\tkeybindings: KeybindingsManager,\n\t\tsearch: (query: string, signal: AbortSignal) => Promise<HuggingFaceModel[]>,\n\t\tcache: Map<string, HuggingFaceModel[]>,\n\t\tonSelectModel: (model: string | undefined) => void,\n\t) {\n\t\tsuper();\n\t\tthis.tui = tui;\n\t\tthis.theme = theme;\n\t\tthis.keybindings = keybindings;\n\t\tthis.search = search;\n\t\tthis.cache = cache;\n\t\tthis.onSelectModel = onSelectModel;\n\t\tthis.addChild(new Text(theme.fg(\"dim\", \"Model name or owner/repository[:quant]\"), 1, 0));\n\t\tthis.addChild(this.input);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(this.resultsContainer);\n\t\tthis.updateResults();\n\t}\n\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.input.focused = value;\n\t}\n\n\tprivate updateResults(): void {\n\t\tthis.resultsContainer.clear();\n\t\tconst maxVisible = 10;\n\t\tconst start = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filteredResults.length - maxVisible),\n\t\t);\n\t\tconst end = Math.min(start + maxVisible, this.filteredResults.length);\n\t\tfor (let index = start; index < end; index++) {\n\t\t\tconst model = this.filteredResults[index];\n\t\t\tif (!model) continue;\n\t\t\tconst prefix = index === this.selectedIndex ? \"→ \" : \"  \";\n\t\t\tconst details = `${compactCount(model.downloads)} downloads`;\n\t\t\tthis.resultsContainer.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\tindex === this.selectedIndex\n\t\t\t\t\t\t? this.theme.fg(\"accent\", `${prefix}${model.id}  ${details}`)\n\t\t\t\t\t\t: `${prefix}${model.id}${this.theme.fg(\"muted\", `  ${details}`)}`,\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (start > 0 || end < this.filteredResults.length) {\n\t\t\tthis.resultsContainer.addChild(\n\t\t\t\tnew Text(this.theme.fg(\"dim\", `  (${this.selectedIndex + 1}/${this.filteredResults.length})`), 0, 0),\n\t\t\t);\n\t\t}\n\t\tif (this.filteredResults.length === 0) {\n\t\t\tthis.resultsContainer.addChild(new Text(this.theme.fg(\"dim\", `  ${this.status}`), 0, 0));\n\t\t} else if (this.status === \"Searching Hugging Face…\") {\n\t\t\tthis.resultsContainer.addChild(new Text(this.theme.fg(\"dim\", `  ${this.status}`), 0, 0));\n\t\t}\n\t\tthis.tui.requestRender();\n\t}\n\n\tprivate filterResults(): void {\n\t\tif (this.query) {\n\t\t\tconst matches = new Set(fuzzyFilter(this.results, this.query, (model) => model.id).map((model) => model.id));\n\t\t\tthis.filteredResults = this.results.filter((model) => matches.has(model.id));\n\t\t} else {\n\t\t\tthis.filteredResults = this.results;\n\t\t}\n\t\tthis.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredResults.length - 1));\n\t\tthis.updateResults();\n\t}\n\n\tprivate scheduleSearch(): void {\n\t\tif (this.debounce) clearTimeout(this.debounce);\n\t\tthis.request?.abort();\n\t\tthis.request = undefined;\n\t\tif (this.query.length < 2) {\n\t\t\tthis.status = \"Type at least 2 characters\";\n\t\t\tthis.filterResults();\n\t\t\treturn;\n\t\t}\n\t\tconst cached = this.cache.get(this.query.toLowerCase());\n\t\tif (cached) {\n\t\t\tthis.results = cached;\n\t\t\tthis.status = cached.length === 0 ? \"No GGUF models found\" : \"\";\n\t\t\tthis.filterResults();\n\t\t\treturn;\n\t\t}\n\t\tthis.status = \"Searching Hugging Face…\";\n\t\tthis.filterResults();\n\t\tthis.debounce = setTimeout(() => void this.runSearch(this.query), 500);\n\t}\n\n\tprivate async runSearch(query: string): Promise<void> {\n\t\tconst request = new AbortController();\n\t\tthis.request = request;\n\t\ttry {\n\t\t\tconst results = await this.search(query, request.signal);\n\t\t\tthis.cache.set(query.toLowerCase(), results);\n\t\t\tif (this.closed || request.signal.aborted || this.query !== query) return;\n\t\t\tthis.results = results;\n\t\t\tthis.selectedIndex = 0;\n\t\t\tthis.status = results.length === 0 ? \"No GGUF models found\" : \"\";\n\t\t\tthis.filterResults();\n\t\t} catch (error) {\n\t\t\tif (this.closed || request.signal.aborted || this.query !== query) return;\n\t\t\tthis.results = [];\n\t\t\tthis.status = error instanceof Error ? error.message : String(error);\n\t\t\tthis.filterResults();\n\t\t} finally {\n\t\t\tif (this.request === request) this.request = undefined;\n\t\t}\n\t}\n\n\tprivate close(model: string | undefined): void {\n\t\tif (this.closed) return;\n\t\tthis.closed = true;\n\t\tif (this.debounce) clearTimeout(this.debounce);\n\t\tthis.request?.abort();\n\t\tthis.onSelectModel(model);\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (this.keybindings.matches(data, \"tui.select.up\")) {\n\t\t\tif (this.filteredResults.length > 0) {\n\t\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.filteredResults.length - 1 : this.selectedIndex - 1;\n\t\t\t\tthis.updateResults();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.down\")) {\n\t\t\tif (this.filteredResults.length > 0) {\n\t\t\t\tthis.selectedIndex = this.selectedIndex === this.filteredResults.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t\t\tthis.updateResults();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.confirm\")) {\n\t\t\tconst exact = /^[^/\\s]+\\/[^:\\s]+(?::[^\\s:]+)?$/u.test(this.query) ? this.query : undefined;\n\t\t\tconst selected = exact ?? this.filteredResults[this.selectedIndex]?.id;\n\t\t\tif (selected) this.close(selected);\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.cancel\")) {\n\t\t\tthis.close(undefined);\n\t\t\treturn;\n\t\t}\n\t\tthis.input.handleInput(data);\n\t\tconst query = this.input.getValue().trim();\n\t\tif (query === this.query) return;\n\t\tthis.query = query;\n\t\tthis.scheduleSearch();\n\t}\n}\n\nclass LlamaView implements LlamaUi, Focusable {\n\tprivate readonly tui: TUI;\n\tprivate readonly theme: Theme;\n\tprivate readonly keybindings: KeybindingsManager;\n\tprivate readonly searchCache = new Map<string, HuggingFaceModel[]>();\n\tprivate content: Container;\n\tprivate inputHandler: { handleInput?(data: string): void } | undefined;\n\tprivate inputTarget: Focusable | undefined;\n\tprivate progressPromise: Promise<void> | undefined;\n\tprivate progressResolver: (() => void) | undefined;\n\tprivate showingProgress = false;\n\tprivate _focused = false;\n\n\tconstructor(tui: TUI, theme: Theme, keybindings: KeybindingsManager) {\n\t\tthis.tui = tui;\n\t\tthis.theme = theme;\n\t\tthis.keybindings = keybindings;\n\t\tthis.content = frame(theme, \"llama.cpp models\", [new Text(theme.fg(\"muted\", \"Loading…\"), 1, 1)]);\n\t}\n\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tif (this.inputTarget) this.inputTarget.focused = value;\n\t}\n\n\tprivate setContent(\n\t\tcontent: Container,\n\t\tinputHandler?: { handleInput?(data: string): void },\n\t\tinputTarget?: Focusable,\n\t): void {\n\t\tif (this.inputTarget) this.inputTarget.focused = false;\n\t\tthis.progressPromise = undefined;\n\t\tthis.progressResolver = undefined;\n\t\tthis.showingProgress = false;\n\t\tthis.content = content;\n\t\tthis.inputHandler = inputHandler;\n\t\tthis.inputTarget = inputTarget;\n\t\tif (this.inputTarget) this.inputTarget.focused = this._focused;\n\t\tthis.tui.requestRender();\n\t}\n\n\tshowModels(serverUrl: string, models: LlamaModelInfo[]): Promise<LlamaManagerAction> {\n\t\tconst sorted = [...models].sort((left, right) => {\n\t\t\tconst loaded = Number(right.status.value === \"loaded\") - Number(left.status.value === \"loaded\");\n\t\t\treturn loaded || left.id.localeCompare(right.id);\n\t\t});\n\t\tconst byId = new Map(sorted.map((model) => [model.id, model]));\n\t\tconst items: SelectItem[] = [\n\t\t\t...sorted.map((model) => ({\n\t\t\t\tvalue: model.id,\n\t\t\t\tlabel: model.id,\n\t\t\t\tdescription: modelDescription(model),\n\t\t\t})),\n\t\t\t{ value: DOWNLOAD_VALUE, label: \"Download model…\", description: \"Hugging Face owner/repository[:quant]\" },\n\t\t];\n\t\treturn new Promise((resolve) => {\n\t\t\tconst list = new SelectList(items, Math.min(items.length, 12), selectTheme(this.theme), {\n\t\t\t\tminPrimaryColumnWidth: 36,\n\t\t\t\tmaxPrimaryColumnWidth: 56,\n\t\t\t});\n\t\t\tlist.onSelect = (item) => {\n\t\t\t\tif (item.value === DOWNLOAD_VALUE) resolve({ type: \"download\" });\n\t\t\t\telse {\n\t\t\t\t\tconst model = byId.get(item.value);\n\t\t\t\t\tif (model) resolve({ type: \"model\", model });\n\t\t\t\t}\n\t\t\t};\n\t\t\tlist.onCancel = () => resolve({ type: \"close\" });\n\t\t\tthis.setContent(\n\t\t\t\tframe(\n\t\t\t\t\tthis.theme,\n\t\t\t\t\t\"llama.cpp models\",\n\t\t\t\t\t[new Text(this.theme.fg(\"dim\", serverUrl), 1, 0), new Spacer(1), list],\n\t\t\t\t\t`${keyHint(\"tui.select.confirm\", \"load/unload/download\")} • ${keyHint(\"tui.select.cancel\", \"close\")}`,\n\t\t\t\t),\n\t\t\t\tlist,\n\t\t\t);\n\t\t});\n\t}\n\n\tselect(title: string, options: string[]): Promise<string | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst list = new SelectList(\n\t\t\t\toptions.map((option) => ({ value: option, label: option })),\n\t\t\t\tMath.min(options.length, 12),\n\t\t\t\tselectTheme(this.theme),\n\t\t\t);\n\t\t\tlist.onSelect = (item) => resolve(item.value);\n\t\t\tlist.onCancel = () => resolve(undefined);\n\t\t\tthis.setContent(\n\t\t\t\tframe(\n\t\t\t\t\tthis.theme,\n\t\t\t\t\ttitle,\n\t\t\t\t\t[new Spacer(1), list],\n\t\t\t\t\t`${keyHint(\"tui.select.confirm\", \"select\")} • ${keyHint(\"tui.select.cancel\", \"cancel\")}`,\n\t\t\t\t),\n\t\t\t\tlist,\n\t\t\t);\n\t\t});\n\t}\n\n\tasync confirm(title: string, message: string): Promise<boolean> {\n\t\treturn (await this.select(`${title}\\n${message}`, [\"Yes\", \"No\"])) === \"Yes\";\n\t}\n\n\tasync connectionError(serverUrl: string, message: string): Promise<\"retry\" | \"close\"> {\n\t\tconst choice = await this.select(`llama.cpp unavailable\\n${serverUrl}\\n\\n${message}`, [\"Retry\", \"Close\"]);\n\t\treturn choice === \"Retry\" ? \"retry\" : \"close\";\n\t}\n\n\tsearchModels(\n\t\tsearch: (query: string, signal: AbortSignal) => Promise<HuggingFaceModel[]>,\n\t): Promise<string | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst component = new HuggingFaceSearch(\n\t\t\t\tthis.tui,\n\t\t\t\tthis.theme,\n\t\t\t\tthis.keybindings,\n\t\t\t\tsearch,\n\t\t\t\tthis.searchCache,\n\t\t\t\tresolve,\n\t\t\t);\n\t\t\tthis.setContent(\n\t\t\t\tframe(\n\t\t\t\t\tthis.theme,\n\t\t\t\t\t\"Download model\",\n\t\t\t\t\t[new Spacer(1), component],\n\t\t\t\t\t`${keyHint(\"tui.select.confirm\", \"select\")} • ${keyHint(\"tui.select.cancel\", \"back\")}`,\n\t\t\t\t),\n\t\t\t\tcomponent,\n\t\t\t\tcomponent,\n\t\t\t);\n\t\t});\n\t}\n\n\tshowStatus(title: string, message: string): void {\n\t\tthis.setContent(frame(this.theme, title, [new Spacer(1), new Text(this.theme.fg(\"muted\", message), 1, 0)]));\n\t}\n\n\tprogress(state: ProgressState): Promise<void> {\n\t\tif (!this.progressPromise) {\n\t\t\tthis.progressPromise = new Promise((resolve) => {\n\t\t\t\tthis.progressResolver = resolve;\n\t\t\t});\n\t\t}\n\t\tthis.showingProgress = true;\n\t\tthis.updateProgress(state);\n\t\treturn this.progressPromise;\n\t}\n\n\tupdateProgress(state: ProgressState): void {\n\t\tif (!this.showingProgress) return;\n\t\tconst body = [\n\t\t\tnew Text(this.theme.fg(\"text\", state.model), 1, 0),\n\t\t\tnew Spacer(1),\n\t\t\tnew Text(this.theme.fg(\"muted\", state.message), 1, 0),\n\t\t];\n\t\tif (state.ratio !== undefined) {\n\t\t\tconst available = 40;\n\t\t\tconst filled = Math.round(Math.max(0, Math.min(1, state.ratio)) * available);\n\t\t\tbody.push(\n\t\t\t\tnew Text(\n\t\t\t\t\tthis.theme.fg(\n\t\t\t\t\t\t\"accent\",\n\t\t\t\t\t\t`${\"█\".repeat(filled)}${\"─\".repeat(available - filled)} ${Math.round(state.ratio * 100)}%`,\n\t\t\t\t\t),\n\t\t\t\t\t1,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (state.detail) body.push(new Text(this.theme.fg(\"dim\", state.detail), 1, 0));\n\t\tthis.content = frame(this.theme, state.title, body, keyHint(\"tui.select.cancel\", \"stop\"));\n\t\tthis.inputHandler = undefined;\n\t\tthis.tui.requestRender();\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (this.progressResolver && this.keybindings.matches(data, \"tui.select.cancel\")) {\n\t\t\tconst resolve = this.progressResolver;\n\t\t\tthis.progressPromise = undefined;\n\t\t\tthis.progressResolver = undefined;\n\t\t\tresolve();\n\t\t\treturn;\n\t\t}\n\t\tthis.inputHandler?.handleInput?.(data);\n\t\tthis.tui.requestRender();\n\t}\n\n\trender(width: number): string[] {\n\t\treturn this.content\n\t\t\t.render(width)\n\t\t\t.map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width, \"\") : line));\n\t}\n\n\tinvalidate(): void {\n\t\tthis.content.invalidate();\n\t}\n}\n\nexport async function showLlamaUi(ctx: ExtensionCommandContext, run: (ui: LlamaUi) => Promise<void>): Promise<void> {\n\tawait ctx.ui.custom<void>((tui, theme, keybindings, done) => {\n\t\tconst view = new LlamaView(tui, theme, keybindings);\n\t\tvoid run(view).then(\n\t\t\t() => done(),\n\t\t\t(error: unknown) => {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t\tdone();\n\t\t\t},\n\t\t);\n\t\treturn view;\n\t});\n}\n\nexport async function runWithProgress<T>(\n\tui: LlamaUi,\n\toptions: {\n\t\ttitle: string;\n\t\tmodel: string;\n\t\tinitialMessage: string;\n\t\tcancelTitle: string;\n\t\tcancelMessage: string;\n\t\trun(signal: AbortSignal, update: (progress: LlamaProgress) => void): Promise<T>;\n\t\tcancel(): Promise<void>;\n\t},\n): Promise<{ cancelled: true } | { cancelled: false; value: T }> {\n\tconst controller = new AbortController();\n\tconst state: ProgressState = { title: options.title, model: options.model, message: options.initialMessage };\n\tconst settled = options\n\t\t.run(controller.signal, (progress) => {\n\t\t\tObject.assign(state, progress);\n\t\t\tui.updateProgress(state);\n\t\t})\n\t\t.then(\n\t\t\t(value) => ({ ok: true as const, value }),\n\t\t\t(error: unknown) => ({ ok: false as const, error }),\n\t\t);\n\tlet completed = false;\n\tsettled.finally(() => {\n\t\tcompleted = true;\n\t});\n\n\twhile (!completed) {\n\t\tconst outcome = await Promise.race([\n\t\t\tsettled.then(() => \"settled\" as const),\n\t\t\tui.progress(state).then(() => \"stop\" as const),\n\t\t]);\n\t\tif (outcome === \"settled\") break;\n\t\tconst stop = await ui.confirm(options.cancelTitle, options.cancelMessage);\n\t\tif (!stop || completed) continue;\n\t\ttry {\n\t\t\tawait options.cancel();\n\t\t} finally {\n\t\t\tcontroller.abort(new Error(\"Cancelled\"));\n\t\t}\n\t\tawait settled;\n\t\treturn { cancelled: true };\n\t}\n\n\tconst result = await settled;\n\tif (!result.ok) throw result.error;\n\treturn { cancelled: false, value: result.value };\n}\n"]}