Skip to content
Open
29 changes: 23 additions & 6 deletions apps/server/scripts/record-codex-app-server-replay-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ type ReplayStep =
| {
readonly type: "rollback";
readonly label: string;
readonly numTurns: number;
readonly afterTurnLabel: string;
}
| {
readonly type: "fork";
Expand Down Expand Up @@ -799,7 +799,7 @@ function scenarios(): ReadonlyArray<ReplayScenario> {
{
type: "rollback",
label: "rollback-latest-turn",
numTurns: 1,
afterTurnLabel: "first-before-rollback",
},
{
type: "turn",
Expand Down Expand Up @@ -834,7 +834,7 @@ function scenarios(): ReadonlyArray<ReplayScenario> {
{
type: "rollback",
label: "rollback-latest-turn",
numTurns: 1,
afterTurnLabel: "first-before-rollback",
},
{
type: "turn",
Expand Down Expand Up @@ -879,7 +879,7 @@ function scenarios(): ReadonlyArray<ReplayScenario> {
{
type: "rollback",
label: "rollback-to-stopped-turn",
numTurns: 1,
afterTurnLabel: "stopped-mid-tool",
},
{
type: "turn",
Expand Down Expand Up @@ -1222,9 +1222,25 @@ const runReplaySession = Effect.fn("record-codex-app-server-replay-fixture.runRe
approvalGate ? Deferred.await(approvalGate) : Effect.void;
const model = scenarioModel(scenario);
const threadRuntimeParams = { cwd: process.cwd(), model, config: CODEX_THREAD_CONFIG };
const turnIdsByLabel = new Map<string, string>();
const lastTurnIdByThread = new Map<string, string>();
const runningCommandProcessIds = new Map<string, Map<string, string>>();

const rollbackToRecordedTurn = Effect.fn(
"record-codex-app-server-replay-fixture.rollbackToRecordedTurn",
)(function* (
client: CodexClient.CodexAppServerClient["Service"],
threadId: string,
afterTurnLabel: string,
) {
const afterTurnId = turnIdsByLabel.get(afterTurnLabel);
if (afterTurnId === undefined) {
throw new Error(`Unknown replay checkpoint turn '${afterTurnLabel}'.`);
}
yield* revertCodexThread(client, threadId, { afterTurnId });
lastTurnIdByThread.set(threadId, afterTurnId);
});

const initializeClient = Effect.gen(function* () {
const client = yield* CodexClient.CodexAppServerClient;

Expand Down Expand Up @@ -1311,6 +1327,7 @@ const runReplaySession = Effect.fn("record-codex-app-server-replay-fixture.runRe

const completed = yield* getCompletion(turnId);
yield* Deferred.await(completed);
turnIdsByLabel.set(step.label, turnId);
lastTurnIdByThread.set(threadId, turnId);
});

Expand Down Expand Up @@ -1402,7 +1419,7 @@ const runReplaySession = Effect.fn("record-codex-app-server-replay-fixture.runRe
// Fresh app-servers report notLoaded; resume before thread/revert and again on the next turn.
yield* client.request("thread/read", { threadId, includeTurns: false });
yield* client.request("thread/resume", resumeParams);
yield* revertCodexThread(client, threadId, rollback.numTurns);
yield* rollbackToRecordedTurn(client, threadId, rollback.afterTurnLabel);
yield* client.request("thread/resume", resumeParams);
yield* runTurnStep(client, threadId, after);
}).pipe(Effect.provide(layerCodex({ recorder })));
Expand All @@ -1421,7 +1438,7 @@ const runReplaySession = Effect.fn("record-codex-app-server-replay-fixture.runRe
for (const [stepIndex, step] of run.steps.entries()) {
if (step.type === "rollback") {
yield* client.request("thread/read", { threadId: activeThreadId, includeTurns: false });
yield* revertCodexThread(client, activeThreadId, step.numTurns);
yield* rollbackToRecordedTurn(client, activeThreadId, step.afterTurnLabel);
continue;
}
if (step.type === "fork") {
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/auth/RpcAuthorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.filesystemGetMetadata]: AuthFilesystemReadScope,
[WS_METHODS.agentSessionsScan]: AuthOrchestrationReadScope,
[WS_METHODS.agentSessionsImport]: AuthOrchestrationOperateScope,
[WS_METHODS.agentSessionsRefreshCodexHistory]: AuthOrchestrationOperateScope,
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
[WS_METHODS.assetsPersistChatAttachments]: AuthOrchestrationOperateScope,
[WS_METHODS.attachmentsCreateUploadUrl]: AuthOrchestrationOperateScope,
Expand Down
73 changes: 70 additions & 3 deletions apps/server/src/checkpointing/CheckpointDiffQuery.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, vi } from "@effect/vitest";
import { CheckpointRef, CheckpointScopeId, RunId, ThreadId } from "@t3tools/contracts";
import {
CheckpointId,
CheckpointRef,
CheckpointScopeId,
RunId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
Expand Down Expand Up @@ -36,6 +42,8 @@ function makeProjection(): ProjectionCheckpointContext {
],
checkpoints: [
{
id: CheckpointId.make("checkpoint:second"),
parentCheckpointId: null,
scopeId: secondScopeId,
runId: secondRunId,
ordinalWithinScope: 1,
Expand Down Expand Up @@ -112,6 +120,8 @@ function makeProjectionAfterStoppedRun(stoppedRunCheckpoint: boolean) {
ordinalWithinScope: number,
runId: RunId | null,
): ProjectionCheckpointContext["checkpoints"][number] => ({
id: CheckpointId.make(`checkpoint:root:${ordinalWithinScope}`),
parentCheckpointId: null,
scopeId: firstScopeId,
runId,
ordinalWithinScope,
Expand All @@ -132,6 +142,7 @@ function makeProjectionAfterStoppedRun(stoppedRunCheckpoint: boolean) {
checkpoints: [
{
...checkpoint(2, null),
id: CheckpointId.make("checkpoint:tool:2"),
scopeId: secondScopeId,
ref: CheckpointRef.make("refs/t3/test/tool/2"),
},
Expand Down Expand Up @@ -190,6 +201,44 @@ it.effect.each([false, true])(
},
);

it.effect(
"uses the captured parent when refreshed history separates app and scope ordinals",
() => {
const projection = makeProjectionAfterStoppedRun(true);
const parent = { ...projection.checkpoints[3]!, appRunOrdinal: 3 };
const unusedBaseline = { ...projection.checkpoints[4]!, runId: null, appRunOrdinal: null };
const target = {
...projection.checkpoints[4]!,
id: CheckpointId.make("checkpoint:root:4"),
parentCheckpointId: parent.id,
ordinalWithinScope: 4,
appRunOrdinal: 4,
ref: CheckpointRef.make("refs/t3/test/ordinal/4"),
};
const diffCheckpoints = vi.fn((_input: CheckpointStore.DiffCheckpointsInput) =>
Effect.succeed("diff --git a/file b/file"),
);
const layer = layerFor({
projection: Effect.succeed({
...projection,
runs: projection.runs.map((run) =>
run.ordinal === 1 ? run : { ...run, ordinal: run.ordinal + 1 },
),
checkpoints: [...projection.checkpoints.slice(0, 3), parent, unusedBaseline, target],
}),
diffCheckpoints,
});
return Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
yield* query.getTurnDiff({ threadId, fromTurnCount: 3, toTurnCount: 4 });
assert.deepEqual(
diffCheckpoints.mock.calls.map(([input]) => input.fromCheckpointRef),
[parent.ref],
);
}).pipe(Effect.provide(layer));
},
);

const layerVcsProcess = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
const layerStore = CheckpointStore.layer.pipe(
Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(layerVcsProcess))),
Expand Down Expand Up @@ -260,6 +309,8 @@ it.effect("shares the turn and full-thread diff budget across real Git batches",
checkpointScopes: [{ id: scopeId, runId, kind: "root_run", cwd }],
checkpoints: [
{
id: CheckpointId.make("checkpoint:patch-budget:1"),
parentCheckpointId: null,
scopeId,
runId,
ordinalWithinScope: 1,
Expand Down Expand Up @@ -360,6 +411,8 @@ it.effect("adds a patch for each tracked repository that changed in the range",
repositoryPath: cwd,
},
checkpoints: ordinals.map((ordinalWithinScope) => ({
id: CheckpointId.make(`checkpoint:${name}:${ordinalWithinScope}`),
parentCheckpointId: null,
scopeId: id,
runId: ordinalWithinScope === 2 ? secondRunId : null,
ordinalWithinScope,
Expand All @@ -380,14 +433,26 @@ it.effect("adds a patch for each tracked repository that changed in the range",
const layer = layerFor({
projection: Effect.succeed({
...projection,
runs: [
projection.runs[0]!,
{ id: RunId.make("imported-turn"), ordinal: 2, status: "completed" },
{ ...projection.runs[1]!, ordinal: 3 },
],
checkpointScopes: [
...projection.checkpointScopes.map((scope) => ({ ...scope, cwd: "/work/app" })),
sibling.scope,
nested.scope,
later.scope,
],
checkpoints: [
...projection.checkpoints,
{
...projection.checkpoints[0]!,
id: CheckpointId.make("checkpoint:first"),
runId: firstRunId,
appRunOrdinal: 1,
ref: CheckpointRef.make("refs/t3/test/first"),
},
{ ...projection.checkpoints[0]!, ordinalWithinScope: 2, appRunOrdinal: 3 },
...sibling.checkpoints,
...nested.checkpoints,
...later.checkpoints,
Expand All @@ -397,7 +462,7 @@ it.effect("adds a patch for each tracked repository that changed in the range",
});
return Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const result = yield* query.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 2 });
const result = yield* query.getTurnDiff({ threadId, fromTurnCount: 2, toTurnCount: 3 });
assert.deepEqual(result.repositories, [
{
name: "shared",
Expand All @@ -412,6 +477,8 @@ it.effect("adds a patch for each tracked repository that changed in the range",
diffCheckpoints.mock.calls.find(([input]) => input.cwd === "/work/app")?.[0].excludePaths,
["packages/ui"],
);
const aggregate = yield* query.getFullThreadDiff({ threadId, toTurnCount: 3 });
assert.deepEqual(aggregate.repositories, result.repositories);
}).pipe(Effect.provide(layer));
});

Expand Down
49 changes: 38 additions & 11 deletions apps/server/src/checkpointing/CheckpointDiffQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,21 +100,43 @@ type ContextCheckpoint = ProjectionCheckpointContext["checkpoints"][number];
*/
function repositoryDiffRange(
checkpoints: ReadonlyArray<ContextCheckpoint>,
range: { readonly fromTurnCount: number; readonly toTurnCount: number },
range: { readonly fromOrdinal: number; readonly toOrdinal: number },
): { readonly from: ContextCheckpoint; readonly to: ContextCheckpoint } | undefined {
const ready = checkpoints
.filter(
(checkpoint) =>
checkpoint.status === "ready" &&
checkpoint.ordinalWithinScope >= range.fromTurnCount &&
checkpoint.ordinalWithinScope <= range.toTurnCount,
checkpoint.ordinalWithinScope >= range.fromOrdinal &&
checkpoint.ordinalWithinScope <= range.toOrdinal,
)
.toSorted((left, right) => left.ordinalWithinScope - right.ordinalWithinScope);
const from = ready[0];
const to = ready.at(-1);
return from === undefined || to === undefined || from === to ? undefined : { from, to };
}

// Imported turns have no snapshots; a repository range starts at the first captured turn's baseline.
function repositoryRangeStart(
checkpoints: ReadonlyArray<ContextCheckpoint>,
range: { readonly fromTurnCount: number; readonly toTurnCount: number },
toOrdinal: number,
): number {
if (range.fromTurnCount === 0) return 0;
let firstOrdinal = toOrdinal;
for (const checkpoint of checkpoints) {
if (
checkpoint.status !== "stale" &&
checkpoint.appRunOrdinal !== null &&
checkpoint.appRunOrdinal > range.fromTurnCount &&
checkpoint.appRunOrdinal <= range.toTurnCount &&
checkpoint.ordinalWithinScope < firstOrdinal
) {
firstOrdinal = checkpoint.ordinalWithinScope;
}
}
return firstOrdinal - 1;
}

/** @public */
export const make = Effect.gen(function* () {
const threads = yield* ThreadManagement.ThreadManagementService;
Expand Down Expand Up @@ -193,8 +215,8 @@ export const make = Effect.gen(function* () {
const repositoryDiffs = Effect.fn("CheckpointDiffQuery.repositoryDiffs")(function* (input: {
readonly projection: ProjectionCheckpointContext;
readonly threadCwd: string;
readonly fromTurnCount: number;
readonly toTurnCount: number;
readonly fromOrdinal: number;
readonly toOrdinal: number;
readonly ignoreWhitespace: boolean;
readonly nested: ReadonlyMap<string, ReadonlyArray<string>>;
readonly maxBytes: number;
Expand Down Expand Up @@ -346,7 +368,7 @@ export const make = Effect.gen(function* () {
projection.checkpoints.some(
(checkpoint) =>
checkpoint.scopeId === scope.id &&
checkpoint.ordinalWithinScope <= input.toTurnCount,
checkpoint.ordinalWithinScope <= toCheckpoint.ordinalWithinScope,
),
),
]).pipe(
Expand All @@ -361,8 +383,12 @@ export const make = Effect.gen(function* () {
: yield* repositoryDiffs({
projection,
threadCwd: toScope.cwd,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
fromOrdinal: repositoryRangeStart(
projection.checkpoints,
input,
toCheckpoint.ordinalWithinScope,
),
toOrdinal: toCheckpoint.ordinalWithinScope,
ignoreWhitespace,
nested,
maxBytes: Math.max(0, CHECKPOINT_DIFF_MAX_OUTPUT_BYTES - Buffer.byteLength(diff)),
Expand All @@ -378,15 +404,16 @@ export const make = Effect.gen(function* () {
});
if (toCheckpoint.status === "missing") return yield* withRepositories("");

// Capture compares against the preceding scope ordinal, even when that
// checkpoint belongs to a stopped run or has no run.
// Imported turns can move app ordinals while the captured parent and its ref stay in place.
const parentCheckpoint =
input.fromTurnCount === input.toTurnCount - 1
? projection.checkpoints.find(
(checkpoint) =>
checkpoint.status === "ready" &&
checkpoint.scopeId === toCheckpoint.scopeId &&
checkpoint.ordinalWithinScope === toCheckpoint.ordinalWithinScope - 1,
(toCheckpoint.parentCheckpointId === null
? checkpoint.ordinalWithinScope === toCheckpoint.ordinalWithinScope - 1
: checkpoint.id === toCheckpoint.parentCheckpointId),
)
: undefined;

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 @@ -207,6 +207,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.filesystemGetMetadata]: "workspace",
[WS_METHODS.agentSessionsScan]: "workspace",
[WS_METHODS.agentSessionsImport]: "workspace",
[WS_METHODS.agentSessionsRefreshCodexHistory]: "workspace",
[WS_METHODS.assetsCreateUrl]: "workspace",
[WS_METHODS.assetsPersistChatAttachments]: "orchestration",
[WS_METHODS.attachmentsCreateUploadUrl]: "workspace",
Expand Down
Loading
Loading