Skip to content
Open
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
28 changes: 21 additions & 7 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3468,15 +3468,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
// the server or scheduled tasks, so a later completed run releases those unless it was stopped.
const releaseUnattendedHolds = Effect.fn("Orchestrator.releaseUnattendedHolds")(function* (
threadId: ThreadId,
completedRunId: RunId,
completedRun: OrchestrationV2Run,
) {
const completedRunId = completedRun.id;
const held = yield* projectionStore.getHeldQueuedRuns(threadId);
if (held.length === 0) return;
const projection = yield* projectionStore.getThreadRecords(
threadId,
["runs", "messages", "turnItems"],
{
messageIds: held.map((run) => run.userMessageId),
messageIds: [...held.map((run) => run.userMessageId), completedRun.userMessageId],
turnItemTypes: ["run_interrupt_request"],
turnItemRunIds: [completedRunId],
},
Expand All @@ -3495,8 +3496,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
.filter((message) => message.createdBy !== "user" || message.scheduledTaskId !== undefined)
.map((message) => message.id),
);
// A restart that cut a compaction records the holds it added; redoing it releases those.
// Retried or re-cut continuations chain back to the run that recorded them.
const restartHeld = new Set<RunId>();
const isCompaction = messages.some(
(message) => message.id === completedRun.userMessageId && isCompactionCommandMessage(message),
);
let id = isCompaction ? completedRun.restartContinuationOfRunId : undefined;
for (let hops = 0; id !== undefined && hops < projection.runs.length; hops++) {
const source = projection.runs.find((run) => run.id === id);
for (const heldId of source?.restartHeldRunIds ?? []) restartHeld.add(heldId);
id = source?.restartContinuationOfRunId;
}
const now = yield* DateTime.now;
const released = held.filter((run) => unattended.has(run.userMessageId));
const released = held.filter(
(run) => unattended.has(run.userMessageId) || restartHeld.has(run.id),
Comment thread
Derpedyea marked this conversation as resolved.
Resolved
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (released.length === 0) return;
yield* writeSystemEvents(
released.map((run) => ({
Expand Down Expand Up @@ -7364,8 +7379,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio

// The service checked idleness before this command; a run or a delegated result that landed
// since makes the thread busy, and that turn refreshes the cache anyway.
// A restart's queued runs are held, so they will not refresh the cache.
if (
command.idleCompaction === "beforeCacheExpires" &&
command.restartContinuationOfRunId === undefined &&
projection.runs.some(
(run) =>
run.status === "queued" ||
Expand Down Expand Up @@ -16786,10 +16803,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
yield* threadDispatch
.withLock(
threadId,
(run.status === "completed"
? releaseUnattendedHolds(threadId, run.id)
: Effect.void
).pipe(
(run.status === "completed" ? releaseUnattendedHolds(threadId, run) : Effect.void).pipe(
Effect.andThen(
requeueUnreadSteers(threadId, [run.id]).pipe(
Effect.catchCause((cause) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,8 @@ it.effect(
providerThreadId,
providerInstanceId: ProviderInstanceId.make("codex"),
},
{ id: RunId.make("run_recovery_queued"), status: "queued", ordinal: 2 },
{ id: RunId.make("run_recovery_held"), status: "queued", ordinal: 3, queueHeld: true },
],
attempts: [
{
Expand Down Expand Up @@ -903,6 +905,8 @@ it.effect(
Layer.mock(ProjectionStore.ProjectionStoreV2)({
getRecoveryThreadIds: () => Effect.succeed([threadId]),
getRuntimeRecoveryProjection: () => Effect.succeed(projection),
getMessagesById: () => Effect.succeed(new Map()),
getThreadRecords: () => Effect.succeed(projection),
}),
Layer.mock(EventSink.EventSinkV2)({
commitCommand: (input) => {
Expand Down Expand Up @@ -943,6 +947,7 @@ it.effect(
"status" in event.payload ? event.payload.status : null,
]),
[
["run.updated", "queued"],
["run.updated", "cancelled"],
["run-attempt.updated", "cancelled"],
["node.updated", "cancelled"],
Expand All @@ -957,6 +962,13 @@ it.effect(
["provider-session.updated", "stopped"],
],
);
// Only the hold this restart added is recorded on the run it cut.
const cutRun = events.find(
(event) => event.type === "run.updated" && event.payload.status === "cancelled",
);
assert.deepEqual(cutRun?.type === "run.updated" ? cutRun.payload.restartHeldRunIds : null, [
RunId.make("run_recovery_queued"),
]);
const messageEvent = events.find((event) => event.type === "message.updated");
assert.isFalse(messageEvent?.type === "message.updated" && messageEvent.payload.streaming);
const stoppedSession = events.find((event) => event.type === "provider-session.updated");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
isProviderNativeSubagentThread,
type OrchestrationV2DomainEvent,
type ProviderThreadId,
type RunId,
type RunAttemptId,
type OrchestrationV2RestartCancelledBackgroundWork,
type OrchestrationV2Subagent,
Expand Down Expand Up @@ -567,12 +568,14 @@ export const make = Effect.gen(function* () {
...retryableRuns,
...queuedRunsInDeliveryOrder({ runs: queuedRuns, messages: queuedMessages }),
];
const restartHeldRunIds: Array<RunId> = [];
for (const [index, run] of heldRuns.entries()) {
if (bufferedMessageIds.has(run.userMessageId)) {
runs.push(run);
continue;
}
if (run.queueHeld === true && retryableRuns.length === 0) continue;
if (run.queueHeld !== true) restartHeldRunIds.push(run.id);
events.push({
id: yield* allocateEventId(),
type: "run.updated",
Expand Down Expand Up @@ -682,7 +685,13 @@ export const make = Effect.gen(function* () {
runId: run.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
payload: {
...run,
status: "cancelled",
queuePosition: null,
completedAt: now,
...(restartHeldRunIds.length > 0 ? { restartHeldRunIds } : {}),
},
});
for (const attempt of projection.attempts.filter(
(candidate) =>
Expand Down
25 changes: 20 additions & 5 deletions apps/server/src/orchestration-v2/RestartContinuation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1230,14 +1230,29 @@ it.effect("does not continue a run the user asked to stop before the restart", (
}),
);

it.effect("does not continue a cut /compact or /logout turn", () =>
it.effect("compacts again after a cut /compact turn, and does not continue a cut /logout", () =>
Effect.gen(function* () {
for (const text of ["/compact", " /LOGOUT "]) {
const texts = yield* continuationTexts({
for (const [text, creationSource, expected] of [
[" /Compact ", "mcp", ["user:/compact"]],
// Servers before `idleCompaction` marked their own compaction this way.
["/compact", "server", ["agent:/compact"]],
[" /LOGOUT ", "mcp", []],
] as const) {
const sent = yield* continuationDispatches({
...cutMidTurn(),
messages: [{ id: MessageId.make("message:user"), text, attachments: [] }],
messages: [
{
id: MessageId.make("message:user"),
role: "user",
createdBy: "agent",
creationSource,
text,
attachments: [],
},
],
} as unknown as OrchestrationV2ThreadProjection);
assert.deepEqual(texts, [], text);
const texts = sent.map((command) => `${command.createdBy}:${command.text}`);
assert.deepEqual(texts, [...expected], text);
}
const texts = yield* continuationTexts({
...cutMidTurn(),
Expand Down
45 changes: 31 additions & 14 deletions apps/server/src/orchestration-v2/RestartContinuation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import {
CommandId,
IDLE_COMPACTION_TEXT,
idleCompactionOf,
isCompactionCommandMessage,
isOrchestrationV2WorkActive,
latestProviderTurnForAttempt,
MessageId,
Expand Down Expand Up @@ -311,7 +314,13 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta
const sourceMessage = (yield* threads.getThreadRecords(input.threadId, ["messages"], {
messageIds: [source.userMessageId],
})).messages.find((message) => message.id === source.userMessageId);
if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return;
// Compaction changes nothing a repeat could double, so a cut one runs again.
const recompact =
sourceMessage !== undefined &&
isCompactionCommandMessage(sourceMessage) &&
!isRestartNoteSource(source, projection.providerTurns);
if (!recompact && sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage))
return;
const note = restartContinuationNote(
source,
projection.runs,
Expand All @@ -334,22 +343,30 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta
commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`),
threadId: input.threadId,
messageId,
text,
notification: {
source: { kind: "system" },
outcome: "updated",
summary:
input.cause === "provider_exit"
? "The agent runtime exited and stopped background work"
: note.settled
? "T3 Code restarted and stopped background work"
: "T3 Code restarted and resumed this turn",
detail: text,
},
text: recompact ? IDLE_COMPACTION_TEXT : text,
idleCompaction: recompact ? sourceMessage.idleCompaction : undefined,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exempt restarted compactions from the fresh-idle busy check

With restart continuation enabled and idle compaction set to beforeCacheExpires, queueing a follow-up during /compact and then restarting forwards that marker into the continuation. The existing busy guard in Orchestrator.ts:7382–7404 then acknowledges and returns because it sees a queued run, even though recovery has held it. No resumed compaction is created, so the new hold-release logic never executes and the follow-up still requires manual Resume. Exempt restart continuations from that fresh-idle-compaction check while preserving their marker.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c445255. The fresh-idle busy check now skips commands that carry restartContinuationOfRunId, since the restart's queued runs are held and won't refresh the cache. The resumed compaction keeps its beforeCacheExpires marker. The existing restart-hold release test now sends its final continuation that way, with held runs queued; without the change no run is created.

notification: recompact
? undefined
: {
source: { kind: "system" },
outcome: "updated",
summary:
input.cause === "provider_exit"
? "The agent runtime exited and stopped background work"
: note.settled
? "T3 Code restarted and stopped background work"
: "T3 Code restarted and resumed this turn",
detail: text,
},
attachments: [],
modelSelection: source.modelSelection,
dispatchMode: { type: "start_immediately" },
createdBy: "agent",
// Agent + server with no idleCompaction reads as an automatic idle compaction.
createdBy: !recompact
? "agent"
: idleCompactionOf(sourceMessage) === undefined
? "user"
: sourceMessage.createdBy,
creationSource: "server",
restartContinuationOfRunId: input.sourceRunId,
})
Expand Down
37 changes: 35 additions & 2 deletions apps/server/src/orchestration-v2/runtimeLayer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1623,7 +1623,7 @@
});
yield* worker.drain();
const captured = yield* orchestrator.getThreadProjection(threadId);
assert.equal(

Check failure on line 1626 in apps/server/src/orchestration-v2/runtimeLayer.test.ts

View workflow job for this annotation

GitHub Actions / Test Server 7

src/orchestration-v2/runtimeLayer.test.ts > OrchestrationV2LayerLive > captures and repeatedly rewinds non-Git conversations without losing run links

AssertionError: expected 'waiting' to equal 'completed' Expected: "completed" Received: "waiting" ❯ src/orchestration-v2/runtimeLayer.test.ts:1626:18 ❯ ~effect/Effect/successCont ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a7acd734809d8dddbf2c19c4ec01fdd2ffae60a612de42b5ed29860216052a/node_modules/effect/src/internal/effect.ts:1498:28 ❯ ~effect/Effect/evaluate ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a7acd734809d8dddbf2c19c4ec01fdd2ffae60a612de42b5ed29860216052a/node_modules/effect/src/internal/core.ts:586:30 ❯ FiberImpl.runLoop ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a7acd734809d8dddbf2c19c4ec01fdd2ffae60a612de42b5ed29860216052a/node_modules/effect/src/internal/effect.ts:711:43 ❯ FiberImpl.evaluate ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a7acd734809d8dddbf2c19c4ec01fdd2ffae60a612de42b5ed29860216052a/node_modules/effect/src/internal/effect.ts:637:23 ❯ FiberImpl.evaluate ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a7acd734809d8dddbf2c19c4ec01fdd2ffae60a612de42b5ed29860216052a/node_modules/effect/src/internal/effect.ts:626:29 ❯ ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a7acd734809d8dddbf2c19c4ec01fdd2ffae60a612de42b5ed29860216052a/node_modules/effect/src/internal/effect.ts:1226:17 ❯ Array.<anonymous> ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a7acd734809d8dddbf2c19c4ec01fdd2ffae60a612de42b5ed29860216052a/node_modules/effect/src/internal/effect.ts:1780:11
captured.runs.find((candidate) => candidate.id === run.id)?.status,
"completed",
);
Expand Down Expand Up @@ -9382,8 +9382,14 @@
branch: null,
worktreePath: process.cwd(),
});
const send = (key: string, createdBy: "user" | "agent", start: boolean) =>
const send = (
key: string,
createdBy: "user" | "agent",
start: boolean,
extra: { idleCompaction?: "beforeCacheExpires"; restartContinuationOfRunId?: RunId } = {},
) =>
orchestrator.dispatch({
...extra,
type: "message.dispatch",
createdBy,
creationSource: createdBy === "user" ? "web" : "server",
Expand Down Expand Up @@ -9432,7 +9438,7 @@
});
const end = (
key: string,
status: "completed" | "failed",
status: "completed" | "failed" | "cancelled",
revision = "",
patch: Partial<OrchestrationV2Run> = {},
) =>
Expand Down Expand Up @@ -9582,6 +9588,33 @@
}),
);

it.effect("a compaction resumed after a restart releases only what that restart held", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("runtime-layer-held-queue-resumed-compaction");
const { send, runFor, end, startedRunIds, awaitHeld } = yield* queueTestThread(threadId);
yield* send("failed", "agent", true);
yield* send("earlier", "user", false);
yield* send("later", "user", false);
yield* end("failed", "failed");
yield* awaitHeld("later");
yield* send("cut", "agent", true);
yield* end("cut", "cancelled", "", { restartHeldRunIds: [(yield* runFor("later")).id] });
// A second restart cuts the first continuation, which adds no holds of its own.
yield* send(" /compact", "agent", true);
yield* end(" /compact", "cancelled", "", {
restartContinuationOfRunId: (yield* runFor("cut")).id,
});
// Queued runs are held, so an idle compaction does not wait for them.
yield* send("/compact", "agent", true, {
idleCompaction: "beforeCacheExpires",
restartContinuationOfRunId: (yield* runFor(" /compact")).id,
});
yield* end("/compact", "completed");
assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("later")).id);
assert.isTrue((yield* runFor("earlier")).queueHeld);
}),
);

it.effect("keeps held agent messages while the thread's worktree setup is unresolved", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
Expand Down
1 change: 1 addition & 0 deletions docs/user/composer.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ the provider, Resume sends that request again.

Sending a new message also resumes the queue, unless it steers a turn that is already
running. You can edit or remove held messages without starting them.
A `/compact` cut by a restart runs again, and messages queued behind it send when it finishes.

The pencil on a queued message opens it in the composer for editing. The original message
stays in the queue until you save, and it is highlighted while you edit. The message's
Expand Down
2 changes: 2 additions & 0 deletions packages/contracts/src/orchestrationV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,8 @@ export const OrchestrationV2Run = Schema.Struct({
restartCancelledBackgroundWork: Schema.optional(
Schema.Array(OrchestrationV2RestartCancelledBackgroundWork),
),
/** Queued runs a restart held when it cut this run, as opposed to holds already in place. */
restartHeldRunIds: Schema.optional(Schema.Array(RunId)),
sourcePlanRef: Schema.optional(
Schema.Struct({
threadId: ThreadId,
Expand Down
Loading