From 21db1260cbfb4265f107f2ba94eeafe0c257f2ef Mon Sep 17 00:00:00 2001 From: Greg Anders Date: Sat, 24 Oct 2026 13:46:48 -0500 Subject: [PATCH] Return workspace sessions to their parent session --- agent/extensions/workspaces/index.ts | 95 ++++++++++++++++--- .../workspaces/test/workspaces.test.ts | 62 +++++++++++- 2 files changed, 138 insertions(+), 19 deletions(-) diff --git a/agent/extensions/workspaces/index.ts b/agent/extensions/workspaces/index.ts index afa2a2f..4cb2f52 100644 --- a/agent/extensions/workspaces/index.ts +++ b/agent/extensions/workspaces/index.ts @@ -1,5 +1,12 @@ -import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; -import { isAbsolute, join, relative, resolve } from "node:path"; +import { + appendFileSync, + existsSync, + readdirSync, + readFileSync, + statSync, + writeFileSync, +} from "node:fs"; +import { basename, isAbsolute, join, relative, resolve } from "node:path"; import { StringEnum } from "@earendil-works/pi-ai"; import { type ExtensionAPI, @@ -63,9 +70,11 @@ interface Repository { } interface Move { target: string; - remove?: string; + remove?: { root: string; path: string }; /** An existing session file to open instead of a fork. */ file?: string; + parent?: string; + workspace?: string; } interface Outcome { move?: Move; @@ -165,12 +174,53 @@ async function create(pi: ExtensionAPI, repo: Repository, target: string, revisi } } +/** The session that this session forked from, if it is in the repository. */ +function parentSession(ctx: ExtensionContext, repo: Repository) { + const file = ctx.sessionManager.getHeader()?.parentSession; + if (!file || !existsSync(file)) { + return undefined; + } + const cwd = SessionManager.open(file).getCwd(); + return isDirectory(cwd) && [repo.main, repo.workspaces].some((dir) => inside(dir, cwd)) + ? { file, cwd } + : undefined; +} + +/** Appends the conversation to `parent`, unless `parent` has entries that this session lacks. */ +function rejoin(ctx: ExtensionCommandContext, parent: string): boolean { + const before = SessionManager.open(parent); + if (!before.getEntries().every((entry) => ctx.sessionManager.getEntry(entry.id))) { + return false; + } + const added = ctx.sessionManager.getEntries().filter((entry) => !before.getEntry(entry.id)); + appendFileSync(parent, added.map((entry) => `${JSON.stringify(entry)}\n`).join("")); + const name = before.getSessionName(); + if (name && ctx.sessionManager.getSessionName()?.endsWith(` [${basename(ctx.cwd)}]`)) { + SessionManager.open(parent).appendSessionInfo(name); + } + return true; +} + /** A session file for `target` that continues the current conversation. */ -function sessionIn(ctx: ExtensionCommandContext, target: string): string | undefined { +function sessionIn( + ctx: ExtensionCommandContext, + target: string, + workspace?: string, +): string | undefined { const file = ctx.sessionManager.getSessionFile(); const dir = ctx.sessionManager.getSessionDir(); if (file && existsSync(file)) { - return SessionManager.forkFrom(file, target, dir).getSessionFile(); + const session = SessionManager.forkFrom(file, target, dir); + const name = ctx.sessionManager.getSessionName(); + if (name) { + const suffix = ` [${basename(ctx.cwd)}]`; + const base = name.endsWith(suffix) ? name.slice(0, -suffix.length) : name; + const next = workspace ? `${base} [${workspace}]` : base; + if (next !== name) { + session.appendSessionInfo(next); + } + } + return session.getSessionFile(); } const session = SessionManager.create(target, dir); const path = session.getSessionFile(); @@ -204,10 +254,11 @@ async function act( ); } } + const workspace = name === MAIN ? undefined : name; if (action === "create") { await create(pi, repo, target, revision); return { - move: { target }, + move: { target, workspace }, message: `Created ${target}. The session moves there after this response.`, }; } @@ -218,15 +269,27 @@ async function act( if (target === ctx.cwd) { throw new Error(`The session is already in ${target}.`); } - return { move: { target }, message: `The session moves to ${target} after this response.` }; + const parent = parentSession(ctx, repo); + return { + move: { target, workspace, parent: parent?.cwd === target ? parent.file : undefined }, + message: `The session moves to ${target} after this response.`, + }; } if (target === repo.main) { throw new Error("The main checkout cannot be removed."); } if (inside(target, ctx.cwd)) { + const parent = parentSession(ctx, repo); + const back = parent && !inside(target, parent.cwd) ? parent : undefined; + const home = back?.cwd ?? repo.main; return { - move: { target: repo.main, remove: target }, - message: `The session moves to ${repo.main} and removes ${target} after this response.`, + move: { + target: home, + remove: { root: repo.main, path: target }, + parent: back?.file, + workspace: home === repo.main ? undefined : basename(home), + }, + message: `The session moves to ${home} and removes ${target} after this response.`, }; } await request(pi, REMOVE_EVENT, { root: repo.main, path: target }); @@ -239,13 +302,17 @@ async function move( step: Move, resume: boolean, ): Promise { - const file = step.file ?? sessionIn(ctx, step.target); + if (step.remove) { + await request(pi, REMOVE_EVENT, step.remove); + } + const file = + step.file ?? + (step.parent && rejoin(ctx, step.parent) + ? step.parent + : sessionIn(ctx, step.target, step.workspace)); if (!file) { throw new Error("This session is not saved, so it cannot move."); } - if (step.remove) { - await request(pi, REMOVE_EVENT, { root: step.target, path: step.remove }); - } await ctx.switchSession(file, { withSession: async (next) => { if (resume) { @@ -258,7 +325,7 @@ async function move( { triggerTurn: true }, ); } else if (step.remove) { - next.ui.notify(`Removed ${step.remove}`, "info"); + next.ui.notify(`Removed ${step.remove.path}`, "info"); } }, }); diff --git a/agent/extensions/workspaces/test/workspaces.test.ts b/agent/extensions/workspaces/test/workspaces.test.ts index 188a2be..4adb5f7 100644 --- a/agent/extensions/workspaces/test/workspaces.test.ts +++ b/agent/extensions/workspaces/test/workspaces.test.ts @@ -140,12 +140,15 @@ function setup( ) => { const session = SessionManager.open(file); log.push(`switch ${session.getCwd()} ${session.getEntries().length}`); + ctx.sessionManager = session; + ctx.cwd = session.getCwd(); await withSession(next); }, }; return { main, log, + ctx, call: async (params: Params) => { assert.ok(tool); return (await tool.execute("call", params, undefined, undefined, ctx)).content[0]?.text; @@ -204,19 +207,68 @@ test("commands use workspace names, and removing the current workspace moves to await assert.rejects(fixture.command("feat"), /Usage/); await fixture.command("switch default"); await fixture.command("switch new"); - await fixture.call({ action: "remove", name: "feat" }); + await fixture.call({ action: "remove", name: "new" }); await fixture.settle(); + const added = join(fixture.main, ".workspaces", "new"); assert.deepEqual(fixture.log, [ `switch ${fixture.main} 0`, - `create ${join(fixture.main, ".workspaces", "new")}`, - `switch ${join(fixture.main, ".workspaces", "new")} 0`, + `create ${added}`, + `switch ${added} 0`, "prompt /workspace", - `remove ${workspace}`, + `remove ${added}`, `switch ${fixture.main} 0`, - `notify Removed ${workspace}`, + `notify Removed ${added}`, ]); }); +test("a workspace session returns its conversation to the parent session", async (t) => { + const fixture = setup(t, { trusted: false, saved: true }); + const { ctx } = fixture; + ctx.sessionManager.appendSessionInfo("Plan"); + const parent = ctx.sessionManager.getSessionFile(); + assert.ok(parent); + const say = (text: string) => + ctx.sessionManager.appendMessage({ role: "user", content: text, timestamp: 3 }); + await fixture.call({ action: "create", name: "feat" }); + await fixture.settle(); + assert.equal(ctx.sessionManager.getSessionName(), "Plan [feat]"); + say("In feat"); + await fixture.call({ action: "switch", name: "default" }); + await fixture.settle(); + assert.equal(ctx.sessionManager.getSessionFile(), parent); + assert.equal(ctx.sessionManager.getSessionName(), "Plan"); + await fixture.call({ action: "switch", name: "feat" }); + await fixture.settle(); + say("Again in feat"); + await fixture.call({ action: "remove", name: "feat" }); + await fixture.settle(); + assert.equal(ctx.sessionManager.getSessionFile(), parent); + assert.deepEqual( + ctx.sessionManager + .getBranch() + .flatMap((entry) => + entry.type === "message" && entry.message.role === "user" + ? [entry.message.content] + : [], + ), + ["Start", "In feat", "Again in feat"], + ); + await fixture.command("switch a"); + const outer = ctx.sessionManager.getSessionFile(); + await fixture.command("switch b"); + await fixture.call({ action: "remove", name: "b" }); + await fixture.settle(); + assert.equal(ctx.sessionManager.getSessionFile(), outer); + assert.equal(ctx.sessionManager.getSessionName(), "Plan [a]"); + await fixture.command("switch default"); + await fixture.command("switch feat"); + say("Elsewhere"); + SessionManager.open(parent).appendSessionInfo("Changed"); + await fixture.command("switch default"); + assert.notEqual(ctx.sessionManager.getSessionFile(), parent); + assert.equal(ctx.sessionManager.getSessionName(), "Plan"); +}); + test("running work blocks agent moves, and the user can cancel the work to move", async (t) => { const fixture = setup(t, { trusted: false, saved: true, busy: "1 subagent", confirm: true }); await assert.rejects( -- knotmirror 0.0.1