Add worktree handoff and status tools to the t3-code MCP server #3754
t3code/codex-turn-mapping fromrefs/pull/3754/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- packages/contracts/src/worktree.ts lines 135 to 140OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +120,21 @@120+}121+122+export class WorktreeOperationError extends Schema.TaggedErrorClass<WorktreeOperationError>()(123+ "WorktreeOperationError",124+ {125+ operation: Schema.Literals([126+ "resolveThread",127+ "resolveProject",128+ "resolveBaseRef",129+ "fetchRemote",130+ "resolveRemoteTrackingCommit",131+ "createWorktree",132+ "updateThreadMetadata",133+ "resolveSettings",134+ ]),135+ detail: Schema.String,136+ },137+) {138+ override get message(): string {139+ return `Worktree operation '${this.operation}' failed: ${this.detail}`;140+ }
- apps/server/src/mcp/toolkits/worktree/handlers.ts line 136OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -0,0 +116,21 @@116+ if (startFromOrigin) {117+ yield* gitWorkflow118+ .fetchRemote({ cwd: projectCwd, remoteName: "origin" })119+ .pipe(Effect.mapError(asOperationError("fetchRemote")));120+ const resolvedRemoteBase = yield* gitWorkflow121+ .resolveRemoteTrackingCommit({122+ cwd: projectCwd,123+ refName: baseRef,124+ fallbackRemoteName: "origin",125+ })126+ .pipe(Effect.mapError(asOperationError("resolveRemoteTrackingCommit")));127+ worktreeBaseRef = resolvedRemoteBase.commitSha;128+ }129+130+ const worktree = yield* gitWorkflow131+ .createWorktree({132+ cwd: projectCwd,133+ refName: worktreeBaseRef,134+ newRefName: input.branch,135+ baseRefName: baseRef,136+ path: input.path ?? null,
- apps/server/src/mcp/toolkits/worktree/handlers.ts line 71OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +51,21 @@51+});52+53+const worktreeHandoff = Effect.fn("WorktreeToolkit.worktreeHandoff")(function* (54+ input: WorktreeHandoffInput,55+) {56+ const invocation = yield* requireWorktreeCapability();57+ const crypto = yield* Crypto.Crypto;58+ const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;59+ const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;60+ const serverSettings = yield* ServerSettings.ServerSettingsService;61+ const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;62+ const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;63+ const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;64+65+ const thread = yield* projectionSnapshotQuery66+ .getThreadDetailById(invocation.threadId)67+ .pipe(Effect.map(Option.getOrUndefined), Effect.mapError(asOperationError("resolveThread")));68+ if (!thread) {69+ return yield* new WorktreeThreadNotFoundError({ threadId: invocation.threadId });70+ }71+ if (thread.worktreePath !== null) {packages/contracts/src/worktree.ts line 29OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +9,21 @@9+ * Creates a git worktree for the calling agent thread and re-points the10+ * thread at it. The provider session restarts inside the worktree at the11+ * start of the next turn, resuming the conversation.12+ */13+export const WorktreeHandoffInput = Schema.Struct({14+ branch: TrimmedNonEmptyString.annotate({15+ description: "Branch name to create for the worktree (e.g. 'feature/my-change').",16+ }),17+ baseRef: Schema.optional(18+ TrimmedNonEmptyString.annotate({19+ description:20+ "Branch or ref the worktree branch starts from. Defaults to the branch currently checked out in the project workspace.",21+ }),22+ ),23+ startFromOrigin: Schema.optional(24+ Schema.Boolean.annotate({25+ description:26+ "Fetch origin and start the worktree branch from the remote-tracking commit of baseRef instead of the local ref. Defaults to the server's 'new worktrees start from origin' setting.",27+ }),28+ ),29+ path: Schema.optional(
- apps/server/src/mcp/toolkits/worktree/handlers.ts line 153OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +133,21 @@133+ refName: worktreeBaseRef,134+ newRefName: input.branch,135+ baseRefName: baseRef,136+ path: input.path ?? null,137+ })138+ .pipe(Effect.mapError(asOperationError("createWorktree")));139+ const worktreePath = worktree.worktree.path;140+141+ const commandId = yield* crypto.randomUUIDv4.pipe(142+ Effect.map((uuid) => CommandId.make(`server:mcp-worktree-handoff:${uuid}`)),143+ Effect.orDie,144+ );145+ yield* orchestrationEngine146+ .dispatch({147+ type: "thread.meta.update",148+ commandId,149+ threadId: invocation.threadId,150+ branch: worktree.worktree.refName,151+ worktreePath,152+ })153+ .pipe(Effect.mapError(asOperationError("updateThreadMetadata")));
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/mcp/toolkits/worktree/handlers.ts lines 83 to 88OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +68,21 @@68+ .pipe(Effect.map(Option.getOrUndefined), Effect.mapError(asOperationError("resolveThread")));69+ if (!thread) {70+ return yield* new WorktreeThreadNotFoundError({ threadId: invocation.threadId });71+ }72+ if (thread.worktreePath !== null) {73+ return yield* new WorktreeHandoffAlreadyInWorktreeError({74+ threadId: invocation.threadId,75+ worktreePath: thread.worktreePath,76+ });77+ }78+79+ const project = yield* projectionSnapshotQuery80+ .getProjectShellById(thread.projectId)81+ .pipe(Effect.map(Option.getOrUndefined), Effect.mapError(asOperationError("resolveProject")));82+ if (!project) {83+ return yield* new WorktreeOperationError({84+ operation: "resolveProject",85+ cause: new Error(86+ `Project '${thread.projectId}' was not found for thread '${invocation.threadId}'.`,87+ ),88+ });
- apps/server/src/mcp/toolkits/worktree/handlers.ts line 140OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +120,21 @@120+ (yield* serverSettings.getSettings.pipe(121+ Effect.map((settings) => settings.newWorktreesStartFromOrigin),122+ Effect.mapError(asOperationError("resolveSettings")),123+ ));124+125+ let worktreeBaseRef = baseRef;126+ if (startFromOrigin) {127+ yield* gitWorkflow128+ .fetchRemote({ cwd: projectCwd, remoteName: "origin" })129+ .pipe(Effect.mapError(asOperationError("fetchRemote")));130+ const resolvedRemoteBase = yield* gitWorkflow131+ .resolveRemoteTrackingCommit({132+ cwd: projectCwd,133+ refName: baseRef,134+ fallbackRemoteName: "origin",135+ })136+ .pipe(Effect.mapError(asOperationError("resolveRemoteTrackingCommit")));137+ worktreeBaseRef = resolvedRemoteBase.commitSha;138+ }139+140+ const worktree = yield* gitWorkflow
- apps/server/src/mcp/toolkits/worktree/handlers.ts line 225OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +205,21 @@205+ worktreePath,206+ })207+ .pipe(208+ Effect.map(209+ (result): WorktreeHandoffSetupScriptStatus =>210+ result.status === "started"211+ ? {212+ status: "started",213+ scriptName: result.scriptName,214+ terminalId: result.terminalId,215+ }216+ : { status: "no-script" },217+ ),218+ Effect.catch(219+ (error: unknown): Effect.Effect<WorktreeHandoffSetupScriptStatus> =>220+ Effect.logWarning("worktree handoff setup script failed", {221+ threadId: invocation.threadId,222+ worktreePath,223+ detail: errorDetail(error),224+ }).pipe(Effect.as({ status: "failed", detail: errorDetail(error) } as const)),225+ ),
juliusmarminge requested changes
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/mcp/WorktreeMcpService.ts line 244OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -0,0 +224,21 @@224+ .dispatch({225+ type: "thread.metadata.update",226+ commandId,227+ threadId: scope.threadId,228+ branch: worktree.worktree.refName,229+ worktreePath,230+ })231+ .pipe(232+ Effect.mapError((error) =>233+ failure(234+ "operation_failed",235+ `Unable to re-point the thread at the worktree: ${errorMessage(error)}`,236+ ),237+ ),238+ // The worktree was already created; if the thread cannot be re-pointed239+ // at it, remove it again so a failed handoff leaves nothing behind.240+ Effect.catch((error) =>241+ gitWorkflow242+ .removeWorktree({ cwd: projectCwd, path: worktreePath, force: true })243+ .pipe(Effect.ignoreCause({ log: true }), Effect.andThen(Effect.fail(error))),244+ ),apps/server/src/mcp/WorktreeMcpService.ts line 145OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -0,0 +116,21 @@116+ "mcp",117+ encodeURIComponent(scope.providerSessionId),118+ "worktree-handoff",119+ uuid,120+ ].join(":"),121+ ),122+ ),123+ Effect.orDie,124+ );125+126+ const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* (127+ scope: McpInvocationScope,128+ input: WorktreeMcpHandoffInput,129+ ) {130+ const projection = yield* loadThread(scope);131+ if (projection.thread.worktreePath !== null) {132+ return yield* failure(133+ "already_in_worktree",134+ `Thread '${scope.threadId}' is already attached to worktree '${projection.thread.worktreePath}'.`,135+ );136+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/mcp/WorktreeMcpService.ts lines 28 to 41OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +21,21 @@21+import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";22+import * as ProjectService from "../project/ProjectService.ts";23+import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";24+import * as ServerSettings from "../serverSettings.ts";25+import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";26+import type { McpInvocationScope } from "./McpInvocationContext.ts";27+28+export interface WorktreeMcpServiceShape {29+ readonly handoff: (30+ scope: McpInvocationScope,31+ input: WorktreeMcpHandoffInput,32+ ) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;33+ readonly status: (34+ scope: McpInvocationScope,35+ ) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;36+}37+38+export class WorktreeMcpService extends Context.Service<39+ WorktreeMcpService,40+ WorktreeMcpServiceShape41+>()("t3/mcp/WorktreeMcpService") {}
- apps/server/src/mcp/WorktreeMcpService.ts line 235OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +202,21 @@202+ ),203+ );204+ worktreeBaseRef = resolvedRemoteBase.commitSha;205+ }206+207+ const worktree = yield* gitWorkflow208+ .createWorktree({209+ cwd: projectCwd,210+ refName: worktreeBaseRef,211+ newRefName: input.branch,212+ baseRefName: baseRef,213+ path: input.path ?? null,214+ })215+ .pipe(216+ Effect.mapError((error) =>217+ failure("operation_failed", `Unable to create the worktree: ${errorMessage(error)}`),218+ ),219+ );220+ const worktreePath = worktree.worktree.path;221+222+ const ids = yield* handoffIds(scope);
- apps/server/src/mcp/WorktreeMcpService.ts line 93OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -0,0 +70,21 @@70+ const requireCapability = (scope: McpInvocationScope) =>71+ scope.capabilities.has("worktree")72+ ? Effect.void73+ : Effect.fail(74+ failure("capability_denied", "This MCP credential does not grant worktree capabilities."),75+ );76+77+ const loadThread = (scope: McpInvocationScope) =>78+ threadManagement.getThreadProjection(scope.threadId).pipe(79+ Effect.mapError((error) =>80+ error._tag === "OrchestratorProjectionError"81+ ? failure("thread_not_found", `Thread '${scope.threadId}' was not found.`)82+ : failure(83+ "operation_failed",84+ `Unable to read thread ${scope.threadId}: ${errorMessage(error)}`,85+ ),86+ ),87+ Effect.filterOrFail(88+ (projection) => projection.thread.deletedAt === null,89+ () => failure("thread_not_found", `Thread '${scope.threadId}' was not found.`),90+ ),
- apps/server/src/mcp/toolkits/worktree/tools.ts lines 26 to 27OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+import { Tool, Toolkit } from "effect/unstable/ai";8+9+import * as McpInvocationContext from "../../McpInvocationContext.ts";10+import { WorktreeMcpService } from "../../WorktreeMcpService.ts";11+12+const dependencies = [McpInvocationContext.McpInvocationContext, WorktreeMcpService];13+14+export const WorktreeHandoffTool = Tool.make("t3_worktree_handoff", {15+ description:16+ "Move this agent thread into a new git worktree. Creates the worktree branch (optionally from origin), re-points the thread at the worktree, and by default runs the project's setup script there. Changing the workspace detaches the live provider session, so the current turn ends shortly after the handoff is recorded; call this as the last action of the turn. To keep working after the handoff, pass continuationPrompt with the remaining work: it is queued as the thread's next message and starts a new turn inside the worktree with the conversation preserved. Without it the thread stays idle until the next message. The worktree is not removed automatically when the thread is deleted. Fails if the thread is already attached to a worktree.",17+ parameters: WorktreeMcpHandoffInput,18+ success: WorktreeMcpHandoffResult,19+ failure: WorktreeMcpFailure,20+ failureMode: "return",21+ dependencies,22+})23+ .annotate(Tool.Title, "Hand off thread to a git worktree")24+ .annotate(Tool.Readonly, false)25+ .annotate(Tool.Destructive, false)26+ .annotate(Tool.Idempotent, false)27+ .annotate(Tool.OpenWorld, false);apps/server/src/mcp/toolkits/worktree/tools.ts line 25OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -0,0 +5,21 @@5+ WorktreeMcpStatusResult,6+} from "@t3tools/contracts";7+import { Tool, Toolkit } from "effect/unstable/ai";8+9+import * as McpInvocationContext from "../../McpInvocationContext.ts";10+import { WorktreeMcpService } from "../../WorktreeMcpService.ts";11+12+const dependencies = [McpInvocationContext.McpInvocationContext, WorktreeMcpService];13+14+export const WorktreeHandoffTool = Tool.make("t3_worktree_handoff", {15+ description:16+ "Move this agent thread into a new git worktree. Creates the worktree branch (optionally from origin), re-points the thread at the worktree, and by default runs the project's setup script there. Changing the workspace detaches the live provider session, so the current turn ends shortly after the handoff is recorded; call this as the last action of the turn. To keep working after the handoff, pass continuationPrompt with the remaining work: it is queued as the thread's next message and starts a new turn inside the worktree with the conversation preserved. Without it the thread stays idle until the next message. The worktree is not removed automatically when the thread is deleted. Fails if the thread is already attached to a worktree.",17+ parameters: WorktreeMcpHandoffInput,18+ success: WorktreeMcpHandoffResult,19+ failure: WorktreeMcpFailure,20+ failureMode: "return",21+ dependencies,22+})23+ .annotate(Tool.Title, "Hand off thread to a git worktree")24+ .annotate(Tool.Readonly, false)25+ .annotate(Tool.Destructive, false)
- apps/server/src/mcp/WorktreeMcpService.ts line 234OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -0,0 +214,21 @@214+215+ const worktree = yield* gitWorkflow216+ .createWorktree({217+ cwd: projectCwd,218+ refName: worktreeBaseRef,219+ newRefName: input.branch,220+ baseRefName: baseRef,221+ path: input.path ?? null,222+ })223+ .pipe(224+ Effect.mapError((error) =>225+ failure("operation_failed", `Unable to create the worktree: ${errorMessage(error)}`),226+ ),227+ );228+ const worktreePath = worktree.worktree.path;229+230+ // The projection was read before the potentially slow git work above; a231+ // concurrent binding (for example from the UI) could have attached the232+ // thread in the meantime. Re-check before committing and back the created233+ // worktree out again so the race cannot leave a second, untracked worktree.234+ const recheck = yield* loadThread(scope);
- apps/server/src/mcp/WorktreeMcpService.ts line 328OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -0,0 +308,21 @@308+ Effect.catchCause(309+ (cause): Effect.Effect<WorktreeMcpContinuationStatus> =>310+ Effect.logWarning("worktree handoff continuation failed to queue", {311+ threadId: scope.threadId,312+ worktreePath,313+ detail: errorMessage(Cause.squash(cause)),314+ }).pipe(315+ Effect.as({316+ status: "failed",317+ detail: errorMessage(Cause.squash(cause)),318+ } as const),319+ ),320+ ),321+ ),322+ );323+324+ // Uninterruptible: once the binding commits, the scheduled session detach325+ // can sever this request's connection and interrupt the fiber. The326+ // continuation must be durably queued before that interrupt is honored,327+ // or the prompt would be silently lost and the thread left idle.328+ const continuation = yield* Effect.uninterruptible(
- apps/server/src/mcp/WorktreeMcpService.ts line 241OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -0,0 +221,21 @@221+ threadId: scope.threadId,222+ worktreePath,223+ detail,224+ }).pipe(Effect.as({ status: "failed", detail } as const));225+ });226+227+ const ids = yield* handoffIds(scope);228+ const removeCreatedWorktree = gitWorkflow229+ .removeWorktree({ cwd: projectCwd, path: worktreePath, force: true })230+ .pipe(Effect.ignoreCause({ log: true }));231+232+ const recheckAndBind = Effect.gen(function* () {233+ // The projection was read before the potentially slow git work above; a234+ // concurrent binding (for example from the UI) could have attached the235+ // thread in the meantime. Re-check before committing so the race cannot236+ // leave a second, untracked worktree.237+ const recheck = yield* loadThread(scope);238+ if (recheck.thread.worktreePath !== null) {239+ return yield* alreadyInWorktree(recheck.thread.worktreePath);240+ }241+ yield* threadManagement
- apps/server/src/mcp/WorktreeMcpService.ts lines 283 to 285OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +267,21 @@267+ return Effect.logWarning(logMessage, {268+ threadId: scope.threadId,269+ worktreePath,270+ detail,271+ }).pipe(Effect.as({ status: "failed", detail } as const));272+ });273+274+ // suspend: build the removal call only if cleanup actually runs.275+ const removeCreatedWorktree = Effect.suspend(() =>276+ gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }),277+ ).pipe(Effect.ignoreCause({ log: true }));278+279+ const recheckAndBind = Effect.gen(function* () {280+ // The projection was read before the potentially slow git work281+ // above; a concurrent binding (for example from the UI) could have282+ // attached the thread in the meantime. Re-check before committing so283+ // the race cannot leave a second, untracked worktree.284+ const recheck = yield* loadThread(scope);285+ if (recheck.thread.worktreePath !== null) {286+ return yield* alreadyInWorktree(recheck.thread.worktreePath);287+ }
- apps/server/src/mcp/WorktreeMcpService.ts lines 28 to 41OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -0,0 +21,21 @@21+import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";22+import * as ProjectService from "../project/ProjectService.ts";23+import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";24+import * as ServerSettings from "../serverSettings.ts";25+import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";26+import type { McpInvocationScope } from "./McpInvocationContext.ts";27+28+export interface WorktreeMcpServiceShape {29+ readonly handoff: (30+ scope: McpInvocationScope,31+ input: WorktreeMcpHandoffInput,32+ ) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;33+ readonly status: (34+ scope: McpInvocationScope,35+ ) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;36+}37+38+export class WorktreeMcpService extends Context.Service<39+ WorktreeMcpService,40+ WorktreeMcpServiceShape41+>()("t3/mcp/WorktreeMcpService") {}
- apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 1417 to 1420OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -1273,3 +1406,15 @@12731406 updated.set(key, entry);12741407 return updated;12751408 });1409+ // Revalidate after the entry is visible: a concurrent release of1410+ // a predecessor session could have revoked the credential this1411+ // open prepared before this entry existed to veto it. Now that1412+ // the entry is in the map, the release guard protects the1413+ // credential, so a single re-check (which rotates if the token1414+ // died in the window) closes the race for good. Adapters read1415+ // the config slot lazily at thread start/resume, so a rotation1416+ // here is picked up by the provider process.1417+ const revalidated = yield* prepareMcpSession(1418+ input.threadId,1419+ input.modelSelection.instanceId,1420+ );
- apps/server/src/mcp/WorktreeMcpService.ts line 368OutdatedResolvedby nsxdavid(GitHub profile, opens in a new tab)@@ -0,0 +348,21 @@348+ messageId: ids.continuationMessageId,349+ text: input.continuationPrompt,350+ attachments: [],351+ mode: "queue",352+ createdBy: "agent",353+ creationSource: "mcp",354+ })355+ .pipe(356+ Effect.map(357+ (sendResult): WorktreeMcpContinuationStatus => ({358+ status: "scheduled",359+ delivery: sendResult.delivery,360+ }),361+ ),362+ // catchCause via reportFailed: the binding is already recorded,363+ // so a failed continuation must be reported, not fail the handoff.364+ reportFailed("worktree handoff continuation failed to queue"),365+ ),366+ );367+368+ const continuation = yield* recheckAndBind.pipe(Effect.andThen(queueContinuation));
juliusmarminge approved these changes
- @@ -268,0 +325,21 @@325+ threadId,326+ Effect.gen(function* () {327+ // Reuse a still-valid credential for this thread instead of328+ // rotating: long-lived provider processes (codex app-server)329+ // build their MCP client once per conversation and keep using330+ // the credential it started with, so a thread that detaches and331+ // re-attaches across a workspace handoff must come back to the332+ // same token or the process's tool calls fail auth.333+ const existing = McpProviderSession.readMcpProviderSession(threadId);334+ if (existing !== undefined) {335+ // Reserve before the async resolve so a release cannot336+ // revoke the credential between validation and reservation.337+ reserveMcpCredential(threadId, existing.providerSessionId);338+ const rawToken = existing.authorizationHeader.replace(/^Bearer\s+/, "");339+ const resolved = yield* mcpSessionRegistry.resolve(rawToken);340+ if (341+ resolved !== undefined &&342+ resolved.threadId === threadId &&343+ resolved.providerInstanceId === providerInstanceId344+ ) {345+ return { mcpCredentialId: existing.providerSessionId, issued: false };@@ -577,0 +692,21 @@692+ entry.mcpCredentialIdByThread,693+ ([threadId, mcpCredentialId]) => {694+ // Id-sensitive: a stale record for the same thread but695+ // a DIFFERENT credential (left behind by an old session696+ // the thread rotated away from) must not veto revoking697+ // this session's own credential, or it leaks forever.698+ // A reservation means an in-flight open is configuring699+ // a provider process with this credential right now;700+ // revoking it here would strand that process (eager701+ // adapters cannot pick up a rotated token).702+ const heldElsewhere =703+ isMcpCredentialReserved(threadId, mcpCredentialId) ||704+ Array.from(current.values()).some(705+ (other) =>706+ other !== entry &&707+ (other.attachedThreadIds.has(threadId) ||708+ other.mcpCredentialIdByThread.get(threadId) === mcpCredentialId),709+ );710+ return heldElsewhere711+ ? Effect.void712+ : clearMcpSession(threadId, mcpCredentialId);@@ -0,0 +107,21 @@107+ ),108+ onSome: Effect.succeed,109+ }),110+ ),111+ );112+113+ const readDefaultStartFromOrigin = serverSettings.getSettings.pipe(114+ Effect.map((settings) => settings.newWorktreesStartFromOrigin),115+ asOperationFailed("Unable to read server settings"),116+ );117+118+ const handoffIds = (scope: McpInvocationScope) =>119+ crypto.randomUUIDv4.pipe(120+ Effect.map((uuid) => {121+ const part = (kind: string, operation: string) =>122+ [kind, "mcp", encodeURIComponent(scope.providerSessionId), operation, uuid].join(":");123+ return {124+ commandId: CommandId.make(part("command", "worktree-handoff")),125+ continuationCommandId: CommandId.make(part("command", "worktree-continuation")),126+ continuationMessageId: MessageId.make(part("message", "worktree-continuation")),127+ };
juliusmarminge merged this4dffcad
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
3c2bf006-89a5-4bdf-93ee-2e88e56797e8You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share