Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions UPSTREAM.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>();
const release = yield* Deferred.make<void>();
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", () =>
Expand Down
114 changes: 112 additions & 2 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")),
);
Expand Down Expand Up @@ -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",
Expand Down
58 changes: 50 additions & 8 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2079,6 +2079,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
const pendingRuntimeRequests = yield* Ref.make(
new Map<string, PendingCodexRuntimeRequest>(),
);
/** Completed by thread/closed after this connection unsubscribes from the native thread. */
const threadClosings = new Map<string, Deferred.Deferred<void>>();
/** Codex acceptForSession covers only the exact command or patch, not future commands. */
const sessionApprovals = new Map<
string,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -7014,20 +7019,31 @@ 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<string, unknown>,
) {
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);
},
}),
);
});
Expand Down Expand Up @@ -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<void>());
}
// 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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
);

Expand Down
Loading
Loading