Files
oh-my-pi/packages/coding-agent/test/agent-hub-activate.test.ts
T

450 lines
14 KiB
TypeScript

/**
* Hub Enter contract: activating a non-remote agent row delegates to the
* `focusAgent` dep (session focus proxy) and closes the hub on success; a
* focus failure keeps the hub open and surfaces the error as a notice.
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "bun:test";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { resetSettingsForTest, Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
import { IrcBus } from "@oh-my-pi/pi-coding-agent/irc/bus";
import { AgentHubOverlayComponent } from "@oh-my-pi/pi-coding-agent/modes/components/agent-hub";
import { SelectorController } from "@oh-my-pi/pi-coding-agent/modes/controllers/selector-controller";
import { SessionObserverRegistry } from "@oh-my-pi/pi-coding-agent/modes/session-observer-registry";
import { initTheme } from "@oh-my-pi/pi-coding-agent/modes/theme/theme";
import type { InteractiveModeContext } from "@oh-my-pi/pi-coding-agent/modes/types";
import { AgentRegistry } from "@oh-my-pi/pi-coding-agent/registry/agent-registry";
import type { AgentSession } from "@oh-my-pi/pi-coding-agent/session/agent-session";
import { SessionManager } from "@oh-my-pi/pi-coding-agent/session/session-manager";
import { TempDir } from "@oh-my-pi/pi-utils";
const AGENT_ID = "Worker";
const TEST_CWD = path.resolve("agent-hub-cwd");
function makeHub(focusAgent: (id: string) => Promise<void>) {
const agents = new AgentRegistry();
agents.register({
id: AGENT_ID,
displayName: AGENT_ID,
kind: "sub",
parentId: "Main",
session: { subscribe: () => () => {} } as unknown as AgentSession,
sessionFile: null,
status: "running",
});
let doneCalls = 0;
const done = Promise.withResolvers<void>();
const renderRequested = Promise.withResolvers<void>();
const hub = new AgentHubOverlayComponent({
observers: new SessionObserverRegistry(),
hubKeys: [],
onDone: () => {
doneCalls++;
done.resolve();
},
requestRender: () => renderRequested.resolve(),
registry: agents,
irc: new IrcBus(agents),
focusAgent,
});
return { hub, doneCalls: () => doneCalls, done: done.promise, renderRequested: renderRequested.promise };
}
describe("Agent hub Enter activation", () => {
beforeAll(() => {
initTheme();
});
beforeEach(async () => {
resetSettingsForTest();
await Settings.init({ inMemory: true });
});
afterEach(() => {
resetSettingsForTest();
});
it("Enter focuses the selected agent and closes the hub", async () => {
const focusedIds: string[] = [];
const { hub, doneCalls, done } = makeHub(async id => {
focusedIds.push(id);
});
hub.handleInput("\r");
await done; // activation is fire-and-forget async; onDone signals completion
expect(focusedIds).toEqual([AGENT_ID]);
expect(doneCalls()).toBe(1);
hub.dispose();
});
it("a focus failure keeps the hub open and shows the error as a notice", async () => {
const message = 'Agent "X" is aborted and cannot be revived';
const { hub, doneCalls, renderRequested } = makeHub(() => Promise.reject(new Error(message)));
hub.handleInput("\r");
await renderRequested; // the rejection path requests a render after setting the notice
expect(doneCalls()).toBe(0);
const rendered = Bun.stripANSI(hub.render(120).join("\n"));
expect(rendered).toContain(message);
hub.dispose();
});
it("lists persisted subagent session files after restart", async () => {
using tempDir = TempDir.createSync("@omp-agent-hub-persisted-");
const sessionFile = path.join(tempDir.path(), "main.jsonl");
const workerSessionFile = path.join(tempDir.path(), "main", "Worker.jsonl");
await Bun.write(sessionFile, "");
await Bun.write(workerSessionFile, "");
const agents = new AgentRegistry();
const hub = new AgentHubOverlayComponent({
observers: new SessionObserverRegistry(),
hubKeys: [],
onDone: () => {},
requestRender: () => {},
registry: agents,
irc: new IrcBus(agents),
focusAgent: async () => {},
sessionFile,
});
await hub.persistedSubagentsReady;
const rendered = Bun.stripANSI(hub.render(120).join("\n"));
expect(rendered).toContain("Worker");
expect(rendered).toContain("parked");
expect(agents.get("Worker")?.sessionFile).toBe(workerSessionFile);
hub.dispose();
});
it("does not generically revive active or tombstoned Vibe children copied by a post-exit fork", async () => {
using tempDir = TempDir.createSync("@omp-agent-hub-vibe-fork-");
const manager = SessionManager.create(tempDir.path(), tempDir.path());
manager.appendModeChange("vibe");
const parentSessionId = manager.getSessionId();
for (const id of ["ActiveVibe", "KilledVibe"]) {
manager.appendCustomEntry("vibe-session-lifecycle", {
version: 1,
action: "spawn",
id,
ownerId: "Main",
parentSessionId,
cli: "fast",
agent: "sonic",
childSessionFile: `${id}.jsonl`,
createdAt: Date.now(),
});
}
manager.appendCustomEntry("vibe-session-lifecycle", {
version: 1,
action: "tombstone",
id: "KilledVibe",
ownerId: "Main",
parentSessionId,
reason: "mode-exit",
});
manager.appendModeChange("none");
await manager.ensureOnDisk();
await manager.flush();
const sourceSessionFile = manager.getSessionFile();
if (!sourceSessionFile) throw new Error("Expected source session file");
const sourceArtifacts = sourceSessionFile.slice(0, -6);
await fs.mkdir(sourceArtifacts, { recursive: true });
for (const id of ["ActiveVibe", "KilledVibe", "OrdinaryTask"]) {
await fs.writeFile(path.join(sourceArtifacts, `${id}.jsonl`), "persisted child");
}
const fork = await manager.fork();
if (!fork) throw new Error("Expected persisted fork");
await fs.cp(sourceArtifacts, fork.newSessionFile.slice(0, -6), { recursive: true });
await manager.close();
const agents = new AgentRegistry();
const hub = new AgentHubOverlayComponent({
observers: new SessionObserverRegistry(),
hubKeys: [],
onDone: () => {},
requestRender: () => {},
registry: agents,
irc: new IrcBus(agents),
focusAgent: async () => {},
sessionFile: fork.newSessionFile,
});
await hub.persistedSubagentsReady;
expect(agents.get("ActiveVibe")).toBeUndefined();
expect(agents.get("KilledVibe")).toBeUndefined();
expect(agents.get("OrdinaryTask")?.status).toBe("parked");
hub.dispose();
});
it("selector controller restores focus to the editor after Enter focuses an agent", async () => {
const agents = new AgentRegistry();
agents.register({
id: AGENT_ID,
displayName: AGENT_ID,
kind: "sub",
parentId: "Main",
session: { subscribe: () => () => {} } as unknown as AgentSession,
sessionFile: null,
status: "running",
});
const editor = {};
let capturedHub: AgentHubOverlayComponent | undefined;
let editorRestoredCount = 0;
const focusedIds: string[] = [];
const focusResolved = Promise.withResolvers<void>();
const editorFocused = Promise.withResolvers<void>();
const focusTargets: unknown[] = [];
const editorContainer = {
clear: () => {},
addChild: (child: unknown) => {
if (child === editor) editorRestoredCount++;
else capturedHub = child as AgentHubOverlayComponent;
},
};
const ctx = {
keybindings: { getKeys: () => [] },
ui: {
setFocus: (target: unknown) => {
focusTargets.push(target);
if (target === editor) editorFocused.resolve();
},
requestRender: () => {},
},
editor,
editorContainer,
collabGuest: { agentRegistry: agents, hubRemote: undefined },
focusAgentSession: async (id: string) => {
focusedIds.push(id);
focusResolved.resolve();
},
session: { getToolByName: () => undefined, extensionRunner: undefined },
sessionManager: { getCwd: () => TEST_CWD, getSessionFile: () => null },
hideThinkingBlock: false,
};
const controller = new SelectorController(ctx as unknown as InteractiveModeContext);
controller.showAgentHub(new SessionObserverRegistry());
expect(capturedHub).toBeDefined();
expect(focusTargets[0]).toBe(capturedHub);
capturedHub!.handleInput("\r");
await focusResolved.promise;
await editorFocused.promise;
expect(focusedIds).toEqual([AGENT_ID]);
expect(editorRestoredCount).toBe(1);
expect(focusTargets.at(-1)).toBe(editor);
capturedHub!.dispose();
});
});
describe("Agent hub double-← gating", () => {
beforeAll(() => {
initTheme();
});
afterEach(() => {
resetSettingsForTest();
});
function setup(agents: AgentRegistry, sessionFile: string | null = null) {
let shown: AgentHubOverlayComponent | undefined;
const shownReady = Promise.withResolvers<AgentHubOverlayComponent>();
const editor = {};
const focusTargets: unknown[] = [];
const ctx = {
keybindings: { getKeys: () => [] },
ui: {
setFocus: (target: unknown) => {
focusTargets.push(target);
},
requestRender: () => {},
},
editor,
editorContainer: {
clear: () => {},
addChild: (child: unknown) => {
if (child !== editor) {
shown = child as AgentHubOverlayComponent;
shownReady.resolve(shown);
}
},
},
collabGuest: { agentRegistry: agents, hubRemote: undefined },
focusAgentSession: async () => {},
session: { getToolByName: () => undefined, extensionRunner: undefined },
sessionManager: { getCwd: () => TEST_CWD, getSessionFile: () => sessionFile },
hideThinkingBlock: false,
};
const controller = new SelectorController(ctx as unknown as InteractiveModeContext);
return {
controller,
editor,
shown: () => shown,
shownReady: shownReady.promise,
focusTargets,
};
}
function registerWorker(agents: AgentRegistry) {
agents.register({
id: AGENT_ID,
displayName: AGENT_ID,
kind: "sub",
parentId: "Main",
session: { subscribe: () => () => {} } as unknown as AgentSession,
sessionFile: null,
status: "running",
});
}
it("requireContent keeps the hub closed when only Main is registered", () => {
const agents = new AgentRegistry();
agents.register({
id: "Main",
displayName: "Main",
kind: "main",
session: null,
sessionFile: null,
status: "running",
});
const { controller, shown } = setup(agents);
controller.showAgentHub(new SessionObserverRegistry(), { requireContent: true });
expect(shown()).toBeUndefined();
});
it("requireContent opens the hub once a subagent exists", () => {
const agents = new AgentRegistry();
registerWorker(agents);
const { controller, shown } = setup(agents);
controller.showAgentHub(new SessionObserverRegistry(), { requireContent: true });
expect(shown()).toBeDefined();
shown()!.dispose();
});
it("requireContent opens the hub after persisted subagents load", async () => {
using tempDir = TempDir.createSync("@omp-agent-hub-require-content-");
const sessionFile = path.join(tempDir.path(), "main.jsonl");
const workerSessionFile = path.join(tempDir.path(), "main", "Worker.jsonl");
await Bun.write(sessionFile, "");
await Bun.write(workerSessionFile, "");
const agents = new AgentRegistry();
const { controller, shown, shownReady } = setup(agents, sessionFile);
controller.showAgentHub(new SessionObserverRegistry(), { requireContent: true });
expect(shown()).toBeUndefined();
const shownHub = await shownReady;
expect(shownHub).toBeDefined();
expect(agents.get("Worker")?.sessionFile).toBe(workerSessionFile);
shownHub!.dispose();
});
it("the explicit hub key opens the empty roster even with no subagents", () => {
const agents = new AgentRegistry();
const { controller, shown } = setup(agents);
controller.showAgentHub(new SessionObserverRegistry());
expect(shown()).toBeDefined();
shown()!.dispose();
});
it("armCloseTap lets a single ← dismiss the hub the opening ←← raised", () => {
const agents = new AgentRegistry();
// A parked/persisted agent opens the hub under requireContent (issue #4780).
agents.register({
id: "Parked",
displayName: "Parked",
kind: "sub",
parentId: "Main",
session: { subscribe: () => () => {} } as unknown as AgentSession,
sessionFile: null,
status: "parked",
});
const { controller, editor, shown, focusTargets } = setup(agents);
controller.showAgentHub(new SessionObserverRegistry(), { requireContent: true, armCloseTap: true });
const hub = shown();
expect(hub).toBeDefined();
expect(focusTargets.at(-1)).toBe(hub);
// One ← — the editor's detector consumed the ←← that opened the hub — now
// closes it, returning focus to the editor. Without armCloseTap this ← only
// primes the hub's fresh detector and the user stays trapped.
hub!.handleInput("\x1b[D");
expect(focusTargets.at(-1)).toBe(editor);
});
});
describe("Agent hub data refresh coalescing", () => {
beforeAll(() => {
initTheme();
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
AgentRegistry.resetGlobalForTests();
});
it("coalesces a synchronous registry burst into one render and refreshes rows", async () => {
vi.useFakeTimers();
const agents = new AgentRegistry();
const observers = new SessionObserverRegistry();
const requestRender = vi.fn();
const hub = new AgentHubOverlayComponent({
observers,
hubKeys: [],
onDone: () => {},
requestRender,
registry: agents,
irc: new IrcBus(agents),
focusAgent: async () => {},
});
try {
await hub.persistedSubagentsReady;
requestRender.mockClear();
for (const id of ["BurstA", "BurstB", "BurstC"]) {
agents.register({
id,
displayName: id,
kind: "sub",
parentId: "Main",
session: { subscribe: () => () => {} } as unknown as AgentSession,
sessionFile: null,
status: "running",
});
}
expect(requestRender).not.toHaveBeenCalled();
expect(Bun.stripANSI(hub.render(120).join("\n"))).not.toContain("BurstA");
vi.advanceTimersByTime(99);
expect(requestRender).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(requestRender).toHaveBeenCalledTimes(1);
const rendered = Bun.stripANSI(hub.render(120).join("\n"));
expect(rendered).toContain("BurstA");
expect(rendered).toContain("BurstB");
expect(rendered).toContain("BurstC");
} finally {
hub.dispose();
vi.useRealTimers();
}
});
});