interactive-mode-status.test.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. import { homedir } from "node:os";
  2. import * as path from "node:path";
  3. import { type AutocompleteProvider, CombinedAutocompleteProvider } from "@earendil-works/pi-tui";
  4. import { beforeAll, describe, expect, test, vi } from "vitest";
  5. import { type Component, Container, type Focusable, TUI } from "../../tui/src/tui.ts";
  6. import { VirtualTerminal } from "../../tui/test/virtual-terminal.ts";
  7. import type { AutocompleteProviderFactory } from "../src/core/extensions/types.ts";
  8. import type { SourceInfo } from "../src/core/source-info.ts";
  9. import { InteractiveMode } from "../src/modes/interactive/interactive-mode.ts";
  10. import { initTheme } from "../src/modes/interactive/theme/theme.ts";
  11. function renderLastLine(container: Container, width = 120): string {
  12. const last = container.children[container.children.length - 1];
  13. if (!last) return "";
  14. return last.render(width).join("\n");
  15. }
  16. function renderAll(container: Container, width = 120): string {
  17. return container.children.flatMap((child) => child.render(width)).join("\n");
  18. }
  19. class TestFocusableComponent implements Component, Focusable {
  20. focused = false;
  21. inputs: string[] = [];
  22. private readonly label: string;
  23. private text = "";
  24. constructor(label: string) {
  25. this.label = label;
  26. }
  27. handleInput(data: string): void {
  28. this.inputs.push(data);
  29. }
  30. getText(): string {
  31. return this.text;
  32. }
  33. setText(text: string): void {
  34. this.text = text;
  35. }
  36. render(): string[] {
  37. return [this.label];
  38. }
  39. invalidate(): void {}
  40. }
  41. async function flushTui(tui: TUI, terminal: VirtualTerminal): Promise<void> {
  42. tui.requestRender(true);
  43. await Promise.resolve();
  44. await terminal.waitForRender();
  45. }
  46. function normalizeRenderedOutput(container: Container, width = 220): string {
  47. return renderAll(container, width)
  48. .replace(/\u001b\[[0-9;]*m/g, "")
  49. .replace(/\\/g, "/")
  50. .split("\n")
  51. .map((line) => line.replace(/\s+$/g, ""))
  52. .join("\n")
  53. .trim();
  54. }
  55. type ExtensionFixture = {
  56. path: string;
  57. sourceInfo?: SourceInfo;
  58. };
  59. describe("InteractiveMode.showStatus", () => {
  60. beforeAll(() => {
  61. // showStatus uses the global theme instance
  62. initTheme("dark");
  63. });
  64. test("coalesces immediately-sequential status messages", () => {
  65. const fakeThis: any = {
  66. chatContainer: new Container(),
  67. ui: { requestRender: vi.fn() },
  68. lastStatusSpacer: undefined,
  69. lastStatusText: undefined,
  70. };
  71. (InteractiveMode as any).prototype.showStatus.call(fakeThis, "STATUS_ONE");
  72. expect(fakeThis.chatContainer.children).toHaveLength(2);
  73. expect(renderLastLine(fakeThis.chatContainer)).toContain("STATUS_ONE");
  74. (InteractiveMode as any).prototype.showStatus.call(fakeThis, "STATUS_TWO");
  75. // second status updates the previous line instead of appending
  76. expect(fakeThis.chatContainer.children).toHaveLength(2);
  77. expect(renderLastLine(fakeThis.chatContainer)).toContain("STATUS_TWO");
  78. expect(renderLastLine(fakeThis.chatContainer)).not.toContain("STATUS_ONE");
  79. });
  80. test("appends a new status line if something else was added in between", () => {
  81. const fakeThis: any = {
  82. chatContainer: new Container(),
  83. ui: { requestRender: vi.fn() },
  84. lastStatusSpacer: undefined,
  85. lastStatusText: undefined,
  86. };
  87. (InteractiveMode as any).prototype.showStatus.call(fakeThis, "STATUS_ONE");
  88. expect(fakeThis.chatContainer.children).toHaveLength(2);
  89. // Something else gets added to the chat in between status updates
  90. fakeThis.chatContainer.addChild({ render: () => ["OTHER"], invalidate: () => {} });
  91. expect(fakeThis.chatContainer.children).toHaveLength(3);
  92. (InteractiveMode as any).prototype.showStatus.call(fakeThis, "STATUS_TWO");
  93. // adds spacer + text
  94. expect(fakeThis.chatContainer.children).toHaveLength(5);
  95. expect(renderLastLine(fakeThis.chatContainer)).toContain("STATUS_TWO");
  96. });
  97. });
  98. describe("InteractiveMode.setToolsExpanded", () => {
  99. test("applies expansion state to the active header and chat entries", () => {
  100. const header = { setExpanded: vi.fn() };
  101. const chatChild = { setExpanded: vi.fn() };
  102. const fakeThis: any = {
  103. toolOutputExpanded: false,
  104. customHeader: undefined,
  105. builtInHeader: header,
  106. chatContainer: { children: [chatChild] },
  107. ui: { requestRender: vi.fn() },
  108. };
  109. (InteractiveMode as any).prototype.setToolsExpanded.call(fakeThis, true);
  110. expect(fakeThis.toolOutputExpanded).toBe(true);
  111. expect(header.setExpanded).toHaveBeenCalledWith(true);
  112. expect(chatChild.setExpanded).toHaveBeenCalledWith(true);
  113. expect(fakeThis.ui.requestRender).toHaveBeenCalledTimes(1);
  114. });
  115. });
  116. describe("InteractiveMode.createExtensionUIContext setTheme", () => {
  117. test("persists theme changes to settings manager", () => {
  118. initTheme("dark");
  119. let currentTheme = "dark";
  120. const settingsManager = {
  121. getTheme: vi.fn(() => currentTheme),
  122. setTheme: vi.fn((theme: string) => {
  123. currentTheme = theme;
  124. }),
  125. };
  126. const fakeThis: any = {
  127. session: { settingsManager },
  128. settingsManager,
  129. ui: { requestRender: vi.fn() },
  130. };
  131. const uiContext = (InteractiveMode as any).prototype.createExtensionUIContext.call(fakeThis);
  132. const result = uiContext.setTheme("light");
  133. expect(result.success).toBe(true);
  134. expect(settingsManager.setTheme).toHaveBeenCalledWith("light");
  135. expect(currentTheme).toBe("light");
  136. expect(fakeThis.ui.requestRender).toHaveBeenCalledTimes(1);
  137. });
  138. test("does not persist invalid theme names", () => {
  139. initTheme("dark");
  140. const settingsManager = {
  141. getTheme: vi.fn(() => "dark"),
  142. setTheme: vi.fn(),
  143. };
  144. const fakeThis: any = {
  145. session: { settingsManager },
  146. settingsManager,
  147. ui: { requestRender: vi.fn() },
  148. };
  149. const uiContext = (InteractiveMode as any).prototype.createExtensionUIContext.call(fakeThis);
  150. const result = uiContext.setTheme("__missing_theme__");
  151. expect(result.success).toBe(false);
  152. expect(settingsManager.setTheme).not.toHaveBeenCalled();
  153. expect(fakeThis.ui.requestRender).not.toHaveBeenCalled();
  154. });
  155. });
  156. describe("InteractiveMode.showExtensionCustom", () => {
  157. beforeAll(() => {
  158. initTheme("dark");
  159. });
  160. test("overlay custom UI reclaims input after non-overlay custom UI closes", async () => {
  161. const terminal = new VirtualTerminal(80, 24);
  162. const ui = new TUI(terminal);
  163. const editorContainer = new Container();
  164. const editor = new TestFocusableComponent("EDITOR");
  165. const palette = new TestFocusableComponent("PALETTE");
  166. const overlay = new TestFocusableComponent("OVERLAY");
  167. const replacement = new TestFocusableComponent("REPLACEMENT");
  168. let closeOverlay: (value: string) => void = () => {
  169. throw new Error("closeOverlay was not initialized");
  170. };
  171. let closeReplacement: (value: string) => void = () => {
  172. throw new Error("closeReplacement was not initialized");
  173. };
  174. const fakeThis = {
  175. editor,
  176. editorContainer,
  177. keybindings: {},
  178. ui,
  179. };
  180. const showExtensionCustom = <T>(
  181. factory: (tui: TUI, theme: unknown, keybindings: unknown, done: (result: T) => void) => Component,
  182. options?: { overlay?: boolean },
  183. ): Promise<T> =>
  184. (InteractiveMode as any).prototype.showExtensionCustom.call(fakeThis, factory, options) as Promise<T>;
  185. editorContainer.addChild(editor);
  186. ui.addChild(editorContainer);
  187. ui.addChild(palette);
  188. ui.setFocus(palette);
  189. ui.start();
  190. try {
  191. const overlayPromise = showExtensionCustom<string>(
  192. (_tui, _theme, _keybindings, done) => {
  193. closeOverlay = done;
  194. return overlay;
  195. },
  196. { overlay: true },
  197. );
  198. await flushTui(ui, terminal);
  199. expect(overlay.focused).toBe(true);
  200. const replacementPromise = showExtensionCustom<string>((_tui, _theme, _keybindings, done) => {
  201. closeReplacement = done;
  202. return replacement;
  203. });
  204. await flushTui(ui, terminal);
  205. expect(replacement.focused).toBe(true);
  206. closeReplacement("done");
  207. await replacementPromise;
  208. await flushTui(ui, terminal);
  209. terminal.sendInput("x");
  210. await flushTui(ui, terminal);
  211. expect(overlay.inputs).toEqual(["x"]);
  212. expect(editor.inputs).toEqual([]);
  213. expect(overlay.focused).toBe(true);
  214. closeOverlay("closed");
  215. await overlayPromise;
  216. } finally {
  217. ui.stop();
  218. }
  219. });
  220. });
  221. describe("InteractiveMode.createExtensionUIContext addAutocompleteProvider", () => {
  222. test("stores wrapper factories and rebuilds autocomplete immediately", () => {
  223. const wrapper: AutocompleteProviderFactory = (current) => current;
  224. const fakeThis = {
  225. autocompleteProviderWrappers: [] as AutocompleteProviderFactory[],
  226. setupAutocompleteProvider: vi.fn(),
  227. };
  228. const uiContext = (InteractiveMode as any).prototype.createExtensionUIContext.call(fakeThis);
  229. uiContext.addAutocompleteProvider(wrapper);
  230. expect(fakeThis.autocompleteProviderWrappers).toEqual([wrapper]);
  231. expect(fakeThis.setupAutocompleteProvider).toHaveBeenCalledTimes(1);
  232. });
  233. });
  234. describe("InteractiveMode.setupAutocompleteProvider", () => {
  235. test("stacks wrapper factories over a fresh base provider", () => {
  236. const defaultEditor = { setAutocompleteProvider: vi.fn() };
  237. const customEditor = { setAutocompleteProvider: vi.fn() };
  238. const calls: string[] = [];
  239. const wrap1: AutocompleteProviderFactory = (current): AutocompleteProvider => ({
  240. async getSuggestions(lines, cursorLine, cursorCol, options) {
  241. calls.push("getSuggestions:wrap1");
  242. return current.getSuggestions(lines, cursorLine, cursorCol, options);
  243. },
  244. applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
  245. calls.push("applyCompletion:wrap1");
  246. return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
  247. },
  248. shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
  249. calls.push("shouldTrigger:wrap1");
  250. return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
  251. },
  252. });
  253. const wrap2: AutocompleteProviderFactory = (current): AutocompleteProvider => ({
  254. async getSuggestions(lines, cursorLine, cursorCol, options) {
  255. calls.push("getSuggestions:wrap2");
  256. return current.getSuggestions(lines, cursorLine, cursorCol, options);
  257. },
  258. applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
  259. calls.push("applyCompletion:wrap2");
  260. return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
  261. },
  262. shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
  263. calls.push("shouldTrigger:wrap2");
  264. return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
  265. },
  266. });
  267. const fakeThis = {
  268. createBaseAutocompleteProvider: () => new CombinedAutocompleteProvider([], "/tmp/project", undefined),
  269. defaultEditor,
  270. editor: customEditor,
  271. autocompleteProviderWrappers: [wrap1, wrap2],
  272. };
  273. (InteractiveMode as any).prototype.setupAutocompleteProvider.call(fakeThis);
  274. expect(defaultEditor.setAutocompleteProvider).toHaveBeenCalledTimes(1);
  275. expect(customEditor.setAutocompleteProvider).toHaveBeenCalledTimes(1);
  276. const provider = defaultEditor.setAutocompleteProvider.mock.calls[0]?.[0] as AutocompleteProvider;
  277. expect(provider).toBe(customEditor.setAutocompleteProvider.mock.calls[0]?.[0]);
  278. expect(provider.shouldTriggerFileCompletion?.(["foo"], 0, 3)).toBe(true);
  279. expect(calls).toEqual(["shouldTrigger:wrap2", "shouldTrigger:wrap1"]);
  280. });
  281. test("merges triggerCharacters from wrapper factories", () => {
  282. const defaultEditor = { setAutocompleteProvider: vi.fn() };
  283. const customEditor = { setAutocompleteProvider: vi.fn() };
  284. const passThrough =
  285. (triggerCharacters: string[]): AutocompleteProviderFactory =>
  286. (current) => ({
  287. triggerCharacters,
  288. getSuggestions: (lines, cursorLine, cursorCol, options) =>
  289. current.getSuggestions(lines, cursorLine, cursorCol, options),
  290. applyCompletion: (lines, cursorLine, cursorCol, item, prefix) =>
  291. current.applyCompletion(lines, cursorLine, cursorCol, item, prefix),
  292. });
  293. const fakeThis = {
  294. createBaseAutocompleteProvider: () => new CombinedAutocompleteProvider([], "/tmp/project", undefined),
  295. defaultEditor,
  296. editor: customEditor,
  297. autocompleteProviderWrappers: [passThrough(["$"]), passThrough(["!"])],
  298. };
  299. (
  300. InteractiveMode as unknown as {
  301. prototype: { setupAutocompleteProvider: (this: typeof fakeThis) => void };
  302. }
  303. ).prototype.setupAutocompleteProvider.call(fakeThis);
  304. const provider = defaultEditor.setAutocompleteProvider.mock.calls[0]?.[0] as AutocompleteProvider;
  305. expect(provider.triggerCharacters).toEqual(["$", "!"]);
  306. });
  307. });
  308. describe("InteractiveMode.showLoadedResources", () => {
  309. beforeAll(() => {
  310. initTheme("dark");
  311. });
  312. function createShowLoadedResourcesThis(options: {
  313. quietStartup: boolean;
  314. verbose?: boolean;
  315. toolOutputExpanded?: boolean;
  316. cwd?: string;
  317. contextFiles?: Array<{ path: string; content?: string }>;
  318. extensions?: ExtensionFixture[];
  319. skills?: Array<{ filePath: string; name: string }>;
  320. skillDiagnostics?: Array<{ type: "warning" | "error" | "collision"; message: string }>;
  321. useRealScopeGroups?: boolean;
  322. }) {
  323. const fakeThis: any = {
  324. options: { verbose: options.verbose ?? false },
  325. toolOutputExpanded: options.toolOutputExpanded ?? false,
  326. chatContainer: new Container(),
  327. settingsManager: {
  328. getQuietStartup: () => options.quietStartup,
  329. },
  330. sessionManager: {
  331. getCwd: () => options.cwd ?? "/tmp/project",
  332. },
  333. session: {
  334. promptTemplates: [],
  335. extensionRunner: {
  336. getCommandDiagnostics: () => [],
  337. getShortcutDiagnostics: () => [],
  338. },
  339. resourceLoader: {
  340. getPathMetadata: () => new Map(),
  341. getAgentsFiles: () => ({ agentsFiles: options.contextFiles ?? [] }),
  342. getSkills: () => ({
  343. skills: options.skills ?? [],
  344. diagnostics: options.skillDiagnostics ?? [],
  345. }),
  346. getPrompts: () => ({ prompts: [], diagnostics: [] }),
  347. getExtensions: () => ({ extensions: options.extensions ?? [], errors: [], runtime: {} }),
  348. getThemes: () => ({ themes: [], diagnostics: [] }),
  349. },
  350. },
  351. formatDisplayPath: (p: string) => (InteractiveMode as any).prototype.formatDisplayPath.call(fakeThis, p),
  352. formatExtensionDisplayPath: (p: string) =>
  353. (InteractiveMode as any).prototype.formatExtensionDisplayPath.call(fakeThis, p),
  354. formatContextPath: (p: string) => (InteractiveMode as any).prototype.formatContextPath.call(fakeThis, p),
  355. getStartupExpansionState: () => (InteractiveMode as any).prototype.getStartupExpansionState.call(fakeThis),
  356. buildScopeGroups: () => [],
  357. formatScopeGroups: () => "resource-list",
  358. isPackageSource: (sourceInfo?: SourceInfo) =>
  359. (InteractiveMode as any).prototype.isPackageSource.call(fakeThis, sourceInfo),
  360. getShortPath: (p: string, sourceInfo?: SourceInfo) =>
  361. (InteractiveMode as any).prototype.getShortPath.call(fakeThis, p, sourceInfo),
  362. getCompactPathLabel: (p: string, sourceInfo?: SourceInfo) =>
  363. (InteractiveMode as any).prototype.getCompactPathLabel.call(fakeThis, p, sourceInfo),
  364. getCompactPackageSourceLabel: (sourceInfo?: SourceInfo) =>
  365. (InteractiveMode as any).prototype.getCompactPackageSourceLabel.call(fakeThis, sourceInfo),
  366. getCompactExtensionLabel: (p: string, sourceInfo?: SourceInfo) =>
  367. (InteractiveMode as any).prototype.getCompactExtensionLabel.call(fakeThis, p, sourceInfo),
  368. getCompactDisplayPathSegments: (p: string) =>
  369. (InteractiveMode as any).prototype.getCompactDisplayPathSegments.call(fakeThis, p),
  370. getCompactNonPackageExtensionLabel: (
  371. p: string,
  372. index: number,
  373. allPaths: Array<{ path: string; segments: string[] }>,
  374. ) => (InteractiveMode as any).prototype.getCompactNonPackageExtensionLabel.call(fakeThis, p, index, allPaths),
  375. getCompactExtensionLabels: (extensions: ExtensionFixture[]) =>
  376. (InteractiveMode as any).prototype.getCompactExtensionLabels.call(fakeThis, extensions),
  377. formatDiagnostics: () => "diagnostics",
  378. getBuiltInCommandConflictDiagnostics: () => [],
  379. };
  380. if (options.useRealScopeGroups) {
  381. fakeThis.getScopeGroup = (sourceInfo?: SourceInfo) =>
  382. (InteractiveMode as any).prototype.getScopeGroup.call(fakeThis, sourceInfo);
  383. fakeThis.buildScopeGroups = (items: Array<{ path: string; sourceInfo?: SourceInfo }>) =>
  384. (InteractiveMode as any).prototype.buildScopeGroups.call(fakeThis, items);
  385. fakeThis.formatScopeGroups = (groups: unknown, formatOptions: unknown) =>
  386. (InteractiveMode as any).prototype.formatScopeGroups.call(fakeThis, groups, formatOptions);
  387. }
  388. return fakeThis;
  389. }
  390. function createSourceInfo(
  391. filePath: string,
  392. options: {
  393. source: string;
  394. scope: "user" | "project" | "temporary";
  395. origin: "package" | "top-level";
  396. baseDir?: string;
  397. },
  398. ): SourceInfo {
  399. return {
  400. path: filePath,
  401. source: options.source,
  402. scope: options.scope,
  403. origin: options.origin,
  404. baseDir: options.baseDir,
  405. };
  406. }
  407. function createExtensionFixtures(): ExtensionFixture[] {
  408. return [
  409. {
  410. path: "/tmp/project/.pi/extensions/answer.ts",
  411. sourceInfo: createSourceInfo("/tmp/project/.pi/extensions/answer.ts", {
  412. source: "local",
  413. scope: "project",
  414. origin: "top-level",
  415. baseDir: "/tmp/project/.pi/extensions",
  416. }),
  417. },
  418. {
  419. path: "/tmp/project/.pi/extensions/local-index/index.ts",
  420. sourceInfo: createSourceInfo("/tmp/project/.pi/extensions/local-index/index.ts", {
  421. source: "local",
  422. scope: "project",
  423. origin: "top-level",
  424. baseDir: "/tmp/project/.pi/extensions",
  425. }),
  426. },
  427. {
  428. path: "/tmp/agent/extensions/user-index/index.ts",
  429. sourceInfo: createSourceInfo("/tmp/agent/extensions/user-index/index.ts", {
  430. source: "local",
  431. scope: "user",
  432. origin: "top-level",
  433. baseDir: "/tmp/agent/extensions",
  434. }),
  435. },
  436. {
  437. path: "/tmp/project/.pi/npm/node_modules/pi-markdown-preview/extensions/index.ts",
  438. sourceInfo: createSourceInfo("/tmp/project/.pi/npm/node_modules/pi-markdown-preview/extensions/index.ts", {
  439. source: "npm:pi-markdown-preview",
  440. scope: "project",
  441. origin: "package",
  442. baseDir: "/tmp/project/.pi/npm/node_modules/pi-markdown-preview",
  443. }),
  444. },
  445. {
  446. path: "/tmp/project/.pi/npm/node_modules/@scope/pi-scoped/extensions/index.ts",
  447. sourceInfo: createSourceInfo("/tmp/project/.pi/npm/node_modules/@scope/pi-scoped/extensions/index.ts", {
  448. source: "npm:@scope/pi-scoped",
  449. scope: "project",
  450. origin: "package",
  451. baseDir: "/tmp/project/.pi/npm/node_modules/@scope/pi-scoped",
  452. }),
  453. },
  454. {
  455. path: "/tmp/project/.pi/git/github.com/HazAT/pi-interactive-subagents/extensions/index.ts",
  456. sourceInfo: createSourceInfo(
  457. "/tmp/project/.pi/git/github.com/HazAT/pi-interactive-subagents/extensions/index.ts",
  458. {
  459. source: "git:github.com/HazAT/pi-interactive-subagents",
  460. scope: "project",
  461. origin: "package",
  462. baseDir: "/tmp/project/.pi/git/github.com/HazAT/pi-interactive-subagents",
  463. },
  464. ),
  465. },
  466. {
  467. path: "/tmp/project/.pi/git/github.com/HazAT/pi-interactive-subagents/extensions/subagents/index.ts",
  468. sourceInfo: createSourceInfo(
  469. "/tmp/project/.pi/git/github.com/HazAT/pi-interactive-subagents/extensions/subagents/index.ts",
  470. {
  471. source: "git:github.com/HazAT/pi-interactive-subagents",
  472. scope: "project",
  473. origin: "package",
  474. baseDir: "/tmp/project/.pi/git/github.com/HazAT/pi-interactive-subagents",
  475. },
  476. ),
  477. },
  478. {
  479. path: "/tmp/temp/cli-extension.ts",
  480. sourceInfo: createSourceInfo("/tmp/temp/cli-extension.ts", {
  481. source: "cli",
  482. scope: "temporary",
  483. origin: "top-level",
  484. baseDir: "/tmp/temp",
  485. }),
  486. },
  487. ];
  488. }
  489. test("shows a compact resource listing by default", () => {
  490. const fakeThis = createShowLoadedResourcesThis({
  491. quietStartup: false,
  492. skills: [{ filePath: "/tmp/skill/SKILL.md", name: "commit" }],
  493. });
  494. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  495. force: false,
  496. });
  497. const output = renderAll(fakeThis.chatContainer);
  498. expect(output).toContain("[Skills]");
  499. expect(output).toContain("commit");
  500. expect(output).not.toContain("resource-list");
  501. });
  502. test("shows full resource listing when expanded", () => {
  503. const fakeThis = createShowLoadedResourcesThis({
  504. quietStartup: false,
  505. toolOutputExpanded: true,
  506. skills: [{ filePath: "/tmp/skill/SKILL.md", name: "commit" }],
  507. });
  508. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  509. force: false,
  510. });
  511. const output = renderAll(fakeThis.chatContainer);
  512. expect(output).toContain("[Skills]");
  513. expect(output).toContain("resource-list");
  514. expect(output).not.toContain("commit");
  515. });
  516. test("shows full resource listing on verbose startup even when tool output is collapsed", () => {
  517. const fakeThis = createShowLoadedResourcesThis({
  518. quietStartup: true,
  519. verbose: true,
  520. toolOutputExpanded: false,
  521. skills: [{ filePath: "/tmp/skill/SKILL.md", name: "commit" }],
  522. });
  523. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  524. force: false,
  525. });
  526. const output = renderAll(fakeThis.chatContainer);
  527. expect(output).toContain("[Skills]");
  528. expect(output).toContain("resource-list");
  529. expect(output).not.toContain("commit");
  530. });
  531. test("abbreviates extensions in compact listing", () => {
  532. const fakeThis = createShowLoadedResourcesThis({
  533. quietStartup: false,
  534. extensions: [{ path: "/tmp/extensions/answer.ts" }, { path: "/tmp/extensions/btw.ts" }],
  535. });
  536. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  537. force: false,
  538. });
  539. const output = renderAll(fakeThis.chatContainer);
  540. expect(output).toContain("[Extensions]");
  541. expect(output).toContain("answer.ts, btw.ts");
  542. expect(output).not.toContain("extensions/answer.ts");
  543. });
  544. test("captures mixed extension layouts in compact output", () => {
  545. const fakeThis = createShowLoadedResourcesThis({
  546. quietStartup: false,
  547. extensions: createExtensionFixtures(),
  548. useRealScopeGroups: true,
  549. });
  550. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  551. force: false,
  552. });
  553. expect(normalizeRenderedOutput(fakeThis.chatContainer)).toMatchInlineSnapshot(`
  554. "[Extensions]
  555. @scope/pi-scoped, answer.ts, cli-extension.ts, HazAT/pi-interactive-subagents, HazAT/pi-interactive-subagents:subagents, local-index, pi-markdown-preview, user-index"`);
  556. });
  557. test("adds more parent folders until local extension labels are unique", () => {
  558. const extensions: ExtensionFixture[] = [
  559. {
  560. path: "/tmp/alpha/one/index.ts",
  561. sourceInfo: createSourceInfo("/tmp/alpha/one/index.ts", {
  562. source: "cli",
  563. scope: "temporary",
  564. origin: "top-level",
  565. baseDir: "/tmp/alpha",
  566. }),
  567. },
  568. {
  569. path: "/tmp/beta/one/index.ts",
  570. sourceInfo: createSourceInfo("/tmp/beta/one/index.ts", {
  571. source: "cli",
  572. scope: "temporary",
  573. origin: "top-level",
  574. baseDir: "/tmp/beta",
  575. }),
  576. },
  577. {
  578. path: "/tmp/gamma/one/index.ts",
  579. sourceInfo: createSourceInfo("/tmp/gamma/one/index.ts", {
  580. source: "cli",
  581. scope: "temporary",
  582. origin: "top-level",
  583. baseDir: "/tmp/gamma",
  584. }),
  585. },
  586. ];
  587. const fakeThis = createShowLoadedResourcesThis({
  588. quietStartup: false,
  589. extensions,
  590. useRealScopeGroups: true,
  591. });
  592. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  593. force: false,
  594. });
  595. expect(normalizeRenderedOutput(fakeThis.chatContainer)).toMatchInlineSnapshot(`
  596. "[Extensions]
  597. alpha/one, beta/one, gamma/one"`);
  598. });
  599. test("strips index.ts from local extension label, showing parent dir", () => {
  600. const extensions: ExtensionFixture[] = [
  601. {
  602. path: "/tmp/extensions/plan-mode/index.ts",
  603. sourceInfo: createSourceInfo("/tmp/extensions/plan-mode/index.ts", {
  604. source: "local",
  605. scope: "project",
  606. origin: "top-level",
  607. baseDir: "/tmp/extensions",
  608. }),
  609. },
  610. ];
  611. const fakeThis = createShowLoadedResourcesThis({
  612. quietStartup: false,
  613. extensions,
  614. useRealScopeGroups: true,
  615. });
  616. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  617. force: false,
  618. });
  619. expect(normalizeRenderedOutput(fakeThis.chatContainer)).toMatchInlineSnapshot(`
  620. "[Extensions]
  621. plan-mode"`);
  622. });
  623. test("strips index.js from local extension label, showing parent dir", () => {
  624. const extensions: ExtensionFixture[] = [
  625. {
  626. path: "/tmp/extensions/plan-mode/index.js",
  627. sourceInfo: createSourceInfo("/tmp/extensions/plan-mode/index.js", {
  628. source: "local",
  629. scope: "project",
  630. origin: "top-level",
  631. baseDir: "/tmp/extensions",
  632. }),
  633. },
  634. ];
  635. const fakeThis = createShowLoadedResourcesThis({
  636. quietStartup: false,
  637. extensions,
  638. useRealScopeGroups: true,
  639. });
  640. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  641. force: false,
  642. });
  643. expect(normalizeRenderedOutput(fakeThis.chatContainer)).toMatchInlineSnapshot(`
  644. "[Extensions]
  645. plan-mode"`);
  646. });
  647. test("mixed single-file and subdirectory index.ts extensions strip index.ts", () => {
  648. const extensions: ExtensionFixture[] = [
  649. {
  650. path: "/tmp/extensions/webfetch.ts",
  651. sourceInfo: createSourceInfo("/tmp/extensions/webfetch.ts", {
  652. source: "local",
  653. scope: "project",
  654. origin: "top-level",
  655. baseDir: "/tmp/extensions",
  656. }),
  657. },
  658. {
  659. path: "/tmp/extensions/plan-mode/index.ts",
  660. sourceInfo: createSourceInfo("/tmp/extensions/plan-mode/index.ts", {
  661. source: "local",
  662. scope: "project",
  663. origin: "top-level",
  664. baseDir: "/tmp/extensions",
  665. }),
  666. },
  667. ];
  668. const fakeThis = createShowLoadedResourcesThis({
  669. quietStartup: false,
  670. extensions,
  671. useRealScopeGroups: true,
  672. });
  673. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  674. force: false,
  675. });
  676. expect(normalizeRenderedOutput(fakeThis.chatContainer)).toMatchInlineSnapshot(`
  677. "[Extensions]
  678. plan-mode, webfetch.ts"`);
  679. });
  680. test("multiple index.ts with unique parent dirs need no disambiguation", () => {
  681. const extensions: ExtensionFixture[] = [
  682. {
  683. path: "/tmp/extensions/foo/index.ts",
  684. sourceInfo: createSourceInfo("/tmp/extensions/foo/index.ts", {
  685. source: "local",
  686. scope: "project",
  687. origin: "top-level",
  688. baseDir: "/tmp/extensions",
  689. }),
  690. },
  691. {
  692. path: "/tmp/extensions/bar/index.ts",
  693. sourceInfo: createSourceInfo("/tmp/extensions/bar/index.ts", {
  694. source: "local",
  695. scope: "project",
  696. origin: "top-level",
  697. baseDir: "/tmp/extensions",
  698. }),
  699. },
  700. ];
  701. const fakeThis = createShowLoadedResourcesThis({
  702. quietStartup: false,
  703. extensions,
  704. useRealScopeGroups: true,
  705. });
  706. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  707. force: false,
  708. });
  709. expect(normalizeRenderedOutput(fakeThis.chatContainer)).toMatchInlineSnapshot(`
  710. "[Extensions]
  711. bar, foo"`);
  712. });
  713. test("multiple index.ts with same parent dir name disambiguated with grandparent", () => {
  714. const extensions: ExtensionFixture[] = [
  715. {
  716. path: "/tmp/alpha/tools/index.ts",
  717. sourceInfo: createSourceInfo("/tmp/alpha/tools/index.ts", {
  718. source: "cli",
  719. scope: "temporary",
  720. origin: "top-level",
  721. baseDir: "/tmp/alpha",
  722. }),
  723. },
  724. {
  725. path: "/tmp/beta/tools/index.ts",
  726. sourceInfo: createSourceInfo("/tmp/beta/tools/index.ts", {
  727. source: "cli",
  728. scope: "temporary",
  729. origin: "top-level",
  730. baseDir: "/tmp/beta",
  731. }),
  732. },
  733. ];
  734. const fakeThis = createShowLoadedResourcesThis({
  735. quietStartup: false,
  736. extensions,
  737. useRealScopeGroups: true,
  738. });
  739. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  740. force: false,
  741. });
  742. expect(normalizeRenderedOutput(fakeThis.chatContainer)).toMatchInlineSnapshot(`
  743. "[Extensions]
  744. alpha/tools, beta/tools"`);
  745. });
  746. test("non-index file in subdirectory stays as filename", () => {
  747. const extensions: ExtensionFixture[] = [
  748. {
  749. path: "/tmp/extensions/my-ext/main.ts",
  750. sourceInfo: createSourceInfo("/tmp/extensions/my-ext/main.ts", {
  751. source: "local",
  752. scope: "project",
  753. origin: "top-level",
  754. baseDir: "/tmp/extensions",
  755. }),
  756. },
  757. ];
  758. const fakeThis = createShowLoadedResourcesThis({
  759. quietStartup: false,
  760. extensions,
  761. useRealScopeGroups: true,
  762. });
  763. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  764. force: false,
  765. });
  766. expect(normalizeRenderedOutput(fakeThis.chatContainer)).toMatchInlineSnapshot(`
  767. "[Extensions]
  768. main.ts"`);
  769. });
  770. test("package extensions still strip index.ts correctly (regression guard)", () => {
  771. const extensions: ExtensionFixture[] = [
  772. {
  773. path: "/tmp/project/.pi/npm/node_modules/pi-markdown-preview/extensions/index.ts",
  774. sourceInfo: createSourceInfo("/tmp/project/.pi/npm/node_modules/pi-markdown-preview/extensions/index.ts", {
  775. source: "npm:pi-markdown-preview",
  776. scope: "project",
  777. origin: "package",
  778. baseDir: "/tmp/project/.pi/npm/node_modules/pi-markdown-preview",
  779. }),
  780. },
  781. ];
  782. const fakeThis = createShowLoadedResourcesThis({
  783. quietStartup: false,
  784. extensions,
  785. useRealScopeGroups: true,
  786. });
  787. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  788. force: false,
  789. });
  790. expect(normalizeRenderedOutput(fakeThis.chatContainer)).toMatchInlineSnapshot(`
  791. "[Extensions]
  792. pi-markdown-preview"`);
  793. });
  794. test("captures mixed extension layouts in expanded output", () => {
  795. const fakeThis = createShowLoadedResourcesThis({
  796. quietStartup: false,
  797. toolOutputExpanded: true,
  798. extensions: createExtensionFixtures(),
  799. useRealScopeGroups: true,
  800. });
  801. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  802. force: false,
  803. });
  804. expect(normalizeRenderedOutput(fakeThis.chatContainer)).toMatchInlineSnapshot(`
  805. "[Extensions]
  806. project
  807. /tmp/project/.pi/extensions/answer.ts
  808. /tmp/project/.pi/extensions/local-index
  809. git:github.com/HazAT/pi-interactive-subagents
  810. extensions
  811. extensions/subagents
  812. npm:@scope/pi-scoped
  813. extensions
  814. npm:pi-markdown-preview
  815. extensions
  816. user
  817. /tmp/agent/extensions/user-index
  818. path
  819. /tmp/temp/cli-extension.ts"`);
  820. });
  821. test("shows context paths relative to cwd while preserving full external paths", () => {
  822. const home = homedir();
  823. const cwd = path.join(home, "Development", "pi-mono");
  824. const fakeThis = createShowLoadedResourcesThis({
  825. quietStartup: false,
  826. cwd,
  827. contextFiles: [{ path: path.join(home, ".pi", "agent", "AGENTS.md") }, { path: path.join(cwd, "AGENTS.md") }],
  828. });
  829. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  830. force: false,
  831. });
  832. const output = renderAll(fakeThis.chatContainer).replace(/\\/g, "/");
  833. expect(output).toContain("[Context]");
  834. expect(output).toContain("~/.pi/agent/AGENTS.md, AGENTS.md");
  835. expect(output).not.toContain(`${cwd.replace(/\\/g, "/")}/AGENTS.md`);
  836. });
  837. test("shows full context paths when expanded", () => {
  838. const home = homedir();
  839. const cwd = path.join(home, "Development", "pi-mono");
  840. const fakeThis = createShowLoadedResourcesThis({
  841. quietStartup: false,
  842. toolOutputExpanded: true,
  843. cwd,
  844. contextFiles: [{ path: path.join(home, ".pi", "agent", "AGENTS.md") }, { path: path.join(cwd, "AGENTS.md") }],
  845. });
  846. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  847. force: false,
  848. });
  849. const output = renderAll(fakeThis.chatContainer).replace(/\\/g, "/");
  850. expect(output).toContain("[Context]");
  851. expect(output).toContain("~/.pi/agent/AGENTS.md");
  852. expect(output).toContain("~/Development/pi-mono/AGENTS.md");
  853. expect(output).not.toContain("~/.pi/agent/AGENTS.md, AGENTS.md");
  854. });
  855. test("does not show verbose listing on quiet startup during reload", () => {
  856. const fakeThis = createShowLoadedResourcesThis({
  857. quietStartup: true,
  858. skills: [{ filePath: "/tmp/skill/SKILL.md", name: "commit" }],
  859. });
  860. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  861. extensions: [{ path: "/tmp/ext/index.ts" }],
  862. force: false,
  863. showDiagnosticsWhenQuiet: true,
  864. });
  865. expect(fakeThis.chatContainer.children).toHaveLength(0);
  866. });
  867. test("still shows diagnostics on quiet startup when requested", () => {
  868. const fakeThis = createShowLoadedResourcesThis({
  869. quietStartup: true,
  870. skills: [{ filePath: "/tmp/skill/SKILL.md", name: "commit" }],
  871. skillDiagnostics: [{ type: "warning", message: "duplicate skill name" }],
  872. });
  873. (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {
  874. force: false,
  875. showDiagnosticsWhenQuiet: true,
  876. });
  877. const output = renderAll(fakeThis.chatContainer);
  878. expect(output).toContain("[Skill conflicts]");
  879. expect(output).not.toContain("[Skills]");
  880. });
  881. });