From ed2ca16bcc5427a63803d5367fbcceecfda44b9c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 28 Jun 2026 17:58:14 -0700 Subject: [PATCH] Adopt userdata-v2 and subagent activity mapping - Move desktop and server state paths to `userdata-v2` - Handle Codex subagent activity events in orchestration v2 - Update related path and lifecycle tests --- .../src/app/DesktopAppIdentity.test.ts | 6 +- .../app/DesktopConnectionCatalogStore.test.ts | 16 +- .../src/app/DesktopEnvironment.test.ts | 12 +- .../DesktopBackendConfiguration.test.ts | 2 +- .../backend/DesktopBackendConfiguration.ts | 2 +- .../DesktopClientSettings.diagnostics.test.ts | 2 +- .../settings/DesktopSavedEnvironments.test.ts | 8 +- apps/server/src/cli/config.test.ts | 4 +- apps/server/src/config.ts | 5 +- .../Adapters/CodexAdapterV2.ts | 484 ++++++++++-------- .../RunExecutionService.test.ts | 208 ++++++++ .../orchestration-v2/RunExecutionService.ts | 198 +++++-- .../CodexReplayFixtures.integration.test.ts | 13 + .../testkit/fixtures/index.ts | 14 + .../testkit/fixtures/shared.ts | 1 + .../fixtures/subagent_v2/codex_output.ts | 77 +++ .../subagent_v2/codex_transcript.ndjson | 25 + .../testkit/fixtures/subagent_v2/input.ts | 7 + packages/ssh/src/tunnel.test.ts | 2 +- packages/ssh/src/tunnel.ts | 2 +- 20 files changed, 785 insertions(+), 303 deletions(-) create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.ts create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/input.ts diff --git a/apps/desktop/src/app/DesktopAppIdentity.test.ts b/apps/desktop/src/app/DesktopAppIdentity.test.ts index da767a0370..5365484984 100644 --- a/apps/desktop/src/app/DesktopAppIdentity.test.ts +++ b/apps/desktop/src/app/DesktopAppIdentity.test.ts @@ -129,7 +129,7 @@ const withIdentity = ( input.legacyPathProbeError ? Effect.fail(input.legacyPathProbeError) : Effect.succeed( - input.legacyPathExists === true && path.includes("T3 Code (Alpha)"), + input.legacyPathExists === true && path.includes("T3 Code (Alpha v2)"), ), readFileString: () => Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'), @@ -150,14 +150,14 @@ describe("DesktopAppIdentity", () => { const identity = yield* DesktopAppIdentity.DesktopAppIdentity; const userDataPath = yield* identity.resolveUserDataPath; - assert.equal(userDataPath, "/Users/alice/Library/Application Support/T3 Code (Alpha)"); + assert.equal(userDataPath, "/Users/alice/Library/Application Support/T3 Code (Alpha v2)"); }), { legacyPathExists: true }, ), ); it.effect("preserves failures while inspecting the legacy userData path", () => { - const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)"; + const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha v2)"; const cause = PlatformError.systemError({ _tag: "PermissionDenied", module: "FileSystem", diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts index c58830b30a..17d08a124d 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts @@ -255,7 +255,7 @@ describe("DesktopConnectionCatalogStore", () => { _tag: "PermissionDenied", module: "FileSystem", method: "readFileString", - pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`, + pathOrDescriptor: `${baseDir}/userdata-v2/connection-catalog.json`, }); const fileSystemLayer = Layer.succeed( FileSystem.FileSystem, @@ -272,11 +272,11 @@ describe("DesktopConnectionCatalogStore", () => { error, DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError, ); - assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`); + assert.equal(error.catalogPath, `${baseDir}/userdata-v2/connection-catalog.json`); assert.strictEqual(error.cause, permissionError); assert.equal( error.message, - `Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`, + `Failed to read the desktop connection catalog at ${baseDir}/userdata-v2/connection-catalog.json.`, ); assert.notEqual(error.message, permissionError.message); }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), @@ -292,7 +292,7 @@ describe("DesktopConnectionCatalogStore", () => { _tag: "PermissionDenied", module: "FileSystem", method: "makeDirectory", - pathOrDescriptor: `${baseDir}/userdata`, + pathOrDescriptor: `${baseDir}/userdata-v2`, }); const fileSystemLayer = Layer.succeed( FileSystem.FileSystem, @@ -310,11 +310,11 @@ describe("DesktopConnectionCatalogStore", () => { DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError, ); assert.equal(error.operation, "create-directory"); - assert.equal(error.path, `${baseDir}/userdata`); + assert.equal(error.path, `${baseDir}/userdata-v2`); assert.strictEqual(error.cause, permissionError); assert.equal( error.message, - `Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`, + `Desktop connection catalog write failed during create-directory at ${baseDir}/userdata-v2.`, ); assert.notEqual(error.message, permissionError.message); }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), @@ -399,14 +399,14 @@ describe("DesktopConnectionCatalogStore", () => { DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError, ); assert.equal(error.operation, "decrypt-catalog"); - assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`); + assert.equal(error.catalogPath, `${baseDir}/userdata-v2/connection-catalog.json`); assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError); const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError; assert.instanceOf(decryptError.cause, Error); assert.equal(decryptError.cause.message, "invalid encrypted catalog"); assert.equal( error.message, - `Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`, + `Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata-v2/connection-catalog.json.`, ); assert.notEqual(error.message, decryptError.message); yield* Ref.set(failDecrypt, false); diff --git a/apps/desktop/src/app/DesktopEnvironment.test.ts b/apps/desktop/src/app/DesktopEnvironment.test.ts index 218e2c3e4b..864b21cc4a 100644 --- a/apps/desktop/src/app/DesktopEnvironment.test.ts +++ b/apps/desktop/src/app/DesktopEnvironment.test.ts @@ -82,7 +82,7 @@ describe("DesktopEnvironment", () => { }), ); - it.effect("stores production state under userdata in an explicit home", () => + it.effect("derives production state paths under userdata-v2", () => Effect.gen(function* () { const environment = yield* makeEnvironment( {}, @@ -92,10 +92,12 @@ describe("DesktopEnvironment", () => { ); assert.equal(environment.isDevelopment, false); - assert.equal(environment.stateDir, "/tmp/t3/userdata"); - assert.equal(environment.logDir, "/tmp/t3/userdata/logs"); - assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts"); - assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json"); + assert.equal(environment.stateDir, "/tmp/t3/userdata-v2"); + assert.equal(environment.logDir, "/tmp/t3/userdata-v2/logs"); + assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata-v2/browser-artifacts"); + assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata-v2/settings.json"); + assert.equal(environment.userDataDirName, "t3code-v2"); + assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha v2)"); }), ); diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 2bbde73aba..b8f5d64db5 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -404,7 +404,7 @@ describe("DesktopBackendConfiguration", () => { const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-desktop-backend-config-test-", }); - const settingsPath = path.join(baseDir, "userdata", "settings.json"); + const settingsPath = path.join(baseDir, "userdata-v2", "settings.json"); const cause = PlatformError.systemError({ _tag: "PermissionDenied", module: "FileSystem", diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index bcce731a59..86dc69fbc0 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -556,7 +556,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl }; // Forward the dev-server URL as an explicit CLI flag so the WSL backend's - // config resolution lands in dev/ instead of userdata/. Inheriting through + // config resolution lands in dev/ instead of userdata-v2/. Inheriting through // WSLENV is unreliable in practice (URL-shaped values with colons / // slashes get translated unpredictably depending on flags), and the // packaged build leaves devServerUrl as None anyway. diff --git a/apps/desktop/src/settings/DesktopClientSettings.diagnostics.test.ts b/apps/desktop/src/settings/DesktopClientSettings.diagnostics.test.ts index 5034df44cf..db68a51b2d 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.diagnostics.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.diagnostics.test.ts @@ -83,7 +83,7 @@ describe("DesktopClientSettings diagnostics", () => { _tag: "PermissionDenied", module: "FileSystem", method: "readFileString", - pathOrDescriptor: `${baseDir}/userdata/client-settings.json`, + pathOrDescriptor: `${baseDir}/userdata-v2/client-settings.json`, }); return Effect.gen(function* () { diff --git a/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts b/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts index 05b1ca1444..02c89e239c 100644 --- a/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts +++ b/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts @@ -404,7 +404,7 @@ describe("DesktopSavedEnvironments", () => { const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({ prefix: "t3-desktop-saved-environments-test-", }); - const registryPath = `${baseDir}/userdata/saved-environments.json`; + const registryPath = `${baseDir}/userdata-v2/saved-environments.json`; const permissionError = PlatformError.systemError({ _tag: "PermissionDenied", module: "FileSystem", @@ -440,7 +440,7 @@ describe("DesktopSavedEnvironments", () => { _tag: "PermissionDenied", module: "FileSystem", method: "makeDirectory", - pathOrDescriptor: `${baseDir}/userdata`, + pathOrDescriptor: `${baseDir}/userdata-v2`, }); const fileSystemLayer = Layer.succeed( FileSystem.FileSystem, @@ -456,11 +456,11 @@ describe("DesktopSavedEnvironments", () => { const error = yield* savedEnvironments.setRegistry([savedRegistryRecord]).pipe(Effect.flip); assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsWriteError); assert.equal(error.operation, "create-directory"); - assert.equal(error.path, `${baseDir}/userdata`); + assert.equal(error.path, `${baseDir}/userdata-v2`); assert.strictEqual(error.cause, permissionError); assert.equal( error.message, - `Desktop saved-environment write failed during create-directory at ${baseDir}/userdata.`, + `Desktop saved-environment write failed during create-directory at ${baseDir}/userdata-v2.`, ); assert.notEqual(error.message, permissionError.message); }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index def63b61fa..1d93bee60d 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -355,9 +355,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { tailscaleServeEnabled: false, tailscaleServePort: 443, }); - assert.equal(join(baseDir, "userdata"), resolved.stateDir); - assert.equal(resolved.desktopTelemetryFd, 4); - assert.equal(resolved.desktopTelemetryControlFd, 5); + assert.equal(join(baseDir, "userdata-v2"), resolved.stateDir); }), ); diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index e678264dde..1173ee0a15 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -102,10 +102,7 @@ export const deriveServerPaths = Effect.fn(function* ( options: DeriveServerPathsOptions = {}, ): Effect.fn.Return { const { join } = yield* Path.Path; - const stateDir = join( - baseDir, - devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata", - ); + const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata-v2"); const dbPath = join(stateDir, "state.sqlite"); const attachmentsDir = join(stateDir, "attachments"); const logsDir = join(stateDir, "logs"); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index cac42a567b..2578101394 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -776,6 +776,17 @@ export type CodexDynamicToolItem = Extract< { readonly type: "mcpToolCall" | "dynamicToolCall" } >; +type CodexCollabAgentToolCallItem = Extract< + CodexSchema.V2ItemCompletedNotification__ThreadItem, + { readonly type: "collabAgentToolCall" } +>; + +type CodexSubAgentActivityItem = Extract< + | CodexSchema.V2ItemStartedNotification__ThreadItem + | CodexSchema.V2ItemCompletedNotification__ThreadItem, + { readonly type: "subAgentActivity" } +>; + export interface CodexAgentMessageDeltaUpdate { readonly turnId: string; readonly itemId: string; @@ -1569,160 +1580,181 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); }); - const registerSubagentThreads = (input: { + const registerSubagentThread = (input: { readonly context: ActiveCodexTurnContext; - readonly item: Extract< - CodexSchema.V2ItemCompletedNotification__ThreadItem, - { type: "collabAgentToolCall" } - >; + readonly nativeThreadId: string; + readonly nativeItemId: string; + readonly nativeToolCallId: string; + readonly prompt: string; + readonly title: string | null; + readonly model: string | null; + readonly ordinal: number; + readonly emitInitialPrompt: boolean; }) => Effect.gen(function* () { - if (input.item.tool !== "spawnAgent" || input.item.receiverThreadIds.length === 0) { + const registeredSubagents = yield* Ref.get(subagentThreads); + if (registeredSubagents.has(input.nativeThreadId)) { return; } const now = yield* DateTime.now; - for (const [index, nativeThreadId] of input.item.receiverThreadIds.entries()) { - const registeredSubagents = yield* Ref.get(subagentThreads); - if (registeredSubagents.has(nativeThreadId)) { - continue; - } + const subagentNodeId = idAllocator.derive.nodeFromProviderItem({ + driver: CODEX_PROVIDER, + nativeItemId: input.nativeItemId, + }); + const childRootNodeId = idAllocator.derive.nodeFromProviderItem({ + driver: CODEX_PROVIDER, + nativeItemId: `${input.nativeItemId}:thread-root`, + }); + const childThreadId = idAllocator.derive.threadFromProviderThread({ + driver: CODEX_PROVIDER, + nativeThreadId: input.nativeThreadId, + }); + const turnItemOrdinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); + const providerThread = { + id: idAllocator.derive.providerThread({ + driver: CODEX_PROVIDER, + nativeThreadId: input.nativeThreadId, + }), + driver: CODEX_PROVIDER, + providerInstanceId: input.context.input.modelSelection.instanceId, + providerSessionId: input.context.providerThread.providerSessionId, + appThreadId: childThreadId, + ownerNodeId: null, + nativeThreadRef: { + driver: CODEX_PROVIDER, + nativeId: input.nativeThreadId, + strength: "strong" as const, + }, + nativeConversationHeadRef: null, + status: "idle" as const, + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: { + providerThreadId: input.context.providerThread.id, + providerTurnId: input.context.providerTurnId, + }, + createdAt: now, + updatedAt: now, + } satisfies OrchestrationV2ProviderThread; + const task = { + id: subagentNodeId, + threadId: input.context.input.threadId, + runId: input.context.input.runId, + parentNodeId: input.context.rootNodeId, + origin: "provider_native", + createdBy: "agent", + driver: CODEX_PROVIDER, + providerInstanceId: input.context.input.modelSelection.instanceId, + providerThreadId: providerThread.id, + childThreadId, + nativeTaskRef: codexNativeItemRef(input.nativeItemId), + prompt: input.prompt, + title: input.title, + model: input.model, + status: "running", + result: null, + startedAt: now, + completedAt: null, + updatedAt: now, + } satisfies OrchestrationV2Subagent; + const subagent = { + parentContext: input.context, + providerThread, + subagentNodeId, + childRootNodeId, + childThreadId, + nativeToolCallId: input.nativeToolCallId, + ordinal: input.ordinal, + startedAt: now, + turnItemId: idAllocator.derive.turnItemFromProviderItem({ + driver: CODEX_PROVIDER, + nativeItemId: input.nativeItemId, + }), + turnItemOrdinal, + task, + } satisfies CodexSubagentThreadContext; - const nativeItemId = `${input.item.id}:${nativeThreadId}`; - const subagentNodeId = idAllocator.derive.nodeFromProviderItem({ - driver: CODEX_PROVIDER, - nativeItemId, - }); - const childRootNodeId = idAllocator.derive.nodeFromProviderItem({ - driver: CODEX_PROVIDER, - nativeItemId: `${nativeItemId}:thread-root`, - }); - const childThreadId = idAllocator.derive.threadFromProviderThread({ - driver: CODEX_PROVIDER, - nativeThreadId, - }); - const turnItemOrdinal = yield* resolveItemOrdinal(input.context, nativeItemId); - const providerThread = { - id: idAllocator.derive.providerThread({ - driver: CODEX_PROVIDER, - nativeThreadId, - }), - driver: CODEX_PROVIDER, - providerInstanceId: input.context.input.modelSelection.instanceId, - providerSessionId: input.context.providerThread.providerSessionId, - appThreadId: childThreadId, - ownerNodeId: null, - nativeThreadRef: { - driver: CODEX_PROVIDER, - nativeId: nativeThreadId, - strength: "strong" as const, - }, - nativeConversationHeadRef: null, - status: "idle" as const, - firstRunOrdinal: null, - lastRunOrdinal: null, - handoffIds: [], - forkedFrom: { - providerThreadId: input.context.providerThread.id, - providerTurnId: input.context.providerTurnId, - }, - createdAt: now, - updatedAt: now, - } satisfies OrchestrationV2ProviderThread; - const task = { + yield* Ref.update(subagentThreads, (current) => { + const updated = new Map(current); + updated.set(input.nativeThreadId, subagent); + return updated; + }); + const childThread = makeSubagentChildThread({ + parentThread: input.context.input.appThread, + childThreadId, + parentNodeId: subagentNodeId, + activeProviderThreadId: providerThread.id, + providerInstanceId: input.context.input.modelSelection.instanceId, + modelSelection: { + ...input.context.input.modelSelection, + model: task.model ?? input.context.input.modelSelection.model, + }, + title: subagentThreadTitle({ + parentTitle: input.context.input.appThread.title, + prompt: task.prompt, + title: task.title, + ordinal: input.ordinal, + }), + now, + createdBy: "agent", + creationSource: "provider", + }); + yield* emitProviderEvent({ + type: "app_thread.created", + driver: CODEX_PROVIDER, + appThread: childThread, + }); + yield* emitProviderEvent({ + type: "node.updated", + driver: CODEX_PROVIDER, + node: { id: subagentNodeId, threadId: input.context.input.threadId, runId: input.context.input.runId, parentNodeId: input.context.rootNodeId, - origin: "provider_native", - createdBy: "agent", - driver: CODEX_PROVIDER, - providerInstanceId: input.context.input.modelSelection.instanceId, - providerThreadId: providerThread.id, - childThreadId, - nativeTaskRef: codexNativeItemRef(nativeItemId), - prompt: input.item.prompt ?? "", - title: null, - model: - typeof input.item.model === "string" && input.item.model.length > 0 - ? input.item.model - : null, + rootNodeId: input.context.rootNodeId, + kind: "subagent", status: "running", - result: null, + countsForRun: false, + providerThreadId: providerThread.id, + providerTurnId: input.context.providerTurnId, + nativeItemRef: codexNativeItemRef(input.nativeToolCallId), + runtimeRequestId: null, + checkpointScopeId: null, startedAt: now, completedAt: null, - updatedAt: now, - } satisfies OrchestrationV2Subagent; - const subagent = { - parentContext: input.context, - providerThread, - subagentNodeId, - childRootNodeId, - childThreadId, - nativeToolCallId: input.item.id, - ordinal: index + 1, - startedAt: now, - turnItemId: idAllocator.derive.turnItemFromProviderItem({ - driver: CODEX_PROVIDER, - nativeItemId, - }), - turnItemOrdinal, - task, - } satisfies CodexSubagentThreadContext; - - const emitProviderEvent = (event: ProviderAdapterV2Event) => - Queue.offer(events, event).pipe(Effect.asVoid); - - const findActiveTurnByNativeThreadId = (nativeThreadId: string) => - Effect.gen(function* () { - const turns = Array.from((yield* Ref.get(activeTurns)).values()); - return turns.find( - (context) => - context.input.providerThread.nativeThreadRef?.nativeId === nativeThreadId, - ); + }, }); - - const resolveItemOrdinal = (context: ActiveCodexTurnContext, nativeItemId: string) => - Effect.gen(function* () { - const existing = (yield* Ref.get(itemOrdinals)).get(nativeItemId); - if (existing !== undefined) { - return existing; - } - - const turnKey = context.nativeTurnId; - const nextWithinTurn = yield* Ref.modify(nextItemOrdinalsByTurn, (current) => { - const next = (current.get(turnKey) ?? 0) + 1; - const updated = new Map(current); - updated.set(turnKey, next); - return [next, updated]; - }); - const nextOrdinal = context.providerTurnOrdinal * 100 + nextWithinTurn; - yield* Ref.update(itemOrdinals, (current) => { - const updated = new Map(current); - updated.set(nativeItemId, nextOrdinal); - return updated; - }); - const childThread = makeSubagentChildThread({ - parentThread: input.context.input.appThread, - childThreadId, - parentNodeId: subagentNodeId, - activeProviderThreadId: providerThread.id, - providerInstanceId: input.context.input.modelSelection.instanceId, - modelSelection: { - ...input.context.input.modelSelection, - model: task.model ?? input.context.input.modelSelection.model, - }, - title: subagentThreadTitle({ - parentTitle: input.context.input.appThread.title, - prompt: task.prompt, - title: task.title, - ordinal: index + 1, - }), - now, - createdBy: "agent", - creationSource: "provider", - }); - const promptNativeItemId = `${nativeItemId}:prompt`; + yield* emitProviderEvent({ + type: "node.updated", + driver: CODEX_PROVIDER, + node: { + id: childRootNodeId, + threadId: childThreadId, + runId: null, + parentNodeId: null, + rootNodeId: childRootNodeId, + kind: "root_turn", + status: "running", + countsForRun: false, + providerThreadId: providerThread.id, + providerTurnId: null, + nativeItemRef: codexNativeItemRef(input.nativeItemId), + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: now, + completedAt: null, + }, + }); + yield* emitProviderEvent({ + type: "provider_thread.updated", + driver: CODEX_PROVIDER, + providerThread, + }); + if (input.emitInitialPrompt && input.prompt.length > 0) { + const promptNativeItemId = `${input.nativeItemId}:prompt`; const promptArtifacts = makeSubagentConversationArtifacts({ messageId: idAllocator.derive.messageFromProviderItem({ driver: CODEX_PROVIDER, @@ -1738,62 +1770,10 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi providerTurnId: null, nativeItemRef: codexNativeItemRef(promptNativeItemId), role: "user", - text: task.prompt, + text: input.prompt, ordinal: 100, now, }); - yield* emitProviderEvent({ - type: "app_thread.created", - driver: CODEX_PROVIDER, - appThread: childThread, - }); - yield* emitProviderEvent({ - type: "node.updated", - driver: CODEX_PROVIDER, - node: { - id: subagentNodeId, - threadId: input.context.input.threadId, - runId: input.context.input.runId, - parentNodeId: input.context.rootNodeId, - rootNodeId: input.context.rootNodeId, - kind: "subagent", - status: "running", - countsForRun: false, - providerThreadId: providerThread.id, - providerTurnId: input.context.providerTurnId, - nativeItemRef: codexNativeItemRef(input.item.id), - runtimeRequestId: null, - checkpointScopeId: null, - startedAt: now, - completedAt: null, - }, - }); - yield* emitProviderEvent({ - type: "node.updated", - driver: CODEX_PROVIDER, - node: { - id: childRootNodeId, - threadId: childThreadId, - runId: null, - parentNodeId: null, - rootNodeId: childRootNodeId, - kind: "root_turn", - status: "running", - countsForRun: false, - providerThreadId: providerThread.id, - providerTurnId: null, - nativeItemRef: codexNativeItemRef(nativeItemId), - runtimeRequestId: null, - checkpointScopeId: null, - startedAt: now, - completedAt: null, - }, - }); - yield* emitProviderEvent({ - type: "provider_thread.updated", - driver: CODEX_PROVIDER, - providerThread, - }); yield* emitProviderEvent({ type: "message.updated", driver: CODEX_PROVIDER, @@ -1804,41 +1784,91 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi driver: CODEX_PROVIDER, turnItem: promptArtifacts.turnItem, }); - yield* emitSubagentTaskUpdate({ - subagent, - status: "running", - }); - - const resolvePlanId = (context: ActiveCodexTurnContext, planKey: string) => - Effect.gen(function* () { - const existing = (yield* Ref.get(planIds)).get(planKey); - if (existing !== undefined) { - return existing; - } - const planId = yield* idAllocator.allocate.plan({ - threadId: context.input.threadId, - runId: context.input.runId, - provider: CODEX_PROVIDER, - }); - yield* Ref.update(planIds, (current) => { - const updated = new Map(current); - updated.set(planKey, planId); - return updated; - }); - return planId; + } + yield* emitSubagentTaskUpdate({ + subagent, + status: "running", }); - const updateSubagentStates = (input: { - readonly item: Extract< - CodexSchema.V2ItemCompletedNotification__ThreadItem, - { type: "collabAgentToolCall" } - >; + const pendingTurns = yield* Ref.modify(pendingSubagentTurns, (current) => { + const pending = current.get(input.nativeThreadId) ?? []; + const updated = new Map(current); + updated.delete(input.nativeThreadId); + return [pending, updated]; + }); + for (const pendingTurn of pendingTurns) { + yield* emitSubagentProviderTurnStarted(subagent, pendingTurn); + } + }); + + const registerSubagentThreads = (input: { + readonly context: ActiveCodexTurnContext; + readonly item: CodexCollabAgentToolCallItem; }) => Effect.gen(function* () { - if (input.item.tool !== "spawnAgent") { + if (input.item.tool !== "spawnAgent" || input.item.receiverThreadIds.length === 0) { return; } + for (const [index, nativeThreadId] of input.item.receiverThreadIds.entries()) { + const model = + typeof input.item.model === "string" && input.item.model.length > 0 + ? input.item.model + : null; + yield* registerSubagentThread({ + context: input.context, + nativeThreadId, + nativeItemId: `${input.item.id}:${nativeThreadId}`, + nativeToolCallId: input.item.id, + prompt: input.item.prompt ?? "", + title: null, + model, + ordinal: index + 1, + emitInitialPrompt: true, + }); + } + }); + + const registerSubagentActivity = (input: { + readonly context: ActiveCodexTurnContext; + readonly item: CodexSubAgentActivityItem; + }) => + Effect.gen(function* () { + if (input.item.kind === "started") { + const registeredSubagents = yield* Ref.get(subagentThreads); + const ordinal = + Array.from(registeredSubagents.values()).filter( + (subagent) => subagent.parentContext.rootNodeId === input.context.rootNodeId, + ).length + 1; + yield* registerSubagentThread({ + context: input.context, + nativeThreadId: input.item.agentThreadId, + nativeItemId: `${input.item.id}:${input.item.agentThreadId}`, + nativeToolCallId: input.item.id, + prompt: "", + title: input.item.agentPath, + model: null, + ordinal, + emitInitialPrompt: false, + }); + return; + } + + const subagent = (yield* Ref.get(subagentThreads)).get(input.item.agentThreadId); + if (subagent === undefined) { + return; + } + + if (input.item.kind === "interrupted") { + yield* emitSubagentTaskUpdate({ + subagent, + status: "interrupted", + }); + } + }); + + const updateSubagentStates = (input: { readonly item: CodexCollabAgentToolCallItem }) => + Effect.gen(function* () { const subagents = yield* Ref.get(subagentThreads); for (const [nativeThreadId, state] of Object.entries(input.item.agentsStates)) { const subagent = subagents.get(nativeThreadId); @@ -3379,6 +3409,14 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi } } + if (payload.item.type === "subAgentActivity") { + yield* registerSubagentActivity({ + context, + item: payload.item, + }); + return; + } + if (payload.item.type === "commandExecution") { const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item); yield* emitProviderEvent({ @@ -3566,6 +3604,14 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi return; } + if (payload.item.type === "subAgentActivity") { + yield* registerSubagentActivity({ + context, + item: payload.item, + }); + return; + } + if (payload.item.type !== "agentMessage") { return; } diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index cd9f177ea4..a588bb25bc 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -20,8 +20,10 @@ import { ThreadId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; 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 Stream from "effect/Stream"; @@ -251,3 +253,209 @@ it.effect("rechecks run ownership immediately before calling the provider", () = assert.equal(yield* Ref.get(providerStarts), 0); }).pipe(Effect.provide(RunExecutionTestLayer)), ); + +it.effect("keeps ingesting owned child events after the root turn terminalizes", () => + Effect.gen(function* () { + const threadId = ThreadId.make("thread:run-execution-late-child"); + const childThreadId = ThreadId.make("thread:run-execution-late-child:child"); + const runId = RunId.make("run:run-execution-late-child"); + const attemptId = RunAttemptId.make("attempt:run-execution-late-child"); + const providerInstanceId = ProviderInstanceId.make("codex"); + const providerSessionId = ProviderSessionId.make("session:run-execution-late-child"); + const providerThreadId = ProviderThreadId.make("provider-thread:run-execution-late-child"); + const childProviderThreadId = ProviderThreadId.make( + "provider-thread:run-execution-late-child:child", + ); + const rootProviderTurnId = ProviderTurnId.make("provider-turn:run-execution-late-child"); + const childProviderTurnId = ProviderTurnId.make("provider-turn:run-execution-late-child:child"); + const rootNodeId = NodeId.make("node:run-execution-late-child"); + const childNodeId = NodeId.make("node:run-execution-late-child:child"); + const subagentNodeId = NodeId.make("node:run-execution-late-child:subagent"); + const childMessageIngested = yield* Deferred.make(); + const order = yield* Ref.make>([]); + const testLayer = runExecutionServiceLayer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(CheckpointServiceV2)({ captureBaseline: () => Effect.void }), + Layer.mock(EventSinkV2)({ + write: () => Effect.succeed([]), + writeWithEffects: (input) => + Effect.gen(function* () { + if ( + input.events.some( + (event) => event.type === "run.updated" && event.runId === runId, + ) + ) { + yield* Ref.update(order, (current) => [...current, "root-finalized"]); + } + return []; + }), + writeIfRunCurrent: () => Effect.succeed({ committed: true, storedEvents: [] }), + }), + idAllocatorLayer, + Layer.mock(ProviderEventIngestorV2)({ + ingestNormalized: (input) => + Effect.gen(function* () { + if ( + input.event.type === "message.updated" && + input.event.message.threadId === childThreadId + ) { + yield* Ref.update(order, (current) => [...current, "child-message"]); + yield* Deferred.succeed(childMessageIngested, undefined).pipe(Effect.ignore); + } + return []; + }), + }), + ServerSettingsService.layerTest(), + ), + ), + ); + const events: ReadonlyArray = [ + { + type: "app_thread.created", + driver, + appThread: { + id: childThreadId, + lineage: { + parentThreadId: threadId, + relationshipToParent: "subagent", + rootThreadId: threadId, + }, + }, + } as ProviderAdapterV2Event, + { + type: "provider_thread.updated", + driver, + providerThread: { + id: childProviderThreadId, + appThreadId: childThreadId, + }, + } as ProviderAdapterV2Event, + { + type: "subagent.updated", + driver, + subagent: { + id: subagentNodeId, + threadId, + runId, + status: "running", + }, + } as ProviderAdapterV2Event, + { + type: "provider_turn.updated", + driver, + threadId: childThreadId, + providerTurn: { + id: childProviderTurnId, + providerThreadId: childProviderThreadId, + nodeId: childNodeId, + runAttemptId: null, + status: "running", + }, + } as ProviderAdapterV2Event, + { + type: "turn.terminal", + driver, + providerThreadId, + providerTurnId: rootProviderTurnId, + runOrdinal: 1, + status: "completed", + failure: null, + threadDisposition: "reusable", + }, + { + type: "message.updated", + driver, + message: { + id: MessageId.make("message:run-execution-late-child:child"), + threadId: childThreadId, + runId: null, + nodeId: childNodeId, + role: "assistant", + text: "Hello.", + streaming: false, + }, + } as ProviderAdapterV2Event, + { + type: "provider_turn.updated", + driver, + threadId: childThreadId, + providerTurn: { + id: childProviderTurnId, + providerThreadId: childProviderThreadId, + nodeId: childNodeId, + runAttemptId: null, + status: "completed", + }, + } as ProviderAdapterV2Event, + { + type: "subagent.updated", + driver, + subagent: { + id: subagentNodeId, + threadId, + runId, + status: "completed", + }, + } as ProviderAdapterV2Event, + ]; + + yield* Effect.gen(function* () { + const runExecution = yield* RunExecutionServiceV2; + yield* runExecution.startRootRun({ + commandId: CommandId.make("command:run-execution-late-child"), + appThread: { id: threadId } as OrchestrationV2AppThread, + providerSessionId, + session: { + events: Stream.fromIterable(events), + startTurn: () => Effect.void, + } as unknown as ProviderAdapterV2SessionRuntime, + run: { + id: runId, + threadId, + ordinal: 1, + providerInstanceId, + } as OrchestrationV2Run, + rootNode: { id: rootNodeId } as OrchestrationV2ExecutionNode, + checkpointScope: { + id: CheckpointScopeId.make("checkpoint-scope:run-execution-late-child"), + } as OrchestrationV2CheckpointScope, + providerThread: { + id: providerThreadId, + driver, + } as OrchestrationV2ProviderThread, + attempt: { + id: attemptId, + providerTurnId: rootProviderTurnId, + } as OrchestrationV2RunAttempt, + attemptId, + providerTurnOrdinal: 1, + message: { + messageId: MessageId.make("message:run-execution-late-child:user"), + text: "Spawn a child and finish.", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" }, + runtimePolicy: { + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }); + }).pipe(Effect.provide(testLayer)); + + const observed = yield* Deferred.await(childMessageIngested).pipe( + Effect.timeoutOption("2 seconds"), + ); + assert.isTrue(Option.isSome(observed), "child message was not ingested after root terminal"); + assert.deepEqual(yield* Ref.get(order), ["root-finalized", "child-message"]); + }), +); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 4010f5f151..c3da3c886f 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -1,13 +1,16 @@ import { CommandId, type ModelSelection, + type NodeId, type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, type OrchestrationV2ExecutionNode, type OrchestrationV2ProviderFailure, type OrchestrationV2ProviderThread, + type OrchestrationV2ProviderTurn, type OrchestrationV2Run, type OrchestrationV2RunAttempt, + type OrchestrationV2Subagent, type OrchestrationV2TurnItem, type ProviderSessionId, type ProviderThreadId, @@ -54,6 +57,24 @@ export interface ProviderEventRouteIdentity { type ProviderTerminalEvent = Extract; +function isTerminalProviderTurnStatus(status: OrchestrationV2ProviderTurn["status"]): boolean { + return ( + status === "completed" || + status === "interrupted" || + status === "failed" || + status === "cancelled" + ); +} + +function isTerminalSubagentStatus(status: OrchestrationV2Subagent["status"]): boolean { + return ( + status === "completed" || + status === "interrupted" || + status === "failed" || + status === "cancelled" + ); +} + export function finalProviderThreadStatus( disposition: ProviderTerminalEvent["threadDisposition"], ): OrchestrationV2ProviderThread["status"] { @@ -532,6 +553,82 @@ export const layer: Layer.Layer< : { relatedProviderThreadIds: input.relatedProviderThreadIds }), }), ); + const rootTerminalSeen = yield* Ref.make(false); + const rootRunFinalized = yield* Ref.make(false); + const activeChildProviderTurns = yield* Ref.make>(new Set()); + const activeChildSubagents = yield* Ref.make>(new Set()); + const finalizeRootRun = (terminal: ProviderTerminalEvent) => + Effect.gen(function* () { + if (yield* Ref.get(rootRunFinalized)) { + return; + } + const providerThread = yield* Ref.get(latestProviderThread); + yield* writeFinalRunEvents({ + run: input.run, + rootNode: input.rootNode, + checkpointScope: input.checkpointScope, + providerThread, + attempt: input.attempt, + ...(input.shouldFinalizeRun === undefined + ? {} + : { shouldFinalizeRun: input.shouldFinalizeRun }), + terminal, + failureItemPersisted: terminal.status === "failed", + }).pipe( + Effect.mapError( + (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), + ), + ); + yield* Ref.set(rootRunFinalized, true); + }); + const trackChildLifecycle = (event: ProviderAdapterV2Event) => + Effect.gen(function* () { + const routing = yield* Ref.get(eventRouting); + if (event.type === "provider_turn.updated") { + const isRoot = + event.providerTurn.runAttemptId === input.attempt.id || + event.providerTurn.id === routing.rootProviderTurnId; + if (!isRoot) { + yield* Ref.update(activeChildProviderTurns, (current) => { + const next = new Set(current); + if (isTerminalProviderTurnStatus(event.providerTurn.status)) { + next.delete(event.providerTurn.id); + } else { + next.add(event.providerTurn.id); + } + return next; + }); + } + } + if (event.type === "subagent.updated") { + const belongsToRootRun = event.subagent.runId === input.run.id; + const belongsToOwnedChildThread = + event.subagent.threadId !== input.run.threadId && + routing.ownedThreadIds.has(event.subagent.threadId); + if (belongsToRootRun || belongsToOwnedChildThread) { + yield* Ref.update(activeChildSubagents, (current) => { + const next = new Set(current); + if (isTerminalSubagentStatus(event.subagent.status)) { + next.delete(event.subagent.id); + } else { + next.add(event.subagent.id); + } + return next; + }); + } + } + }); + const shouldStopProviderEventIngestion = Effect.gen(function* () { + if (!(yield* Ref.get(rootTerminalSeen))) { + return false; + } + const childProviderTurns = yield* Ref.get(activeChildProviderTurns); + if (childProviderTurns.size > 0) { + return false; + } + const childSubagents = yield* Ref.get(activeChildSubagents); + return childSubagents.size === 0; + }); const eventSubscription = input.session.subscribeEvents === undefined ? { events: input.session.events, close: Effect.void } @@ -540,8 +637,7 @@ export const layer: Layer.Layer< Stream.filterEffect((event) => Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)), ), - Stream.takeUntil((event) => event.type === "turn.terminal"), - Stream.runForEach((event) => + Stream.tap((event) => Effect.gen(function* () { let storedEventCount = 0; if (shouldDeliverProviderEvent(event, assistantStreamingEnabled)) { @@ -581,9 +677,14 @@ export const layer: Layer.Layer< } if (event.type === "turn.terminal") { yield* Ref.set(terminalEvent, event); + yield* Ref.set(rootTerminalSeen, true); + yield* finalizeRootRun(event); } + yield* trackChildLifecycle(event); }), ), + Stream.takeUntilEffect(() => shouldStopProviderEventIngestion), + Stream.runDrain, Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })), Effect.flatMap(() => Effect.gen(function* () { @@ -591,62 +692,55 @@ export const layer: Layer.Layer< if (terminal === null) { return; } - const providerThread = yield* Ref.get(latestProviderThread); - yield* writeFinalRunEvents({ - run: input.run, - rootNode: input.rootNode, - checkpointScope: input.checkpointScope, - providerThread, - attempt: input.attempt, - ...(input.shouldFinalizeRun === undefined - ? {} - : { shouldFinalizeRun: input.shouldFinalizeRun }), - terminal, - failureItemPersisted: terminal.status === "failed", - }).pipe( - Effect.mapError( - (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), - ), - ); + yield* finalizeRootRun(terminal); }), ), Effect.catchCause((cause) => - Effect.logWarning("orchestration V2 provider event ingestion failed", { - runId: input.run.id, - cause, - }).pipe( - Effect.andThen(Ref.get(latestProviderThread)), - Effect.flatMap((providerThread) => - Ref.get(latestTurnItemOrdinal).pipe( - Effect.flatMap((latestItemOrdinal) => - writeFinalRunEvents({ - run: input.run, - rootNode: input.rootNode, - checkpointScope: input.checkpointScope, - providerThread, - attempt: input.attempt, - ...(input.shouldFinalizeRun === undefined - ? {} - : { shouldFinalizeRun: input.shouldFinalizeRun }), - terminal: makeFailedTerminalEvent( - makeProviderFailure({ - cause: Cause.squash(cause), - class: "unknown", - }), - latestItemOrdinal + 1, - ), - failureItemPersisted: false, - }), + Ref.get(rootRunFinalized).pipe( + Effect.flatMap((finalized) => + Effect.logWarning("orchestration V2 provider event ingestion failed", { + runId: input.run.id, + cause, + }).pipe( + Effect.andThen( + finalized + ? Effect.void + : Ref.get(latestProviderThread).pipe( + Effect.flatMap((providerThread) => + Ref.get(latestTurnItemOrdinal).pipe( + Effect.flatMap((latestItemOrdinal) => + writeFinalRunEvents({ + run: input.run, + rootNode: input.rootNode, + checkpointScope: input.checkpointScope, + providerThread, + attempt: input.attempt, + ...(input.shouldFinalizeRun === undefined + ? {} + : { shouldFinalizeRun: input.shouldFinalizeRun }), + terminal: makeFailedTerminalEvent( + makeProviderFailure({ + cause: Cause.squash(cause), + class: "unknown", + }), + latestItemOrdinal + 1, + ), + failureItemPersisted: false, + }), + ), + ), + ), + ), + ), + Effect.mapError( + (writeCause) => + new RunExecutionIngestError({ + runId: input.run.id, + cause: { ingest: cause, write: writeCause }, + }), ), ), ), - Effect.mapError( - (writeCause) => - new RunExecutionIngestError({ - runId: input.run.id, - cause: { ingest: cause, write: writeCause }, - }), - ), ), ), Effect.ensuring(eventSubscription.close), diff --git a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts index 55a0906297..d47fb5cdaa 100644 --- a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts @@ -136,6 +136,19 @@ const scenarioExpectations = { turnCompletedCount: 0, approvalRequestCount: 0, }, + subagent_v2: { + outgoing: ["initialize", "initialized", "thread/start", "turn/start"], + incoming: [ + "turn/started", + "item/completed/subAgentActivity-started", + "turn/started/child", + "item/completed/child-answer", + "turn/completed", + ], + turnStartCount: 1, + turnCompletedCount: 2, + approvalRequestCount: 0, + }, multi_turn: { outgoing: ["initialize", "initialized", "thread/start", "turn/start"], incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"], diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts index 460bdbdf22..59fcb72a78 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts @@ -29,6 +29,8 @@ import { subagentInput } from "./subagent/input.ts"; import { assertCursorSubagentOutput } from "./subagent/cursor_output.ts"; import { assertSubagentContinueOutput } from "./subagent_continue/codex_output.ts"; import { subagentContinueInput } from "./subagent_continue/input.ts"; +import { assertSubagentV2Output } from "./subagent_v2/codex_output.ts"; +import { subagentV2Input } from "./subagent_v2/input.ts"; import { assertClaudeThreadRollbackOutput } from "./thread_rollback/claude_output.ts"; import { assertThreadRollbackOutput } from "./thread_rollback/codex_output.ts"; import { threadRollbackInput } from "./thread_rollback/input.ts"; @@ -322,6 +324,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ }, ], }, + { + name: "subagent_v2", + buildInput: subagentV2Input, + providers: [ + { + driver: ProviderDriverKind.make("codex"), + transcriptFile: new URL("./subagent_v2/codex_transcript.ndjson", import.meta.url), + modelSelection: CODEX_MODEL_SELECTION, + assertOutput: assertSubagentV2Output, + }, + ], + }, { name: "opencode_subagent", buildInput: openCodeSubagentInput, diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts index 1dd8fe2d73..49744c57ad 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts @@ -42,6 +42,7 @@ export const MESSAGE_STEERING_INITIAL_PROMPT = "Respond with exactly: steering fixture initial response"; export const SUBAGENT_PROMPT = "Spawn 2 subagents, one to read package.json and one to read tsconfig.json"; +export const SUBAGENT_V2_PROMPT = "just say hello"; export const OPENCODE_SUBAGENT_PROMPT = "Use the task tool exactly once. Delegate to the general subagent with this prompt: Respond exactly CHILD_OK. After the task completes, respond exactly PARENT_OK."; export const SUBAGENT_CONTINUE_PROMPT = diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.ts new file mode 100644 index 0000000000..b3154161a6 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.ts @@ -0,0 +1,77 @@ +import { assert } from "@effect/vitest"; +import type { ProviderReplayTranscript } from "@t3tools/contracts"; + +import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts"; +import { + assertBaseProjection, + assertExecutionNodeKinds, + assertNoExtraAppRunsForProviderChildren, + assertRunProviderTurnCardinality, + assertSemanticProjectionIntegrity, + assertTurnItemTypes, + assertUserMessagesInclude, + projectionFor, + SUBAGENT_V2_PROMPT, +} from "../shared.ts"; + +export function assertSubagentV2Output( + result: OrchestratorV2ScenarioResult, + transcript: ProviderReplayTranscript, +) { + assertBaseProjection({ + result, + transcript, + runCount: 1, + runStatuses: ["completed"], + }); + + const projection = projectionFor(result, transcript.scenario); + assertSemanticProjectionIntegrity(projection); + assertTurnItemTypes(projection, ["user_message", "subagent", "assistant_message"]); + assertExecutionNodeKinds(projection, ["root_turn", "subagent"]); + assertRunProviderTurnCardinality({ projection, rootRunCount: 1 }); + assertNoExtraAppRunsForProviderChildren({ projection, expectedAppRuns: 1 }); + assertUserMessagesInclude(projection, [SUBAGENT_V2_PROMPT]); + assert.lengthOf(projection.subagents, 1); + assert.lengthOf(result.shellSnapshot.threads, 2); + + const subagent = projection.subagents[0]!; + assert.equal(subagent.origin, "provider_native"); + assert.equal(subagent.createdBy, "agent"); + assert.equal(subagent.driver, "codex"); + assert.equal(subagent.title, "/root/hello_agent"); + assert.equal(subagent.prompt, ""); + assert.equal(subagent.status, "completed"); + assert.equal(subagent.result, "Hello."); + assert.isNotNull(subagent.childThreadId); + assert.isNotNull(subagent.providerThreadId); + assert.isNotNull(subagent.nativeTaskRef); + assert.isNotNull(subagent.completedAt); + if (subagent.childThreadId === null) { + throw new Error(`Subagent ${subagent.id} is missing its child thread`); + } + + const providerThread = projection.providerThreads.find( + (thread) => thread.id === subagent.providerThreadId, + ); + assert.isDefined(providerThread); + assert.equal(providerThread.appThreadId, subagent.childThreadId); + assert.isNull(providerThread.ownerNodeId); + + const childProjection = result.projections.get(subagent.childThreadId); + assert.isDefined(childProjection); + assert.equal(childProjection.thread.lineage.parentThreadId, projection.thread.id); + assert.equal(childProjection.thread.lineage.relationshipToParent, "subagent"); + assert.equal(childProjection.thread.activeProviderThreadId, providerThread.id); + assert.lengthOf(childProjection.runs, 0); + assert.lengthOf(childProjection.providerThreads, 1); + assert.lengthOf(childProjection.providerTurns, 1); + assertTurnItemTypes(childProjection, ["assistant_message"]); + assert.isTrue( + childProjection.turnItems.some( + (item) => item.type === "assistant_message" && item.text.includes("Hello."), + ), + "child thread must contain the post-root subagent response", + ); + assert.equal(childProjection.providerTurns[0]?.status, "completed"); +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson new file mode 100644 index 0000000000..f5a86c8a2f --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_transcript.ndjson @@ -0,0 +1,25 @@ +{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.141.0","scenario":"subagent_v2","metadata":{"source":"observed-codex-app-server-replay-fixture","fileName":"subagent_v2.ndjson","description":"Agents-v2 Codex subagent spawn observed from a real run: parent emits subAgentActivity(started), child emits a normal turn and final agent message."}} +{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true},"clientInfo":{"name":"t3code_desktop","title":"T3 Code Desktop","version":"0.1.0"}}}} +{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.141.0","codexHome":"/tmp/codex-home","platformFamily":"unix","platformOs":"macos"}}} +{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"native-v2-root-thread","sessionId":"native-v2-root-thread","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1782622440,"updatedAt":1782622440,"status":{"type":"idle"},"path":"/tmp/root-thread.jsonl","cwd":"/tmp","cliVersion":"0.141.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":null,"cwd":"/tmp","instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false},"reasoningEffort":"medium"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"just say hello","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"native-v2-root-thread"}}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":3,"result":{"turn":{"id":"native-v2-root-turn","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"thread/status/changed/root-active","frame":{"method":"thread/status/changed","params":{"threadId":"native-v2-root-thread","status":{"type":"active","activeFlags":[]}}}} +{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"native-v2-root-thread","turn":{"id":"native-v2-root-turn","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1782622440,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"item/completed/root-user","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"root-user-v2","clientId":null,"content":[{"type":"text","text":"just say hello","text_elements":[]}]},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","completedAtMs":1782622440261}}} +{"type":"emit_inbound","label":"thread/status/changed/child-idle-before-start","frame":{"method":"thread/status/changed","params":{"threadId":"native-v2-child-thread","status":{"type":"idle"}}}} +{"type":"emit_inbound","label":"item/completed/subAgentActivity-started","frame":{"method":"item/completed","params":{"item":{"type":"subAgentActivity","id":"call-v2-spawn","kind":"started","agentThreadId":"native-v2-child-thread","agentPath":"/root/hello_agent"},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","completedAtMs":1782622442529}}} +{"type":"emit_inbound","label":"thread/status/changed/child-active","frame":{"method":"thread/status/changed","params":{"threadId":"native-v2-child-thread","status":{"type":"active","activeFlags":[]}}}} +{"type":"emit_inbound","label":"turn/started/child","frame":{"method":"turn/started","params":{"threadId":"native-v2-child-thread","turn":{"id":"native-v2-child-turn","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1782622442,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"item/completed/root-commentary","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"root-commentary-v2","text":"I spawned a subagent to say hello.","phase":"commentary","memoryCitation":null},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","completedAtMs":1782622443818}}} +{"type":"emit_inbound","label":"item/started/wait-agent","frame":{"method":"item/started","params":{"item":{"type":"collabAgentToolCall","id":"wait-call-v2","tool":"wait","status":"inProgress","senderThreadId":"native-v2-root-thread","receiverThreadIds":[],"prompt":null,"model":null,"reasoningEffort":null,"agentsStates":{}},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","startedAtMs":1782622444012}}} +{"type":"emit_inbound","label":"item/completed/wait-agent","frame":{"method":"item/completed","params":{"item":{"type":"collabAgentToolCall","id":"wait-call-v2","tool":"wait","status":"completed","senderThreadId":"native-v2-root-thread","receiverThreadIds":[],"prompt":null,"model":null,"reasoningEffort":null,"agentsStates":{}},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","completedAtMs":1782622454013}}} +{"type":"emit_inbound","label":"item/completed/root-answer","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"root-answer-v2","text":"Subagent spawned as `/root/hello_agent`. It hasn't returned within the short wait window yet.","phase":"final_answer","memoryCitation":null},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","completedAtMs":1782622455859}}} +{"type":"emit_inbound","label":"thread/status/changed/root-idle","frame":{"method":"thread/status/changed","params":{"threadId":"native-v2-root-thread","status":{"type":"idle"}}}} +{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"native-v2-root-thread","turn":{"id":"native-v2-root-turn","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1782622440,"completedAt":1782622455,"durationMs":15598}}}} +{"type":"emit_inbound","label":"item/completed/child-answer","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"child-answer-v2","text":"Hello.","phase":"final_answer","memoryCitation":null},"threadId":"native-v2-child-thread","turnId":"native-v2-child-turn","completedAtMs":1782622463754}}} +{"type":"emit_inbound","label":"thread/status/changed/child-idle","frame":{"method":"thread/status/changed","params":{"threadId":"native-v2-child-thread","status":{"type":"idle"}}}} +{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"native-v2-child-thread","turn":{"id":"native-v2-child-turn","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1782622442,"completedAt":1782622463,"durationMs":21247}}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/input.ts b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/input.ts new file mode 100644 index 0000000000..e257e763bd --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/input.ts @@ -0,0 +1,7 @@ +import { SUBAGENT_V2_PROMPT, type OrchestratorFixtureInput } from "../shared.ts"; + +export function subagentV2Input(): OrchestratorFixtureInput { + return { + steps: [{ type: "message", text: SUBAGENT_V2_PROMPT }], + }; +} diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index 461509ea0a..6dcf6092a5 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -210,7 +210,7 @@ describe("ssh tunnel scripts", () => { assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"'); assert.include( buildRemoteLaunchScript(), - 'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"', + 'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata-v2/server-runtime.json"', ); assert.include(buildRemoteLaunchScript(), "resolve_default_runtime_port()"); assert.include( diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index 12ab002780..0ae667701d 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -457,7 +457,7 @@ export const REMOTE_LAUNCH_SCRIPT = `set -eu STATE_KEY="$1" STATE_DIR="$HOME/.t3/ssh-launch/$STATE_KEY" DEFAULT_SERVER_HOME="$HOME/.t3" -DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json" +DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata-v2/server-runtime.json" PORT_FILE="$STATE_DIR/port" PID_FILE="$STATE_DIR/pid" MANAGED_FILE="$STATE_DIR/managed"