diff --git a/UPSTREAM.md b/UPSTREAM.md index e817bd668f..d57d0fc8ef 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -260,6 +260,30 @@ native offering and adopted provider work retain their receipt-aware control. Preserve upstream's effect ordering and transaction/cancellation machinery. The maintained boundaries are in [the separation map](docs/internals/scient-fork-divergence.md#extracted-owners-and-host-mounts). +Scient's switch planning also runs on ordinary sends, so a project-folder move replaces the +native binding. For providers that negotiate per-thread workspaces in a pooled process, +`ProviderSwitchService.ts` compares the last bound workspace recorded by +`ProviderTurnStartService.ts` in the optional `nativeMetadata.cwd`, not the pooled process's +launch cwd; older records keep the conservative session-cwd fallback. Marked seams in +`ProviderEventIngestor.ts` and `RunExecutionService.ts` apply +`scient-provider/RecordedWorkspace.ts`, so the recorded value wins over an adapter's cached copy +of the same session's row. Detach passes Scient's optional `awaitRelease` (`provider-core` +`ProviderAdapter.ts`), and a marked block in `Adapters/CodexAdapterV2.ts` then waits up to 5 +seconds for `thread/closed`, including a close still pending from an earlier idle unsubscribe, +because the next owner may be another app-server process. `ProviderSessionManager.ts` remembers +threads an idle unload released (`idleUnloadedProviderThreads`) so a later handoff detach still +joins that release. Preserve these divergences. + +The same change pre-adopts two open upstream fixes in their touched hunks: +[#30647](https://github.com/pingdotgg/t3code/pull/30647)'s detach of the held native thread +(`ProviderSessionManager.ts`, without its per-thread config fixture churn) and +[#33767](https://github.com/pingdotgg/t3code/pull/33767)'s Codex unload delay launch argument and +closing-thread resume retry. When syncing, take upstream's version of those hunks, then reapply +the marked Scient additions inside them: the `awaitRelease` detach argument and +`idleUnloadedProviderThreads` fallback in `ProviderSessionManager.ts`, the release wait in +`CodexAdapterV2.unloadThread`, the `expectedRuntime` release argument, and the linked-environments +test assertions. See [provider lifecycle](docs/internals/providers.md#registry-and-routing). + This is the public ScientFactory-owned T3-derived desktop application. Official T3 supplies the maintained generic host platform; ScientFactory owns product policy, identity, scientific behavior, release decisions, and every deliberate diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.scient.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.scient.test.ts index 1bf2cd95d9..d5b86a75c3 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.scient.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.scient.test.ts @@ -5317,6 +5317,96 @@ describe("Codex restored Sessions", () => { ), ), ); + it.effect.each([ + { + name: "a handoff unload waits for the withheld thread/closed", + idleFirst: false, + awaitRelease: true, + }, + { + name: "an idle unload returns on the unsubscribe reply", + idleFirst: false, + awaitRelease: false, + }, + { + name: "a handoff after an idle unsubscribe waits for that pending thread/closed", + idleFirst: true, + awaitRelease: true, + }, + ])("$name", ({ idleFirst, awaitRelease }) => + Effect.gen(function* () { + const nativeThreadId = "handoff-thread"; + const closed = { + type: "emit_inbound" as const, + label: "withheld closure", + frame: { method: "thread/closed", params: { threadId: nativeThreadId } }, + }; + const unsubscribe = (id: number, status: string) => [ + { + type: "expect_outbound" as const, + frame: { id, method: "thread/unsubscribe", params: { threadId: nativeThreadId } }, + }, + { type: "emit_inbound" as const, frame: { id, result: { status } } }, + ]; + const transcript = makeCodexReplayTranscript({ + scenario: `handoff-release-${idleFirst}-${awaitRelease}`, + entries: [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "unused", + prompt: "unused", + }).slice(0, 5), + ...unsubscribe(3, "unsubscribed"), + // Codex 0.167 answers a second unsubscribe while the first close is still pending. + ...(idleFirst ? unsubscribe(4, "notSubscribed") : []), + closed, + ], + }); + const withheld = yield* Deferred.make(); + const release = yield* Deferred.make(); + yield* Effect.addFinalizer(() => Deferred.succeed(release, undefined)); + const driver = yield* CodexReplay.makeReplayDriver(transcript, { + beforeEmitInbound: (entry) => + entry.label === closed.label + ? Deferred.succeed(withheld, undefined).pipe(Effect.andThen(Deferred.await(release))) + : Effect.void, + }); + const harness = yield* makeCodexReplayHarness( + transcript, + undefined, + undefined, + undefined, + undefined, + undefined, + { replayDriver: driver }, + ); + if (idleFirst) { + yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread }); + } + const done = yield* Ref.make(false); + const unload = yield* harness.runtime.unloadThread!({ + providerThread: harness.providerThread, + awaitRelease, + }).pipe(Effect.andThen(Ref.set(done, true)), Effect.forkChild); + yield* Deferred.await(withheld); + // Codex has acknowledged the unsubscribe but still holds the writer. + yield* Effect.yieldNow; + const doneBeforeClose = yield* Ref.get(done); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(unload); + assert.equal(doneBeforeClose, !awaitRelease); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + NodeServices.layer, + NodeCrypto.layer, + McpProviderSessions.layer, + ), + ), + ), + ); // regression: de34391427 feat(orchestrator): introduce new orchestrator (#2829) it.effect("keeps the app-server failure as the cause when an unload is rejected", () => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 52e64fde88..2f11b43ecf 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -488,8 +488,15 @@ describe("CodexAdapterV2 process spawning", () => { yield* open({ T3CODE_CODEX_LAUNCH_ARGS: " --enable env-feature " }); assert.deepEqual(spawnedArgs, [ - ["app-server", "--strict-config", "-c", "model_reasoning_summary=detailed"], - ["app-server", "--enable", "env-feature"], + [ + "app-server", + "-c", + "thread_unload_delay_secs=0", + "--strict-config", + "-c", + "model_reasoning_summary=detailed", + ], + ["app-server", "-c", "thread_unload_delay_secs=0", "--enable", "env-feature"], ]); }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); @@ -3549,6 +3556,109 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + // regression: #33747 Codex refuses thread/resume until an unsubscribed thread finishes closing + it.effect.each([ + { name: "waits for thread/closed after a closing error", closedFirst: false }, + { name: "retries at once when the thread already closed", closedFirst: true }, + ])("$name", ({ name, closedFirst }) => + Effect.scoped( + Effect.gen(function* () { + const nativeThreadId = "closing-thread"; + const params = { + threadId: nativeThreadId, + excludeTurns: true, + cwd: CODEX_TEST_RUNTIME_POLICY.cwd, + model: CODEX_TEST_MODEL_SELECTION.model, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, + }; + const closed: CodexReplay.CodexAppServerReplayEntry = { + type: "emit_inbound", + label: "thread closed", + frame: { method: "thread/closed", params: { threadId: nativeThreadId } }, + }; + const closingError: CodexReplay.CodexAppServerReplayEntry = { + type: "emit_inbound", + label: "resume closing error", + frame: { + id: 4, + error: { + code: -32600, + message: `thread ${nativeThreadId} is closing; retry thread/resume after the thread is closed`, + }, + }, + }; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: name, + entries: [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "unused-turn", + prompt: "unused-prompt", + }).slice(0, 5), + { + type: "expect_outbound", + label: "unsubscribe", + frame: { + id: 3, + method: "thread/unsubscribe", + params: { threadId: nativeThreadId }, + }, + }, + { + type: "emit_inbound", + label: "unsubscribe result", + frame: { id: 3, result: { status: "unsubscribed" } }, + }, + { + type: "expect_outbound", + label: "resume closing thread", + frame: { id: 4, method: "thread/resume", params }, + }, + ...(closedFirst ? [closed, closingError] : [closingError, closed]), + { + type: "expect_outbound", + label: "retry identical resume", + frame: { id: 5, method: "thread/resume", params }, + }, + { + type: "emit_inbound", + label: "retry result", + frame: { + id: 5, + result: { + thread: { + id: nativeThreadId, + updatedAt: 1782622450, + turns: [{ type: "unknown-history-item" }], + }, + }, + }, + }, + ], + }), + ); + yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread }); + const resumed = yield* harness.runtime.resumeThread({ + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); + assert.equal(resumed.status, "idle"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + it.effect.each([ "recover", "completion-only", diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index f54dfd9f36..cbecef06f1 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -2079,6 +2079,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const pendingRuntimeRequests = yield* Ref.make( new Map(), ); + /** Completed by thread/closed after this connection unsubscribes from the native thread. */ + const threadClosings = new Map>(); /** Codex acceptForSession covers only the exact command or patch, not future commands. */ const sessionApprovals = new Map< string, @@ -5047,6 +5049,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( // their command items, while the shared provider session stays alive. yield* client.handleServerNotification("thread/closed", (payload) => Effect.gen(function* () { + const closing = threadClosings.get(payload.threadId); + threadClosings.delete(payload.threadId); + if (closing !== undefined) yield* Deferred.succeed(closing, undefined); const completedAt = yield* DateTime.now; for (const context of (yield* Ref.get(settledTurns)).values()) { if (context.providerThread.nativeThreadRef?.nativeId !== payload.threadId) continue; @@ -7014,7 +7019,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); }); - // Codex refuses to resume a session archived elsewhere until it is unarchived. + // Codex refuses to resume a session archived elsewhere until it is unarchived, and + // one it is still unloading after thread/unsubscribe until it emits thread/closed. const resumeNativeThread = Effect.fn("CodexAdapterV2.resumeNativeThread")(function* ( threadId: string, params: Record, @@ -7022,12 +7028,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const resume = client.raw.request("thread/resume", { threadId, ...params }); return yield* resume.pipe( Effect.catchTags({ - CodexAppServerRequestError: (cause) => - /\bsession \S+ is archived\b|\bcodex unarchive\b/i.test(cause.errorMessage) - ? client.raw - .request("thread/unarchive", { threadId }) - .pipe(Effect.andThen(resume)) - : Effect.fail(cause), + CodexAppServerRequestError: (cause) => { + if (/\bsession \S+ is archived\b|\bcodex unarchive\b/i.test(cause.errorMessage)) { + return client.raw + .request("thread/unarchive", { threadId }) + .pipe(Effect.andThen(resume)); + } + if (/\bthread \S+ is closing\b/i.test(cause.errorMessage)) { + const closing = threadClosings.get(threadId); + return ( + closing === undefined + ? Effect.void + : Deferred.await(closing).pipe(Effect.timeoutOption("10 seconds")) + ).pipe(Effect.andThen(resume)); + } + return Effect.fail(cause); + }, }), ); }); @@ -7582,7 +7598,33 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( function* (unloadInput) { const nativeThreadId = yield* getNativeThreadId(unloadInput.providerThread); sessionApprovals.delete(nativeThreadId); - yield* client.request("thread/unsubscribe", { threadId: nativeThreadId }); + // SCIENT-FORK:START — an earlier (idle) unsubscribe may still be closing the thread. + const pendingClose = threadClosings.get(nativeThreadId); + // SCIENT-FORK:END + // A resume may already wait on the pending entry; replacing it would strand that wait. + if (!threadClosings.has(nativeThreadId)) { + threadClosings.set(nativeThreadId, yield* Deferred.make()); + } + // SCIENT-FORK:START — a handoff's next owner is another process; Codex releases the + // writer only when the thread closes, after the unsubscribe reply. + const closing = threadClosings.get(nativeThreadId); + const unsubscribed = yield* client.request("thread/unsubscribe", { + threadId: nativeThreadId, + }); + if (closing === undefined) return; + // No thread/closed follows when the thread is gone or this call opened no close. + if ( + unsubscribed.status === "notLoaded" || + (unsubscribed.status === "notSubscribed" && pendingClose === undefined) + ) { + if (threadClosings.get(nativeThreadId) === closing) { + threadClosings.delete(nativeThreadId); + } + yield* Deferred.succeed(closing, undefined); + } else if (unloadInput.awaitRelease === true) { + yield* Deferred.await(closing).pipe(Effect.timeoutOption("5 seconds")); + } + // SCIENT-FORK:END }, (effect, unloadInput) => effect.pipe( diff --git a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts index efc2afce95..99c9e74dd9 100644 --- a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts +++ b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts @@ -464,6 +464,14 @@ describe("OpenCode 2 through the orchestrator", () => { projection.runs.map((run) => run.status), ["completed", "completed"], ); + // SCIENT-FORK:START — the binding records the folder the moved session now runs in. + assert.equal( + projection.providerThreads.find( + (providerThread) => providerThread.id === projection.thread.activeProviderThreadId, + )?.nativeMetadata?.cwd, + after, + ); + // SCIENT-FORK:END }).pipe(Effect.scoped), ); diff --git a/apps/server/src/orchestration-v2/PooledWorkspace.scient.integration.test.ts b/apps/server/src/orchestration-v2/PooledWorkspace.scient.integration.test.ts new file mode 100644 index 0000000000..4d71d2bdbb --- /dev/null +++ b/apps/server/src/orchestration-v2/PooledWorkspace.scient.integration.test.ts @@ -0,0 +1,185 @@ +import { assert, it } from "@effect/vitest"; +import { CommandId, EventId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as EventStore from "./EventStore.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderSessionManager from "./ProviderSessionManager.ts"; +import { layerWithRegistry } from "./testkit/ProviderReplayHarness.ts"; +import { awaitThreadProjection } from "./testkit/awaitThreadProjection.testkit.ts"; +import { + emptyState, + makeProviderAdapter, + makeProviderThread, + modelSelection, + runtimePolicy, +} from "./testkit/ProviderSessionManagerTestHarness.ts"; + +it.effect( + "completes a second turn in a pooled thread whose workspace differs from the process cwd", + () => + Effect.gen(function* () { + const allocator = yield* IdAllocator.IdAllocatorV2; + const state = yield* Ref.make(emptyState); + const workspace = yield* checkpointWorkspace("pooled-second-turn"); + const openingWorkspace = `${workspace}/opening-thread`; + yield* (yield* FileSystem.FileSystem).makeDirectory(openingWorkspace); + const registry = Layer.effect( + ProviderAdapterRegistry.ProviderAdapterRegistryV2, + Effect.gen(function* () { + const delegate = yield* makeProviderAdapter(state); + return ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({ + get: () => + Effect.succeed({ + ...delegate, + openSession: Effect.fn("PooledFixture.openSession")(function* (input) { + const runtime = yield* delegate.openSession(input); + return { + ...runtime, + ensureThread: Effect.fn("PooledFixture.ensureThread")(function* (request) { + return makeProviderThread({ + idAllocator: allocator, + threadId: request.threadId, + providerSessionId: input.providerSessionId, + now: yield* DateTime.now, + nativeThreadId: `native-${request.threadId}`, + }); + }), + startTurn: Effect.fn("PooledFixture.startTurn")(function* (request) { + const events = (yield* Ref.get(state)).eventQueues.get( + String(input.providerSessionId), + )!; + const now = yield* DateTime.now; + const providerTurnId = allocator.derive.providerTurn({ + driver: runtime.driver, + nativeTurnId: String(request.runId), + }); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver: runtime.driver, + providerTurn: { + id: providerTurnId, + providerThreadId: request.providerThread.id, + nodeId: request.rootNodeId, + runAttemptId: request.attemptId, + nativeTurnRef: { + driver: runtime.driver, + nativeId: String(request.runId), + strength: "strong", + }, + ordinal: request.providerTurnOrdinal, + status: "completed", + startedAt: now, + completedAt: now, + }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver: runtime.driver, + providerThreadId: request.providerThread.id, + providerTurnId, + status: "completed", + runOrdinal: request.runOrdinal, + failure: null, + threadDisposition: "reusable", + }); + }), + }; + }), + }), + list: () => Effect.succeed([delegate.instanceId]), + }); + }), + ); + const layer = layerWithRegistry( + { name: "pooled-second-turn", runtimePolicyOverride: { cwd: workspace } }, + registry, + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectId = ProjectId.make("pooled-project"); + const threadId = ThreadId.make("pooled-conversation"); + const openingThreadId = ThreadId.make("opening-conversation"); + const now = yield* DateTime.now; + const timestamp = DateTime.formatIso(now); + yield* (yield* EventStore.EventStoreV2).appendProjectEvent({ + eventId: EventId.make("pooled-project-created"), + aggregateKind: "project", + aggregateId: projectId, + occurredAt: timestamp, + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "project.created", + payload: { + projectId, + title: "Pooled project", + workspaceRoot: workspace, + defaultModelSelection: modelSelection, + scripts: [], + createdAt: timestamp, + updatedAt: timestamp, + }, + }); + for (const id of [openingThreadId, threadId]) + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${id}`), + threadId: id, + projectId, + title: String(id), + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + const sessionId = allocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + yield* manager.open({ + threadId: openingThreadId, + providerSessionId: sessionId, + modelSelection, + runtimePolicy: { ...runtimePolicy, cwd: openingWorkspace }, + }); + for (const ordinal of [1, 2]) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`send:${ordinal}`), + threadId, + messageId: MessageId.make(`message:${ordinal}`), + text: `Turn ${ordinal}`, + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const projection = yield* awaitThreadProjection( + threadId, + (p) => p.runs.find((run) => run.ordinal === ordinal)?.status === "completed", + ); + assert.equal( + projection.providerThreads.find( + (thread) => thread.id === projection.thread.activeProviderThreadId, + )?.providerSessionId, + sessionId, + ); + } + assert.equal((yield* Ref.get(state)).openCount, 1); + assert.equal((yield* Ref.get(state)).closeCount, 0); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, IdAllocator.layer)), Effect.scoped), +); diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.scient.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.scient.test.ts new file mode 100644 index 0000000000..ac5f128ea1 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.scient.test.ts @@ -0,0 +1,173 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { + type OrchestrationV2AppThread, + type OrchestrationV2ProviderThread, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as ServerConfig from "../config.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import * as EventSink from "./EventSink.ts"; +import * as EventStore from "./EventStore.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderEventIngestor from "./ProviderEventIngestor.ts"; +import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; + +const database = SqlitePersistence.layerMemory; +const stores = Layer.merge(EventStore.layer, ProjectionStore.layer).pipe(Layer.provide(database)); +const sink = EventSink.layer.pipe(Layer.provide(Layer.mergeAll(stores, database))); +const git = GitVcsDriver.layer.pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "ingestor-scient-git-" })), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), +); +const instances = Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({ + getInstance: () => Effect.undefined, +}); +const layerTest = Layer.mergeAll( + database, + stores, + sink, + IdAllocator.layer, + ProviderEventIngestor.layer.pipe( + Layer.provide( + Layer.mergeAll(instances, stores, sink, IdAllocator.layer, ThreadCommandExecutor.layer, git), + ), + ), +); + +const driver = ProviderDriverKind.make("opencode"); +const instanceId = ProviderInstanceId.make("opencode"); + +it.effect.each([ + { + name: "restores a workspace the same session's update omits", + sameSession: true, + adapterCwd: undefined, + expected: "/projects/second", + }, + { + name: "replaces a stale workspace the same session's update carries", + sameSession: true, + adapterCwd: "/projects/before-move", + expected: "/projects/second", + }, + { + name: "leaves another session's update alone", + sameSession: false, + adapterCwd: undefined, + expected: undefined, + }, +])("ingesting a provider-thread update $name", (row) => + Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const ids = yield* IdAllocator.IdAllocatorV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make(`recorded-workspace-${row.sameSession}`); + const providerThreadId = ids.derive.providerThread({ driver, nativeThreadId: "ses_native" }); + const sessionId = yield* ids.allocate.providerSession({ + providerInstanceId: instanceId, + threadId, + }); + const otherSessionId = yield* ids.allocate.providerSession({ + providerInstanceId: instanceId, + threadId, + }); + const thread: OrchestrationV2AppThread = { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("recorded-workspace-project"), + title: "Recorded workspace", + providerInstanceId: instanceId, + modelSelection: { instanceId, model: "opencode/big-pickle" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + branchPullRequest: null, + activeOrderKey: null, + activeProviderThreadId: providerThreadId, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; + const bound: OrchestrationV2ProviderThread = { + id: providerThreadId, + driver, + providerInstanceId: instanceId, + providerSessionId: sessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: "ses_native", strength: "strong" }, + nativeConversationHeadRef: null, + status: "active", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + nativeMetadata: { title: "Recorded workspace", cwd: "/projects/second" }, + createdAt: now, + updatedAt: now, + }; + // Turn start records the binding; OpenCode then re-emits its cached row without it. + yield* eventSink.write({ + events: [ + { + id: yield* ids.allocate.event({ threadId }), + type: "thread.created", + threadId, + occurredAt: now, + payload: thread, + }, + { + id: yield* ids.allocate.event({ threadId }), + type: "provider-thread.updated", + threadId, + driver, + occurredAt: now, + payload: bound, + }, + ], + }); + yield* ingestor.ingestNormalized({ + providerSessionId: sessionId, + providerInstanceId: instanceId, + threadId, + event: { + type: "provider_thread.updated", + driver, + providerThread: { + ...bound, + providerSessionId: row.sameSession ? sessionId : otherSessionId, + nativeMetadata: { + title: "Renamed natively", + ...(row.adapterCwd === undefined ? {} : { cwd: row.adapterCwd }), + }, + }, + }, + }); + const stored = (yield* projections.getThreadProjection(threadId)).providerThreads.find( + (candidate) => candidate.id === providerThreadId, + ); + assert.equal(stored?.nativeMetadata?.title, "Renamed natively"); + assert.equal(stored?.nativeMetadata?.cwd, row.expected); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index f01cd8d876..7e74d4f944 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -8,6 +8,7 @@ import { type OrchestrationV2Run, type OrchestrationV2Subagent, type OrchestrationV2ThreadProjection, + type OrchestrationV2ProviderThread, type ModelSelection, ProviderInstanceId, ProviderSessionId, @@ -45,6 +46,9 @@ import { AttachmentReservationReconciliation, reconcileReservationsBestEffort, } from "./AttachmentReservationReconciliation.ts"; +// SCIENT-FORK:START — the turn-start workspace binding survives adapter row updates. +import { withRecordedWorkspace } from "./scient-provider/RecordedWorkspace.ts"; +// SCIENT-FORK:END import { boundFileChangeForStorage } from "./WireProjection.ts"; export class ProviderEventNormalizeError extends Schema.TaggedError()( @@ -463,6 +467,23 @@ export const layer: Layer.Layer< return events; }); + // SCIENT-FORK:START — keep the turn-start workspace binding on same-session adapter updates. + const keepRecordedWorkspace = Effect.fnUntraced(function* ( + threadId: ThreadId, + providerThread: OrchestrationV2ProviderThread, + ) { + const recorded = yield* projections + .getThreadRecords(threadId, ["providerThreads"], { providerThreadIds: [providerThread.id] }) + .pipe( + Effect.map((records) => + records.providerThreads.find((thread) => thread.id === providerThread.id), + ), + Effect.orElseSucceed(() => undefined), + ); + return withRecordedWorkspace(recorded, providerThread); + }); + // SCIENT-FORK:END + const normalize: ProviderEventIngestorV2Shape["normalize"] = /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ Effect.fnUntraced( @@ -512,10 +533,16 @@ export const layer: Layer.Layer< ]; case "provider_thread.updated": { const threadId = input.event.providerThread.appThreadId ?? input.threadId; + // SCIENT-FORK:START — the bound workspace is orchestration-owned; adapters omit it. + const providerThread = yield* keepRecordedWorkspace( + threadId, + input.event.providerThread, + ); + // SCIENT-FORK:END const updated = yield* makeDomainEvent(input, { type: "provider-thread.updated", threadId, - payload: input.event.providerThread, + payload: providerThread, }); return input.event.retainedNativeTurnIds === undefined ? [updated] diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.scient.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.scient.test.ts index b067542bfd..546b828bcf 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.scient.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.scient.test.ts @@ -3081,6 +3081,8 @@ function runIdleThreadUnloadScenario( /** Ends run `ordinal` on a thread and waits for the session to process it. */ readonly endTurn: (threadId: ThreadId, ordinal: number) => Effect.Effect; readonly resume: (threadId: ThreadId) => Effect.Effect; + /** Repoints the thread's durable provider row to another session, as a handoff does. */ + readonly reassign: (threadId: ThreadId, owner: ProviderSessionId) => Effect.Effect; }) => Effect.Effect, options: { readonly hasPendingBackgroundWorkForThread?: Effect.Effect; @@ -3202,6 +3204,21 @@ function runIdleThreadUnloadScenario( yield* Fiber.join(received); }), ).pipe(Effect.orDie); + const reassign = (threadId: ThreadId, owner: ProviderSessionId) => + Effect.gen(function* () { + yield* eventSink.write({ + events: [ + { + id: yield* idAllocator.allocate.event({ threadId }), + type: "provider-thread.updated", + threadId, + driver: CODEX_DRIVER, + occurredAt: now, + payload: { ...providerThreadOf(threadId), providerSessionId: owner }, + }, + ], + }); + }).pipe(Effect.orDie); // B's running turn keeps the shared runtime itself busy throughout. yield* startTurn(threadB, 1); @@ -3216,6 +3233,7 @@ function runIdleThreadUnloadScenario( startTurnOnly, endTurn, resume, + reassign, }); }).pipe( Effect.provide( @@ -3311,6 +3329,45 @@ it.effect.each(["resume", "start"] as const)( }).pipe(Effect.scoped), ); +it.effect( + "ProviderSessionManagerV2 handoff detach waits for an in-flight idle unload and re-joins its release", + () => + Effect.gen(function* () { + const unloadStarted = yield* Deferred.make(); + const releaseUnload = yield* Deferred.make(); + yield* runIdleThreadUnloadScenario( + "idle-unload-handoff", + ({ state, manager, providerSessionId, threadA, startTurn, endTurn, reassign }) => + Effect.gen(function* () { + yield* startTurn(threadA, 1); + yield* endTurn(threadA, 1); + yield* TestClock.adjust("1 second"); + // The idle unsubscribe is in flight and its tracking row is gone. + yield* Deferred.await(unloadStarted); + yield* reassign(threadA, ProviderSessionId.make("replacement-owner")); + const detach = yield* manager + .detach({ providerSessionId, threadId: threadA }) + .pipe(Effect.forkScoped); + yield* Effect.yieldNow; + yield* Effect.yieldNow; + // The replacement may resume once detach returns; the old writer is still held. + assert.isUndefined(detach.pollUnsafe()); + yield* Deferred.succeed(releaseUnload, undefined); + yield* Fiber.join(detach); + assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, [ + `native-${threadA}`, + `native-${threadA}`, + ]); + }).pipe(Effect.scoped), + { + beforeUnload: Deferred.succeed(unloadStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseUnload)), + ), + }, + ); + }).pipe(Effect.scoped), +); + it.effect.each(["resume", "start"] as const)( "ProviderSessionManagerV2 prevents idle-unload overlap at measured native %s scheduling checkpoints", (operation) => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index d25d67077f..c27f958e14 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -4497,6 +4497,7 @@ it.effect( threadId: secondThreadId, providerSessionId, now, + nativeThreadId: "native-thread-second", }); const firstRunId = idAllocator.derive.run({ threadId: firstThreadId, ordinal: 1 }); yield* eventSink.write({ @@ -4570,7 +4571,7 @@ it.effect( yield* settings.updateSettings({ linkedEnvironmentsEnabled: true }); yield* resumeSecondThread; assert.equal((yield* Ref.get(state)).resumeCount, 4); - assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, ["native-thread"]); + assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, ["native-thread-second"]); const subscribe = firstRuntime.subscribeEvents; assert.isDefined(subscribe); if (subscribe === undefined) return; @@ -4604,14 +4605,18 @@ it.effect( yield* resumeSecondThread; assert.equal((yield* Ref.get(state)).resumeCount, 5); - assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, ["native-thread"]); + assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, [ + "native-thread-second", + "native-thread-second", + ]); yield* manager.detach({ providerSessionId, threadId: firstThreadId }); assert.isTrue(Option.isSome(yield* manager.get(providerSessionId))); assert.equal((yield* Ref.get(state)).closeCount, 0); assert.equal((yield* Ref.get(state)).interruptCount, 1); assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, [ - "native-thread", + "native-thread-second", + "native-thread-second", "native-thread", ]); @@ -4935,6 +4940,74 @@ it.effect( }), ); +it.effect( + "ProviderSessionManagerV2 unloads a thread from its old session after it resumes on another instance", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("cross-instance-switch"); + const providerSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), + { + id: yield* idAllocator.allocate.event({ threadId }), + type: "provider-thread.updated", + threadId, + driver: CODEX_DRIVER, + occurredAt: now, + payload: providerThread, + }, + ], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + yield* runtime.resumeThread({ providerThread, threadId, modelSelection, runtimePolicy }); + + // A restart_and_resume switch moves the same row to the other instance's session. + const otherInstanceId = ProviderInstanceId.make("codex-other"); + yield* eventSink.write({ + events: [ + { + id: yield* idAllocator.allocate.event({ threadId }), + type: "provider-thread.updated", + threadId, + driver: CODEX_DRIVER, + occurredAt: now, + payload: { + ...providerThread, + providerInstanceId: otherInstanceId, + providerSessionId: idAllocator.derive.providerSession({ + providerInstanceId: otherInstanceId, + }), + }, + }, + ], + }); + yield* manager.detach({ providerSessionId, threadId }); + + assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, ["native-thread"]); + }).pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1000 })), Effect.scoped); + }), +); + it.effect( "ProviderSessionManagerV2 re-attaching a thread waits for its in-flight unload, then reloads it", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 8d261a82dc..4dd25e1a62 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -333,6 +333,9 @@ interface LiveSessionEntry { readonly idleFiber: Fiber.Fiber | null; readonly pinnedSinceMs: number | null; readonly idleThreadUnloads: ReadonlyMap; + // SCIENT-FORK:START — an idle unload's native close may still be pending when a handoff detaches. + readonly idleUnloadedProviderThreads: ReadonlyMap; + // SCIENT-FORK:END } interface IdleThreadUnload { @@ -2283,11 +2286,16 @@ export const layerWithOptions = ( loadedProviderThreadKeyByThread.delete(input.threadId); const idleThreadUnloads = new Map(latest.idleThreadUnloads); idleThreadUnloads.delete(input.threadId); + // SCIENT-FORK:START — detach re-joins this release if a handoff follows. + const idleUnloadedProviderThreads = new Map(latest.idleUnloadedProviderThreads); + idleUnloadedProviderThreads.set(input.threadId, pending.providerThread); + // SCIENT-FORK:END const updated = new Map(current); updated.set(key, { ...latest, loadedProviderThreadKeyByThread, idleThreadUnloads, + idleUnloadedProviderThreads, }); return [true, updated] as const; }); @@ -3481,6 +3489,8 @@ export const layerWithOptions = ( idleFiber: null, pinnedSinceMs: null, idleThreadUnloads: new Map(), + // SCIENT-FORK: idle releases a handoff may need to wait for. + idleUnloadedProviderThreads: new Map(), }; // SCIENT-FORK:START — publication cannot resurrect a closing layer owner. yield* Effect.suspend(() => @@ -3730,6 +3740,7 @@ export const layerWithOptions = ( return [ Option.none<{ readonly entry: LiveSessionEntry; + readonly heldProviderThread: OrchestrationV2ProviderThread | undefined; readonly idleUnloadFiber: Fiber.Fiber | null; }>(), current, @@ -3753,6 +3764,10 @@ export const layerWithOptions = ( : entry.mcpCredentialIdByThread; const idleThreadUnloads = new Map(entry.idleThreadUnloads); idleThreadUnloads.delete(input.threadId); + // SCIENT-FORK:START — the handoff waits for an idle release already under way. + const idleUnloadedProviderThreads = new Map(entry.idleUnloadedProviderThreads); + idleUnloadedProviderThreads.delete(input.threadId); + // SCIENT-FORK:END const updatedEntry = { ...entry, attachedThreadIds, @@ -3760,12 +3775,17 @@ export const layerWithOptions = ( linkedEnvironmentsByThread, mcpCredentialIdByThread, idleThreadUnloads, + idleUnloadedProviderThreads, }; const updated = new Map(current); updated.set(key, updatedEntry); return [ Option.some({ entry: updatedEntry, + heldProviderThread: + entry.idleThreadUnloads.get(input.threadId)?.providerThread ?? + // SCIENT-FORK: an idle unload may have released it before the row moved. + entry.idleUnloadedProviderThreads.get(input.threadId), idleUnloadFiber: entry.idleThreadUnloads.get(input.threadId)?.fiber ?? null, }), updated, @@ -3781,29 +3801,37 @@ export const layerWithOptions = ( if (Option.isSome(detachResult)) { yield* cancelIdleFiber(detachResult.value.idleUnloadFiber); } - const detached = Option.map(detachResult, (result) => result.entry); // Plain detaches preserve credentials held by live shared providers across workspace handoffs. if (input.revokeMcpCredential === true) { yield* mcpPrepareLock.withLock(input.threadId, clearMcpSession(input.threadId)); } - if (Option.isNone(detached)) { + if (Option.isNone(detachResult)) { return; } + const { entry: detached, heldProviderThread } = detachResult.value; if ( - detached.value.attachedThreadIds.size === 0 && - !detached.value.supportsMultipleProviderThreads + detached.attachedThreadIds.size === 0 && + !detached.supportsMultipleProviderThreads ) { yield* releaseEntry({ providerSessionId: input.providerSessionId, - expectedRuntime: detached.value.runtime, + expectedRuntime: detached.runtime, reason: "manual_shutdown", ...(input.detail === undefined ? {} : { detail: input.detail }), detachedThreadId: input.threadId, }); return; } - const unloadThread = detached.value.exposedRuntime.unloadThread; - if (detached.value.supportsMultipleProviderThreads && unloadThread !== undefined) { + const unloadThread = detached.exposedRuntime.unloadThread; + if (detached.supportsMultipleProviderThreads && unloadThread !== undefined) { + // A cross-instance switch repoints the row before this detach, so the projection + // can miss what this session still holds for the thread. + if ( + heldProviderThread !== undefined && + !detachedProviderThreads.some((thread) => thread.id === heldProviderThread.id) + ) { + detachedProviderThreads = [...detachedProviderThreads, heldProviderThread]; + } // The projection includes native children owned by other app threads; // lock each owner so an attached child stays loaded and later attaches wait. for (const providerThread of detachedProviderThreads) { @@ -3817,12 +3845,13 @@ export const layerWithOptions = ( Effect.gen(function* () { const entry = (yield* Ref.get(sessions)).get(key); if ( - entry?.runtime !== detached.value.runtime || + entry?.runtime !== detached.runtime || entry.attachedThreadIds.has(ownerThreadId) ) { return; } - yield* unloadThread({ providerThread }).pipe( + // SCIENT-FORK: the replacement owner may resume as soon as detach returns. + yield* unloadThread({ providerThread, awaitRelease: true }).pipe( Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), Effect.catchCause((cause) => Effect.logWarning("orchestration-v2.driver-session.detach-unload-failed", { diff --git a/apps/server/src/orchestration-v2/ProviderSessionOwnership.scient.test.ts b/apps/server/src/orchestration-v2/ProviderSessionOwnership.scient.test.ts new file mode 100644 index 0000000000..dead170921 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderSessionOwnership.scient.test.ts @@ -0,0 +1,169 @@ +import { assert, it } from "@effect/vitest"; +import { ProviderSessionId, ThreadId } from "@t3tools/contracts"; +import { ProviderAdapterProtocolError } from "@t3tools/provider-core/server/ProviderAdapter"; +import * as DateTime from "effect/DateTime"; +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 EventSink from "./EventSink.ts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderSessionManager from "./ProviderSessionManager.ts"; +import { + CODEX_DRIVER, + emptyState, + makeProviderAdapter, + makeProviderThread, + makeTestLayer, + makeThreadCreatedEvent, + modelSelection, + runtimePolicy, +} from "./testkit/ProviderSessionManagerTestHarness.ts"; + +it.effect( + "releases the old native writer after its durable thread is reassigned, without unloading a peer", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const owners = yield* Ref.make(new Map()); + const registry = Layer.effect( + ProviderAdapterRegistry.ProviderAdapterRegistryV2, + Effect.gen(function* () { + const delegate = yield* makeProviderAdapter(state); + return ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({ + get: () => + Effect.succeed({ + ...delegate, + openSession: Effect.fn("WriterFixture.openSession")(function* (input) { + const runtime = yield* delegate.openSession(input); + return { + ...runtime, + resumeThread: Effect.fn("WriterFixture.resumeThread")(function* (request) { + const nativeId = request.providerThread.nativeThreadRef?.nativeId; + if (nativeId == null) return yield* Effect.die("Missing fixture native id"); + const owner = (yield* Ref.get(owners)).get(nativeId); + if (owner !== undefined && owner !== input.providerSessionId) + return yield* new ProviderAdapterProtocolError({ + driver: CODEX_DRIVER, + detail: "Conversation has another native writer.", + }); + yield* Ref.update(owners, (current) => + new Map(current).set(nativeId, input.providerSessionId), + ); + return yield* runtime.resumeThread(request); + }), + unloadThread: Effect.fn("WriterFixture.unloadThread")(function* (request) { + const nativeId = request.providerThread.nativeThreadRef?.nativeId; + if (nativeId == null) return yield* Effect.die("Missing fixture native id"); + yield* Ref.update(owners, (current) => { + if (current.get(nativeId) !== input.providerSessionId) return current; + const next = new Map(current); + next.delete(nativeId); + return next; + }); + yield* runtime.unloadThread!(request); + }), + }; + }), + }), + list: () => Effect.succeed([modelSelection.instanceId]), + }); + }), + ); + yield* Effect.gen(function* () { + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("reassigned-writer"); + const peerId = ThreadId.make("unrelated-writer"); + const oldSessionId = ProviderSessionId.make("shared-owner"); + const newSessionId = ProviderSessionId.make("replacement-owner"); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId: oldSessionId, + now, + }); + const peer = makeProviderThread({ + idAllocator, + threadId: peerId, + providerSessionId: oldSessionId, + nativeThreadId: "peer-native", + now, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), + yield* makeThreadCreatedEvent({ idAllocator, threadId: peerId, now }), + ], + }); + const old = yield* manager.open({ + threadId, + providerSessionId: oldSessionId, + modelSelection, + runtimePolicy, + }); + yield* manager.open({ + threadId: peerId, + providerSessionId: oldSessionId, + modelSelection, + runtimePolicy, + }); + yield* old.resumeThread({ threadId, providerThread, modelSelection, runtimePolicy }); + yield* old.resumeThread({ + threadId: peerId, + providerThread: peer, + modelSelection, + runtimePolicy, + }); + const replacement = { ...providerThread, providerSessionId: newSessionId }; + yield* eventSink.write({ + events: [ + { + id: yield* idAllocator.allocate.event({ threadId }), + type: "provider-thread.updated", + threadId, + driver: CODEX_DRIVER, + occurredAt: now, + payload: replacement, + }, + ], + }); + yield* manager.detach({ providerSessionId: oldSessionId, threadId }); + const next = yield* manager.open({ + threadId, + providerSessionId: newSessionId, + modelSelection, + runtimePolicy, + }); + yield* next.resumeThread({ + threadId, + providerThread: replacement, + modelSelection, + runtimePolicy, + }); + yield* manager.detach({ providerSessionId: oldSessionId, threadId }); + assert.deepEqual( + [...(yield* Ref.get(owners))], + [ + ["peer-native", oldSessionId], + ["native-thread", newSessionId], + ], + ); + assert.isTrue(Option.isSome(yield* manager.get(oldSessionId))); + assert.equal((yield* Ref.get(state)).closeCount, 0); + }).pipe( + Effect.provide( + makeTestLayer({ + state, + idleTimeoutMs: 1000, + configureMcp: false, + adapterRegistryLayer: registry, + }), + ), + Effect.scoped, + ); + }), +); diff --git a/apps/server/src/orchestration-v2/ProviderSwitchService.scient.test.ts b/apps/server/src/orchestration-v2/ProviderSwitchService.scient.test.ts new file mode 100644 index 0000000000..4cff069c1b --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderSwitchService.scient.test.ts @@ -0,0 +1,108 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderSwitch from "./ProviderSwitchService.ts"; +import * as RuntimePolicy from "./RuntimePolicy.ts"; +import { + CodexCapabilities, + makeProviderSession, + makeProviderThread, + makeThreadCreatedEvent, + makeProviderAdapter, + emptyState, + modelSelection, +} from "./testkit/ProviderSessionManagerTestHarness.ts"; +import * as DateTime from "effect/DateTime"; +import * as Ref from "effect/Ref"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import { ThreadId, ProviderSessionId } from "@t3tools/contracts"; + +it.effect.each([ + { name: "per-thread workspace", multiple: true, perThread: true, transition: "reuse" }, + { + name: "process-wide workspace", + multiple: true, + perThread: false, + transition: "restart_and_resume", + }, + { name: "exclusive process", multiple: false, perThread: true, transition: "restart_and_resume" }, +] as const)("uses the negotiated $name authority for a second turn", (scenario) => + Effect.gen(function* () { + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const now = yield* DateTime.now; + const state = yield* Ref.make(emptyState); + const capabilities = { + ...CodexCapabilities, + sessions: { + ...CodexCapabilities.sessions, + supportsMultipleProviderThreadsPerSession: scenario.multiple, + supportsPerThreadWorkspace: scenario.perThread, + }, + }; + const adapter = yield* makeProviderAdapter(state, { capabilities }); + const threadId = ThreadId.make("pooled-workspace"); + const providerSessionId = ProviderSessionId.make("shared-process"); + const thread = (yield* makeThreadCreatedEvent({ idAllocator, threadId, now })).payload; + const providerThread = makeProviderThread({ idAllocator, threadId, providerSessionId, now }); + const projection = { + thread: { ...thread, worktreePath: "/second-project" }, + providerSessions: [ + { + ...makeProviderSession({ providerSessionId, now, capabilities }), + cwd: "/first-project", + }, + ], + providerThreads: [{ ...providerThread, nativeMetadata: { cwd: "/second-project" } }], + } satisfies Pick< + OrchestrationV2ThreadProjection, + "thread" | "providerSessions" | "providerThreads" + >; + const service = yield* ProviderSwitch.ProviderSwitchServiceV2.pipe( + Effect.provide( + ProviderSwitch.layer.pipe( + Layer.provide( + Layer.mergeAll( + RuntimePolicy.layer, + NodeServices.layer, + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + get: () => Effect.succeed(adapter), + getMetadata: () => + Effect.succeed({ + driver: adapter.driver, + continuationKey: "codex:account:primary", + enabled: true, + capabilities, + }), + }), + ), + ), + ), + ), + ); + const plan = yield* service.plan({ projection, targetModelSelection: modelSelection }); + assert.equal(plan.transition.type, scenario.transition); + assert.deepEqual( + plan.releaseProviderSessionIds, + scenario.transition === "reuse" ? [] : [providerSessionId], + ); + + if (scenario.transition === "reuse") { + const moved = yield* service.plan({ + projection, + targetThread: { ...projection.thread, worktreePath: "/third-project" }, + targetModelSelection: modelSelection, + }); + assert.equal(moved.transition.type, "restart_and_resume"); + assert.deepEqual(moved.releaseProviderSessionIds, [providerSessionId]); + } + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + Effect.scoped, + ), +); diff --git a/apps/server/src/orchestration-v2/ProviderSwitchService.ts b/apps/server/src/orchestration-v2/ProviderSwitchService.ts index d0a4a34a57..6f72a86226 100644 --- a/apps/server/src/orchestration-v2/ProviderSwitchService.ts +++ b/apps/server/src/orchestration-v2/ProviderSwitchService.ts @@ -141,9 +141,15 @@ export const layer: Layer.Layer< sessionCapabilities: negotiatedCapabilities ?? currentInstance.value.capabilities, }) : undefined; - // SCIENT-FORK:START — native canonical paths do not change workspace authority. + // SCIENT-FORK:START — pooled processes do not own their threads' workspaces. + const perThreadWorkspace = + negotiatedCapabilities?.sessions.supportsMultipleProviderThreadsPerSession === true && + negotiatedCapabilities.sessions.supportsPerThreadWorkspace === true; const currentWorkspace = - currentSession?.cwd ?? projection.thread.worktreePath ?? ""; + (perThreadWorkspace ? currentProviderThread?.nativeMetadata?.cwd : undefined) ?? + currentSession?.cwd ?? + projection.thread.worktreePath ?? + ""; let targetWorkspace = targetPolicy.cwd ?? currentSession?.cwd ?? ""; if (currentWorkspace !== targetWorkspace) { const sameWorkspace = yield* Effect.all([ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index d4e046b636..6b34070573 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1712,6 +1712,12 @@ export const layer: Layer.Layer< // SCIENT-FORK:END const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, + // SCIENT-FORK:START — retain binding authority across later project/worktree relocation. + nativeMetadata: { + ...loadedProviderThread.nativeMetadata, + cwd: resolvedRuntimePolicy.cwd ?? session.providerSession.cwd, + }, + // SCIENT-FORK:END contextUsage: handoffUsage, id: providerThread.id, driver: session.driver, diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index a61eeca29a..8e2fb5dd87 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -93,6 +93,9 @@ import { routeWorkflowSubagentEvent, } from "./scient-fork/NativeWorkflowOwnership.ts"; // SCIENT-FORK:END +// SCIENT-FORK:START — the turn-start workspace binding survives adapter row updates. +import { withRecordedWorkspace } from "./scient-provider/RecordedWorkspace.ts"; +// SCIENT-FORK:END import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; import { userFacingDatabaseErrorMessage } from "./UserFacingErrors.ts"; @@ -1774,7 +1777,11 @@ export const layer: Layer.Layer< } if (event.type === "provider_thread.updated") { if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) { - yield* Ref.set(latestProviderThread, event.providerThread); + // SCIENT-FORK: finalization writes this row; keep the recorded workspace. + yield* Ref.set( + latestProviderThread, + withRecordedWorkspace(input.providerThread, event.providerThread), + ); rootSnapshotPendingWork = event.pendingBackgroundWork === true; } } diff --git a/apps/server/src/orchestration-v2/WorkspaceRelocation.integration.test.ts b/apps/server/src/orchestration-v2/WorkspaceRelocation.integration.test.ts index 9228207518..f284ad547d 100644 --- a/apps/server/src/orchestration-v2/WorkspaceRelocation.integration.test.ts +++ b/apps/server/src/orchestration-v2/WorkspaceRelocation.integration.test.ts @@ -132,6 +132,7 @@ for (const detached of [false, true]) { appThreadId: threadId, ownerNodeId: null, nativeThreadRef, + nativeMetadata: { cwd: "/tmp/workspace-before" }, nativeConversationHeadRef: null, status: "idle", firstRunOrdinal: null, diff --git a/apps/server/src/orchestration-v2/scient-fork/ConversationForkBufferedText.native.integration.test.ts b/apps/server/src/orchestration-v2/scient-fork/ConversationForkBufferedText.native.integration.test.ts index 73dd6daa0d..10923c3fe3 100644 --- a/apps/server/src/orchestration-v2/scient-fork/ConversationForkBufferedText.native.integration.test.ts +++ b/apps/server/src/orchestration-v2/scient-fork/ConversationForkBufferedText.native.integration.test.ts @@ -595,6 +595,10 @@ it.live.each( frame: { id: 5, method: "thread/unsubscribe", params: { threadId: nativeThreadId } }, }, { type: "emit_inbound", frame: { id: 5, result: { status: "unsubscribed" } } }, + { + type: "emit_inbound", + frame: { method: "thread/closed", params: { threadId: nativeThreadId } }, + }, ]; const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript( makeCodexReplayTranscript({ diff --git a/apps/server/src/orchestration-v2/scient-fork/ConversationRunForkPrefix.integration.test.ts b/apps/server/src/orchestration-v2/scient-fork/ConversationRunForkPrefix.integration.test.ts index 3ae990b81f..d83e6f2521 100644 --- a/apps/server/src/orchestration-v2/scient-fork/ConversationRunForkPrefix.integration.test.ts +++ b/apps/server/src/orchestration-v2/scient-fork/ConversationRunForkPrefix.integration.test.ts @@ -202,6 +202,10 @@ it.live.each( label: "thread/unsubscribe/source", frame: { id: 4, result: { status: "unsubscribed" } }, }, + { + type: "emit_inbound", + frame: { method: "thread/closed", params: { threadId: "native-source-thread" } }, + }, ); } const transcript = { ...full, entries }; @@ -443,6 +447,10 @@ it.live.each( label: "thread/unsubscribe/parent", frame: { id: 6, result: { status: "unsubscribed" } }, }, + { + type: "emit_inbound", + frame: { method: "thread/closed", params: { threadId: "native-fork-thread" } }, + }, { type: "expect_outbound", label: "thread/start/grandchild", diff --git a/apps/server/src/orchestration-v2/scient-provider/RecordedWorkspace.ts b/apps/server/src/orchestration-v2/scient-provider/RecordedWorkspace.ts new file mode 100644 index 0000000000..3eeb00d279 --- /dev/null +++ b/apps/server/src/orchestration-v2/scient-provider/RecordedWorkspace.ts @@ -0,0 +1,21 @@ +import type { OrchestrationV2ProviderThread } from "@t3tools/contracts"; + +/** + * Turn start records the workspace a native thread is bound to. Adapters do not own that binding + * and re-emit cached copies of the row, possibly from before a relocation, so while the same + * session owns the thread the recorded value wins over whatever the adapter carries. + */ +export const withRecordedWorkspace = ( + recorded: OrchestrationV2ProviderThread | undefined, + update: OrchestrationV2ProviderThread, +): OrchestrationV2ProviderThread => { + if (recorded?.id !== update.id || recorded.providerSessionId !== update.providerSessionId) + return update; + const cwd = recorded.nativeMetadata?.cwd; + if (cwd === update.nativeMetadata?.cwd) return update; + const { cwd: _adapterCwd, ...nativeMetadata } = update.nativeMetadata ?? {}; + return { + ...update, + nativeMetadata: cwd === undefined ? nativeMetadata : { ...nativeMetadata, cwd }, + }; +}; diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 0be2d114b4..f6187616fe 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -4091,8 +4091,8 @@ it.layer( assert.deepStrictEqual( spawnedCommands.filter((probe) => probe.command === firstMissing), [ - { command: firstMissing, args: ["app-server"] }, - { command: firstMissing, args: ["app-server"] }, + { command: firstMissing, args: ["app-server", "-c", "thread_unload_delay_secs=0"] }, + { command: firstMissing, args: ["app-server", "-c", "thread_unload_delay_secs=0"] }, ], ); // Disabled managed providers still perform their existing passive runtime @@ -4134,8 +4134,8 @@ it.layer( const [reprobedCodex] = yield* rebuiltError; assert.deepStrictEqual(spawnedCommands, [ ...initialProbes, - { command: secondMissing, args: ["app-server"] }, - { command: secondMissing, args: ["app-server"] }, + { command: secondMissing, args: ["app-server", "-c", "thread_unload_delay_secs=0"] }, + { command: secondMissing, args: ["app-server", "-c", "thread_unload_delay_secs=0"] }, ]); assert.strictEqual(reprobedCodex?.status, "error"); assert.strictEqual(reprobedCodex?.installed, false); diff --git a/apps/server/src/provider/codexLaunchArgs.test.ts b/apps/server/src/provider/codexLaunchArgs.test.ts index ce18c8f3f1..1a1af71402 100644 --- a/apps/server/src/provider/codexLaunchArgs.test.ts +++ b/apps/server/src/provider/codexLaunchArgs.test.ts @@ -5,11 +5,24 @@ import { describe, it } from "vite-plus/test"; import { codexAppServerArgs, codexExecLaunchArgs } from "./codexLaunchArgs.ts"; describe("codexAppServerArgs", () => { - it("preserves escaped TOML quotes in config values", () => { - NodeAssert.deepStrictEqual( - codexAppServerArgs(String.raw`--config model=\"gpt-6.1-sol\" --strict-config`), - ["app-server", "--config", 'model="gpt-6.1-sol"', "--strict-config"], - ); + it.each([ + { + name: "preserves escaped TOML quotes in config values", + launchArgs: String.raw`--config model=\"gpt-6.1-sol\" --strict-config`, + expected: ["--config", 'model="gpt-6.1-sol"', "--strict-config"], + }, + { + name: "lets launch args override the unload delay", + launchArgs: "-c thread_unload_delay_secs=1800", + expected: ["-c", "thread_unload_delay_secs=1800"], + }, + ])("asks Codex to unload unsubscribed threads immediately and $name", (row) => { + NodeAssert.deepStrictEqual(codexAppServerArgs(row.launchArgs), [ + "app-server", + "-c", + "thread_unload_delay_secs=0", + ...row.expected, + ]); }); }); diff --git a/apps/server/src/provider/codexLaunchArgs.ts b/apps/server/src/provider/codexLaunchArgs.ts index 33def5ce9a..cd819cb449 100644 --- a/apps/server/src/provider/codexLaunchArgs.ts +++ b/apps/server/src/provider/codexLaunchArgs.ts @@ -9,8 +9,11 @@ export const resolveCodexLaunchArgs = ( const codexLaunchArgv = (launchArgs?: string): ReadonlyArray => tokenizeCliArgs(launchArgs); +// T3 unsubscribes only when it unloads a thread; Codex's own unload delay would stack on that. export const codexAppServerArgs = (launchArgs?: string) => [ "app-server", + "-c", + "thread_unload_delay_secs=0", ...codexLaunchArgv(launchArgs), ]; diff --git a/docs/internals/providers.md b/docs/internals/providers.md index cce2bec033..98a495e80b 100644 --- a/docs/internals/providers.md +++ b/docs/internals/providers.md @@ -177,6 +177,28 @@ Configuration and execution share the canonical instance registry: per-turn selected-skill scope, idle release and exact-instance teardown. Durable provider sessions and threads remain V2 facts even when an in-memory process has gone away. +For a provider session that negotiates both multiple threads and +per-thread workspaces, switch planning compares the last bound native workspace +(`nativeMetadata.cwd`) with the conversation's resolved target, not with the shared +process's opening directory. A genuine workspace change still restarts the binding. +Older bindings without that metadata conservatively use the session's cwd until rebound. +Adapters do not own this binding and re-emit cached copies of the row, sometimes from before a +relocation (OpenCode 2 does). While the same session owns the thread, `ProviderEventIngestor` +and run finalization in `RunExecutionService` restore the recorded `nativeMetadata.cwd` over +whatever the adapter carries (`scient-provider/RecordedWorkspace.ts`). +Detach also unloads the native thread its runtime still holds for the app thread when the +durable record already names a replacement session; attached peers remain loaded. Because the +next owner may be another process, detach asks the adapter to wait for the release +(`awaitRelease`): Codex answers `thread/unsubscribe` before it closes the thread, so the Codex +adapter then waits up to 5 seconds for `thread/closed`, including a close still pending from an +earlier idle unsubscribe. Detach also re-joins a thread an idle unload already released, because +the reassigned row no longer names the old session. Idle unloads do not wait. + +Codex launches with `-c thread_unload_delay_secs=0` ahead of user launch arguments, so Codex +closes a thread as soon as Scient unsubscribes; a launch-argument override still wins. A +`thread/resume` that Codex refuses because the thread is still closing waits up to 10 seconds +for this connection's `thread/closed`, then retries. + `ProviderTurnStartService` projects typed composer context, applies selected Scient skills, resolves native or portable context transfers, and calls the session manager and `RunExecutionService`. Native start and steer expand supported composer citations. Current-input validation includes that diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 31163610de..120af84181 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1143,6 +1143,8 @@ export const OrchestrationV2ProviderThreadNativeMetadata = Schema.Struct({ /** Driver-validated continuation state; a native id alone does not grant resume authority. */ resumeCursor: Schema.optional(Schema.Unknown), modelSelection: Schema.optional(ModelSelection), + /** Last bound native workspace; a pooled session's cwd belongs to its opening thread. */ + cwd: Schema.optional(TrimmedNonEmptyString), title: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), updatedAt: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), itemIdentityVersion: Schema.optional(Schema.Literal(2)), diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 9f0cf74713..4c53589ed1 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -763,6 +763,8 @@ export interface ProviderAdapterV2SessionRuntime extends ScientTextSnapshotRunti }) => Effect.Effect; readonly unloadThread?: (input: { readonly providerThread: OrchestrationV2ProviderThread; + // SCIENT-FORK: a detach hands the native writer to another process; wait for its release. + readonly awaitRelease?: boolean; }) => Effect.Effect; readonly respondToRuntimeRequest: ( input: ProviderAdapterV2RuntimeRequestResponseInput,