Skip to content
Closed
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
66 changes: 66 additions & 0 deletions apps/mobile/src/features/threads/RestartCodexCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { useAtomValue } from "@effect/atom-react";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, ThreadId, RunId } from "@t3tools/contracts";
import { useState } from "react";
import { Alert, Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { orchestrationEnvironment } from "../../state/orchestration";
import { useAtomCommand } from "../../state/use-atom-command";

export function RestartCodexCard({
environmentId,
threadId,
retryRunId,
continueWork = false,
}: {
environmentId: EnvironmentId;
threadId: ThreadId;
retryRunId: RunId;
continueWork?: boolean;
}) {
const restart = useAtomCommand(orchestrationEnvironment.restartCodex, { reportFailure: false });
const allowed = useAtomValue(orchestrationEnvironment.restartCodex.permissionAtom(environmentId));
const [pending, setPending] = useState(false);
const [message, setMessage] = useState<string | null>(null);
return (
<View className="mx-3 mb-2 gap-2 rounded-xl border border-border bg-screen p-3">
<Pressable
accessibilityRole="button"
disabled={!allowed || pending}
accessibilityState={{ disabled: !allowed || pending, busy: pending }}
className="self-start rounded-lg bg-subtle px-3 py-2 active:opacity-70"
onPress={async () => {
if (pending) return;
setPending(true);
setMessage(null);
try {
const result = await restart({ environmentId, input: { threadId, retryRunId } });
if (result._tag === "Failure") throw squashAtomCommandFailure(result);
Alert.alert(continueWork ? "Conversation continued" : "Message resent");
} catch (cause) {
setMessage(
cause instanceof Error ? cause.message : "Could not recover the conversation.",
);
} finally {
setPending(false);
}
}}
>
<Text className="text-sm text-foreground">
{pending
? continueWork
? "Continuing…"
: "Retrying message…"
: continueWork
? "Continue"
: "Retry message"}
</Text>
</Pressable>
{message ? (
<Text accessibilityRole="alert" className="text-sm text-foreground">
{message}
</Text>
) : null}
</View>
);
}
12 changes: 12 additions & 0 deletions apps/mobile/src/features/threads/ThreadDetailScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { CodexRecoveryAction } from "@t3tools/client-runtime/state/thread-execution";
import * as Dialog from "../../components/ui/Dialog";
import { useAtomValue } from "@effect/atom-react";
import { useChildThreadInputs, useThreadReportedModelSelection } from "../../state/entities";
import { RestartCodexCard } from "./RestartCodexCard";
import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";
import { useNavigation } from "@react-navigation/native";
import type { WorktreeSetupCardProps } from "./worktree-setup-card";
Expand Down Expand Up @@ -154,6 +156,7 @@ import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
import { useGlobalVoiceInput } from "../voice-input/VoiceInputProvider";

export interface ThreadDetailScreenProps {
readonly codexRecovery: CodexRecoveryAction | null;
readonly worktreeSetup?: WorktreeSetupCardProps | null;
readonly setupWorkingStartedAt?: string | null;
readonly canOperateThread: boolean;
Expand Down Expand Up @@ -1201,6 +1204,15 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
/>
</Animated.View>
) : null}
{props.codexRecovery !== null ? (
<RestartCodexCard
key={`${props.environmentId}:${props.selectedThread.id}`}
environmentId={props.environmentId}
threadId={props.selectedThread.id}
retryRunId={props.codexRecovery.runId}
continueWork={props.codexRecovery.continueWork}
/>
) : null}
<UsageLimitRecoveryCard
key={props.selectedThread.latestRun?.runId}
thread={props.selectedThread}
Expand Down
6 changes: 6 additions & 0 deletions apps/mobile/src/features/threads/ThreadRouteScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { deriveCodexRecoveryAction } from "@t3tools/client-runtime/state/thread-execution";
import * as Dialog from "../../components/ui/Dialog";
import { useOpenPullRequest } from "../../native/useOpenPullRequest";
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
Expand Down Expand Up @@ -284,6 +285,10 @@ function ThreadRouteContent(
);
const selectedThreadDetailState = props.selectedThreadDetailState;
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
const codexRecovery = useMemo(
() => deriveCodexRecoveryAction(selectedThreadDetail),
[selectedThreadDetail],
);
const { selectedThreadCwd } = useSelectedThreadWorktree();
const composer = useThreadComposerState();
const gitState = useSelectedThreadGitState();
Expand Down Expand Up @@ -967,6 +972,7 @@ function ThreadRouteContent(

<ThreadPane>
<ThreadDetailScreen
codexRecovery={codexRecovery}
canOperateThread={canOperateThread}
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
selectedThreadDetailRef={selectedThreadDetailRef}
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/observability/RpcInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const RPC_AGGREGATES = {
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: "orchestrationV2",
[ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.restartCodex]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.getTurnItem]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: "orchestration",
Expand Down
157 changes: 85 additions & 72 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3372,90 +3372,103 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);

