diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index e6fe9966910cb..7e353d66dab8d 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Versucht, nach {count} Geheimnis zu fragen} other {Versucht, nach {count} Geheimnissen zu fragen}}", "3685ecb8634fe00c": "{count, plural, one {An {count} Worktree übergeben} other {An {count} Worktrees übergeben}}", "186bc3ed600d2102": "{count, plural, one {Versucht, an {count} Worktree zu übergeben} other {Versucht, an {count} Worktrees zu übergeben}}", + "0166c0dc3f34c937": "{count, plural, one {Freigegeben: {count} Worktree} other {Freigegeben: {count} Worktrees}}", + "8131c8e477f5e30b": "{count, plural, one {Freigabe versucht: {count} Worktree} other {Freigabe versucht: {count} Worktrees}}", "ea38f91437c9fd84": "{count, plural, one {{count} Projekt gelesen} other {{count} Projekte gelesen}}", "962b5c9a64a23fda": "{count, plural, one {Versucht, {count} Projekt zu lesen} other {Versucht, {count} Projekte zu lesen}}", "5f6309ffbb9206e5": "{count, plural, one {{count} Projekt registriert} other {{count} Projekte registriert}}", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 13d1178a1eb5c..71ef9b17450ef 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Tried to ask for {count} secret} other {Tried to ask for {count} secrets}}", "3685ecb8634fe00c": "{count, plural, one {Handed off to {count} worktree} other {Handed off to {count} worktrees}}", "186bc3ed600d2102": "{count, plural, one {Tried to hand off to {count} worktree} other {Tried to hand off to {count} worktrees}}", + "0166c0dc3f34c937": "{count, plural, one {Released {count} worktree} other {Released {count} worktrees}}", + "8131c8e477f5e30b": "{count, plural, one {Tried to release {count} worktree} other {Tried to release {count} worktrees}}", "ea38f91437c9fd84": "{count, plural, one {Read {count} project} other {Read {count} projects}}", "962b5c9a64a23fda": "{count, plural, one {Tried to read {count} project} other {Tried to read {count} projects}}", "5f6309ffbb9206e5": "{count, plural, one {Registered {count} project} other {Registered {count} projects}}", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index b839834f248e0..d38fe7f695a35 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Intentó pedir {count} secreto} other {Intentó pedir {count} secretos}}", "3685ecb8634fe00c": "{count, plural, one {Traspasó a {count} worktree} other {Traspasó a {count} worktrees}}", "186bc3ed600d2102": "{count, plural, one {Intentó traspasar a {count} worktree} other {Intentó traspasar a {count} worktrees}}", + "0166c0dc3f34c937": "{count, plural, one {Liberado: {count} árbol de trabajo} other {Liberado: {count} árboles de trabajo}}", + "8131c8e477f5e30b": "{count, plural, one {Se intentó liberar: {count} árbol de trabajo} other {Se intentó liberar: {count} árboles de trabajo}}", "ea38f91437c9fd84": "{count, plural, one {Leyó {count} proyecto} other {Leyó {count} proyectos}}", "962b5c9a64a23fda": "{count, plural, one {Intentó leer {count} proyecto} other {Intentó leer {count} proyectos}}", "5f6309ffbb9206e5": "{count, plural, one {Registró {count} proyecto} other {Registró {count} proyectos}}", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 8a659455e3b59..3cad1207858ed 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Tentative de demande de {count} secret} other {Tentative de demande de {count} secrets}}", "3685ecb8634fe00c": "{count, plural, one {Transféré vers {count} worktree} other {Transféré vers {count} worktrees}}", "186bc3ed600d2102": "{count, plural, one {Tentative de transfert vers {count} worktree} other {Tentative de transfert vers {count} worktrees}}", + "0166c0dc3f34c937": "{count, plural, one {Libéré : {count} arbre de travail} other {Libéré : {count} arbres de travail}}", + "8131c8e477f5e30b": "{count, plural, one {Tentative de libération : {count} arbre de travail} other {Tentative de libération : {count} arbres de travail}}", "ea38f91437c9fd84": "{count, plural, one {{count} projet lu} other {{count} projets lus}}", "962b5c9a64a23fda": "{count, plural, one {Tentative de lecture de {count} projet} other {Tentative de lecture de {count} projets}}", "5f6309ffbb9206e5": "{count, plural, one {{count} projet enregistré} other {{count} projets enregistrés}}", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index adb255de9dd11..6aeb5a08c8793 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, other {シークレットを {count} 件求めようとしました}}", "3685ecb8634fe00c": "{count, plural, other {{count} 件のワークツリーに引き継ぎました}}", "186bc3ed600d2102": "{count, plural, other {{count} 件のワークツリーに引き継ごうとしました}}", + "0166c0dc3f34c937": "{count, plural, one {解放済み: {count} ワークツリー} other {解放済み: {count} ワークツリー}}", + "8131c8e477f5e30b": "{count, plural, one {解放を試行: {count} ワークツリー} other {解放を試行: {count} ワークツリー}}", "ea38f91437c9fd84": "{count, plural, other {{count} 件のプロジェクトを読み取りました}}", "962b5c9a64a23fda": "{count, plural, other {{count} 件のプロジェクトを読み取ろうとしました}}", "5f6309ffbb9206e5": "{count, plural, other {{count} 件のプロジェクトを登録しました}}", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 0ff760787a094..39222971e50d0 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, other {시크릿 {count}개 요청 시도함}}", "3685ecb8634fe00c": "{count, plural, other {워크트리 {count}개로 넘김}}", "186bc3ed600d2102": "{count, plural, other {워크트리 {count}개로 넘기기 시도함}}", + "0166c0dc3f34c937": "{count, plural, one {해제됨: {count} 작업 트리} other {해제됨: {count} 작업 트리}}", + "8131c8e477f5e30b": "{count, plural, one {해제 시도: {count} 작업 트리} other {해제 시도: {count} 작업 트리}}", "ea38f91437c9fd84": "{count, plural, other {프로젝트 {count}개를 읽음}}", "962b5c9a64a23fda": "{count, plural, other {프로젝트 {count}개 읽기 시도함}}", "5f6309ffbb9206e5": "{count, plural, other {프로젝트 {count}개를 등록함}}", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 66624b02182fc..5db2b556fc034 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Tentou pedir {count} segredo} other {Tentou pedir {count} segredos}}", "3685ecb8634fe00c": "{count, plural, one {Transferiu para {count} worktree} other {Transferiu para {count} worktrees}}", "186bc3ed600d2102": "{count, plural, one {Tentou transferir para {count} worktree} other {Tentou transferir para {count} worktrees}}", + "0166c0dc3f34c937": "{count, plural, one {Liberado: {count} árvore de trabalho} other {Liberado: {count} árvores de trabalho}}", + "8131c8e477f5e30b": "{count, plural, one {Tentativa de liberar: {count} árvore de trabalho} other {Tentativa de liberar: {count} árvores de trabalho}}", "ea38f91437c9fd84": "{count, plural, one {Leu {count} projeto} other {Leu {count} projetos}}", "962b5c9a64a23fda": "{count, plural, one {Tentou ler {count} projeto} other {Tentou ler {count} projetos}}", "5f6309ffbb9206e5": "{count, plural, one {Registrou {count} projeto} other {Registrou {count} projetos}}", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index f3f1fdd012ace..14174fd5c2fa6 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Попытка запросить {count} секрет} few {Попытка запросить {count} секрета} many {Попытка запросить {count} секретов} other {Попытка запросить {count} секрета}}", "3685ecb8634fe00c": "{count, plural, one {Передано в {count} рабочее дерево} few {Передано в {count} рабочих дерева} many {Передано в {count} рабочих деревьев} other {Передано в {count} рабочего дерева}}", "186bc3ed600d2102": "{count, plural, one {Попытка передать в {count} рабочее дерево} few {Попытка передать в {count} рабочих дерева} many {Попытка передать в {count} рабочих деревьев} other {Попытка передать в {count} рабочего дерева}}", + "0166c0dc3f34c937": "{count, plural, one {Освобождено: {count} рабочее дерево} other {Освобождено: {count} рабочих деревьев}}", + "8131c8e477f5e30b": "{count, plural, one {Попытка освободить: {count} рабочее дерево} other {Попытка освободить: {count} рабочих деревьев}}", "ea38f91437c9fd84": "{count, plural, one {Прочитан {count} проект} few {Прочитано {count} проекта} many {Прочитано {count} проектов} other {Прочитано {count} проекта}}", "962b5c9a64a23fda": "{count, plural, one {Попытка прочитать {count} проект} few {Попытка прочитать {count} проекта} many {Попытка прочитать {count} проектов} other {Попытка прочитать {count} проекта}}", "5f6309ffbb9206e5": "{count, plural, one {Зарегистрирован {count} проект} few {Зарегистрировано {count} проекта} many {Зарегистрировано {count} проектов} other {Зарегистрировано {count} проекта}}", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 351210012940e..3a2a345ecf78f 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Försökte be om {count} hemlighet} other {Försökte be om {count} hemligheter}}", "3685ecb8634fe00c": "{count, plural, one {Lämnade över till {count} worktree} other {Lämnade över till {count} worktrees}}", "186bc3ed600d2102": "{count, plural, one {Försökte lämna över till {count} worktree} other {Försökte lämna över till {count} worktrees}}", + "0166c0dc3f34c937": "{count, plural, one {Frigjorde {count} arbetsträd} other {Frigjorde {count} arbetsträd}}", + "8131c8e477f5e30b": "{count, plural, one {Försökte frigöra {count} arbetsträd} other {Försökte frigöra {count} arbetsträd}}", "ea38f91437c9fd84": "{count, plural, one {Läste {count} projekt} other {Läste {count} projekt}}", "962b5c9a64a23fda": "{count, plural, one {Försökte läsa {count} projekt} other {Försökte läsa {count} projekt}}", "5f6309ffbb9206e5": "{count, plural, one {Registrerade {count} projekt} other {Registrerade {count} projekt}}", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 04afa392e5fe2..52db4d53dc34b 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, other {尝试请求 {count} 个凭据}}", "3685ecb8634fe00c": "{count, plural, other {已移交给 {count} 个工作树}}", "186bc3ed600d2102": "{count, plural, other {尝试移交给 {count} 个工作树}}", + "0166c0dc3f34c937": "{count, plural, one {已释放 {count} 工作树} other {已释放 {count} 工作树}}", + "8131c8e477f5e30b": "{count, plural, one {尝试释放 {count} 工作树} other {尝试释放 {count} 工作树}}", "ea38f91437c9fd84": "{count, plural, other {已读取 {count} 个项目}}", "962b5c9a64a23fda": "{count, plural, other {尝试读取 {count} 个项目}}", "5f6309ffbb9206e5": "{count, plural, other {已注册 {count} 个项目}}", diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index b519d7ac09c31..53bd848ba51b5 100644 --- a/apps/server/src/mcp/WorktreeMcpService.test.ts +++ b/apps/server/src/mcp/WorktreeMcpService.test.ts @@ -5,9 +5,11 @@ import { CommandId, EnvironmentId, type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadShell, type Project, ProjectId, ProviderInstanceId, + ProviderSessionId, ThreadId, WorktreeMcpHandoffInput, } from "@t3tools/contracts"; @@ -21,8 +23,10 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ServerConfig from "../config.ts"; import { @@ -79,7 +83,12 @@ const makeProjection = (overrides: ThreadFixture = {}): OrchestrationV2ThreadPro deletedAt: null, ...overrides, }, - }) as OrchestrationV2ThreadProjection; + providerSessions: [ + { + id: ProviderSessionId.make("provider-session-worktree-test"), + }, + ], + }) as unknown as OrchestrationV2ThreadProjection; const project: Project = { id: projectId, @@ -94,6 +103,10 @@ const project: Project = { interface HarnessOptions { readonly git?: Partial; + readonly gitDriver?: Partial; + readonly isLive?: ProviderSessionManager.ProviderSessionManagerV2["Service"]["isLive"]; + readonly otherThreadWorktreePaths?: ReadonlyArray; + readonly onRefreshStatus?: Effect.Effect; readonly thread?: ThreadFixture | null; readonly threadReadError?: "projection" | "dispatch"; readonly capabilities?: ReadonlySet; @@ -119,6 +132,8 @@ interface HarnessOptions { readonly deleteLocalBranchFails?: boolean; readonly createWorktreeGate?: Effect.Effect; readonly existsFails?: boolean; + readonly dirty?: boolean; + readonly project?: Partial; } const makeHarness = (options: HarnessOptions = {}) => { @@ -186,7 +201,7 @@ const makeHarness = (options: HarnessOptions = {}) => { ? (Effect.fail("simulated project read failure") as never) : Effect.succeed( id === projectId && options.projectMissing !== true - ? Option.some(project) + ? Option.some({ ...project, ...options.project }) : Option.none(), ), ); @@ -247,11 +262,13 @@ const makeHarness = (options: HarnessOptions = {}) => { hasPrimaryRemote: true, isDefaultRef: false, refName: options.currentBranch === undefined ? "dev" : options.currentBranch, - hasWorkingTreeChanges: false, + hasWorkingTreeChanges: options.dirty === true, workingTree: { files: [], insertions: 0, deletions: 0 }, }), ); - const refreshStatus = vi.fn((_: string) => Effect.die("refreshStatus stub")); + const refreshStatus = vi.fn((_: string) => + (options.onRefreshStatus ?? Effect.void).pipe(Effect.andThen(Effect.die("refreshStatus stub"))), + ); const runForThread = vi.fn((input: { readonly worktreePath: string }) => { switch (options.setupScript ?? "started") { case "no-script": @@ -284,6 +301,22 @@ const makeHarness = (options: HarnessOptions = {}) => { Layer.mock(ThreadManagementService.ThreadManagementService)({ dispatch, getThreadRecords, + getShellSnapshot: (input) => + Effect.succeed({ + schemaVersion: 1, + snapshotSequence: 1, + threads: (options.otherThreadWorktreePaths ?? []).flatMap((worktreePath, index) => + worktreePath === input?.worktreePath + ? [ + { + id: ThreadId.make(`thread-sharing-${index}`), + worktreePath, + } as OrchestrationV2ThreadShell, + ] + : [], + ), + archivedThreads: [], + }), } satisfies Partial), Layer.mock(ProjectService.ProjectService)({ getById, @@ -310,6 +343,20 @@ const makeHarness = (options: HarnessOptions = {}) => { deleteLocalBranch, ...options.git, } satisfies Partial), + Layer.mock(GitVcsDriver.GitVcsDriver)({ + execute: () => + Effect.succeed({ + exitCode: 0 as GitVcsDriver.ExecuteGitResult["exitCode"], + stdout: "0\n", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }), + ...options.gitDriver, + } satisfies Partial), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ + isLive: options.isLive ?? (() => Effect.succeed(false)), + } satisfies Partial), Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ runForThread, } satisfies Partial), @@ -383,6 +430,15 @@ const runStatus = (harness: ReturnType) => return yield* service.status(harness.scope); }).pipe(Effect.provide(harness.layer)); +const runRelease = ( + harness: ReturnType, + input: Parameters[1] = {}, +) => + Effect.gen(function* () { + const service = yield* WorktreeMcpService.WorktreeMcpService; + return yield* service.release(harness.scope, input); + }).pipe(Effect.provide(harness.layer)); + const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput); describe("t3_worktree_handoff", () => { @@ -687,23 +743,318 @@ describe("t3_worktree_handoff", () => { }); }); -describe("t3_worktree_status", () => { - it.effect("reports an attached thread's worktree and branch", () => { +describe("t3_worktree_release", () => { + const releaseGitLayer = GitVcsDriver.layer.pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "release-git-" })), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); + + // A repository with a pushed main and a worktree on `feature/done` holding one unpushed commit. + const makeReleaseRepo = Effect.fn("makeReleaseRepo")(function* (prefix: string) { + const fs = yield* FileSystem.FileSystem; + const git = yield* GitVcsDriver.GitVcsDriver; + const directory = yield* fs.makeTempDirectoryScoped({ prefix }); + const cwd = `${directory}/repo`; + const remote = `${directory}/remote.git`; + const worktreePath = `${directory}/worktree`; + yield* fs.makeDirectory(cwd); + const command = (at: string, args: string[]) => + git.execute({ operation: "release-test", cwd: at, args }); + yield* command(cwd, ["init", "-b", "main"]); + yield* command(cwd, ["config", "user.name", "Test"]); + yield* command(cwd, ["config", "user.email", "test@example.test"]); + yield* command(cwd, ["commit", "--allow-empty", "-m", "base"]); + yield* command(cwd, ["init", "--bare", remote]); + yield* command(cwd, ["remote", "add", "origin", remote]); + yield* command(cwd, ["push", "-u", "origin", "main"]); + yield* command(cwd, ["worktree", "add", "-b", "feature/done", worktreePath]); + yield* command(worktreePath, ["commit", "--allow-empty", "-m", "work"]); + + const branchDeleted = yield* Deferred.make(); + const removed = yield* Deferred.make(); const harness = makeHarness({ - thread: { - worktreePath: "/worktrees/project/existing", - branch: "feature/existing", + thread: { worktreePath, branch: "feature/done" }, + project: { workspaceRoot: cwd }, + gitDriver: { execute: git.execute }, + git: { + localStatus: () => + Effect.succeed({ + isRepo: true, + hasPrimaryRemote: true, + isDefaultRef: false, + refName: "feature/done", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + }), + removeWorktree: (input) => + git.removeWorktree(input).pipe(Effect.ensuring(Deferred.succeed(removed, undefined))), + deleteLocalBranch: (input) => + git + .deleteLocalBranch(input) + .pipe(Effect.ensuring(Deferred.succeed(branchDeleted, undefined))), }, - projectNewWorktreesStartFromOrigin: true, }); + return { fs, cwd, worktreePath, command, harness, branchDeleted, removed }; + }); + + it.effect("refuses unpushed commits, then removes the worktree and branch once pushed", () => + Effect.gen(function* () { + const { fs, cwd, worktreePath, command, harness, branchDeleted } = + yield* makeReleaseRepo("release-unpushed-"); + + const refused = yield* Effect.exit(runRelease(harness, { deleteBranch: true })); + expectTypedFailure(refused, { _tag: "WorktreeMcpFailure", code: "unsaved_work" }); + expect(harness.dispatch).not.toHaveBeenCalled(); + + yield* command(worktreePath, ["push", "-u", "origin", "feature/done"]); + const result = yield* runRelease(harness, { deleteBranch: true }); + expect(result).toMatchObject({ worktreePath, branch: "feature/done", removal: "scheduled" }); + expect(harness.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ + type: "thread.metadata.update", + worktreePath: null, + branch: null, + expectedWorktreePath: worktreePath, + }), + ); + + yield* Deferred.await(branchDeleted); + expect(yield* fs.exists(worktreePath)).toBe(false); + expect((yield* command(cwd, ["branch", "--list", "feature/done"])).stdout).toBe(""); + }).pipe(Effect.scoped, Effect.provide(releaseGitLayer)), + ); + + it.effect("keeps an unpushed branch whose worktree folder is already gone", () => + Effect.gen(function* () { + const { cwd, worktreePath, command, harness, removed } = + yield* makeReleaseRepo("release-gone-"); + yield* command(cwd, ["worktree", "remove", "--force", worktreePath]); + + const refused = yield* Effect.exit(runRelease(harness, { deleteBranch: true })); + expectTypedFailure(refused, { _tag: "WorktreeMcpFailure", code: "unsaved_work" }); + expect(harness.dispatch).not.toHaveBeenCalled(); + + const released = yield* runRelease(harness); + expect(released.removal).toBe("already-gone"); + yield* Deferred.await(removed); + expect((yield* command(cwd, ["branch", "--list", "feature/done"])).stdout).not.toBe(""); + }).pipe(Effect.scoped, Effect.provide(releaseGitLayer)), + ); + + it.effect("fails closed when git's commit count is unreadable", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-count-" }); + for (const exitCode of [0, 1]) { + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/done" }, + gitDriver: { + execute: () => + Effect.succeed({ + exitCode: exitCode as GitVcsDriver.ExecuteGitResult["exitCode"], + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }), + }, + }); + + const exit = yield* Effect.exit(runRelease(harness)); + expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); + expect(harness.dispatch).not.toHaveBeenCalled(); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("waits for the caller's provider session to exit before removing", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-session-" }); + const firstCheck = yield* Deferred.make(); + const removed = yield* Deferred.make(); + let liveChecks = 0; + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/done" }, + isLive: () => Deferred.succeed(firstCheck, undefined).pipe(Effect.as(++liveChecks === 1)), + git: { + removeWorktree: () => Deferred.succeed(removed, undefined).pipe(Effect.asVoid), + }, + }); + + yield* runRelease(harness); + yield* Deferred.await(firstCheck); + expect(yield* Deferred.isDone(removed)).toBe(false); + + yield* TestClock.adjust("2 seconds"); + yield* Deferred.await(removed); + expect(liveChecks).toBe(2); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("retries a removal that the folder's last process briefly blocks", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-busy-" }); + const firstAttempt = yield* Deferred.make(); + const removed = yield* Deferred.make(); + let attempts = 0; + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/done" }, + git: { + removeWorktree: () => + Effect.suspend(() => + ++attempts === 1 + ? Deferred.succeed(firstAttempt, undefined).pipe( + Effect.andThen(Effect.fail("EBUSY" as never)), + ) + : Deferred.succeed(removed, undefined).pipe(Effect.asVoid), + ), + }, + }); + + yield* runRelease(harness); + yield* Deferred.await(firstAttempt); + yield* TestClock.adjust("2 seconds"); + yield* Deferred.await(removed); + expect(attempts).toBe(2); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("refuses uncommitted changes unless forced", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-dirty-" }); + const removed = yield* Deferred.make(); + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/dirty" }, + dirty: true, + git: { + removeWorktree: (input) => Deferred.succeed(removed, input).pipe(Effect.asVoid), + }, + }); + + const refused = yield* Effect.exit(runRelease(harness)); + expectTypedFailure(refused, { _tag: "WorktreeMcpFailure", code: "unsaved_work" }); + expect(harness.dispatch).not.toHaveBeenCalled(); + + yield* runRelease(harness, { force: true }); + expect(yield* Deferred.await(removed)).toMatchObject({ path: worktreePath, force: true }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("keeps a worktree that another thread still uses", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-shared-" }); + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/shared" }, + otherThreadWorktreePaths: [worktreePath], + dirty: true, + }); + + const result = yield* runRelease(harness); + expect(result.removal).toBe("kept-shared"); + expect(harness.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ worktreePath: null }), + ); + expect(harness.localStatus).not.toHaveBeenCalled(); + expect(harness.removeWorktree).not.toHaveBeenCalled(); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("keeps a worktree another thread binds to between removal attempts", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "release-rebound-" }); + const sharingPaths: Array = []; + let attempts = 0; + const firstAttempt = yield* Deferred.make(); + const refreshed = yield* Deferred.make(); + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/rebound" }, + otherThreadWorktreePaths: sharingPaths, + git: { + removeWorktree: () => + Effect.suspend(() => { + attempts++; + sharingPaths.push(worktreePath); + return Deferred.succeed(firstAttempt, undefined).pipe( + Effect.andThen(Effect.fail("EBUSY" as never)), + ); + }), + }, + onRefreshStatus: Deferred.succeed(refreshed, undefined).pipe(Effect.asVoid), + }); + + const result = yield* runRelease(harness, { deleteBranch: true }); + expect(result.removal).toBe("scheduled"); + yield* Deferred.await(firstAttempt); + yield* TestClock.adjust("2 seconds"); + yield* Deferred.await(refreshed); + expect(attempts).toBe(1); + expect(harness.deleteLocalBranch).not.toHaveBeenCalled(); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("clears the binding of a worktree whose folder is already gone", () => + Effect.gen(function* () { + const removed = yield* Deferred.make(); + const harness = makeHarness({ + thread: { worktreePath: "/worktrees/project/removed-by-hand", branch: "feature/gone" }, + git: { + removeWorktree: () => Deferred.succeed(removed, undefined).pipe(Effect.asVoid), + }, + }); + + const result = yield* runRelease(harness); + expect(result.removal).toBe("already-gone"); + expect(harness.localStatus).not.toHaveBeenCalled(); + expect(harness.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ worktreePath: null, branch: null }), + ); + // Git still holds the worktree's metadata; removal prunes it. + yield* Deferred.await(removed); + }), + ); + + it.effect("fails when the thread has no worktree", () => { + const harness = makeHarness(); return Effect.gen(function* () { + const exit = yield* Effect.exit(runRelease(harness)); + expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "not_in_worktree" }); + expect(harness.dispatch).not.toHaveBeenCalled(); + }); + }); +}); + +describe("t3_worktree_status", () => { + it.effect("reports an attached thread's worktree and branch", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const worktreePath = yield* fs.makeTempDirectoryScoped({ prefix: "worktree-status-" }); + const harness = makeHarness({ + thread: { worktreePath, branch: "feature/existing" }, + projectNewWorktreesStartFromOrigin: true, + }); const result = yield* runStatus(harness); expect(result).toMatchObject({ attached: true, - worktreePath: "/worktrees/project/existing", + worktreePath, + missing: false, branch: "feature/existing", defaultStartFromOrigin: true, }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("reports a bound worktree whose folder is gone as missing", () => { + const harness = makeHarness({ + thread: { worktreePath: "/worktrees/project/removed-by-hand", branch: "feature/gone" }, + }); + return Effect.gen(function* () { + const result = yield* runStatus(harness); + expect(result).toMatchObject({ attached: true, missing: true }); }); }); }); diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index 92582b24efd68..a34a860a0e734 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -4,10 +4,13 @@ import { type TaskFolderError, MessageId, type ProjectId, + type ProviderSessionId, WorktreeMcpFailure, type WorktreeMcpContinuationStatus, type WorktreeMcpHandoffInput, type WorktreeMcpHandoffResult, + type WorktreeMcpReleaseInput, + type WorktreeMcpReleaseResult, type WorktreeMcpSetupScriptStatus, type WorktreeMcpStatusResult, type VcsListRefsInput, @@ -22,12 +25,15 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import type * as PlatformError from "effect/PlatformError"; +import * as Schedule from "effect/Schedule"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ServerSettings from "../serverSettings.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts"; import * as TaskFolders from "../workspace/TaskFolders.ts"; import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts"; @@ -39,6 +45,10 @@ export class WorktreeMcpService extends Context.Service< scope: McpInvocationScope, input: WorktreeMcpHandoffInput, ) => Effect.Effect; + readonly release: ( + scope: McpInvocationScope, + input: WorktreeMcpReleaseInput, + ) => Effect.Effect; readonly status: ( scope: McpInvocationScope, ) => Effect.Effect; @@ -68,6 +78,9 @@ const asOperationFailed = (prefix: string) => failure("operation_failed", `${prefix}: ${errorMessage(error)}`), ); +// Covers a provider session that takes a while to exit, and Windows processes that briefly hold the folder. +const RELEASE_RETRY = { times: 60, schedule: Schedule.spaced("2 seconds") } as const; + const make = Effect.gen(function* () { const random = yield* SecureRandom.SecureRandom; const fileSystem = yield* FileSystem.FileSystem; @@ -75,21 +88,23 @@ const make = Effect.gen(function* () { const projects = yield* ProjectService.ProjectService; const serverSettings = yield* ServerSettings.ServerSettingsService; const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + const gitDriver = yield* GitVcsDriver.GitVcsDriver; + const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; const taskFolders = yield* TaskFolders.TaskFolders; // The administrator's limit, fixed for the server's life as it is where turns start. const maxRuntimeMode = serverSettings.managedPolicy?.limits?.maxRuntimeMode; - // Serialize handoffs per thread to avoid creating two worktrees and orphaning one. - const handoffThreadsInFlight = new Set(); + // Serialize handoffs and releases per thread to avoid creating two worktrees and orphaning one. + const threadsInFlight = new Set(); const requireThreadScope = (scope: McpInvocationScope) => scope.thread === undefined ? Effect.fail( failure( "thread_credential_required", - "Worktree handoff and status act as the calling T3 thread, so they need an agent running inside T3 Code.", + "Worktree handoff, release, and status act as the calling T3 thread, so they need an agent running inside T3 Code.", ), ) : Effect.succeed(scope as McpThreadInvocationScope); @@ -101,8 +116,11 @@ const make = Effect.gen(function* () { failure("capability_denied", "This MCP credential does not grant worktree capabilities."), ); - const loadThread = (scope: McpThreadInvocationScope) => - threadManagement.getThreadRecords(scope.thread.threadId, []).pipe( + const loadThread = ( + scope: McpThreadInvocationScope, + fields: ReadonlyArray<"providerSessions"> = [], + ) => + threadManagement.getThreadRecords(scope.thread.threadId, fields).pipe( Effect.mapError((error) => error._tag === "OrchestratorProjectionError" ? failure("thread_not_found", `Thread '${scope.thread.threadId}' was not found.`) @@ -476,25 +494,254 @@ const make = Effect.gen(function* () { function* (callerScope, input) { yield* requireCapability(callerScope); const scope = yield* requireThreadScope(callerScope); - // Acquire and register cleanup atomically so cancellation cannot strand the guard until restart. - return yield* Effect.uninterruptibleMask((restore) => - Effect.suspend(() => { - if (handoffThreadsInFlight.has(scope.thread.threadId)) { - return Effect.fail( - failure( - "handoff_in_progress", - `A worktree handoff is already in progress for thread '${scope.thread.threadId}'.`, - ), - ); - } - handoffThreadsInFlight.add(scope.thread.threadId); - return restore(performHandoff(scope, input)).pipe( - Effect.ensuring( - Effect.sync(() => handoffThreadsInFlight.delete(scope.thread.threadId)), + return yield* exclusive(scope, performHandoff(scope, input)); + }, + ); + + // Acquire and register cleanup atomically so cancellation cannot strand the guard until restart. + const exclusive = ( + scope: McpThreadInvocationScope, + effect: Effect.Effect, + ): Effect.Effect => + Effect.uninterruptibleMask((restore) => + Effect.suspend(() => { + if (threadsInFlight.has(scope.thread.threadId)) { + return Effect.fail( + failure( + "handoff_in_progress", + `A worktree handoff or release is already in progress for thread '${scope.thread.threadId}'.`, ), ); - }), + } + threadsInFlight.add(scope.thread.threadId); + return restore(effect).pipe( + Effect.ensuring(Effect.sync(() => threadsInFlight.delete(scope.thread.threadId))), + ); + }), + ); + + // Runs detached: the binding change ends the caller's session, and on Windows its process holds the folder until it exits. + const removeReleasedWorktree = Effect.fn("WorktreeMcpService.removeReleasedWorktree")( + function* (input: { + readonly projectCwd: string; + readonly worktreePath: string; + readonly branch: string | null; + readonly providerSessionIds: ReadonlyArray; + readonly force: boolean; + readonly deleteBranch: boolean; + }) { + // Removal still runs if a session outlasts the wait; its own retries cover a brief hold. + yield* Effect.forEach(input.providerSessionIds, providerSessions.isLive).pipe( + Effect.filterOrFail( + (live) => !live.includes(true), + () => "provider session is still open", + ), + Effect.retry(RELEASE_RETRY), + Effect.ignore, + ); + // A thread can bind to the worktree while removal waits or retries; this one's binding is already cleared. + const removed = yield* Effect.suspend(() => + threadManagement.getShellSnapshot({ worktreePath: input.worktreePath }), + ).pipe( + Effect.flatMap((sharing) => + sharing.threads.length + sharing.archivedThreads.length > 0 + ? Effect.succeed(false) + : gitWorkflow + .removeWorktree({ + cwd: input.projectCwd, + path: input.worktreePath, + force: input.force, + }) + .pipe(Effect.as(true)), + ), + Effect.retry(RELEASE_RETRY), ); + if (removed && input.deleteBranch && input.branch !== null) { + yield* gitWorkflow.deleteLocalBranch({ + cwd: input.projectCwd, + refName: input.branch, + force: true, + }); + } + yield* vcsStatusBroadcaster + .refreshStatus(input.projectCwd) + .pipe(Effect.ignoreCause({ log: true })); + }, + (effect, input) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logWarning("worktree release could not remove the worktree", { + worktreePath: input.worktreePath, + detail: errorMessage(Cause.squash(cause)), + }), + ), + ), + ); + + const performRelease = Effect.fn("WorktreeMcpService.performRelease")(function* ( + scope: McpThreadInvocationScope, + input: WorktreeMcpReleaseInput, + ) { + const projection = yield* loadThread(scope, ["providerSessions"]); + const worktreePath = projection.thread.worktreePath; + if (worktreePath === null) { + return yield* failure( + "not_in_worktree", + `Thread '${scope.thread.threadId}' is not attached to a worktree.`, + ); + } + const project = yield* loadProject(scope, projection.thread.projectId); + const projectCwd = project.workspaceRoot; + if (worktreePath === projectCwd) { + return yield* failure( + "invalid_request", + `Thread '${scope.thread.threadId}' runs in the project root, not a separate worktree.`, + ); + } + const force = input.force === true; + const exists = yield* fileSystem + .exists(worktreePath) + .pipe(asOperationFailed("Unable to check the worktree folder")); + // Subagents, side chats, and archived threads can share the checkout. + const sharing = yield* threadManagement + .getShellSnapshot({ worktreePath }) + .pipe(asOperationFailed("Unable to list threads using the worktree")); + const sharedWith = [...sharing.threads, ...sharing.archivedThreads].filter( + (thread) => thread.id !== scope.thread.threadId, + ).length; + + // Commits `revision` reaches that no remote and no other local branch does; null when it does not resolve. + const countUnpushed = (cwd: string, revision: string, ownBranch: string | null) => + gitDriver + .execute({ + operation: "WorktreeMcpService.countUnpushedCommits", + cwd, + args: [ + "rev-list", + "--count", + revision, + "--not", + ...(ownBranch === null ? [] : [`--exclude=${ownBranch}`]), + "--branches", + "--remotes", + ], + allowNonZeroExit: true, + }) + .pipe( + asOperationFailed("Unable to count unpushed commits"), + Effect.flatMap((result) => { + if (result.exitCode !== 0) return Effect.succeed(null); + const output = result.stdout.trim(); + return /^\d+$/.test(output) + ? Effect.succeed(Number(output)) + : Effect.fail( + failure( + "operation_failed", + "Unable to count unpushed commits: unexpected output.", + ), + ); + }), + ); + const refuseUnpushed = (count: number | null, where: string) => + count !== null && count > 0 + ? Effect.fail( + failure( + "unsaved_work", + `${where} has ${count} commit${count === 1 ? "" : "s"} on no remote or other branch. Push them, or pass force: true to discard them.`, + ), + ) + : Effect.void; + + let branch = projection.thread.branch; + if (exists && sharedWith === 0) { + const status = yield* gitWorkflow + .localStatus({ cwd: worktreePath }) + .pipe(asOperationFailed("Unable to read the worktree's git status")); + branch = status.refName ?? branch; + if (!force && status.hasWorkingTreeChanges) { + return yield* failure( + "unsaved_work", + `Worktree '${worktreePath}' has uncommitted changes. Commit and push them, or pass force: true to discard them.`, + ); + } + if (!force) { + const unpushed = yield* countUnpushed(worktreePath, "HEAD", status.refName); + if (unpushed === null) { + return yield* failure("operation_failed", "Unable to count unpushed commits for HEAD."); + } + yield* refuseUnpushed(unpushed, `Worktree '${worktreePath}'`); + } + } + + // The branch can hold commits HEAD does not: a detached HEAD, or a folder already gone. + let deleteBranch = input.deleteBranch === true && branch !== null && sharedWith === 0; + if (deleteBranch && branch !== null && !force) { + const unpushed = yield* countUnpushed(projectCwd, `refs/heads/${branch}`, branch); + if (unpushed === null) deleteBranch = false; + yield* refuseUnpushed(unpushed, `Branch '${branch}'`); + } + + const commandId = yield* random.uuidV4().pipe( + Effect.map((uuid) => + CommandId.make( + [ + "command", + "mcp", + encodeURIComponent(scope.thread.providerSessionId), + "worktree-release", + uuid, + ].join(":"), + ), + ), + Effect.orDie, + ); + const removal: WorktreeMcpReleaseResult["removal"] = + sharedWith > 0 ? "kept-shared" : exists ? "scheduled" : "already-gone"; + + // The binding change detaches the caller, so schedule removal in the same uninterruptible step. + return yield* Effect.uninterruptible( + Effect.gen(function* () { + // Clearing the binding also stops the next turn from recreating the checkout. + yield* threadManagement + .dispatch({ + type: "thread.metadata.update", + commandId, + threadId: scope.thread.threadId, + branch: null, + worktreePath: null, + expectedWorktreePath: worktreePath, + }) + .pipe(asOperationFailed("Unable to re-point the thread at the project root")); + if (removal !== "kept-shared") { + // A folder already gone can still leave Git metadata to prune and a branch to delete. + yield* removeReleasedWorktree({ + projectCwd, + worktreePath, + branch, + providerSessionIds: projection.providerSessions.map((session) => session.id), + force, + deleteBranch, + }).pipe(Effect.forkDetach); + } + const result: WorktreeMcpReleaseResult = { + worktreePath, + branch, + removal, + note: + removal === "kept-shared" + ? `Released. The thread now runs in the project root and this session ends shortly after this call. The worktree stays because ${sharedWith} other thread${sharedWith === 1 ? " uses" : "s use"} it.` + : "Released. The thread now runs in the project root and this session ends shortly after this call. T3 removes the worktree once the session has left it. A folder it cannot remove shows up in the storage cleanup report.", + }; + return result; + }), + ); + }); + + const release: WorktreeMcpService["Service"]["release"] = Effect.fn("WorktreeMcpService.release")( + function* (callerScope, input) { + yield* requireCapability(callerScope); + const scope = yield* requireThreadScope(callerScope); + return yield* exclusive(scope, performRelease(scope, input)); }, ); @@ -507,9 +754,16 @@ const make = Effect.gen(function* () { const defaultStartFromOrigin = yield* readDefaultStartFromOrigin(project.id); + // Storage cleanup and manual removal leave the binding behind. + const worktreePath = projection.thread.worktreePath; + const missing = + worktreePath !== null && + !(yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => true))); + const result: WorktreeMcpStatusResult = { - attached: projection.thread.worktreePath !== null, - worktreePath: projection.thread.worktreePath, + attached: worktreePath !== null, + worktreePath, + missing, branch: projection.thread.branch, projectWorkspaceRoot: project.workspaceRoot, defaultStartFromOrigin, @@ -529,7 +783,7 @@ const make = Effect.gen(function* () { return yield* gitWorkflow.listRefs({ ...refs, cwd }); }); - return WorktreeMcpService.of({ handoff, status, listRefs }); + return WorktreeMcpService.of({ handoff, release, status, listRefs }); }); export const layer: Layer.Layer< @@ -541,6 +795,8 @@ export const layer: Layer.Layer< | ProjectService.ProjectService | ServerSettings.ServerSettingsService | GitWorkflowService.GitWorkflowService + | GitVcsDriver.GitVcsDriver + | ProviderSessionManager.ProviderSessionManagerV2 | ProjectSetupScriptRunner.ProjectSetupScriptRunner | VcsStatusBroadcaster.VcsStatusBroadcaster | TaskFolders.TaskFolders diff --git a/apps/server/src/mcp/toolkits/worktree/handlers.test.ts b/apps/server/src/mcp/toolkits/worktree/handlers.test.ts index 1f5aa888ed763..a40cf9db86f93 100644 --- a/apps/server/src/mcp/toolkits/worktree/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/worktree/handlers.test.ts @@ -22,6 +22,7 @@ import * as Stream from "effect/Stream"; import * as ServerConfig from "../../../config.ts"; import * as GitWorkflowService from "../../../git/GitWorkflowService.ts"; +import * as ProviderSessionManager from "../../../orchestration-v2/ProviderSessionManager.ts"; import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "../../../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../../../project/ProjectSetupScriptRunner.ts"; @@ -147,6 +148,7 @@ const handoffFrom = ( Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({ refreshStatus: () => Effect.die("unused"), }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}), ServerSettings.layerTest({}, managedPolicy), ), ), diff --git a/apps/server/src/mcp/toolkits/worktree/handlers.ts b/apps/server/src/mcp/toolkits/worktree/handlers.ts index 2e78dd2a4f996..a178d99f032d6 100644 --- a/apps/server/src/mcp/toolkits/worktree/handlers.ts +++ b/apps/server/src/mcp/toolkits/worktree/handlers.ts @@ -46,6 +46,13 @@ const handlers = { return yield* service.handoff(scope, input); }), ), + t3_worktree_release: McpToolAccess.actsAsCaller((input) => + Effect.gen(function* () { + const scope = yield* McpInvocationContext.McpInvocationContext; + const service = yield* WorktreeMcpService.WorktreeMcpService; + return yield* service.release(scope, input); + }), + ), t3_worktree_status: McpToolAccess.readsAsCaller(() => Effect.gen(function* () { const scope = yield* McpInvocationContext.McpInvocationContext; diff --git a/apps/server/src/mcp/toolkits/worktree/tools.ts b/apps/server/src/mcp/toolkits/worktree/tools.ts index ce9dd39f7938f..e0e962dc400ce 100644 --- a/apps/server/src/mcp/toolkits/worktree/tools.ts +++ b/apps/server/src/mcp/toolkits/worktree/tools.ts @@ -6,6 +6,8 @@ import { VcsListRefsResult, WorktreeMcpHandoffInput, WorktreeMcpHandoffResult, + WorktreeMcpReleaseInput, + WorktreeMcpReleaseResult, WorktreeMcpStatusResult, ThreadId, } from "@t3tools/contracts"; @@ -41,6 +43,22 @@ const WorktreeHandoffTool = Tool.make("t3_worktree_handoff", { .annotate(Tool.OpenWorld, true) .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); +const WorktreeReleaseTool = Tool.make("t3_worktree_release", { + description: + "Remove THIS thread's worktree once its work is done, e.g. PR merged. Never `git worktree remove` it yourself. Moves the thread to the project root; T3 deletes the folder after the session ends. Refuses unsaved or unpushed work unless `force`. Call last in your turn.", + parameters: WorktreeMcpReleaseInput, + success: WorktreeMcpReleaseResult, + failure: WorktreeToolFailure, + failureMode: "return", + dependencies, +}) + .annotate(Tool.Title, "Release thread's git worktree") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, true) + .annotate(Tool.Idempotent, false) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + const WorktreeStatusTool = Tool.make("t3_worktree_status", { description: "Report this thread's worktree: attached or not, path, branch, project root, and the `startFromOrigin` default. Check before `t3_worktree_handoff`.", @@ -86,6 +104,7 @@ const WorktreeListTool = Tool.make("t3_worktree_list", { .annotate(Tool.Destructive, false); export const WorktreeToolkit = Toolkit.make( WorktreeHandoffTool, + WorktreeReleaseTool, WorktreeStatusTool, WorktreeListTool, ); diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index ad8593c387528..7c50cbb64b753 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -24,6 +24,7 @@ import { } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts"; import { ProviderAdapterRegistryV2 } from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import { ProviderSessionManagerV2 } from "../orchestration-v2/ProviderSessionManager.ts"; import { ThreadIssueService } from "../orchestration-v2/ThreadIssueService.ts"; import { ThreadLaunchService } from "../orchestration-v2/ThreadLaunchService.ts"; import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts"; @@ -80,6 +81,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(ProjectCloneTracker)({}), Layer.mock(ProjectService)({}), Layer.mock(ProjectSetupScriptRunner)({}), + Layer.mock(ProviderSessionManagerV2)({}), Layer.mock(ProviderAdapterRegistryV2)({}), Layer.mock(ProviderRegistry)({}), Layer.mock(PullRequestReviewGuideService)({}), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 6ee87b39f01a3..c05d71421b882 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 62140 + "mcpToolListJsonBytes": 62659 } diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 06bd369d39064..08884cb38ba4d 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Versucht, nach {count} Geheimnis zu fragen} other {Versucht, nach {count} Geheimnissen zu fragen}}", "3685ecb8634fe00c": "{count, plural, one {An {count} Worktree übergeben} other {An {count} Worktrees übergeben}}", "186bc3ed600d2102": "{count, plural, one {Versucht, an {count} Worktree zu übergeben} other {Versucht, an {count} Worktrees zu übergeben}}", + "0166c0dc3f34c937": "{count, plural, one {Freigegeben: {count} Worktree} other {Freigegeben: {count} Worktrees}}", + "8131c8e477f5e30b": "{count, plural, one {Freigabe versucht: {count} Worktree} other {Freigabe versucht: {count} Worktrees}}", "ea38f91437c9fd84": "{count, plural, one {{count} Projekt gelesen} other {{count} Projekte gelesen}}", "962b5c9a64a23fda": "{count, plural, one {Versucht, {count} Projekt zu lesen} other {Versucht, {count} Projekte zu lesen}}", "5f6309ffbb9206e5": "{count, plural, one {{count} Projekt registriert} other {{count} Projekte registriert}}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index f7486d132c4ea..2b8d9235ef80b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Tried to ask for {count} secret} other {Tried to ask for {count} secrets}}", "3685ecb8634fe00c": "{count, plural, one {Handed off to {count} worktree} other {Handed off to {count} worktrees}}", "186bc3ed600d2102": "{count, plural, one {Tried to hand off to {count} worktree} other {Tried to hand off to {count} worktrees}}", + "0166c0dc3f34c937": "{count, plural, one {Released {count} worktree} other {Released {count} worktrees}}", + "8131c8e477f5e30b": "{count, plural, one {Tried to release {count} worktree} other {Tried to release {count} worktrees}}", "ea38f91437c9fd84": "{count, plural, one {Read {count} project} other {Read {count} projects}}", "962b5c9a64a23fda": "{count, plural, one {Tried to read {count} project} other {Tried to read {count} projects}}", "5f6309ffbb9206e5": "{count, plural, one {Registered {count} project} other {Registered {count} projects}}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 8701815c57ac0..efcb1102f359f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Intentó pedir {count} secreto} other {Intentó pedir {count} secretos}}", "3685ecb8634fe00c": "{count, plural, one {Traspasó a {count} worktree} other {Traspasó a {count} worktrees}}", "186bc3ed600d2102": "{count, plural, one {Intentó traspasar a {count} worktree} other {Intentó traspasar a {count} worktrees}}", + "0166c0dc3f34c937": "{count, plural, one {Liberado: {count} árbol de trabajo} other {Liberado: {count} árboles de trabajo}}", + "8131c8e477f5e30b": "{count, plural, one {Se intentó liberar: {count} árbol de trabajo} other {Se intentó liberar: {count} árboles de trabajo}}", "ea38f91437c9fd84": "{count, plural, one {Leyó {count} proyecto} other {Leyó {count} proyectos}}", "962b5c9a64a23fda": "{count, plural, one {Intentó leer {count} proyecto} other {Intentó leer {count} proyectos}}", "5f6309ffbb9206e5": "{count, plural, one {Registró {count} proyecto} other {Registró {count} proyectos}}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 96ca7093de334..a62b6f55432bd 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Tentative de demande de {count} secret} other {Tentative de demande de {count} secrets}}", "3685ecb8634fe00c": "{count, plural, one {Transféré vers {count} worktree} other {Transféré vers {count} worktrees}}", "186bc3ed600d2102": "{count, plural, one {Tentative de transfert vers {count} worktree} other {Tentative de transfert vers {count} worktrees}}", + "0166c0dc3f34c937": "{count, plural, one {Libéré : {count} arbre de travail} other {Libéré : {count} arbres de travail}}", + "8131c8e477f5e30b": "{count, plural, one {Tentative de libération : {count} arbre de travail} other {Tentative de libération : {count} arbres de travail}}", "ea38f91437c9fd84": "{count, plural, one {{count} projet lu} other {{count} projets lus}}", "962b5c9a64a23fda": "{count, plural, one {Tentative de lecture de {count} projet} other {Tentative de lecture de {count} projets}}", "5f6309ffbb9206e5": "{count, plural, one {{count} projet enregistré} other {{count} projets enregistrés}}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 9ddfed0d27fc6..79b0a003399b6 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, other {シークレットを {count} 件求めようとしました}}", "3685ecb8634fe00c": "{count, plural, other {{count} 件のワークツリーに引き継ぎました}}", "186bc3ed600d2102": "{count, plural, other {{count} 件のワークツリーに引き継ごうとしました}}", + "0166c0dc3f34c937": "{count, plural, one {解放済み: {count} ワークツリー} other {解放済み: {count} ワークツリー}}", + "8131c8e477f5e30b": "{count, plural, one {解放を試行: {count} ワークツリー} other {解放を試行: {count} ワークツリー}}", "ea38f91437c9fd84": "{count, plural, other {{count} 件のプロジェクトを読み取りました}}", "962b5c9a64a23fda": "{count, plural, other {{count} 件のプロジェクトを読み取ろうとしました}}", "5f6309ffbb9206e5": "{count, plural, other {{count} 件のプロジェクトを登録しました}}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 5425f800e7afd..936a2facbc7ba 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, other {시크릿 {count}개 요청 시도함}}", "3685ecb8634fe00c": "{count, plural, other {워크트리 {count}개로 넘김}}", "186bc3ed600d2102": "{count, plural, other {워크트리 {count}개로 넘기기 시도함}}", + "0166c0dc3f34c937": "{count, plural, one {해제됨: {count} 작업 트리} other {해제됨: {count} 작업 트리}}", + "8131c8e477f5e30b": "{count, plural, one {해제 시도: {count} 작업 트리} other {해제 시도: {count} 작업 트리}}", "ea38f91437c9fd84": "{count, plural, other {프로젝트 {count}개를 읽음}}", "962b5c9a64a23fda": "{count, plural, other {프로젝트 {count}개 읽기 시도함}}", "5f6309ffbb9206e5": "{count, plural, other {프로젝트 {count}개를 등록함}}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 48bf29a05fe38..b7c4b274bd437 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Tentou pedir {count} segredo} other {Tentou pedir {count} segredos}}", "3685ecb8634fe00c": "{count, plural, one {Transferiu para {count} worktree} other {Transferiu para {count} worktrees}}", "186bc3ed600d2102": "{count, plural, one {Tentou transferir para {count} worktree} other {Tentou transferir para {count} worktrees}}", + "0166c0dc3f34c937": "{count, plural, one {Liberado: {count} árvore de trabalho} other {Liberado: {count} árvores de trabalho}}", + "8131c8e477f5e30b": "{count, plural, one {Tentativa de liberar: {count} árvore de trabalho} other {Tentativa de liberar: {count} árvores de trabalho}}", "ea38f91437c9fd84": "{count, plural, one {Leu {count} projeto} other {Leu {count} projetos}}", "962b5c9a64a23fda": "{count, plural, one {Tentou ler {count} projeto} other {Tentou ler {count} projetos}}", "5f6309ffbb9206e5": "{count, plural, one {Registrou {count} projeto} other {Registrou {count} projetos}}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 8e290bcc070fd..e990fff81f448 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Попытка запросить {count} секрет} few {Попытка запросить {count} секрета} many {Попытка запросить {count} секретов} other {Попытка запросить {count} секрета}}", "3685ecb8634fe00c": "{count, plural, one {Передано в {count} рабочее дерево} few {Передано в {count} рабочих дерева} many {Передано в {count} рабочих деревьев} other {Передано в {count} рабочего дерева}}", "186bc3ed600d2102": "{count, plural, one {Попытка передать в {count} рабочее дерево} few {Попытка передать в {count} рабочих дерева} many {Попытка передать в {count} рабочих деревьев} other {Попытка передать в {count} рабочего дерева}}", + "0166c0dc3f34c937": "{count, plural, one {Освобождено: {count} рабочее дерево} other {Освобождено: {count} рабочих деревьев}}", + "8131c8e477f5e30b": "{count, plural, one {Попытка освободить: {count} рабочее дерево} other {Попытка освободить: {count} рабочих деревьев}}", "ea38f91437c9fd84": "{count, plural, one {Прочитан {count} проект} few {Прочитано {count} проекта} many {Прочитано {count} проектов} other {Прочитано {count} проекта}}", "962b5c9a64a23fda": "{count, plural, one {Попытка прочитать {count} проект} few {Попытка прочитать {count} проекта} many {Попытка прочитать {count} проектов} other {Попытка прочитать {count} проекта}}", "5f6309ffbb9206e5": "{count, plural, one {Зарегистрирован {count} проект} few {Зарегистрировано {count} проекта} many {Зарегистрировано {count} проектов} other {Зарегистрировано {count} проекта}}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 73c8e5a34a37d..dc9ccb8b99208 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, one {Försökte be om {count} hemlighet} other {Försökte be om {count} hemligheter}}", "3685ecb8634fe00c": "{count, plural, one {Lämnade över till {count} worktree} other {Lämnade över till {count} worktrees}}", "186bc3ed600d2102": "{count, plural, one {Försökte lämna över till {count} worktree} other {Försökte lämna över till {count} worktrees}}", + "0166c0dc3f34c937": "{count, plural, one {Frigjorde {count} arbetsträd} other {Frigjorde {count} arbetsträd}}", + "8131c8e477f5e30b": "{count, plural, one {Försökte frigöra {count} arbetsträd} other {Försökte frigöra {count} arbetsträd}}", "ea38f91437c9fd84": "{count, plural, one {Läste {count} projekt} other {Läste {count} projekt}}", "962b5c9a64a23fda": "{count, plural, one {Försökte läsa {count} projekt} other {Försökte läsa {count} projekt}}", "5f6309ffbb9206e5": "{count, plural, one {Registrerade {count} projekt} other {Registrerade {count} projekt}}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 684a35c3900bb..564b31514d11c 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -224,6 +224,8 @@ "bd4141e4464734ae": "{count, plural, other {尝试请求 {count} 个凭据}}", "3685ecb8634fe00c": "{count, plural, other {已移交给 {count} 个工作树}}", "186bc3ed600d2102": "{count, plural, other {尝试移交给 {count} 个工作树}}", + "0166c0dc3f34c937": "{count, plural, one {已释放 {count} 工作树} other {已释放 {count} 工作树}}", + "8131c8e477f5e30b": "{count, plural, one {尝试释放 {count} 工作树} other {尝试释放 {count} 工作树}}", "ea38f91437c9fd84": "{count, plural, other {已读取 {count} 个项目}}", "962b5c9a64a23fda": "{count, plural, other {尝试读取 {count} 个项目}}", "5f6309ffbb9206e5": "{count, plural, other {已注册 {count} 个项目}}", diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts index d7e0a24d0284f..4dafe2266a0f2 100644 --- a/packages/client-runtime/src/t3ToolSummary.ts +++ b/packages/client-runtime/src/t3ToolSummary.ts @@ -463,6 +463,23 @@ export function summarizeT3ToolCalls( ); break; } + case "worktree-release": { + const count = countEntities(entityIds("worktreePath")); + label = done + ? resolve( + msg( + "{count, plural, one {Released {count} worktree} other {Released {count} worktrees}}", + { count }, + ), + ) + : resolve( + msg( + "{count, plural, one {Tried to release {count} worktree} other {Tried to release {count} worktrees}}", + { count }, + ), + ); + break; + } case "project-read": { const count = countEntities(projectIds); label = done diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts index 6e3e7561c7f39..7ca0fcdb7e6af 100644 --- a/packages/client-runtime/src/work-log/presentation.ts +++ b/packages/client-runtime/src/work-log/presentation.ts @@ -726,6 +726,7 @@ function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction) case "queue-steer": case "question-respond": case "worktree-handoff": + case "worktree-release": case "project-create": case "project-update": case "project-delete": diff --git a/packages/contracts/src/worktreeMcp.ts b/packages/contracts/src/worktreeMcp.ts index 07b0240bbaf83..29a869f81dbca 100644 --- a/packages/contracts/src/worktreeMcp.ts +++ b/packages/contracts/src/worktreeMcp.ts @@ -77,6 +77,10 @@ export type WorktreeMcpHandoffResult = typeof WorktreeMcpHandoffResult.Type; export const WorktreeMcpStatusResult = Schema.Struct({ attached: Schema.Boolean, worktreePath: Schema.NullOr(TrimmedNonEmptyString), + missing: Schema.Boolean.annotate({ + description: + "The bound folder is gone. The next turn recreates it; `t3_worktree_release` drops the binding instead.", + }), branch: Schema.NullOr(GitRefName), projectWorkspaceRoot: TrimmedNonEmptyString, defaultStartFromOrigin: Schema.Boolean.annotate({ @@ -85,6 +89,28 @@ export const WorktreeMcpStatusResult = Schema.Struct({ }); export type WorktreeMcpStatusResult = typeof WorktreeMcpStatusResult.Type; +export const WorktreeMcpReleaseInput = Schema.Struct({ + deleteBranch: Schema.optional( + Schema.Boolean.annotate({ + description: "Also delete the local branch.", + }), + ), + force: Schema.optional( + Schema.Boolean.annotate({ + description: "Discard unsaved and unpushed work.", + }), + ), +}); +export type WorktreeMcpReleaseInput = typeof WorktreeMcpReleaseInput.Type; + +export const WorktreeMcpReleaseResult = Schema.Struct({ + worktreePath: TrimmedNonEmptyString, + branch: Schema.NullOr(GitRefName), + removal: Schema.Literals(["scheduled", "already-gone", "kept-shared"]), + note: Schema.String, +}); +export type WorktreeMcpReleaseResult = typeof WorktreeMcpReleaseResult.Type; + export class WorktreeMcpFailure extends Schema.TaggedError()( "WorktreeMcpFailure", { @@ -93,6 +119,8 @@ export class WorktreeMcpFailure extends Schema.TaggedError() "thread_not_found", "project_not_found", "already_in_worktree", + "not_in_worktree", + "unsaved_work", "handoff_in_progress", "invalid_request", "operation_failed", diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index 860f28c44f0a1..976936a19a6e9 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -42,6 +42,7 @@ export type T3McpToolSummaryAction = | "question-respond" | "secret-request" | "worktree-handoff" + | "worktree-release" | "worktree-list" | "worktree-status" | "project-list" @@ -248,6 +249,10 @@ const T3_MCP_TOOLS: Readonly> = { ["Hand off", "Handing off", "Handed off", "thread to a git worktree"], "worktree-handoff", ), + t3_worktree_release: tool( + ["Release", "Releasing", "Released", "the thread's git worktree"], + "worktree-release", + ), t3_worktree_status: tool(["Get", "Getting", "Got", "thread worktree status"], "worktree-status"), preview_status: tool(["Get", "Getting", "Got", "preview browser status"], "browser", "browser"), preview_open: tool(