diff --git a/README.md b/README.md index 1596bd1fdcfee..11d2ffb3778dd 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ This is a personal fork of [pingdotgg/t3code](https://github.com/pingdotgg/t3cod - **Thread tools for agents.** Agents can list custom thread groups with their thread counts, create a group, and move a thread into a group or back to Active with `t3_thread_groups`, and can start new threads directly in a group by passing `groupId` to `t3_thread_launch` or `create_threads`; renaming, deleting, and reordering groups stay with you. `t3_thread_drain_status` tells an agent whether a thread is fully quiet (no active or queued run, no subagents, monitors, or background commands left), for example before handing its session to another machine. `t3_thread_list` can list every project at once and find the threads bound to a worktree path. When a thread an agent started with `t3_thread_launch` fails workspace preparation on the same machine (a branch already in use, a reserved lab), that agent gets a message with the error so it can launch again. -- **Agents edit project actions.** Agents list, add, update, and remove a project's action buttons with `t3_project_actions_list`, `t3_project_actions_upsert`, and `t3_project_actions_remove`. Edits change the same actions the app shows, keep only one worktree setup action, and fail instead of overwriting a concurrent change. Changing actions needs a full-access agent. +- **Agents edit project actions.** Agents add, update, and remove a project's action buttons with `t3_project_actions_upsert` and `t3_project_actions_remove`; `t3_project_read` lists them. Edits change the same actions the app shows, keep only one worktree setup action, and fail instead of overwriting a concurrent change. Changing actions needs a full-access agent. - **Open a project's dev server from an action.** In the desktop app, give an action a Preview URL and turn on **Open in browser, reusing a running dev server**. If a web server is already running from the project or worktree directory, clicking the action opens it in the in-app browser without running the command again. Otherwise it runs the command, waits up to a minute for the server, and opens it. Only the URL's path matters, so Vite moving to another port is fine. Detection uses `lsof` on macOS and Linux; on Windows, or for servers in Docker, the action runs the command and opens the configured URL. diff --git a/apps/server/src/mcp/toolkits/voice/registration.test.ts b/apps/server/src/mcp/toolkits/forkIslands.test.ts similarity index 62% rename from apps/server/src/mcp/toolkits/voice/registration.test.ts rename to apps/server/src/mcp/toolkits/forkIslands.test.ts index 3ac43ac0ba9f3..0eb67dcdc4a90 100644 --- a/apps/server/src/mcp/toolkits/voice/registration.test.ts +++ b/apps/server/src/mcp/toolkits/forkIslands.test.ts @@ -10,52 +10,52 @@ import * as Ref from "effect/Ref"; import { HttpBody, HttpClient, HttpRouter } from "effect/http"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; -import * as DocumentText from "../../../provider/DocumentText.ts"; -import * as ServerConfig from "../../../config.ts"; -import * as DeviceService from "../../../device/DeviceService.ts"; -import * as ServerEnvironment from "../../../environment/ServerEnvironment.ts"; -import * as GitManager from "../../../git/GitManager.ts"; -import * as GitWorkflowService from "../../../git/GitWorkflowService.ts"; -import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts"; -import * as ProjectionStore from "../../../orchestration-v2/ProjectionStore.ts"; -import * as ProviderAdapterRegistry from "../../../orchestration-v2/ProviderAdapterRegistry.ts"; -import * as IssueService from "../../../issue/IssueService.ts"; -import * as ThreadIssueService from "../../../orchestration-v2/ThreadIssueService.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 PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; -import * as PullRequestService from "../../../pullRequest/PullRequestService.ts"; -import * as EnvironmentTheme from "../../../environmentTheme.ts"; -import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts"; -import * as ScheduledTaskService from "../../../scheduledTasks/ScheduledTaskService.ts"; -import * as SecretRequests from "../../../secrets/SecretRequests.ts"; -import * as ServerSettings from "../../../serverSettings.ts"; -import * as AssetSigner from "../../../assets/AssetSigner.ts"; -import * as LabsService from "../../../labs/LabsService.ts"; -import * as TelegramService from "../../../telegram/TelegramService.ts"; -import * as VcsStatusBroadcaster from "../../../vcs/VcsStatusBroadcaster.ts"; -import * as ServerSecretStore from "../../../auth/ServerSecretStore.ts"; -import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts"; -import * as ThreadArchiveScheduler from "../../../orchestration-v2/ThreadArchiveScheduler.ts"; -import * as PeerForwarding from "../../../peer/PeerForwarding.ts"; -import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts"; -import * as PeerLinks from "../../../peer/PeerLinks.ts"; -import * as RemoteDelegation from "../../../peer/RemoteDelegation.ts"; -import * as ThreadLaunchService from "../../../orchestration-v2/ThreadLaunchService.ts"; -import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts"; -import * as ThreadWorktreeSwitchScheduler from "../../../orchestration-v2/ThreadWorktreeSwitchScheduler.ts"; -import * as PreviewManager from "../../../preview/Manager.ts"; -import * as SourceControlRepositoryService from "../../../sourceControl/SourceControlRepositoryService.ts"; -import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts"; -import * as AgentVoiceReply from "../../../voice/AgentVoiceReply.ts"; -import * as ProjectCloneTracker from "../../../project/ProjectCloneTracker.ts"; -import * as McpHttpServer from "../../McpHttpServer.ts"; -import type { McpCapability } from "../../McpInvocationContext.ts"; -import * as McpSessionRegistry from "../../McpSessionRegistry.ts"; -import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; -import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts"; -import * as PreviewBrowser from "../../../preview/PreviewBrowser.ts"; +import * as DocumentText from "../../provider/DocumentText.ts"; +import * as ServerConfig from "../../config.ts"; +import * as DeviceService from "../../device/DeviceService.ts"; +import * as ServerEnvironment from "../../environment/ServerEnvironment.ts"; +import * as GitManager from "../../git/GitManager.ts"; +import * as GitWorkflowService from "../../git/GitWorkflowService.ts"; +import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "../../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as IssueService from "../../issue/IssueService.ts"; +import * as ThreadIssueService from "../../orchestration-v2/ThreadIssueService.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 PullRequestReviewGuideService from "../../pullRequest/PullRequestReviewGuideService.ts"; +import * as PullRequestService from "../../pullRequest/PullRequestService.ts"; +import * as EnvironmentTheme from "../../environmentTheme.ts"; +import * as ProviderRegistry from "../../provider/ProviderRegistry.ts"; +import * as ScheduledTaskService from "../../scheduledTasks/ScheduledTaskService.ts"; +import * as SecretRequests from "../../secrets/SecretRequests.ts"; +import * as ServerSettings from "../../serverSettings.ts"; +import * as AssetSigner from "../../assets/AssetSigner.ts"; +import * as LabsService from "../../labs/LabsService.ts"; +import * as TelegramService from "../../telegram/TelegramService.ts"; +import * as VcsStatusBroadcaster from "../../vcs/VcsStatusBroadcaster.ts"; +import * as ServerSecretStore from "../../auth/ServerSecretStore.ts"; +import * as ManagedProjectFolders from "../../project/ManagedProjectFolders.ts"; +import * as ThreadArchiveScheduler from "../../orchestration-v2/ThreadArchiveScheduler.ts"; +import * as PeerForwarding from "../../peer/PeerForwarding.ts"; +import * as PeerLinkRequests from "../../peer/PeerLinkRequests.ts"; +import * as PeerLinks from "../../peer/PeerLinks.ts"; +import * as RemoteDelegation from "../../peer/RemoteDelegation.ts"; +import * as ThreadLaunchService from "../../orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadSearch from "../../orchestration-v2/ThreadSearch.ts"; +import * as ThreadWorktreeSwitchScheduler from "../../orchestration-v2/ThreadWorktreeSwitchScheduler.ts"; +import * as PreviewManager from "../../preview/Manager.ts"; +import * as SourceControlRepositoryService from "../../sourceControl/SourceControlRepositoryService.ts"; +import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts"; +import * as AgentVoiceReply from "../../voice/AgentVoiceReply.ts"; +import * as ProjectCloneTracker from "../../project/ProjectCloneTracker.ts"; +import * as McpHttpServer from "../McpHttpServer.ts"; +import type { McpCapability } from "../McpInvocationContext.ts"; +import * as McpSessionRegistry from "../McpSessionRegistry.ts"; +import * as McpToolAccessTestkit from "../McpToolAccess.testkit.ts"; +import * as PreviewAutomationBroker from "../PreviewAutomationBroker.ts"; +import * as PreviewBrowser from "../../preview/PreviewBrowser.ts"; const StubServicesLive = Layer.mergeAll( McpProviderSessions.layer, @@ -105,7 +105,7 @@ const StubServicesLive = Layer.mergeAll( Layer.mock(ThreadIssueService.ThreadIssueService)({}), ); -const threadId = ThreadId.make("thread-voice-mcp"); +const threadId = ThreadId.make("thread-fork-islands-mcp"); /** Speaks JSON-RPC to the island the credential's endpoint names. */ const mcpSession = ( @@ -127,7 +127,7 @@ const mcpSession = ( const init = yield* httpClient.post(path, { headers, body: HttpBody.text( - `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"voice","version":"1.0.0"}}}`, + `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"fork-islands","version":"1.0.0"}}}`, "application/json", ), }); @@ -156,7 +156,8 @@ const toolNames = (body: string): ReadonlyArray => { return payload.result.tools.map((tool) => tool.name); }; -it.effect("voice_reply exists only for credentials with the voice capability", () => +// Fork: every island lists the common fork tools; only voice islands list voice_reply. +it.effect("fork tools are listed on the islands their capabilities name", () => Effect.scoped( Effect.gen(function* () { const staged = yield* Ref.make>([]); @@ -167,7 +168,7 @@ it.effect("voice_reply exists only for credentials with the voice capability", ( ), }); const layerEnvironment = Layer.mock(ServerEnvironment.ServerEnvironment)({ - getEnvironmentId: Effect.succeed("environment-voice" as never), + getEnvironmentId: Effect.succeed("environment-fork-islands" as never), }); const registry = Context.get( yield* Layer.build(McpSessionRegistry.layer.pipe(Layer.provide(layerEnvironment))), @@ -184,37 +185,33 @@ it.effect("voice_reply exists only for credentials with the voice capability", ( Layer.build, ); - for (const capabilities of [ - new Set(["voice"]), - new Set(["voice", "preview"]), - new Set(["voice", "device"]), - new Set(["voice", "preview", "device"]), - ]) { - const session = yield* mcpSession(registry, capabilities); - expect(toolNames(yield* session.call(2, "tools/list", {})), session.path).toContain( - "voice_reply", - ); - } + const paths = new Set(); for (const capabilities of [ new Set(), new Set(["preview"]), + new Set(["voice"]), + new Set(["preview", "voice"]), new Set(["device"]), - new Set(["preview", "device"]), + new Set(["device", "preview"]), + new Set(["device", "voice"]), + new Set(["device", "preview", "voice"]), ]) { const session = yield* mcpSession(registry, capabilities); + paths.add(session.path); const names = toolNames(yield* session.call(2, "tools/list", {})); - expect(names, session.path).not.toContain("voice_reply"); - // Fork toolkits that need no extra capability ride on every island. expect(names, session.path).toEqual( expect.arrayContaining([ "archive_thread", - "t3_project_actions_list", "t3_project_actions_upsert", "t3_project_actions_remove", + "t3_thread_drain_status", + "t3_thread_groups", "telegram_send", ]), ); + expect(names.includes("voice_reply"), session.path).toBe(capabilities.has("voice")); } + expect(paths.size).toBe(8); // The call stages for the credential's own thread. const voice = yield* mcpSession(registry, new Set(["voice"])); @@ -229,7 +226,7 @@ it.effect("voice_reply exists only for credentials with the voice capability", ( Effect.provide( Layer.mergeAll( NodeHttpServer.layerTest, - ServerConfig.layerTest(process.cwd(), { prefix: "t3-voice-mcp-" }).pipe( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-fork-islands-mcp-" }).pipe( Layer.provide(NodeServices.layer), ), NodeServices.layer, diff --git a/apps/server/src/mcp/toolkits/projectActions/handlers.test.ts b/apps/server/src/mcp/toolkits/projectActions/handlers.test.ts index 0c8e6d1f912c5..898f15a785201 100644 --- a/apps/server/src/mcp/toolkits/projectActions/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/projectActions/handlers.test.ts @@ -116,12 +116,6 @@ it.effect("edits the calling thread's project actions as a full-access caller", action: "created", projectAction: { id: "test", command: "vp test" }, }); - const listed = yield* call("t3_project_actions_list"); - expect(listed.structuredContent).toMatchObject({ - projectId, - title: "Tools", - actions: [{ id: "test" }], - }); expect( declaredFailure(yield* call("t3_project_actions_remove", { actionId: "lint" })), ).toMatchObject({ code: "invalid_request", message: expect.stringContaining("'lint'") }); @@ -131,9 +125,8 @@ it.effect("edits the calling thread's project actions as a full-access caller", }).pipe(Effect.scoped, Effect.provide(makeLayer("full-access"))), ); -it.effect("lets a narrower caller list but not change actions", () => +it.effect("refuses action changes from a narrower caller", () => Effect.gen(function* () { - expect((yield* call("t3_project_actions_list")).isError).toBe(false); expect( declaredFailure(yield* call("t3_project_actions_upsert", { name: "Test", command: "x" })), ).toMatchObject({ code: "capability_denied" }); @@ -168,9 +161,10 @@ it.effect("refuses an edit when the caller's turn ends while it waits for its lo expect(declaredFailure(yield* Fiber.join(upsert))).toMatchObject({ code: "parent_not_active", }); + // Nothing was written: the action the refused edit would have created does not exist. caller.activeRunId = RunId.make("run-2"); - expect((yield* call("t3_project_actions_list")).structuredContent).toMatchObject({ - actions: [], - }); + expect( + declaredFailure(yield* call("t3_project_actions_remove", { actionId: "test" })), + ).toMatchObject({ code: "invalid_request" }); }).pipe(Effect.scoped, Effect.provide(makeLayer("full-access", caller))); }); diff --git a/apps/server/src/mcp/toolkits/projectActions/handlers.ts b/apps/server/src/mcp/toolkits/projectActions/handlers.ts index 75ab3f6eb905f..7f17ccd044a16 100644 --- a/apps/server/src/mcp/toolkits/projectActions/handlers.ts +++ b/apps/server/src/mcp/toolkits/projectActions/handlers.ts @@ -15,19 +15,11 @@ const resolveTarget = (projectId: ProjectId | undefined) => readCaller().pipe(Effect.flatMap((context) => resolveProjectId(context, projectId))); /** - * Fork: project actions toolkit. Listing reads; edits, like other project - * changes, need a full-access caller, re-checked under the caller's lock - * right before writing. Edits compare-and-set against the actions they read, + * Fork: project actions toolkit. Edits, like other project changes, need a + * full-access caller, re-checked under the caller's lock right before writing. Edits compare-and-set against the actions they read, * so a concurrent change is refused rather than lost. */ export const layer = McpToolAccess.toLayer(ProjectActionsToolkit, { - t3_project_actions_list: McpToolAccess.reads((input) => - Effect.gen(function* () { - const projectId = yield* resolveTarget(input.projectId); - const actions = yield* ProjectActions.ProjectActions; - return yield* actions.list(projectId).pipe(Effect.mapError(failure)); - }), - ), t3_project_actions_upsert: McpToolAccess.writesEnvironment((input, check) => Effect.gen(function* () { const projectId = yield* resolveTarget(input.projectId); diff --git a/apps/server/src/mcp/toolkits/projectActions/tools.ts b/apps/server/src/mcp/toolkits/projectActions/tools.ts index e04588f1d77ec..4da0b9a27b949 100644 --- a/apps/server/src/mcp/toolkits/projectActions/tools.ts +++ b/apps/server/src/mcp/toolkits/projectActions/tools.ts @@ -32,27 +32,10 @@ const projectId = Schema.optional( ProjectId.annotate({ description: "Target project. Defaults to the calling thread's project." }), ); -const ProjectActionsListTool = Tool.make("t3_project_actions_list", { - ...shared, - description: - "List a project's actions: the run buttons the app shows for it (from project overrides or environment defaults). Read them before changing them; t3_project_read's scripts are a legacy field, not these actions.", - parameters: Schema.Struct({ projectId }), - success: Schema.Struct({ - projectId: ProjectId, - title: Schema.String, - workspaceRoot: Schema.String, - actions: Schema.Array(ProjectScript), - }), -}) - .annotate(Tool.Title, "List project actions") - .annotate(Tool.Readonly, true) - .annotate(Tool.Destructive, false) - .annotate(Tool.OpenWorld, false); - const ProjectActionsUpsertTool = Tool.make("t3_project_actions_upsert", { ...shared, description: - "Create or update a project action. Omit actionId to create one (name and command required; its id derives from the name). Pass an actionId from t3_project_actions_list to update it; omitted fields keep their values. Only one action may run on worktree creation: setting runOnWorktreeCreate clears it elsewhere and reports those ids in clearedRunOnWorktreeCreate. Inherited default actions become this project's own actions on the first change. The read and write are atomic, but a list result can be stale: re-list before updating when another client may have edited the actions. Fails with a conflict when they change mid-write; list them again and retry. Requires a full-access/default caller.", + "Create or update a project action. Omit actionId to create one (name and command required; its id derives from the name). Pass an actionId from the project's scripts (t3_project_read with an explicit projectId) to update it; omitted fields keep their values. Only one action may run on worktree creation: setting runOnWorktreeCreate clears it elsewhere and reports those ids in clearedRunOnWorktreeCreate. Inherited default actions become this project's own actions on the first change. The read and write are atomic, but scripts read earlier can be stale: read them again before updating when another client may have edited the actions. Fails with a conflict when they change mid-write; read them again and retry. Requires a full-access/default caller.", parameters: Schema.Struct({ projectId, actionId: Schema.optional( @@ -95,7 +78,7 @@ const ProjectActionsUpsertTool = Tool.make("t3_project_actions_upsert", { const ProjectActionsRemoveTool = Tool.make("t3_project_actions_remove", { ...shared, description: - "Remove a project action by its id from t3_project_actions_list. Fails if the actions changed since they were read; list them again and retry. Requires a full-access/default caller.", + "Remove a project action by its id from the project's scripts (t3_project_read with an explicit projectId). Fails if the actions changed since they were read; read them again and retry. Requires a full-access/default caller.", parameters: Schema.Struct({ projectId, actionId: TrimmedNonEmptyString }), success: Schema.Struct({ projectId: ProjectId, @@ -109,7 +92,6 @@ const ProjectActionsRemoveTool = Tool.make("t3_project_actions_remove", { .annotate(Tool.OpenWorld, false); export const ProjectActionsToolkit = Toolkit.make( - ProjectActionsListTool, ProjectActionsUpsertTool, ProjectActionsRemoveTool, ); diff --git a/apps/server/src/mcp/toolkits/threadGroups/registration.test.ts b/apps/server/src/mcp/toolkits/threadGroups/registration.test.ts deleted file mode 100644 index 2ef279659a0a0..0000000000000 --- a/apps/server/src/mcp/toolkits/threadGroups/registration.test.ts +++ /dev/null @@ -1,208 +0,0 @@ -import { expect, it } from "@effect/vitest"; -import { NodeHttpServer } from "@effect/platform-node"; -import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { ProviderInstanceId, ThreadId } from "@t3tools/contracts"; -import * as Context from "effect/Context"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import { HttpBody, HttpClient, HttpRouter } from "effect/http"; -import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; - -import * as DocumentText from "../../../provider/DocumentText.ts"; -import * as ServerConfig from "../../../config.ts"; -import * as DeviceService from "../../../device/DeviceService.ts"; -import * as ServerEnvironment from "../../../environment/ServerEnvironment.ts"; -import * as GitManager from "../../../git/GitManager.ts"; -import * as GitWorkflowService from "../../../git/GitWorkflowService.ts"; -import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts"; -import * as ProjectionStore from "../../../orchestration-v2/ProjectionStore.ts"; -import * as ProviderAdapterRegistry from "../../../orchestration-v2/ProviderAdapterRegistry.ts"; -import * as IssueService from "../../../issue/IssueService.ts"; -import * as ThreadIssueService from "../../../orchestration-v2/ThreadIssueService.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 PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; -import * as PullRequestService from "../../../pullRequest/PullRequestService.ts"; -import * as EnvironmentTheme from "../../../environmentTheme.ts"; -import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts"; -import * as ScheduledTaskService from "../../../scheduledTasks/ScheduledTaskService.ts"; -import * as SecretRequests from "../../../secrets/SecretRequests.ts"; -import * as ServerSettings from "../../../serverSettings.ts"; -import * as AssetSigner from "../../../assets/AssetSigner.ts"; -import * as LabsService from "../../../labs/LabsService.ts"; -import * as TelegramService from "../../../telegram/TelegramService.ts"; -import * as VcsStatusBroadcaster from "../../../vcs/VcsStatusBroadcaster.ts"; -import * as ServerSecretStore from "../../../auth/ServerSecretStore.ts"; -import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts"; -import * as ThreadArchiveScheduler from "../../../orchestration-v2/ThreadArchiveScheduler.ts"; -import * as PeerForwarding from "../../../peer/PeerForwarding.ts"; -import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts"; -import * as PeerLinks from "../../../peer/PeerLinks.ts"; -import * as RemoteDelegation from "../../../peer/RemoteDelegation.ts"; -import * as ThreadLaunchService from "../../../orchestration-v2/ThreadLaunchService.ts"; -import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts"; -import * as ThreadWorktreeSwitchScheduler from "../../../orchestration-v2/ThreadWorktreeSwitchScheduler.ts"; -import * as PreviewManager from "../../../preview/Manager.ts"; -import * as SourceControlRepositoryService from "../../../sourceControl/SourceControlRepositoryService.ts"; -import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts"; -import * as AgentVoiceReply from "../../../voice/AgentVoiceReply.ts"; -import * as ProjectCloneTracker from "../../../project/ProjectCloneTracker.ts"; -import * as McpHttpServer from "../../McpHttpServer.ts"; -import type { McpCapability } from "../../McpInvocationContext.ts"; -import * as McpSessionRegistry from "../../McpSessionRegistry.ts"; -import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts"; -import * as PreviewBrowser from "../../../preview/PreviewBrowser.ts"; - -const StubServicesLive = Layer.mergeAll( - McpProviderSessions.layer, - Layer.mock(Orchestrator.OrchestratorV2)({}), - Layer.mock(GitManager.GitManager)({}), - // The per-request forge lookup reads the thread shell. - Layer.mock(ProjectionStore.ProjectionStoreV2)({ getThreadShell: () => Effect.succeed(null) }), - Layer.mock(DeviceService.DeviceService)({}), - Layer.mock(AssetSigner.AssetSigner)({}), - Layer.mock(ThreadManagementService.ThreadManagementService)({}), - Layer.mock(ProviderRegistry.ProviderRegistry)({}), - Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({}), - ServerSettings.layerTest({}), - Layer.mock(TelegramService.TelegramService)({}), - Layer.mock(LabsService.LabsService)({}), - Layer.mock(GitWorkflowService.GitWorkflowService)({}), - Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}), - Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}), - Layer.mock(GitVcsDriver.GitVcsDriver)({}), - Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), - Layer.mock(PreviewManager.PreviewManager)({}), - Layer.mock(ServerSecretStore.ServerSecretStore)({}), - Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({}), - Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), - Layer.mock(ThreadSearch.ThreadSearch)({}), - Layer.mock(ThreadArchiveScheduler.ThreadArchiveScheduler)({}), - Layer.mock(PeerForwarding.PeerForwarding)({}), - Layer.mock(PeerLinkRequests.PeerLinkRequests)({}), - Layer.mock(PeerLinks.PeerLinks)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), - Layer.mock(ThreadWorktreeSwitchScheduler.ThreadWorktreeSwitchScheduler)({}), - Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}), - Layer.mock(PullRequestService.PullRequestService)({}), - Layer.mock(EnvironmentTheme.EnvironmentThemeService)({}), - Layer.mock(IssueService.IssueService)({}), - Layer.mock(ThreadIssueService.ThreadIssueService)({}), -); - -const threadId = ThreadId.make("thread-fork-thread-tools-mcp"); - -/** Speaks JSON-RPC to the island the credential's endpoint names. */ -const mcpSession = ( - registry: McpSessionRegistry.McpSessionRegistry["Service"], - capabilities: ReadonlySet, -) => - Effect.gen(function* () { - const credential = yield* registry.issue({ - threadId, - providerInstanceId: ProviderInstanceId.make("claudeAgent"), - capabilities, - }); - const path = new URL(credential.config.endpoint).pathname; - const httpClient = yield* HttpClient.HttpClient; - const headers = { - accept: "application/json, text/event-stream", - authorization: credential.config.authorizationHeader, - }; - const init = yield* httpClient.post(path, { - headers, - body: HttpBody.text( - `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"fork-thread-tools","version":"1.0.0"}}}`, - "application/json", - ), - }); - const sessionId = init.headers["mcp-session-id"]; - const call = (id: number, method: string, params: unknown) => - httpClient - .post(path, { - headers: { - ...headers, - "mcp-protocol-version": "2025-06-18", - ...(sessionId ? { "mcp-session-id": sessionId } : {}), - }, - body: HttpBody.text( - JSON.stringify({ jsonrpc: "2.0", id, method, params }), - "application/json", - ), - }) - .pipe(Effect.flatMap((response) => response.text)); - return { path, call }; - }); - -const toolNames = (body: string): ReadonlyArray => { - const payload = JSON.parse(body.match(/\{.*\}/s)![0]) as { - readonly result: { readonly tools: ReadonlyArray<{ readonly name: string }> }; - }; - return payload.result.tools.map((tool) => tool.name); -}; - -// Fork: thread groups and drain status ride every island, like the other thread tools. -it.effect("t3_thread_groups and t3_thread_drain_status are listed on every island", () => - Effect.scoped( - Effect.gen(function* () { - const layerEnvironment = Layer.mock(ServerEnvironment.ServerEnvironment)({ - getEnvironmentId: Effect.succeed("environment-fork-thread-tools" as never), - }); - const registry = Context.get( - yield* Layer.build(McpSessionRegistry.layer.pipe(Layer.provide(layerEnvironment))), - McpSessionRegistry.McpSessionRegistry, - ); - const routes = McpHttpServer.layer.pipe( - Layer.provide(Layer.succeed(McpSessionRegistry.McpSessionRegistry, registry)), - ); - yield* HttpRouter.serve(routes, { disableListenLog: true, disableLogger: true }).pipe( - Layer.provide(layerEnvironment), - Layer.provide(PreviewAutomationBroker.layer), - Layer.provide(PreviewBrowser.layer), - Layer.provide( - Layer.merge(StubServicesLive, Layer.mock(AgentVoiceReply.AgentVoiceReply)({})), - ), - Layer.build, - ); - - const paths = new Set(); - for (const capabilities of [ - new Set(), - new Set(["preview"]), - new Set(["voice"]), - new Set(["preview", "voice"]), - new Set(["device"]), - new Set(["device", "preview"]), - new Set(["device", "voice"]), - new Set(["device", "preview", "voice"]), - ]) { - const session = yield* mcpSession(registry, capabilities); - paths.add(session.path); - expect(toolNames(yield* session.call(2, "tools/list", {})), session.path).toEqual( - expect.arrayContaining(["t3_thread_groups", "t3_thread_drain_status"]), - ); - } - expect(paths.size).toBe(8); - }), - ).pipe( - Effect.provide( - Layer.mergeAll( - NodeHttpServer.layerTest, - ServerConfig.layerTest(process.cwd(), { prefix: "t3-fork-thread-tools-mcp-" }).pipe( - Layer.provide(NodeServices.layer), - ), - NodeServices.layer, - NodeCrypto.layer, - DocumentText.layer.pipe( - Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - ), - ), - ), - ), -); diff --git a/apps/server/src/orchestration-v2/Adapters/KiroAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/KiroAdapterV2.test.ts index 931f5cf82f11c..7fcf873edf5c6 100644 --- a/apps/server/src/orchestration-v2/Adapters/KiroAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/KiroAdapterV2.test.ts @@ -1,6 +1,6 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, describe, it } from "@effect/vitest"; +import { assert, describe, it, vi } from "@effect/vitest"; import { MessageId, type ModelSelection, @@ -1474,9 +1474,17 @@ describe("Kiro permission policy", () => { // Fork (DECISIONS 5.9): commands the agent runs know their thread and T3 install. it.effect("launches kiro with the thread's self-addressing environment", () => Effect.gen(function* () { + // An agent shell's identity on the server process itself never reaches the agent. + yield* Effect.acquireRelease( + Effect.sync(() => vi.stubEnv("T3CODE_TURN_ID", "server-stale")), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); const launches: Array | undefined> = []; const childProcessSpawner = ChildProcessSpawner.make((command) => { - if (command._tag === "StandardCommand") launches.push(command.options.env); + // Without extendEnv the child receives exactly this environment. + if (command._tag === "StandardCommand" && command.options.extendEnv !== true) { + launches.push(command.options.env); + } return Effect.fail( PlatformError.systemError({ _tag: "NotFound", module: "kiro-env-test", method: "spawn" }), ); @@ -1509,5 +1517,5 @@ it.effect("launches kiro with the thread's self-addressing environment", () => T3CODE_WORKTREE_PATH: process.cwd(), }); assert.notProperty(agent, "T3CODE_TURN_ID"); - }).pipe(Effect.provide(testLayer)), + }).pipe(Effect.scoped, Effect.provide(testLayer)), ); diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index 3f6744e576edd..877367a6cdc08 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -6,6 +6,7 @@ import { type OrchestrationV2Subagent, type OrchestrationV2TurnItem, OrchestrationV2StoredEvent, + type ProviderInstanceId, ProviderThreadId, RunAttemptId, RunId, @@ -90,6 +91,20 @@ const projectedThreadIds = (events: ReadonlyArray) = : [event.threadId], ); +type NativeThreadOwnershipGuard = Pick< + OrchestrationV2ProviderThread, + "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef" +> & { + /** + * Fork: a session store several instances share (a Claude shadow and its default). Its + * current instances own the session, and so does any instance recorded under its key. + */ + readonly sharedSession?: { + readonly continuationKey: string; + readonly instanceIds: ReadonlyArray; + }; +}; + export interface EventSinkV2Shape { /** Items that are not provider snapshots, such as a consumer's own control items, never batch. */ readonly consumeProviderEvents: ( @@ -111,10 +126,7 @@ export interface EventSinkV2Shape { readonly write: (input: { /** Return no events if another thread owns this native session at commit time. */ - readonly unlessNativeThreadOwned?: Pick< - OrchestrationV2ProviderThread, - "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef" - >; + readonly unlessNativeThreadOwned?: NativeThreadOwnershipGuard; readonly guardPendingUserInputCancellations?: boolean; readonly commandId?: CommandId; readonly events: ReadonlyArray; @@ -125,10 +137,7 @@ export interface EventSinkV2Shape { * The batch must not also change that run's lifecycle. */ readonly updateDelegatedCompletionOnly?: boolean; - readonly unlessNativeThreadOwned?: Pick< - OrchestrationV2ProviderThread, - "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef" - >; + readonly unlessNativeThreadOwned?: NativeThreadOwnershipGuard; readonly guardPendingUserInputCancellations?: boolean; readonly commandId?: CommandId; readonly events: ReadonlyArray; @@ -485,6 +494,21 @@ const layerBase: Layer.Layer< ); }); + // Fork: an owner through any instance sharing the session store also owns the session. + const ownerInstanceMatches = (guard: NativeThreadOwnershipGuard, nativeId: string | null) => { + const shared = guard.sharedSession; + const instances = sql`provider_instance_id IN ${sql.in([guard.providerInstanceId, ...(shared?.instanceIds ?? [])])}`; + return shared === undefined + ? instances + : // Uncorrelated, so SQLite keeps the instance index for both branches. + sql`(${instances} OR provider_instance_id IN ( + SELECT provider_instance_id FROM fork_native_continuation + WHERE driver = ${guard.driver} + AND native_thread_id = ${nativeId} + AND continuation_key = ${shared.continuationKey} + ))`; + }; + const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* ( input: Parameters[0], ) { @@ -506,7 +530,7 @@ const layerBase: Layer.Layer< SELECT provider_thread_id FROM orchestration_v2_projection_provider_threads WHERE driver = ${imported.driver} - AND provider_instance_id = ${imported.providerInstanceId} + AND ${ownerInstanceMatches(imported, imported.nativeThreadRef.nativeId)} AND thread_id IS NOT ${imported.appThreadId} AND json_extract(payload_json, '$.nativeThreadRef.nativeId') = ${imported.nativeThreadRef.nativeId} LIMIT 1 diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index 4e24e82af9ed8..cdbbabaa61dd3 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -9,6 +9,7 @@ import { type SourceControlCloneRepositoryInput, ProjectId, OrchestratorMcpFailure, + OrchestratorMcpThreadListResult, ProviderInstanceId, RunId, ThreadId, @@ -20,6 +21,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; import { McpSchema, McpServer } from "effect/ai"; @@ -44,10 +46,12 @@ import * as McpHttpServer from "../mcp/McpHttpServer.ts"; import * as ThreadGroupsMcpService from "../mcp/ThreadGroupsMcpService.ts"; import * as ThreadArchiveScheduler from "../orchestration-v2/ThreadArchiveScheduler.ts"; import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; +import { OrchestratorToolkit } from "../mcp/toolkits/orchestrator/tools.ts"; import { liveThreadShell } from "../mcp/McpToolAccess.testkit.ts"; import * as PeerForwarding from "./PeerForwarding.ts"; import * as PeerLinks from "./PeerLinks.ts"; import * as PeerLinkRequests from "./PeerLinkRequests.ts"; +import * as PeerMcpClient from "./PeerMcpClient.ts"; import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts"; const laptop = descriptorOf("environment-laptop", "Laptop"); @@ -850,3 +854,79 @@ it.effect("retries a newest-page read without its cursor when the peer refuses t expect(sent).toEqual([newest, params]); }), ); + +const decodeThreadListPage = Schema.decodeUnknownEffect( + Schema.fromJsonString(OrchestratorMcpThreadListResult), +); + +it.effect("lists an upstream peer's threads, but refuses the worktreePath filter it ignores", () => + Effect.gen(function* () { + // An upstream peer has no worktreePath, in the item or as a filter. + const upstreamPage = JSON.stringify({ + projectId: boxProject, + currentThreadId: null, + threads: [ + { + threadId: boxThread, + projectId: boxProject, + title: "Box thread", + createdBy: "user", + creationSource: "web", + status: "idle", + latestRunId: null, + providerInstanceId: "codex", + model: "gpt-6-luna", + runtimeMode: "auto", + interactionMode: "default", + linkedPullRequest: null, + settled: false, + settledAt: null, + snoozed: false, + snoozedUntil: null, + parentThreadId: null, + relationshipToParent: null, + itemCount: 0, + createdAt: "2026-10-18T00:00:00.000Z", + updatedAt: "2026-10-18T00:00:00.000Z", + }, + ], + nextCursor: null, + total: 1, + }); + const context = yield* Layer.build( + PeerForwarding.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(PeerMcpClient.PeerMcpClient)({ + call: () => decodeThreadListPage(upstreamPage).pipe(Effect.orDie) as never, + }), + Layer.mock(PeerLinks.PeerLinks)({ enabled: Effect.succeed(true) }), + Layer.mock(ThreadManagement.ThreadManagementService)({}), + NodeCrypto.layer, + ), + ), + ), + ); + const forwarding = Context.get(context, PeerForwarding.PeerForwarding); + const scope: McpInvocationContext.McpInvocationScope = { + environmentId: laptop.environmentId, + requestNamespace: "client:upstream-list", + thread: undefined, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + const list = (worktreePath?: string) => + forwarding.call(scope, OrchestratorToolkit.tools.t3_thread_list, box.environmentId, { + environmentId: box.environmentId, + projectId: boxProject, + ...(worktreePath === undefined ? {} : { worktreePath }), + }); + + expect((yield* list()).threads.map((thread) => thread.threadId)).toEqual([boxThread]); + expect(yield* Effect.flip(list("/work/trees/feature"))).toMatchObject({ + code: "invalid_request", + message: expect.stringContaining("does not support the worktreePath filter"), + }); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts index d60ebcd8f42d7..1f2bd762254bf 100644 --- a/apps/server/src/peer/PeerForwarding.ts +++ b/apps/server/src/peer/PeerForwarding.ts @@ -4,6 +4,8 @@ import { type OrchestratorMcpEnvironmentLinksResult, OrchestratorMcpThreadInterruptInput, OrchestratorMcpThreadInterruptResult, + type OrchestratorMcpThreadListInput, + type OrchestratorMcpThreadListResult, OrchestratorMcpThreadReadInput, OrchestratorMcpThreadReadResult, OrchestratorMcpThreadWaitInput, @@ -112,6 +114,29 @@ export const readNewestOrRetry = Effect.fn("PeerForwarding.readNewestOrRetry")(f return yield* read(newest).pipe(Effect.catchIf(refusesBeforePosition, () => read(params))); }); +/** Fork: a peer without the `worktreePath` filter lists threads unfiltered, without that field. */ +const rejectIgnoredWorktreeFilter = ( + toolName: string, + params: unknown, + listed: Effect.Effect, +) => + toolName !== "t3_thread_list" || + (params as OrchestratorMcpThreadListInput).worktreePath === undefined + ? listed + : Effect.tap(listed, (result) => + (result as OrchestratorMcpThreadListResult).threads.some( + (thread) => thread.worktreePath === undefined, + ) + ? Effect.fail( + new OrchestratorMcpFailure({ + code: "invalid_request", + message: + "The linked environment does not support the worktreePath filter. List its threads without worktreePath.", + }), + ) + : Effect.void, + ); + const make = Effect.gen(function* () { const peers = yield* PeerMcpClient.PeerMcpClient; const links = yield* PeerLinks.PeerLinks; @@ -281,7 +306,10 @@ const make = Effect.gen(function* () { : newest === undefined ? forwardTool(params) : readNewestOrRetry(forwardTool, newest, params); - return Effect.andThen(requireEnabled, forwarded); + return Effect.andThen( + requireEnabled, + rejectIgnoredWorktreeFilter(tool.name, params, forwarded), + ); }; /** diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 18c0946144d4a..8da6096d8b170 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -35,6 +35,7 @@ import * as ServerConfig from "../config.ts"; import * as EventSink from "../orchestration-v2/EventSink.ts"; import * as EventStore from "../orchestration-v2/EventStore.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import { ClaudeProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; @@ -183,6 +184,13 @@ const seedOwner = Effect.fn(function* ( return threadId; }); +// A shadow instance shares its default instance's Claude sessions. +const continuationKeys: Record = { + claudeAgent: "claude:home:/home/user/.claude", + "claude-shadow": "claude:home:/home/user/.claude", + "claude-other": "claude:home:/home/other/.claude", +}; + const makeImporter = Effect.fn(function* ( candidates: ReadonlyArray, beforeTransaction: Effect.Effect = Effect.void, @@ -265,9 +273,20 @@ const makeImporter = Effect.fn(function* ( ), ), }), - Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)( - getAdapter === undefined ? {} : { get: getAdapter }, - ), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + ...(getAdapter === undefined ? {} : { get: getAdapter }), + list: () => + Effect.succeed( + Object.keys(continuationKeys).map((id) => ProviderInstanceId.make(id)), + ), + getMetadata: (instanceId) => + Effect.succeed({ + driver: ProviderDriverKind.make("claudeAgent"), + continuationKey: continuationKeys[instanceId] ?? instanceId, + enabled: true, + capabilities: ClaudeProviderCapabilitiesV2, + }), + }), Layer.succeed( ThreadCommandExecutor.ThreadCommandExecutor, threadCommands ?? (yield* ThreadCommandExecutor.make), @@ -285,7 +304,7 @@ const makeImporter = Effect.fn(function* ( }); it.effect( - "ignores owned sessions, including archived and deleted threads, but imports other instances and unowned sessions", + "ignores owned sessions, including archived, deleted, and shadow-instance threads, but imports other instances and unowned sessions", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; @@ -299,11 +318,36 @@ it.effect( ); const deleted = candidate(CODEX_MODEL_SELECTION, "deleted"); const ownedPi = candidate(PI_MODEL_SELECTION, "owned-pi", "pi"); + const shadowSessionId = "5b8f2f43-34b5-4c1e-9a6f-1f0c7a2d9e10"; + const shadowOwned = candidate(CLAUDE_MODEL_SELECTION, shadowSessionId, "claudeAgent"); + // A since-removed shadow instance recorded the session under the default's key. + const removedSessionId = "7c1d9e52-0b6a-4f3e-8d21-5a9b3c4e6f70"; + const removedOwned = candidate(CLAUDE_MODEL_SELECTION, removedSessionId, "claudeAgent"); + yield* (yield* SqlClient.SqlClient)` + INSERT INTO fork_native_continuation + (provider_instance_id, driver, native_thread_id, continuation_key, recorded_at) + VALUES ('claude-removed', 'claudeAgent', ${removedSessionId}, + ${continuationKeys.claudeAgent!}, ${timestamp}) + `; const owners = [ yield* seedOwner(active), yield* seedOwner(archived, "archived"), yield* seedOwner(deleted, "deleted"), yield* seedOwner(ownedPi), + yield* seedOwner( + candidate( + { ...CLAUDE_MODEL_SELECTION, instanceId: ProviderInstanceId.make("claude-shadow") }, + shadowSessionId, + "claudeAgent", + ), + ), + yield* seedOwner( + candidate( + { ...CLAUDE_MODEL_SELECTION, instanceId: ProviderInstanceId.make("claude-removed") }, + removedSessionId, + "claudeAgent", + ), + ), ]; const before = yield* Effect.forEach(owners, (id) => projections.getThreadRecords(id, ["providerThreads"]), @@ -322,13 +366,15 @@ it.effect( archived, deleted, ownedPi, + shadowOwned, + removedOwned, otherInstance, unowned, unownedPi, ]); expect(yield* importer.run).toEqual({ importedCount: 3, skippedCount: 0 }); - for (const source of [active, archived, deleted, ownedPi]) { + for (const source of [active, archived, deleted, ownedPi, shadowOwned, removedOwned]) { const threadId = importId(source); expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none()); expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]); diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 2c9cd0b4e70a5..f71d963c0a5a8 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -21,6 +21,7 @@ import { type OrchestrationV2DomainEvent, type OrchestrationV2ProviderThread, type OrchestrationV2TurnItem, + type ProviderInstanceId, } from "@t3tools/contracts"; import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; @@ -263,6 +264,27 @@ const make = Effect.gen(function* () { ), ); })).flat(); + // Fork: instances with one continuation key (a Claude shadow and its default) share sessions; + // the guard also matches an owner recorded under that key whose instance is gone. + const getMetadata = registry.getMetadata; + const continuationKeys = new Map( + getMetadata === undefined + ? [] + : (yield* Effect.forEach(yield* registry.list(), (instanceId) => + getMetadata(instanceId).pipe( + Effect.map((metadata) => [instanceId, metadata.continuationKey] as const), + Effect.option, + ), + )).flatMap(Option.toArray), + ); + const sharedSession = (instanceId: ProviderInstanceId) => { + const continuationKey = continuationKeys.get(instanceId); + if (continuationKey === undefined) return {}; + const instanceIds = [...continuationKeys].flatMap(([other, key]) => + key === continuationKey && other !== instanceId ? [other] : [], + ); + return { sharedSession: { continuationKey, instanceIds } }; + }; const outcomes = scanner.recentThreads(project.workspaceRoot, completedSources); const importedThreadIds = new Set(); let importedCount = 0; @@ -422,7 +444,10 @@ const make = Effect.gen(function* () { }; const committed = yield* eventSink.write({ - unlessNativeThreadOwned: providerThread, + unlessNativeThreadOwned: { + ...providerThread, + ...sharedSession(thread.providerInstanceId), + }, events: [ { id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${threadId}:created`), diff --git a/apps/server/src/project/ProjectActions.test.ts b/apps/server/src/project/ProjectActions.test.ts index ceaf10267c41b..8cd54097f2ed9 100644 --- a/apps/server/src/project/ProjectActions.test.ts +++ b/apps/server/src/project/ProjectActions.test.ts @@ -5,6 +5,7 @@ import { type ProjectScript, type ServerSettingsError, } from "@t3tools/contracts"; +import { resolveProjectScripts } from "@t3tools/shared/projectScripts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -32,20 +33,22 @@ const dev: ProjectScript = { autoOpenPreview: true, }; +const project = { + id: projectId, + title: "Actions", + workspaceRoot: "/repo", + scripts: [], +} as unknown as Project; const projectLayer = Layer.mock(ProjectService.ProjectService)({ - getById: (id) => - Effect.succeed( - id === projectId - ? Option.some({ - id: projectId, - title: "Actions", - workspaceRoot: "/repo", - scripts: [], - } as unknown as Project) - : Option.none(), - ), + getById: (id) => Effect.succeed(id === projectId ? Option.some(project) : Option.none()), }); +/** The actions the app shows, as `t3_project_read` returns them. */ +const effectiveActions = ServerSettings.ServerSettingsService.pipe( + Effect.flatMap((settings) => settings.getSettings), + Effect.map((settings) => resolveProjectScripts(settings, project)), +); + /** Environment defaults hold the actions, so the project starts out inheriting them. */ const settingsLayer = ServerSettings.layerTest({ projectSettingsFolded: true, @@ -74,11 +77,7 @@ it.effect("creates an action with a collision-safe id as a project override", () }, clearedRunOnWorktreeCreate: [], }); - expect((yield* actions.list(projectId)).actions.map((action) => action.id)).toEqual([ - "setup", - "dev", - "dev-2", - ]); + expect((yield* effectiveActions).map((action) => action.id)).toEqual(["setup", "dev", "dev-2"]); // The environment defaults stay as they were. const settings = yield* (yield* ServerSettings.ServerSettingsService).getSettings; expect(settings.defaultProjectScripts).toEqual([setup, dev]); @@ -119,7 +118,7 @@ it.effect("an edit keeps the action's settle role", () => yield* actions.upsert({ projectId, name: clean.name, command: clean.command }); const settingsService = yield* ServerSettings.ServerSettingsService; // Give the new action the settle role, as the project settings editor does. - const listed = (yield* actions.list(projectId)).actions; + const listed = yield* effectiveActions; yield* settingsService.updateSettings({ projectScriptUpdate: { projectId, @@ -138,7 +137,7 @@ it.effect("an edit keeps automatic stopping on settle", () => Effect.gen(function* () { const actions = yield* service; const settingsService = yield* ServerSettings.ServerSettingsService; - const listed = (yield* actions.list(projectId)).actions; + const listed = yield* effectiveActions; yield* settingsService.updateSettings({ projectScriptUpdate: { projectId, @@ -160,7 +159,7 @@ it.effect("keeps a single worktree setup action and reports the cleared one", () const actions = yield* service; const result = yield* actions.upsert({ projectId, actionId: "dev", runOnWorktreeCreate: true }); expect(result.clearedRunOnWorktreeCreate).toEqual(["setup"]); - const listed = (yield* actions.list(projectId)).actions; + const listed = yield* effectiveActions; expect( listed.filter((action) => action.runOnWorktreeCreate).map((action) => action.id), ).toEqual(["dev"]); @@ -175,7 +174,7 @@ it.effect("removes an action and reports unknown ids", () => action: "removed", actionId: "dev", }); - expect((yield* actions.list(projectId)).actions).toEqual([setup]); + expect(yield* effectiveActions).toEqual([setup]); const missing = yield* actions.remove({ projectId, actionId: "dev" }).pipe(Effect.flip); expect(missing).toBeInstanceOf(ProjectActions.ProjectActionNotFoundError); }).pipe(Effect.provide(makeLayer())), diff --git a/apps/server/src/project/ProjectActions.ts b/apps/server/src/project/ProjectActions.ts index d2e87c02337af..6713e74df3d5c 100644 --- a/apps/server/src/project/ProjectActions.ts +++ b/apps/server/src/project/ProjectActions.ts @@ -89,13 +89,6 @@ export type ProjectActionsError = | ProjectService.ProjectOperationError | ServerSettingsError; -export interface ProjectActionsList { - readonly projectId: ProjectId; - readonly title: string; - readonly workspaceRoot: string; - readonly actions: ReadonlyArray; -} - /** No `actionId` creates an action (name and command required); an `actionId` updates it. */ export interface ProjectActionUpsertInput { readonly projectId: ProjectId; @@ -127,7 +120,6 @@ export interface ProjectActionRemoveResult { export class ProjectActions extends Context.Service< ProjectActions, { - readonly list: (projectId: ProjectId) => Effect.Effect; readonly upsert: ( input: ProjectActionUpsertInput, ) => Effect.Effect; @@ -277,15 +269,6 @@ const make = Effect.gen(function* () { ); return ProjectActions.of({ - list: Effect.fn("ProjectActions.list")(function* (projectId) { - const { project, scripts } = yield* read(projectId); - return { - projectId: project.id, - title: project.title, - workspaceRoot: project.workspaceRoot, - actions: scripts, - }; - }), upsert: Effect.fn("ProjectActions.upsert")(function* (input) { const { project, scripts } = yield* read(input.projectId); const result = yield* applyUpsert(scripts, input); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 51fc7d35ce69b..9eff47cc01186 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6326, "codexAdditionalContextBytes": 7722, - "mcpToolListJsonBytes": 69436 + "mcpToolListJsonBytes": 69199 } diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index ad3bde4a8bafa..7ac2f871fadcd 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -440,7 +440,8 @@ export const OrchestratorMcpThreadListItem = Schema.Struct({ pendingBackgroundTasks: Schema.optional(Schema.Array(OrchestratorMcpThreadBackgroundTask)), parentThreadId: Schema.NullOr(ThreadId), relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])), - worktreePath: Schema.NullOr(Schema.String), + /** Fork: always set here; absent from linked upstream environments. */ + worktreePath: Schema.optional(Schema.NullOr(Schema.String)), /** The linked environment's thread that delegated this one; absent otherwise. */ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), itemCount: NonNegativeInt, diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index 099cc95e265ec..f9e0eb213805a 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -30,6 +30,7 @@ import type * as EffectAcpSchema from "effect-acp/compat"; import * as EffectAcpProtocol from "effect-acp/protocol"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { AgentScope, AgentScopeThreadId, RAISE_OOM_SCORE_LINE } from "@t3tools/shared/AgentScope"; +import { withoutThreadEnvironment } from "@t3tools/provider-core/server/threadEnvironment"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; @@ -1496,20 +1497,23 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( ...wrapCommandForLinuxCgroup(linuxCgroupLease, containedTargetCommand, spawnCommand.args), shell: false, }; - const spawnEnvironment = - linuxCgroupLease === undefined - ? options.spawn.env - : { - ...options.spawn.env, - ELECTRON_RUN_AS_NODE: "1", - T3_ACP_CGROUP_WRAPPER: "1", - }; + // Fork: thread-scoped variables reach the agent only as its adapter set them, never + // inherited from this server's own environment. + const spawnEnvironment = { + ...((options.spawn.extendEnv ?? true) || options.spawn.env === undefined + ? withoutThreadEnvironment(process.env) + : {}), + ...options.spawn.env, + ...(linuxCgroupLease === undefined + ? {} + : { ELECTRON_RUN_AS_NODE: "1", T3_ACP_CGROUP_WRAPPER: "1" }), + }; const child = yield* spawner .spawn( ChildProcess.make(containedSpawnCommand.command, containedSpawnCommand.args, { ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}), - ...(spawnEnvironment ? { env: spawnEnvironment } : {}), - extendEnv: options.spawn.extendEnv ?? true, + env: spawnEnvironment, + extendEnv: false, // Windows `detached` gives the child its own console, which breaks stdio pipes through // `.cmd` shims; taskkill /T cleans up the tree there without it. ...(options.ownDetachedProcessGroup === undefined diff --git a/packages/provider-core/src/server/instanceEnvironment.ts b/packages/provider-core/src/server/instanceEnvironment.ts index 893e6212dc48c..f8e8dd95ea3dc 100644 --- a/packages/provider-core/src/server/instanceEnvironment.ts +++ b/packages/provider-core/src/server/instanceEnvironment.ts @@ -3,6 +3,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import { expandHomeVariable } from "./pathExpansion.ts"; +import { withoutThreadEnvironment } from "./threadEnvironment.ts"; export const mergeProviderInstanceEnvironment = Effect.fn(function* ( environment: ProviderInstanceEnvironment | undefined, @@ -11,7 +12,8 @@ export const mergeProviderInstanceEnvironment = Effect.fn(function* ( // Drivers retain a stable environment snapshot for the instance lifetime. const home = yield* HostProcess.HomeDirectory; const windows = (yield* HostProcess.Platform) === "win32"; - const next: NodeJS.ProcessEnv = { ...baseEnv }; + // Fork: the server's own thread identity is never part of a provider instance's environment. + const next = withoutThreadEnvironment(baseEnv); for (const variable of environment ?? []) { // An unresolved secret reference carries no value; the registry resolves it for the provider. if (typeof variable.value !== "string") continue; diff --git a/packages/provider-core/src/server/threadEnvironment.test.ts b/packages/provider-core/src/server/threadEnvironment.test.ts index fb0e042b37f3c..c6ec0a8002485 100644 --- a/packages/provider-core/src/server/threadEnvironment.test.ts +++ b/packages/provider-core/src/server/threadEnvironment.test.ts @@ -9,6 +9,8 @@ describe("provider thread environment", () => { T3CODE_THREAD_ID: "parent", T3CODE_TURN_ID: "stale", T3CODE_WORKTREE_PATH: "/parent", + // A Windows environment keeps whatever spelling it inherited. + t3code_Turn_Id: "stale-windows", }; const first = providerThreadEnvironment({ threadId: ThreadId.make("one"), cwd: "/one" }, base, { baseDir: "/t3", diff --git a/packages/provider-core/src/server/threadEnvironment.ts b/packages/provider-core/src/server/threadEnvironment.ts index b7613bcf50c08..30547d755dfcd 100644 --- a/packages/provider-core/src/server/threadEnvironment.ts +++ b/packages/provider-core/src/server/threadEnvironment.ts @@ -26,14 +26,23 @@ export function providerThreadEnvironmentVariables( }; } +const THREAD_VARIABLES = new Set(["T3CODE_THREAD_ID", "T3CODE_TURN_ID", "T3CODE_WORKTREE_PATH"]); + +/** `base` without thread-scoped variables, such as those the server inherited from an agent shell. */ +export function withoutThreadEnvironment(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const environment: NodeJS.ProcessEnv = { ...base }; + // Windows reads names without regard to case, and a copy of process.env keeps its spelling. + for (const name of Object.keys(environment)) { + if (THREAD_VARIABLES.has(name.toUpperCase())) delete environment[name]; + } + return environment; +} + /** Session identity is stable; native turn IDs are allocated after process launch. */ export function providerThreadEnvironment( input: ProviderThreadIdentity, base: NodeJS.ProcessEnv = process.env, paths?: ProviderThreadPaths, ): NodeJS.ProcessEnv { - const environment: NodeJS.ProcessEnv = { ...base }; - delete environment.T3CODE_TURN_ID; - delete environment.T3CODE_WORKTREE_PATH; - return { ...environment, ...providerThreadEnvironmentVariables(input, paths) }; + return { ...withoutThreadEnvironment(base), ...providerThreadEnvironmentVariables(input, paths) }; }