2860-replaced-session-context.test.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import { existsSync, mkdirSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { fauxAssistantMessage, registerFauxProvider } from "@earendil-works/pi-ai";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import type { AgentSession } from "../../../src/core/agent-session.ts";
  7. import {
  8. type CreateAgentSessionRuntimeFactory,
  9. createAgentSessionFromServices,
  10. createAgentSessionRuntime,
  11. createAgentSessionServices,
  12. } from "../../../src/core/agent-session-runtime.ts";
  13. import { AuthStorage } from "../../../src/core/auth-storage.ts";
  14. import { SessionManager } from "../../../src/core/session-manager.ts";
  15. import type { ExtensionAPI, ExtensionCommandContext, ExtensionFactory } from "../../../src/index.ts";
  16. function getText(message: AgentSession["messages"][number]): string {
  17. if (!("content" in message)) {
  18. return "";
  19. }
  20. return typeof message.content === "string"
  21. ? message.content
  22. : message.content
  23. .filter((part): part is { type: "text"; text: string } => part.type === "text")
  24. .map((part) => part.text)
  25. .join("");
  26. }
  27. describe("regression #2860: replaced session callbacks", () => {
  28. const cleanups: Array<() => Promise<void> | void> = [];
  29. afterEach(async () => {
  30. while (cleanups.length > 0) {
  31. await cleanups.pop()?.();
  32. }
  33. });
  34. async function createRuntimeForTest(extensionFactory: ExtensionFactory, responses: string[]) {
  35. const tempDir = join(tmpdir(), `pi-2860-${Date.now()}-${Math.random().toString(36).slice(2)}`);
  36. mkdirSync(tempDir, { recursive: true });
  37. const faux = registerFauxProvider({
  38. models: [{ id: "faux-1", reasoning: false }],
  39. });
  40. faux.setResponses(responses.map((response) => fauxAssistantMessage(response)));
  41. const authStorage = AuthStorage.inMemory();
  42. authStorage.setRuntimeApiKey(faux.getModel().provider, "faux-key");
  43. const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => {
  44. const services = await createAgentSessionServices({
  45. cwd,
  46. agentDir: tempDir,
  47. authStorage,
  48. resourceLoaderOptions: {
  49. extensionFactories: [
  50. (pi: ExtensionAPI) => {
  51. pi.registerProvider(faux.getModel().provider, {
  52. baseUrl: faux.getModel().baseUrl,
  53. apiKey: "faux-key",
  54. api: faux.api,
  55. models: faux.models.map((registeredModel) => ({
  56. id: registeredModel.id,
  57. name: registeredModel.name,
  58. api: registeredModel.api,
  59. reasoning: registeredModel.reasoning,
  60. input: registeredModel.input,
  61. cost: registeredModel.cost,
  62. contextWindow: registeredModel.contextWindow,
  63. maxTokens: registeredModel.maxTokens,
  64. })),
  65. });
  66. extensionFactory(pi);
  67. },
  68. ],
  69. noSkills: true,
  70. noPromptTemplates: true,
  71. noThemes: true,
  72. },
  73. });
  74. return {
  75. ...(await createAgentSessionFromServices({
  76. services,
  77. sessionManager,
  78. sessionStartEvent,
  79. model: faux.getModel(),
  80. })),
  81. services,
  82. diagnostics: services.diagnostics,
  83. };
  84. };
  85. const runtime = await createAgentSessionRuntime(createRuntime, {
  86. cwd: tempDir,
  87. agentDir: tempDir,
  88. sessionManager: SessionManager.create(tempDir),
  89. });
  90. const rebindSession = async (): Promise<void> => {
  91. const session = runtime.session;
  92. await session.bindExtensions({
  93. commandContextActions: {
  94. waitForIdle: () => session.agent.waitForIdle(),
  95. newSession: async (options) => runtime.newSession(options),
  96. fork: async (entryId, options) => {
  97. const result = await runtime.fork(entryId, options);
  98. return { cancelled: result.cancelled };
  99. },
  100. navigateTree: async (targetId, options) => {
  101. const result = await session.navigateTree(targetId, {
  102. summarize: options?.summarize,
  103. customInstructions: options?.customInstructions,
  104. replaceInstructions: options?.replaceInstructions,
  105. label: options?.label,
  106. });
  107. return { cancelled: result.cancelled };
  108. },
  109. switchSession: async (sessionPath, options) => runtime.switchSession(sessionPath, options),
  110. reload: async () => {
  111. await session.reload();
  112. },
  113. },
  114. });
  115. };
  116. runtime.setRebindSession(async () => {
  117. await rebindSession();
  118. });
  119. await rebindSession();
  120. cleanups.push(async () => {
  121. await runtime.dispose();
  122. faux.unregister();
  123. if (existsSync(tempDir)) {
  124. rmSync(tempDir, { recursive: true, force: true });
  125. }
  126. });
  127. return { runtime, faux };
  128. }
  129. it("rebinds before withSession, targets the replacement session, and invalidates stale pi/ctx", async () => {
  130. const events: string[] = [];
  131. let oldCtx: ExtensionCommandContext | undefined;
  132. let oldPi: ExtensionAPI | undefined;
  133. let oldSessionFile: string | undefined;
  134. let staleCtxThrows = false;
  135. let stalePiThrows = false;
  136. let replacementSessionFile: string | undefined;
  137. let instanceId = 0;
  138. const { runtime } = await createRuntimeForTest(
  139. (pi) => {
  140. const currentInstance = ++instanceId;
  141. pi.on("session_start", () => {
  142. events.push(`start:${currentInstance}`);
  143. });
  144. pi.on("session_shutdown", () => {
  145. events.push(`shutdown:${currentInstance}`);
  146. });
  147. pi.registerCommand("repro", {
  148. description: "repro",
  149. handler: async (_args, ctx) => {
  150. oldCtx = ctx;
  151. oldPi = pi;
  152. oldSessionFile = ctx.sessionManager.getSessionFile();
  153. await ctx.newSession({
  154. parentSession: oldSessionFile,
  155. withSession: async (replacedCtx) => {
  156. events.push(`with:${currentInstance}`);
  157. replacementSessionFile = replacedCtx.sessionManager.getSessionFile();
  158. try {
  159. oldCtx?.sessionManager.getSessionFile();
  160. } catch {
  161. staleCtxThrows = true;
  162. }
  163. try {
  164. oldPi?.sendUserMessage("stale message");
  165. } catch {
  166. stalePiThrows = true;
  167. }
  168. await replacedCtx.sendUserMessage("Hello from the new session!");
  169. },
  170. });
  171. },
  172. });
  173. },
  174. ["hello reply"],
  175. );
  176. expect(events).toEqual(["start:1"]);
  177. await runtime.session.prompt("/repro");
  178. expect(events).toEqual(["start:1", "shutdown:1", "start:2", "with:1"]);
  179. expect(replacementSessionFile).toBeDefined();
  180. expect(replacementSessionFile).not.toBe(oldSessionFile);
  181. expect(staleCtxThrows).toBe(true);
  182. expect(stalePiThrows).toBe(true);
  183. expect(runtime.session.messages.map((message) => `${message.role}:${getText(message)}`)).toEqual([
  184. "user:Hello from the new session!",
  185. "assistant:hello reply",
  186. ]);
  187. });
  188. it("supports withSession for fork", async () => {
  189. const { runtime } = await createRuntimeForTest(
  190. (pi) => {
  191. pi.registerCommand("fork-it", {
  192. description: "fork-it",
  193. handler: async (_args, ctx) => {
  194. const leafId = ctx.sessionManager.getLeafId();
  195. if (!leafId) {
  196. throw new Error("Missing leaf id");
  197. }
  198. await ctx.fork(leafId, {
  199. position: "at",
  200. withSession: async (replacedCtx) => {
  201. await replacedCtx.sendUserMessage("fork callback message");
  202. },
  203. });
  204. },
  205. });
  206. },
  207. ["seed reply", "fork reply"],
  208. );
  209. await runtime.session.prompt("seed");
  210. await runtime.session.prompt("/fork-it");
  211. expect(runtime.session.messages.map((message) => `${message.role}:${getText(message)}`)).toEqual([
  212. "user:seed",
  213. "assistant:seed reply",
  214. "user:fork callback message",
  215. "assistant:fork reply",
  216. ]);
  217. });
  218. it("supports withSession for switchSession", async () => {
  219. let targetSessionPath = "";
  220. const { runtime } = await createRuntimeForTest(
  221. (pi) => {
  222. pi.registerCommand("switch-it", {
  223. description: "switch-it",
  224. handler: async (_args, ctx) => {
  225. await ctx.switchSession(targetSessionPath, {
  226. withSession: async (replacedCtx) => {
  227. await replacedCtx.sendUserMessage("switch callback message");
  228. },
  229. });
  230. },
  231. });
  232. },
  233. ["root reply", "target reply", "switch reply"],
  234. );
  235. await runtime.session.prompt("root");
  236. const originalSessionPath = runtime.session.sessionFile;
  237. const newSessionResult = await runtime.newSession();
  238. expect(newSessionResult.cancelled).toBe(false);
  239. await runtime.session.prompt("target");
  240. targetSessionPath = runtime.session.sessionFile!;
  241. await runtime.switchSession(originalSessionPath!);
  242. await runtime.session.prompt("/switch-it");
  243. expect(runtime.session.sessionFile).toBe(targetSessionPath);
  244. expect(runtime.session.messages.map((message) => `${message.role}:${getText(message)}`)).toEqual([
  245. "user:target",
  246. "assistant:target reply",
  247. "user:switch callback message",
  248. "assistant:switch reply",
  249. ]);
  250. });
  251. });