it.effect("continues an interrupted native thread with empty input and reasoning summaries", () =>
Effect.scoped(
Effect.gen(function* () {
const scenario = "codex-restart-promptless";
const nativeThreadId = "native-restart-promptless";
const nativeTurnId = "turn-restart-promptless";
const preamble = codexReplayPreamble({
nativeThreadId,
nativeTurnId,
prompt: "unused",
}).slice(0, 5);
const transcript = makeCodexReplayTranscript({
scenario,
entries: [
...preamble,
{
type: "expect_outbound",
label: "resume",
frame: {
id: 3,
method: "thread/resume",
params: {
threadId: nativeThreadId,
excludeTurns: true,
config: CodexAdapterV2.CODEX_THREAD_CONFIG,
it.effect.each([false, true])(
"resumes native history with the right input for stream recovery (stream failure: %s)",
(streamFailure) =>
Effect.scoped(
Effect.gen(function* () {
const scenario = "codex-restart-promptless";
const nativeThreadId = "native-restart-promptless";
const nativeTurnId = "turn-restart-promptless";
const preamble = codexReplayPreamble({
nativeThreadId,
nativeTurnId,
prompt: "unused",
}).slice(0, 5);
const transcript = makeCodexReplayTranscript({
scenario,
entries: [
...preamble,
{
type: "expect_outbound",
label: "resume",
frame: {
id: 3,
method: "thread/resume",
params: {
threadId: nativeThreadId,
excludeTurns: true,
config: CodexAdapterV2.CODEX_THREAD_CONFIG,
},
},
},
},
{
type: "emit_inbound",
label: "resume",
frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
},
{
type: "expect_outbound",
label: "continue",
frame: {
id: 4,
method: "turn/start",
params: {
threadId: nativeThreadId,
input: [],
cwd: "/workspace",
model: "gpt-5.4",
approvalPolicy: "never",
approvalsReviewer: "user",
sandboxPolicy: { type: "dangerFullAccess" },
summary: "detailed",
{
type: "emit_inbound",
label: "resume",
frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
},
{
type: "expect_outbound",
label: "continue",
frame: {
id: 4,
method: "turn/start",
params: {
threadId: nativeThreadId,
input: streamFailure ? [{ type: "text", text: "Continue" }] : [],
cwd: "/workspace",
model: "gpt-5.4",
approvalPolicy: "never",
approvalsReviewer: "user",
sandboxPolicy: { type: "dangerFullAccess" },
summary: "detailed",
},
},
},
},
{
type: "emit_inbound",
label: "continue",
frame: {
id: 4,
result: { turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }) },
{
type: "emit_inbound",
label: "continue",
frame: {
id: 4,
result: { turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }) },
},
},
},
],
});
const harness = yield* makeCodexReplayHarness(transcript);
const resumed = yield* harness.runtime.resumeThread({
providerThread: harness.providerThread,
modelSelection: CODEX_TEST_MODEL_SELECTION,
runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
});
yield* harness.runtime.startTurn({
...makeCodexTestTurnInput({
],
});
const harness = yield* makeCodexReplayHarness(transcript);
const resumed = yield* harness.runtime.resumeThread({
providerThread: harness.providerThread,
modelSelection: CODEX_TEST_MODEL_SELECTION,
runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
});
const turnInput = makeCodexTestTurnInput({
threadId: harness.threadId,
providerThread: resumed,
now: yield* DateTime.now,
attemptId: RunAttemptId.make("attempt-restart-promptless"),
text: "Continue where you left off.",
}),
restartContinuationOfRunId: RunId.make("run-before-restart"),
});
assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
});
yield* harness.runtime.startTurn({
...turnInput,
...(streamFailure
? {
appContext: [{ key: "previous-tool", text: "Do not repeat this context." }],
message: {
...turnInput.message,
messageId: MessageId.make("message:codex-retry:failed-stream"),
text: "Continue",
},
}
: {}),
restartContinuationOfRunId: RunId.make("run-before-restart"),
});
assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
),
);

it.effect("resolves retryable app-server errors on resumed provider activity", () =>
Expand Down
9 changes: 7 additions & 2 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6614,11 +6614,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
: null;
if (goalCommand !== null) return runGoalCommand(turnInput, goalCommand);
return Effect.gen(function* () {
const streamRecovery =
turnInput.restartContinuationOfRunId !== undefined &&
turnInput.message.messageId.startsWith("message:codex-retry:");
yield* startNativeTurn(
turnInput,
streamRecovery ? { ...turnInput, appContext: [] } : turnInput,
turnInput.restartContinuationOfRunId === undefined
? yield* toCodexInput(turnInput)
: [],
: streamRecovery
? [{ type: "text", text: "Continue" }]
: [],
);
}).pipe(
Effect.mapError(
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/orchestration-v2/EffectOutbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
Schema.Struct({
type: Schema.Literal("provider-runtime.continue"),
sourceRunId: RunId,
reason: Schema.optional(Schema.Literal("event_stream_closed")),
}),
Schema.Struct({
type: Schema.Literal("provider-session.detach"),
Expand Down
12 changes: 11 additions & 1 deletion apps/server/src/orchestration-v2/EffectWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import * as ThreadTitleRegenerationService from "./ThreadTitleRegenerationServic
import * as ThreadManagementService from "./ThreadManagementService.ts";
import * as ServerSettings from "../serverSettings.ts";
import { continueRestartedRun } from "./RestartContinuation.ts";
import { continueProviderStream } from "./ProviderStreamContinuation.ts";

export class OrchestrationEffectExecutionError extends Schema.TaggedError<OrchestrationEffectExecutionError>()(
"OrchestrationEffectExecutionError",
Expand Down Expand Up @@ -103,7 +104,16 @@ export const layerExecutor: Layer.Layer<
switch (effect.request.type) {
case "provider-runtime.continue": {
const sourceRunId = effect.request.sourceRunId;
return continueRestartedRun({ threadId: effect.threadId, sourceRunId }).pipe(
const continuation =
effect.request.reason === "event_stream_closed"
? continueProviderStream
: continueRestartedRun;
return continuation({ threadId: effect.threadId, sourceRunId }).pipe(
Effect.andThen(
effect.request.reason === "event_stream_closed"
? threads.recoverDelegatedTask(effect.threadId, sourceRunId)
: Effect.void,
),
Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
Effect.provideService(ServerSettings.ServerSettingsService, settings),
Effect.tapError(() =>
Expand Down
Loading
Loading