@devries-cameron20 / t3code Mirror · read-only / commits / cc0b86ddf1
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 15:45 UTC

fix(server): goals stop the running turn, clear while working, no echoes (#25426)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 26, 2026 at 03:28 UTC cc0b86ddf12a34bd65dce88d6f2ae1f069ef841e
11 files changed +913 -91
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+49
@@ -14524,6 +14524,55 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14524 ),
14525 ),
14526 );
14527 +
14528 + it.effect("keeps the CLI's goal confirmation out of the conversation", () =>
14529 + Effect.gen(function* () {
14530 + const harness = yield* makeWakeHarness;
14531 + const condition = "all tests pass";
14532 + yield* harness.runtime.startTurn(
14533 + makeClaudeTestTurnInput({
14534 + threadId: harness.threadId,
14535 + providerThread: {
14536 + ...harness.providerThread,
14537 + goal: { objective: condition, status: "active", checks: 1 },
14538 + },
14539 + now: yield* DateTime.now,
14540 + attemptId: RunAttemptId.make("goal-clear-attempt"),
14541 + text: "/goal clear",
14542 + attachments: [],
14543 + }),
14544 + );
14545 + yield* Queue.offer(
14546 + harness.sdkMessages,
14547 + syntheticFrame("goal-clear", `Goal cleared: ${condition}`),
14548 + );
14549 + yield* Queue.offer(
14550 + harness.sdkMessages,
14551 + makeResultFrame({
14552 + uuid: "goal-clear-result",
14553 + result: `Goal cleared: ${condition}\n`,
14554 + numTurns: 0,
14555 + }),
14556 + );
14557 + yield* Queue.take(harness.terminalReceipts);
14558 + assert.isTrue(
14559 + harness.events.some(
14560 + (event) =>
14561 + event.type === "provider_thread.updated" && event.providerThread.goal === null,
14562 + ),
14563 + );
14564 + assert.isFalse(
14565 + harness.events.some(
14566 + (event) => event.type === "message.updated" && event.message.role === "assistant",
14567 + ),
14568 + );
14569 + }).pipe(
14570 + Effect.scoped,
14571 + Effect.provide(
14572 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
14573 + ),
14574 + ),
14575 + );
14576 });
14577 });
14578
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+22 -1
@@ -1723,6 +1723,19 @@ function nextClaudeGoal(
1723 };
1724 }
1725
1726 +/** The CLI confirms a goal change as a synthetic reply; the goal row shows that change instead. */
1727 +function isClaudeGoalAcknowledgement(message: SDKMessage): boolean {
1728 + if (
1729 + message.type !== "assistant" ||
1730 + message.parent_tool_use_id !== null ||
1731 + message.message.model !== "<synthetic>"
1732 + ) {
1733 + return false;
1734 + }
1735 + const text = textFromClaudeContent(message.message.content).trim();
1736 + return text.startsWith(CLAUDE_GOAL_SET_PREFIX) || text.startsWith("Goal cleared: ");
1737 +}
1738 +
1739 const providerGoalsEqual = Schema.toEquivalence(Schema.NullOr(OrchestrationV2ProviderGoal));
1740
1741 function normalizeClaudeResultText(text: string): string {
@@ -8895,6 +8908,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8908 });
8909 return;
8910 }
8911 + if (isClaudeGoalAcknowledgement(message)) {
8912 + // The CLI repeats a local command's output as the turn's result text.
8913 + if (assistantText !== null) {
8914 + context.assistant.noticeTexts.add(normalizeClaudeResultText(assistantText.text));
8915 + }
8916 + return;
8917 + }
8918 // Claude Code echoes /compact's stdout ("Not enough messages to compact.") as a
8919 // synthetic assistant message. The compaction item reports that outcome; it is not a
8920 // reply.
@@ -8967,7 +8987,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8987 context.assistant.fallbackText.length === 0 &&
8988 resultText !== null &&
8989 resultText.text.length > 0 &&
8970 - !context.assistant.noticeTexts.has(resultText.text)
8990 + !context.assistant.noticeTexts.has(resultText.text) &&
8991 + !context.assistant.noticeTexts.has(normalizeClaudeResultText(resultText.text))
8992 ) {
8993 context.assistant.fallbackText = resultText.text;
8994 context.assistant.fallbackNativeItemId = resultText.nativeItemId;
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+230
@@ -5958,6 +5958,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5958 nativeThreadId,
5959 nativeTurnId: "goal-turn-1",
5960 prompt: objective,
5961 + sentPrompt: `Start working toward this goal: ${objective}`,
5962 }).slice(5),
5963 5,
5964 ),
@@ -6022,6 +6023,8 @@ describe("CodexAdapterV2 post-settle continuation", () => {
6023 [providerTurnId("goal-turn-2"), RunAttemptId.make("goal-attempt"), 2],
6024 ],
6025 );
6026 + // The goal is set paused until its first turn starts; only the result shows.
6027 + assert.notInclude(providerGoals(harness.events), "paused");
6028 assert.equal(providerGoals(harness.events).at(-1), "complete");
6029 }).pipe(
6030 Effect.scoped,
@@ -6204,6 +6207,233 @@ describe("CodexAdapterV2 post-settle continuation", () => {
6207 ),
6208 );
6209
6210 + it.effect("pauses a goal Codex does not continue before its run settles", () =>
6211 + Effect.gen(function* () {
6212 + const prompt = "Keep going";
6213 + const transcript = makeCodexReplayTranscript({
6214 + scenario: "goal-continuation-expired",
6215 + entries: [
6216 + ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn", prompt }),
6217 + notification("goal active", "thread/goal/updated", {
6218 + threadId: nativeThreadId,
6219 + turnId: "goal-turn",
6220 + goal: codexGoal("active", 10),
6221 + }),
6222 + notification("turn done", "turn/completed", {
6223 + threadId: nativeThreadId,
6224 + turn: makeCodexReplayTurn({ id: "goal-turn", status: "completed" }),
6225 + }),
6226 + notification("goal accounted", "thread/goal/updated", {
6227 + threadId: nativeThreadId,
6228 + turnId: null,
6229 + goal: codexGoal("active", 11),
6230 + }),
6231 + ...request(
6232 + 4,
6233 + "thread/goal/set",
6234 + { threadId: nativeThreadId, status: "paused" },
6235 + { goal: codexGoal("paused", 11) },
6236 + ),
6237 + ],
6238 + });
6239 + const harness = yield* makeCodexReplayHarness(transcript);
6240 + yield* harness.runtime.startTurn(
6241 + makeCodexTestTurnInput({
6242 + threadId: harness.threadId,
6243 + providerThread: harness.providerThread,
6244 + now: yield* DateTime.now,
6245 + attemptId: RunAttemptId.make("goal-expired-attempt"),
6246 + text: prompt,
6247 + }),
6248 + );
6249 + yield* harness.until(() =>
6250 + harness.events.some(
6251 + (event) =>
6252 + event.type === "provider_thread.updated" &&
6253 + event.providerThread.goal?.tokensUsed === 11,
6254 + ),
6255 + );
6256 + assert.lengthOf(harness.terminalEvents(), 0);
6257 + yield* TestClock.adjust("5 seconds");
6258 + yield* harness.firstTerminal;
6259 +
6260 + assert.deepEqual(providerGoals(harness.events), ["active", "active", "paused"]);
6261 + assert.deepEqual(
6262 + harness.terminalEvents().map((event) => event.status),
6263 + ["completed"],
6264 + );
6265 + }).pipe(
6266 + Effect.scoped,
6267 + Effect.provide(
6268 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6269 + ),
6270 + ),
6271 + );
6272 +
6273 + it.effect("stops a turn Codex starts while the expiry pause is in flight", () =>
6274 + Effect.gen(function* () {
6275 + const prompt = "Keep going";
6276 + const transcript = makeCodexReplayTranscript({
6277 + scenario: "goal-continuation-during-expiry",
6278 + entries: [
6279 + ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn", prompt }),
6280 + notification("goal active", "thread/goal/updated", {
6281 + threadId: nativeThreadId,
6282 + turnId: "goal-turn",
6283 + goal: codexGoal("active", 10),
6284 + }),
6285 + notification("turn done", "turn/completed", {
6286 + threadId: nativeThreadId,
6287 + turn: makeCodexReplayTurn({ id: "goal-turn", status: "completed" }),
6288 + }),
6289 + notification("goal accounted", "thread/goal/updated", {
6290 + threadId: nativeThreadId,
6291 + turnId: null,
6292 + goal: codexGoal("active", 11),
6293 + }),
6294 + {
6295 + type: "expect_outbound",
6296 + label: "pause",
6297 + frame: {
6298 + id: 4,
6299 + method: "thread/goal/set",
6300 + params: { threadId: nativeThreadId, status: "paused" },
6301 + },
6302 + },
6303 + notification("goal paused", "thread/goal/updated", {
6304 + threadId: nativeThreadId,
6305 + turnId: null,
6306 + goal: codexGoal("paused", 11),
6307 + }),
6308 + notification("late continuation", "turn/started", {
6309 + threadId: nativeThreadId,
6310 + turn: makeCodexReplayTurn({ id: "goal-turn-2", status: "inProgress" }),
6311 + }),
6312 + ...request(
6313 + 5,
6314 + "thread/goal/set",
6315 + { threadId: nativeThreadId, status: "paused" },
6316 + { goal: codexGoal("paused", 11) },
6317 + ),
6318 + ...request(
6319 + 6,
6320 + "turn/interrupt",
6321 + { threadId: nativeThreadId, turnId: "goal-turn-2" },
6322 + {},
6323 + ),
6324 + {
6325 + type: "emit_inbound",
6326 + label: "paused",
6327 + frame: { id: 4, result: { goal: codexGoal("paused", 11) } },
6328 + },
6329 + ],
6330 + });
6331 + const harness = yield* makeCodexReplayHarness(transcript);
6332 + yield* harness.runtime.startTurn(
6333 + makeCodexTestTurnInput({
6334 + threadId: harness.threadId,
6335 + providerThread: harness.providerThread,
6336 + now: yield* DateTime.now,
6337 + attemptId: RunAttemptId.make("goal-race-attempt"),
6338 + text: prompt,
6339 + }),
6340 + );
6341 + yield* harness.until(() =>
6342 + harness.events.some(
6343 + (event) =>
6344 + event.type === "provider_thread.updated" &&
6345 + event.providerThread.goal?.tokensUsed === 11,
6346 + ),
6347 + );
6348 + yield* TestClock.adjust("5 seconds");
6349 + yield* harness.firstTerminal;
6350 +
6351 + assert.deepEqual(
6352 + harness.terminalEvents().map((event) => [event.providerTurnId, event.status]),
6353 + [
6354 + [
6355 + (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
6356 + driver: CodexAdapterV2.CODEX_DRIVER_KIND,
6357 + nativeTurnId: "goal-turn",
6358 + }),
6359 + "completed",
6360 + ],
6361 + ],
6362 + );
6363 + assert.equal(providerGoals(harness.events).at(-1), "paused");
6364 + }).pipe(
6365 + Effect.scoped,
6366 + Effect.provide(
6367 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6368 + ),
6369 + ),
6370 + );
6371 +
6372 + it.effect("settles the run when Codex never answers the expiry pause", () =>
6373 + Effect.gen(function* () {
6374 + const prompt = "Keep going";
6375 + const transcript = makeCodexReplayTranscript({
6376 + scenario: "goal-expiry-pause-unanswered",
6377 + entries: [
6378 + ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn", prompt }),
6379 + notification("goal active", "thread/goal/updated", {
6380 + threadId: nativeThreadId,
6381 + turnId: "goal-turn",
6382 + goal: codexGoal("active", 10),
6383 + }),
6384 + notification("turn done", "turn/completed", {
6385 + threadId: nativeThreadId,
6386 + turn: makeCodexReplayTurn({ id: "goal-turn", status: "completed" }),
6387 + }),
6388 + notification("goal accounted", "thread/goal/updated", {
6389 + threadId: nativeThreadId,
6390 + turnId: null,
6391 + goal: codexGoal("active", 11),
6392 + }),
6393 + {
6394 + type: "expect_outbound",
6395 + label: "pause",
6396 + frame: {
6397 + id: 4,
6398 + method: "thread/goal/set",
6399 + params: { threadId: nativeThreadId, status: "paused" },
6400 + },
6401 + },
6402 + ],
6403 + });
6404 + const harness = yield* makeCodexReplayHarness(transcript);
6405 + yield* harness.runtime.startTurn(
6406 + makeCodexTestTurnInput({
6407 + threadId: harness.threadId,
6408 + providerThread: harness.providerThread,
6409 + now: yield* DateTime.now,
6410 + attemptId: RunAttemptId.make("goal-unanswered-attempt"),
6411 + text: prompt,
6412 + }),
6413 + );
6414 + yield* harness.until(() =>
6415 + harness.events.some(
6416 + (event) =>
6417 + event.type === "provider_thread.updated" &&
6418 + event.providerThread.goal?.tokensUsed === 11,
6419 + ),
6420 + );
6421 + yield* TestClock.adjust("5 seconds");
6422 + yield* TestClock.adjust("10 seconds");
6423 + yield* harness.firstTerminal;
6424 +
6425 + assert.deepEqual(
6426 + harness.terminalEvents().map((event) => event.status),
6427 + ["completed"],
6428 + );
6429 + }).pipe(
6430 + Effect.scoped,
6431 + Effect.provide(
6432 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6433 + ),
6434 + ),
6435 + );
6436 +
6437 it.effect("pauses an active goal before Stop interrupts its turn", () =>
6438 Effect.gen(function* () {
6439 const prompt = "Keep going";
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+107 -61
@@ -31,7 +31,9 @@ import {
31 CodexSettings,
32 defaultInstanceIdForDriver,
33 isOrchestrationV2WorkActive,
34 + type OrchestrationV2GoalCommand,
35 OrchestrationV2ProviderGoal,
36 + parseGoalCommand,
37 ProviderDriverKind,
38 type ProviderSetupError,
39 } from "@t3tools/contracts";
@@ -882,32 +884,6 @@ const isTerminalProviderTurn = (turn: OrchestrationV2ProviderTurn): boolean =>
884 turn.status === "failed" ||
885 turn.status === "cancelled");
886
885 -export type CodexGoalCommand =
886 - | { readonly type: "show" }
887 - | { readonly type: "clear" }
888 - | { readonly type: "pause" }
889 - | { readonly type: "resume" }
890 - | { readonly type: "set"; readonly objective: string };
891 -
892 -function parseCodexGoalCommand(text: string): CodexGoalCommand | null {
893 - const match = /^\/goal(?:\s+([\s\S]*))?$/u.exec(text.trim());
894 - if (match === null) return null;
895 - const argument = (match[1] ?? "").trim();
896 - switch (argument.toLowerCase()) {
897 - case "":
898 - case "edit":
899 - return { type: "show" };
900 - case "clear":
901 - return { type: "clear" };
902 - case "pause":
903 - return { type: "pause" };
904 - case "resume":
905 - return { type: "resume" };
906 - default:
907 - return { type: "set", objective: argument };
908 - }
909 -}
910 -
887 type CodexThreadGoal = CodexSchema.V2ThreadGoalUpdatedNotification["goal"];
888
889 const CODEX_GOAL_STATUSES = {
@@ -1849,9 +1825,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
1825 const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) =>
1826 Queue.offer(events, event).pipe(Effect.asVoid);
1827
1828 + // Setting a goal passes through cleared and paused states; publish only the result.
1829 + const goalUpdatesHeld = new Set<string>();
1830 const emitGoalUpdate = Effect.fnUntraced(function* (nativeThreadId: string) {
1831 const providerThread = rootProviderThreads.get(nativeThreadId);
1854 - if (providerThread === undefined || !goalsByNativeThread.has(nativeThreadId)) return;
1832 + if (
1833 + providerThread === undefined ||
1834 + !goalsByNativeThread.has(nativeThreadId) ||
1835 + goalUpdatesHeld.has(nativeThreadId)
1836 + ) {
1837 + return;
1838 + }
1839 const goal = goalsByNativeThread.get(nativeThreadId) ?? null;
1840 if (providerGoalsEqual(providerThread.goal ?? null, goal)) return;
1841 const updated = { ...providerThread, goal, updatedAt: yield* DateTime.now };
@@ -1872,6 +1856,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
1856 yield* emitGoalUpdate(nativeThreadId);
1857 });
1858
1859 + const releaseGoalUpdates = (nativeThreadId: string) =>
1860 + Effect.suspend(() => {
1861 + goalUpdatesHeld.delete(nativeThreadId);
1862 + return emitGoalUpdate(nativeThreadId);
1863 + });
1864 +
1865 // Only new model output proves recovery; local item/completed can arrive during upstream retries.
1866 const completeProviderRetry = Effect.fn("CodexAdapterV2.completeProviderRetry")(function* (
1867 context: ActiveCodexTurnContext,
@@ -5695,10 +5685,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
5685 next: yield* Deferred.make<ActiveCodexTurnContext | undefined>(),
5686 });
5687 yield* Effect.sleep(CODEX_GOAL_CONTINUATION_GRACE).pipe(
5688 + Effect.andThen(pauseUncontinuedGoal(nativeThreadId, event)),
5689 Effect.andThen(
5690 turnTerminalizationPermit.withPermits(1)(releaseGoalHold(nativeThreadId, event)),
5691 ),
5701 - Effect.forkIn(scope),
5692 + // The grace window starts when the turn completes, not when the fiber is scheduled.
5693 + Effect.forkIn(scope, { startImmediately: true }),
5694 );
5695 return;
5696 }
@@ -5706,6 +5698,51 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
5698 },
5699 );
5700
5701 + // A goal must not read as active once its run ends. Claiming the hold first
5702 + // makes a turn Codex starts during the pause an orphan, which is stopped.
5703 + const pauseUncontinuedGoal = Effect.fnUntraced(function* (
5704 + nativeThreadId: string,
5705 + expected: CodexRootTerminalEvent,
5706 + ) {
5707 + const hold = goalHolds.get(nativeThreadId);
5708 + if (
5709 + hold?.event !== expected ||
5710 + goalStops.has(nativeThreadId) ||
5711 + goalsByNativeThread.get(nativeThreadId)?.status !== "active"
5712 + ) {
5713 + return;
5714 + }
5715 + goalHolds.delete(nativeThreadId);
5716 + // Keeps a turn Codex starts before settlement an orphan once the goal reads paused.
5717 + goalStops.set(nativeThreadId, (goalStops.get(nativeThreadId) ?? 0) + 1);
5718 + yield* Effect.logWarning("orchestration-v2.codex-goal-continuation-expired", {
5719 + nativeThreadId,
5720 + });
5721 + yield* client
5722 + .request("thread/goal/set", { threadId: nativeThreadId, status: "paused" })
5723 + .pipe(
5724 + // The hold is already claimed, so an unanswered pause must not keep the run open.
5725 + Effect.timeout("10 seconds"),
5726 + Effect.flatMap(({ goal }) => {
5727 + goalsByNativeThread.set(nativeThreadId, providerGoalFromCodex(goal));
5728 + return emitGoalUpdate(nativeThreadId);
5729 + }),
5730 + Effect.catch((cause) =>
5731 + Effect.logWarning("orchestration-v2.codex-goal-pause-failed", { cause }),
5732 + ),
5733 + Effect.ensuring(
5734 + turnTerminalizationPermit.withPermits(1)(settleGoalHold(hold, "completed")),
5735 + ),
5736 + Effect.ensuring(
5737 + Effect.sync(() => {
5738 + const stops = (goalStops.get(nativeThreadId) ?? 1) - 1;
5739 + if (stops > 0) goalStops.set(nativeThreadId, stops);
5740 + else goalStops.delete(nativeThreadId);
5741 + }),
5742 + ),
5743 + );
5744 + });
5745 +
5746 /** Hold the terminalization permit and remove the goalHolds entry before calling. */
5747 const settleGoalHold = Effect.fnUntraced(function* (
5748 hold: CodexGoalHold,
@@ -6084,9 +6121,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6121 }),
6122 );
6123
6124 + /** Settles a /goal turn that never reaches Codex. State changes reply through the goal row. */
6125 const completeGoalCommandTurn = Effect.fnUntraced(function* (
6126 turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
6089 - reply: string,
6127 + reply: string | null,
6128 ) {
6129 const now = yield* DateTime.now;
6130 const nativeId = `goal-command:${turnInput.attemptId}`;
@@ -6131,26 +6169,28 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6169 providerTurn,
6170 });
6171 yield* rememberRootProviderThread(turnInput.providerThread);
6134 - const artifacts = yield* buildAgentMessageArtifacts(
6135 - context,
6136 - { id: nativeId, text: reply },
6137 - true,
6138 - );
6139 - yield* emitProviderEvent({
6140 - type: "node.updated",
6141 - driver: CODEX_PROVIDER,
6142 - node: artifacts.node,
6143 - });
6144 - yield* emitProviderEvent({
6145 - type: "message.updated",
6146 - driver: CODEX_PROVIDER,
6147 - message: artifacts.message,
6148 - });
6149 - yield* emitProviderEvent({
6150 - type: "turn_item.updated",
6151 - driver: CODEX_PROVIDER,
6152 - turnItem: artifacts.turnItem,
6153 - });
6172 + if (reply !== null) {
6173 + const artifacts = yield* buildAgentMessageArtifacts(
6174 + context,
6175 + { id: nativeId, text: reply },
6176 + true,
6177 + );
6178 + yield* emitProviderEvent({
6179 + type: "node.updated",
6180 + driver: CODEX_PROVIDER,
6181 + node: artifacts.node,
6182 + });
6183 + yield* emitProviderEvent({
6184 + type: "message.updated",
6185 + driver: CODEX_PROVIDER,
6186 + message: artifacts.message,
6187 + });
6188 + yield* emitProviderEvent({
6189 + type: "turn_item.updated",
6190 + driver: CODEX_PROVIDER,
6191 + turnItem: artifacts.turnItem,
6192 + });
6193 + }
6194 yield* emitProviderEvent({
6195 type: "provider_turn.updated",
6196 driver: CODEX_PROVIDER,
@@ -6308,7 +6348,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6348 const runGoalCommand = Effect.fn("CodexAdapterV2.runGoalCommand")(
6349 function* (
6350 turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
6311 - command: CodexGoalCommand,
6351 + command: OrchestrationV2GoalCommand,
6352 ) {
6353 const threadId = yield* getNativeThreadId(turnInput.providerThread);
6354 rootProviderThreads.set(threadId, turnInput.providerThread);
@@ -6330,10 +6370,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6370 if (command.type === "clear") {
6371 const { cleared } = yield* client.request("thread/goal/clear", { threadId });
6372 goalsByNativeThread.set(threadId, null);
6333 - return yield* completeGoalCommandTurn(
6334 - turnInput,
6335 - cleared ? "Goal cleared." : "No goal to clear.",
6336 - );
6373 + return yield* completeGoalCommandTurn(turnInput, cleared ? null : "No goal is set.");
6374 }
6375 if (current === null && command.type !== "set") {
6376 return yield* completeGoalCommandTurn(turnInput, "No goal is set.");
@@ -6344,12 +6381,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6381 status: "paused",
6382 });
6383 goalsByNativeThread.set(threadId, providerGoalFromCodex(goal));
6347 - return yield* completeGoalCommandTurn(
6348 - turnInput,
6349 - "Goal paused. Send /goal resume to continue.",
6350 - );
6384 + return yield* completeGoalCommandTurn(turnInput, null);
6385 }
6386 if (command.type === "set") {
6387 + goalUpdatesHeld.add(threadId);
6388 if (current !== null) yield* client.request("thread/goal/clear", { threadId });
6389 // Keep paused until our turn starts so Codex cannot start one first.
6390 const { goal } = yield* client.request("thread/goal/set", {
@@ -6363,12 +6398,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6398 const activation = { stopped: false };
6399 goalActivations.set(threadId, activation);
6400 yield* Effect.gen(function* () {
6401 + // A bare objective reads like a statement, so the model echoes it back.
6402 yield* startNativeTurn(
6403 turnInput,
6404 command.type === "set"
6405 ? yield* toCodexInput({
6406 ...turnInput,
6371 - message: { ...turnInput.message, text: command.objective },
6407 + message: {
6408 + ...turnInput.message,
6409 + text: `Start working toward this goal: ${command.objective}`,
6410 + },
6411 })
6412 : [],
6413 );
@@ -6402,6 +6441,14 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6441 },
6442 (effect, turnInput) =>
6443 effect.pipe(
6444 + Effect.ensuring(
6445 + Effect.suspend(() => {
6446 + const threadId = turnInput.providerThread.nativeThreadRef?.nativeId;
6447 + return threadId == null || !goalUpdatesHeld.has(threadId)
6448 + ? Effect.void
6449 + : releaseGoalUpdates(threadId);
6450 + }),
6451 + ),
6452 Effect.mapError(
6453 (cause) =>
6454 new ProviderAdapter.ProviderAdapterTurnStartError({
@@ -6690,9 +6737,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6737 ),
6738 startTurn: (turnInput) => {
6739 const goalCommand =
6693 - turnInput.message.attachments.length === 0 &&
6740 turnInput.restartContinuationOfRunId === undefined
6695 - ? parseCodexGoalCommand(turnInput.message.text)
6741 + ? parseGoalCommand(turnInput.message)
6742 : null;
6743 if (goalCommand !== null) return runGoalCommand(turnInput, goalCommand);
6744 return Effect.gen(function* () {
apps/server/src/orchestration-v2/CommandPolicy.ts
+22
@@ -4,6 +4,8 @@ import {
4 ModelSelection,
5 type OrchestrationV2Command,
6 OrchestrationV2ProviderCapabilities,
7 + type OrchestrationV2GoalCommand,
8 + type OrchestrationV2ProviderGoalStatus,
9 type OrchestrationV2Run,
10 OrchestrationV2ThreadProjection,
11 ProviderInstanceId,
@@ -128,6 +130,26 @@ export function isNativeMaintenanceCommand(message: {
130 );
131 }
132
133 +/**
134 + * A goal command sent into active work stops that work when it starts or
135 + * replaces goal work, or ends a goal that is driving the run.
136 + */
137 +export function goalCommandStopsActiveRun(
138 + command: OrchestrationV2GoalCommand,
139 + goalStatus: OrchestrationV2ProviderGoalStatus | null,
140 +): boolean {
141 + switch (command.type) {
142 + case "set":
143 + case "resume":
144 + return true;
145 + case "clear":
146 + case "pause":
147 + return goalStatus === "active";
148 + case "show":
149 + return false;
150 + }
151 +}
152 +
153 export function resolveMessageDispatchIntent(
154 projection: OrchestrationV2ThreadProjection,
155 requestedMode: MessageDispatchMode,
apps/server/src/orchestration-v2/Orchestrator.ts
+213 -19
@@ -55,6 +55,7 @@ import {
55 type OrchestrationV2ThreadProjection,
56 type OrchestrationV2TurnItem,
57 latestProviderTurnForAttempt,
58 + parseGoalCommand,
59 orchestrationV2RunWorkStartedAt,
60 ProviderInstanceId,
61 ProviderInteractionMode,
@@ -93,6 +94,7 @@ import {
94 import { CheckpointServiceV2 } from "./CheckpointService.ts";
95 import {
96 CommandPolicyV2,
97 + goalCommandStopsActiveRun,
98 isNativeMaintenanceCommand,
99 resolveMessageDispatchIntent,
100 } from "./CommandPolicy.ts";
@@ -452,13 +454,6 @@ function wakeWorkStartedAt(
454 return previous === undefined ? {} : { workStartedAt: orchestrationV2RunWorkStartedAt(previous) };
455 }
456
455 -function isGoalCommand(message: {
456 - readonly text: string;
457 - readonly attachments: ReadonlyArray<ChatAttachment>;
458 -}): boolean {
459 - return message.attachments.length === 0 && /^\/goal(?:\s|$)/u.test(message.text.trim());
460 -}
461 -
457 const threadPullRequestLinksEqual = Schema.toEquivalence(Schema.NullOr(ThreadLinkedPullRequest));
458
459 function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
@@ -622,10 +617,12 @@ function isBlockingRun(run: OrchestrationV2Run): boolean {
617 }
618
619 /** Waiting runs only drain post-terminal output; their agent turn is over and still needs a wake. */
620 +function isLiveRun(run: OrchestrationV2Run): boolean {
621 + return run.status === "preparing" || run.status === "starting" || run.status === "running";
622 +}
623 +
624 function hasLiveRun(projection: Pick<OrchestrationV2ThreadProjection, "runs">): boolean {
626 - return projection.runs.some(
627 - (run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
628 - );
625 + return projection.runs.some(isLiveRun);
626 }
627
628 function withPullRequestWatch(
@@ -987,6 +984,35 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
984 const threadForkService = yield* ThreadForkServiceV2;
985 const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor;
986
987 + /** The driver when this provider runs `/goal` natively, else undefined. */
988 + const goalDriverFor = Effect.fn("Orchestrator.goalDriverFor")(function* (
989 + command: OrchestrationV2ServerCommand,
990 + providerInstanceId: ProviderInstanceId,
991 + ) {
992 + const { driver } = yield* providerAdapters
993 + .get(providerInstanceId)
994 + .pipe(mapDispatchError(command));
995 + return driver === "codex" || driver === "claudeAgent" ? driver : undefined;
996 + });
997 +
998 + /** Claude Code reads `/goal pause` and `/goal resume` as new goals named "pause" and "resume". */
999 + const ensureGoalCommandSupported = Effect.fn("Orchestrator.ensureGoalCommandSupported")(
1000 + function* (
1001 + command: OrchestrationV2ServerCommand,
1002 + message: { readonly text: string; readonly attachments: ReadonlyArray<ChatAttachment> },
1003 + providerInstanceId: ProviderInstanceId,
1004 + ) {
1005 + const goalCommand = parseGoalCommand(message);
1006 + if (goalCommand?.type !== "pause" && goalCommand?.type !== "resume") return;
1007 + if ((yield* goalDriverFor(command, providerInstanceId)) !== "claudeAgent") return;
1008 + return yield* new OrchestratorDispatchError({
1009 + commandId: command.commandId,
1010 + commandType: command.type,
1011 + cause: "Claude goals cannot be paused or resumed. Send /goal clear to remove the goal.",
1012 + });
1013 + },
1014 + );
1015 +
1016 const mapDispatchError =
1017 (command: OrchestrationV2ServerCommand) =>
1018 <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, OrchestratorDispatchError, R> =>
@@ -4278,7 +4304,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4304 : "Signing out must run as a separate turn. Queue it or wait for the active turn to finish.",
4305 });
4306 }
4281 - if (isGoalCommand(input)) {
4307 + if (parseGoalCommand(input) !== null) {
4308 return yield* new OrchestratorDispatchError({
4309 commandId: input.command.commandId,
4310 commandType: input.command.type,
@@ -5202,6 +5228,45 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5228 ) {
5229 dispatchMode = { type: "queue_after_active" };
5230 }
5231 + // Codex and Claude own /goal; elsewhere it is ordinary text that cannot steer.
5232 + const parsedGoalCommand = parseGoalCommand(command);
5233 + const goalCommand =
5234 + parsedGoalCommand === null ||
5235 + (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined
5236 + ? null
5237 + : parsedGoalCommand;
5238 + let goalStopRunId: RunId | undefined;
5239 + if (goalCommand !== null) {
5240 + yield* ensureGoalCommandSupported(command, command, modelSelection.instanceId);
5241 + // A goal command never joins a running turn. One that starts or ends goal
5242 + // work stops the run and goes first in the queue; the rest wait. A send
5243 + // that asked to be queued (no delivery intent) only queues, and a run
5244 + // that is only finishing or running background work is never stopped.
5245 + const resolvedMode = dispatchMode;
5246 + const target =
5247 + resolvedMode.type === "steer_active" || resolvedMode.type === "restart_active"
5248 + ? projection.runs.find((run) => run.id === resolvedMode.targetRunId)
5249 + : resolvedMode.type === "queue_after_active" && command.deliveryIntent !== undefined
5250 + ? projection.runs.findLast(isLiveRun)
5251 + : undefined;
5252 + if (target !== undefined) {
5253 + const goal = projection.providerThreads.find(
5254 + (candidate) => candidate.id === target.providerThreadId,
5255 + )?.goal;
5256 + const targetMessage = projection.messages.find(
5257 + (message) => message.id === target.userMessageId,
5258 + );
5259 + if (
5260 + isLiveRun(target) &&
5261 + goalCommandStopsActiveRun(goalCommand, goal?.status ?? null) &&
5262 + (targetMessage === undefined || !isNativeMaintenanceCommand(targetMessage)) &&
5263 + !(yield* stopReachedRun(command, command.threadId, target.id))
5264 + ) {
5265 + goalStopRunId = target.id;
5266 + }
5267 + dispatchMode = { type: "queue_after_active" };
5268 + }
5269 + }
5270 if (
5271 command.notification !== undefined &&
5272 (command.createdBy !== "agent" ||
@@ -5547,12 +5612,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5612 ? { queueHeld: true }
5613 : {}),
5614 queuePosition:
5550 - Math.max(
5551 - 0,
5552 - ...projection.runs
5553 - .filter((candidate) => candidate.status === "queued")
5554 - .map((candidate) => candidate.queuePosition ?? candidate.ordinal),
5555 - ) + 1,
5615 + goalStopRunId !== undefined
5616 + ? 1
5617 + : Math.max(
5618 + 0,
5619 + ...projection.runs
5620 + .filter((candidate) => candidate.status === "queued")
5621 + .map((candidate) => candidate.queuePosition ?? candidate.ordinal),
5622 + ) + 1,
5623 requestedAt: now,
5624 startedAt: null,
5625 completedAt: null,
@@ -5705,6 +5772,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5772 },
5773 });
5774 }
5775 + if (goalStopRunId !== undefined) {
5776 + return yield* stopRunForGoalCommand({
5777 + command,
5778 + events,
5779 + effects,
5780 + projection: yield* getProjectionWithPendingEvents(command.threadId, events),
5781 + queuedRunId: runId,
5782 + targetRunId: goalStopRunId,
5783 + now,
5784 + });
5785 + }
5786 return;
5787 }
5788 const pendingForkTransfer = pendingForkTransferForThread(projection);
@@ -8270,6 +8348,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8348
8349 const now = yield* DateTime.now;
8350 const emitEvent = emit(events, command);
8351 + const parsedGoalCommand = parseGoalCommand(queuedMessage);
8352 + const goalCommand =
8353 + parsedGoalCommand === null ||
8354 + (yield* goalDriverFor(command, queuedRun.providerInstanceId)) === undefined
8355 + ? null
8356 + : parsedGoalCommand;
8357 + if (goalCommand !== null) {
8358 + yield* ensureGoalCommandSupported(command, queuedMessage, queuedRun.providerInstanceId);
8359 + const target = projection.runs.find((run) => run.id === command.targetRunId);
8360 + const goal = projection.providerThreads.find(
8361 + (candidate) => candidate.id === target?.providerThreadId,
8362 + )?.goal;
8363 + const targetMessage = projection.messages.find(
8364 + (message) => message.id === target?.userMessageId,
8365 + );
8366 + yield* emitEvent({
8367 + type: "run.updated",
8368 + threadId: command.threadId,
8369 + runId: queuedRun.id,
8370 + nodeId: queuedRootNode.id,
8371 + providerInstanceId: queuedRun.providerInstanceId,
8372 + occurredAt: now,
8373 + payload: { ...queuedRun, queuePosition: 1 },
8374 + });
8375 + const stops =
8376 + target !== undefined &&
8377 + isLiveRun(target) &&
8378 + goalCommandStopsActiveRun(goalCommand, goal?.status ?? null) &&
8379 + (targetMessage === undefined || !isNativeMaintenanceCommand(targetMessage)) &&
8380 + !(yield* stopReachedRun(command, command.threadId, target.id));
8381 + return yield* stopRunForGoalCommand({
8382 + command,
8383 + events,
8384 + effects,
8385 + projection,
8386 + queuedRunId: queuedRun.id,
8387 + targetRunId: stops ? target.id : undefined,
8388 + now,
8389 + });
8390 + }
8391 yield* emitEvent({
8392 type: "run.updated",
8393 threadId: command.threadId,
@@ -8580,6 +8698,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8698 cause: "A guest's message cannot be edited. Cancel it instead.",
8699 });
8700 }
8701 + yield* ensureGoalCommandSupported(
8702 + command,
8703 + { text: command.text, attachments: command.attachments ?? queuedMessage.attachments },
8704 + queuedRun.providerInstanceId,
8705 + );
8706 const queuedTurnItem = projection.turnItems.find(
8707 (candidate) => candidate.type === "user_message" && candidate.messageId === queuedMessage.id,
8708 );
@@ -10371,6 +10494,73 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10494 ),
10495 );
10496
10497 + /** Puts a queued goal command first and, given a target, stops the run in its way. */
10498 + const stopRunForGoalCommand = Effect.fn("Orchestrator.stopRunForGoalCommand")(function* (input: {
10499 + readonly command: Extract<
10500 + OrchestrationV2Command,
10501 + { readonly type: "message.dispatch" | "queued-message.promote-to-steer" }
10502 + >;
10503 + readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
10504 + readonly effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>;
10505 + readonly projection: Pick<OrchestrationV2ThreadProjection, "runs" | "messages">;
10506 + readonly queuedRunId: RunId;
10507 + readonly targetRunId: RunId | undefined;
10508 + readonly now: DateTime.Utc;
10509 + }) {
10510 + const { command, events, effects, projection, now, targetRunId } = input;
10511 + const others = queuedRunsInDeliveryOrder(projection).filter(
10512 + (run) => run.id !== input.queuedRunId && !isAutomaticCompletionRun(projection, run),
10513 + );
10514 + for (const [index, run] of others.entries()) {
10515 + const queuePosition = index + 2;
10516 + if (run.queuePosition === queuePosition) continue;
10517 + yield* emit(
10518 + events,
10519 + command,
10520 + )({
10521 + type: "run.updated",
10522 + threadId: command.threadId,
10523 + runId: run.id,
10524 + ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }),
10525 + providerInstanceId: run.providerInstanceId,
10526 + occurredAt: now,
10527 + payload: { ...run, queuePosition },
10528 + });
10529 + }
10530 + if (targetRunId === undefined) return undefined;
10531 + const interruptEvents = yield* Ref.make<Array<OrchestrationV2DomainEvent>>([]);
10532 + const interruptEffects = yield* Ref.make<Array<PendingOrchestrationEffectV2>>([]);
10533 + const interrupted = yield* Effect.exit(
10534 + dispatchRunInterrupt(
10535 + {
10536 + type: "run.interrupt",
10537 + commandId: command.commandId,
10538 + threadId: command.threadId,
10539 + runId: targetRunId,
10540 + reason: "Stopped to apply /goal",
10541 + },
10542 + interruptEvents,
10543 + interruptEffects,
10544 + ),
10545 + );
10546 + // A failed interrupt may have written part of its events, so they are kept apart.
10547 + // The goal command then waits for the turn to end.
10548 + if (Exit.isFailure(interrupted)) {
10549 + yield* Effect.logWarning("goal command could not stop the running turn", {
10550 + threadId: command.threadId,
10551 + runId: targetRunId,
10552 + cause: interrupted.cause,
10553 + });
10554 + return undefined;
10555 + }
10556 + const written = yield* Ref.get(interruptEvents);
10557 + const enqueued = yield* Ref.get(interruptEffects);
10558 + yield* Ref.update(events, (existing) => [...existing, ...written]);
10559 + yield* Ref.update(effects, (existing) => [...existing, ...enqueued]);
10560 + // Like Stop: a run stopped before its provider started also abandons that start.
10561 + return interrupted.value;
10562 + });
10563 +
10564 const dispatchThreadStop = Effect.fn("Orchestrator.dispatchThreadStop")(function* (
10565 command: Extract<OrchestrationV2ServerCommand, { readonly type: "thread.stop" }>,
10566 events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
@@ -11709,7 +11899,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11899 text: guestSend.text,
11900 context: { version: 1 as const, records: [], guest: guestSend.guest },
11901 };
11712 - yield* dispatchMessage(dispatched, events, effects);
11902 + cancelUnsettledEffects = yield* dispatchMessage(dispatched, events, effects);
11903 yield* recordSubagentFollowup(dispatched, events).pipe(mapDispatchError(command));
11904 break;
11905 }
@@ -11769,7 +11959,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11959 cancelUnsettledEffects = yield* dispatchThreadStop(command, events, effects);
11960 break;
11961 case "queued-message.promote-to-steer":
11772 - yield* dispatchQueuedMessagePromoteToSteer(command, events, effects);
11962 + cancelUnsettledEffects = yield* dispatchQueuedMessagePromoteToSteer(
11963 + command,
11964 + events,
11965 + effects,
11966 + );
11967 break;
11968 case "queued-run.start":
11969 case "queue.resume": {
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+15 -6
@@ -9,6 +9,8 @@ import {
9 type OrchestrationV2Run,
10 type OrchestrationV2RunAttempt,
11 type OrchestrationV2TurnItem,
12 + isCompactionCommandMessage,
13 + parseGoalCommand,
14 RunId,
15 ThreadId,
16 } from "@t3tools/contracts";
@@ -282,11 +284,12 @@ export const layer: Layer.Layer<
284 source.status === "interrupted" ||
285 (source.status === "completed" &&
286 handoff.delivery === undefined &&
287 + // Compaction and /goal turns defer history to the next turn.
288 projection.messages.some(
289 (message) =>
290 message.id === source.userMessageId &&
288 - message.attachments.length === 0 &&
289 - message.text.trim().toLowerCase() === "/compact",
291 + (isCompactionCommandMessage(message) ||
292 + parseGoalCommand(message) !== null),
293 ))),
294 ))),
295 );
@@ -1036,6 +1039,9 @@ export const layer: Layer.Layer<
1039 text: message.text,
1040 records: message.context?.records ?? [],
1041 });
1042 + // Codex and Claude parse /goal from the prompt, so it goes verbatim and history waits a turn.
1043 + const goalDriver = session.driver === "codex" || session.driver === "claudeAgent";
1044 + const goalCommand = goalDriver && parseGoalCommand(message) !== null;
1045 // The provider turn marks cancellation work delivered; restart continuations use their own text or resume natively.
1046 const noteContinuation = isRestartNoteContinuation(
1047 run,
@@ -1050,8 +1056,8 @@ export const layer: Layer.Layer<
1056 projection.messages
1057 .filter(
1058 (candidate) =>
1053 - candidate.attachments.length === 0 &&
1054 - candidate.text.trim().toLowerCase() === "/compact",
1059 + isCompactionCommandMessage(candidate) ||
1060 + (goalDriver && parseGoalCommand(candidate) !== null),
1061 )
1062 .map((candidate) => candidate.id),
1063 ),
@@ -1199,7 +1205,7 @@ export const layer: Layer.Layer<
1205 ];
1206 const delivery = yield* deliverContextHandoffs({
1207 handoffs: [...effectiveHandoffs, ...retryHandoff],
1202 - deferInline: compact,
1208 + deferInline: compact || goalCommand,
1209 providerThread: runningProviderThread,
1210 budget: Effect.gen(function* () {
1211 return handoffBudget({
@@ -1253,7 +1259,10 @@ export const layer: Layer.Layer<
1259 ...(noteContinuation ? promptedInput : turnInput),
1260 message: {
1261 ...turnInput.message,
1256 - text: context === "" ? userText : `${context}\n\nUser message:\n${userText}`,
1262 + text:
1263 + context === "" || goalCommand
1264 + ? userText
1265 + : `${context}\n\nUser message:\n${userText}`,
1266 },
1267 }).pipe(
1268 // Clear pending handoff markers for refused prompts so the next turn retains the native session.
apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+216 -1
@@ -547,7 +547,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
547 yield* Fiber.join(running);
548 return threadId;
549 });
550 - return { events, started, steered, layer, startFirstTurn };
550 + return { cwd, events, started, steered, layer, startFirstTurn };
551 });
552
553 it.effect("sends a selected held message once and preserves the remaining queue order", () =>
@@ -1048,3 +1048,218 @@ it.effect("queues a plain send behind the stopped queue and releases its hold",
1048 }),
1049 ),
1050 );
1051 +
1052 +const goalHarness = Effect.fn("goalHarness")(function* (name: string) {
1053 + const harness = yield* nextTurnSelectionHarness(name);
1054 + const send = (id: string, text: string, delivery: "queue" | "auto") =>
1055 + Effect.gen(function* () {
1056 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1057 + yield* orchestrator.dispatch({
1058 + type: "message.dispatch",
1059 + commandId: CommandId.make(id),
1060 + threadId: ThreadId.make(`thread:${name}`),
1061 + messageId: MessageId.make(`message:${id}`),
1062 + text,
1063 + attachments: [],
1064 + modelSelection: runSelection,
1065 + ...(delivery === "queue"
1066 + ? { dispatchMode: { type: "queue_after_active" } }
1067 + : { dispatchMode: { type: "start_immediately" }, deliveryIntent: "auto" }),
1068 + createdBy: "user",
1069 + creationSource: "web",
1070 + });
1071 + });
1072 + const read = (threadId: ThreadId) =>
1073 + Effect.gen(function* () {
1074 + const projection = yield* (yield* Orchestrator.OrchestratorV2).getThreadProjection(threadId);
1075 + const textOf = (run: (typeof projection.runs)[number]) =>
1076 + projection.messages.find((message) => message.id === run.userMessageId)?.text;
1077 + return {
1078 + queue: projection.runs
1079 + .filter((run) => run.status === "queued")
1080 + .toSorted((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0))
1081 + .map(textOf),
1082 + started: harness.started.map((turn) => turn.message.text),
1083 + stopRequested: projection.turnItems.some(
1084 + (item) =>
1085 + item.type === "run_interrupt_request" && item.runId === harness.started[0]?.runId,
1086 + ),
1087 + };
1088 + });
1089 + return { ...harness, send, read };
1090 +});
1091 +
1092 +it.effect("stops the running turn and starts a goal sent into it next", () =>
1093 + Effect.scoped(
1094 + Effect.gen(function* () {
1095 + const { steered, layer, startFirstTurn, send, read } = yield* goalHarness("goal-steer");
1096 + yield* Effect.gen(function* () {
1097 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1098 + const threadId = yield* startFirstTurn;
1099 + yield* send("queued", "queued", "queue");
1100 + yield* send("goal", "/goal all tests pass", "auto");
1101 + yield* worker.drain();
1102 +
1103 + assert.deepEqual(steered, []);
1104 + assert.deepEqual(yield* read(threadId), {
1105 + queue: ["queued"],
1106 + started: ["first", "/goal all tests pass"],
1107 + stopRequested: true,
1108 + });
1109 + }).pipe(Effect.provide(layer));
1110 + }),
1111 + ),
1112 +);
1113 +
1114 +it.effect("queues a goal clear without stopping work when no goal drives it", () =>
1115 + Effect.scoped(
1116 + Effect.gen(function* () {
1117 + const { steered, layer, startFirstTurn, send, read } = yield* goalHarness("goal-clear");
1118 + yield* Effect.gen(function* () {
1119 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1120 + const threadId = yield* startFirstTurn;
1121 + yield* send("queued", "queued", "queue");
1122 + yield* send("clear", "/goal clear", "auto");
1123 + yield* worker.drain();
1124 +
1125 + assert.deepEqual(steered, []);
1126 + assert.deepEqual(yield* read(threadId), {
1127 + queue: ["queued", "/goal clear"],
1128 + started: ["first"],
1129 + stopRequested: false,
1130 + });
1131 + }).pipe(Effect.provide(layer));
1132 + }),
1133 + ),
1134 +);
1135 +
1136 +it.effect("promotes a queued goal by stopping the running turn", () =>
1137 + Effect.scoped(
1138 + Effect.gen(function* () {
1139 + const { started, steered, layer, startFirstTurn, send, read } =
1140 + yield* goalHarness("goal-promote");
1141 + yield* Effect.gen(function* () {
1142 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1143 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1144 + const threadId = yield* startFirstTurn;
1145 + yield* send("queued", "queued", "queue");
1146 + yield* send("goal", "/goal ship it", "queue");
1147 + const goalRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1148 + (run) => run.userMessageId === MessageId.make("message:goal"),
1149 + )!;
1150 + yield* orchestrator.dispatch({
1151 + type: "queued-message.promote-to-steer",
1152 + commandId: CommandId.make("promote"),
1153 + threadId,
1154 + queuedRunId: goalRun.id,
1155 + targetRunId: started[0]!.runId,
1156 + });
1157 + yield* worker.drain();
1158 +
1159 + assert.deepEqual(steered, []);
1160 + assert.deepEqual(yield* read(threadId), {
1161 + queue: ["queued"],
1162 + started: ["first", "/goal ship it"],
1163 + stopRequested: true,
1164 + });
1165 + }).pipe(Effect.provide(layer));
1166 + }),
1167 + ),
1168 +);
1169 +
1170 +it.effect("stops a turn that is still starting when a goal is sent into it", () =>
1171 + Effect.scoped(
1172 + Effect.gen(function* () {
1173 + const { cwd, layer, send, started } = yield* goalHarness("goal-during-start");
1174 + yield* Effect.gen(function* () {
1175 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1176 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1177 + const threadId = ThreadId.make("thread:goal-during-start");
1178 + yield* orchestrator.dispatch({
1179 + type: "thread.create",
1180 + commandId: CommandId.make("create"),
1181 + threadId,
1182 + projectId: ProjectId.make("project:goal-during-start"),
1183 + title: "Goal during start",
1184 + modelSelection: runSelection,
1185 + runtimeMode: "full-access",
1186 + interactionMode: "default",
1187 + branch: null,
1188 + worktreePath: cwd,
1189 + createdBy: "user",
1190 + creationSource: "web",
1191 + });
1192 + // The stopped run's end starts the queue, which then needs one more drain.
1193 + const goalStarting = yield* orchestrator.streamDomainEvents.pipe(
1194 + Stream.filter(
1195 + (event) => event.type === "run.updated" && event.payload.status === "starting",
1196 + ),
1197 + Stream.take(1),
1198 + Stream.runDrain,
1199 + Effect.forkScoped({ startImmediately: true }),
1200 + );
1201 + yield* send("first", "first", "auto");
1202 + yield* send("goal", "/goal all tests pass", "auto");
1203 + yield* worker.drain();
1204 + yield* Fiber.join(goalStarting);
1205 + yield* worker.drain();
1206 +
1207 + const projection = yield* orchestrator.getThreadProjection(threadId);
1208 + const statusOf = (text: string) =>
1209 + projection.runs.find(
1210 + (run) =>
1211 + projection.messages.find((message) => message.id === run.userMessageId)?.text ===
1212 + text,
1213 + )?.status;
1214 + assert.equal(statusOf("first"), "interrupted");
1215 + assert.deepEqual(
1216 + started.map((turn) => turn.message.text),
1217 + ["/goal all tests pass"],
1218 + );
1219 + }).pipe(Effect.provide(layer));
1220 + }),
1221 + ),
1222 +);
1223 +
1224 +it.effect("stops the running turn when a goal clear ends the goal driving it", () =>
1225 + Effect.scoped(
1226 + Effect.gen(function* () {
1227 + const { events, layer, startFirstTurn, send, read, steered } =
1228 + yield* goalHarness("goal-clear-active");
1229 + yield* Effect.gen(function* () {
1230 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1231 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1232 + const threadId = yield* startFirstTurn;
1233 + const providerThread = (yield* orchestrator.getThreadProjection(threadId))
1234 + .providerThreads[0]!;
1235 + const goalSeen = yield* orchestrator.streamDomainEvents.pipe(
1236 + Stream.filter(
1237 + (event) =>
1238 + event.type === "provider-thread.updated" && event.payload.goal?.status === "active",
1239 + ),
1240 + Stream.take(1),
1241 + Stream.runDrain,
1242 + Effect.forkScoped({ startImmediately: true }),
1243 + );
1244 + yield* Queue.offer(events, {
1245 + type: "provider_thread.updated",
1246 + driver,
1247 + providerThread: {
1248 + ...providerThread,
1249 + goal: { objective: "all tests pass", status: "active" },
1250 + },
1251 + });
1252 + yield* Fiber.join(goalSeen);
1253 + yield* send("clear", "/goal clear", "auto");
1254 + yield* worker.drain();
1255 +
1256 + assert.deepEqual(steered, []);
1257 + assert.deepEqual(yield* read(threadId), {
1258 + queue: [],
1259 + started: ["first", "/goal clear"],
1260 + stopRequested: true,
1261 + });
1262 + }).pipe(Effect.provide(layer));
1263 + }),
1264 + ),
1265 +);
apps/web/src/components/chat/ThreadActivityBanners.tsx
+3 -2
@@ -68,9 +68,10 @@ export function goalBannerItem(input: {
68 ? presentation.title
69 : `${presentation.title} · ${presentation.usage}`,
70 description: presentation.objective,
71 - actions: isWorking ? undefined : (
71 + // Clear stops goal work; Resume would stop unrelated work, so it waits.
72 + actions: (
73 <>
73 - {presentation.canResume ? (
74 + {presentation.canResume && !isWorking ? (
75 <Button
76 size="xs"
77 variant="ghost"
docs/user/composer.md
+5 -1
@@ -252,9 +252,13 @@ row above the composer shows the goal and its progress.
252
253 - `/goal` alone shows the current goal. `/goal clear` removes it.
254 - Codex also supports `/goal pause` and `/goal resume`. Stopping a Codex goal
255 - pauses it.
255 + pauses it, and so does Codex ending its work without meeting the goal.
256 - Stopping Claude ends the current turn, but the goal stays set. Claude checks it
257 again at the end of your next message.
258 +- Sending a new goal, or `/goal resume`, while the agent works stops the current
259 + turn and starts the goal, unless you queue it. `/goal clear` and `/goal pause`
260 + stop the turn only when it is working on the goal. Other goal commands wait for
261 + the turn to end.
262
263 ## Context in your message
264
packages/contracts/src/orchestrationV2.ts
+31
@@ -497,6 +497,37 @@ export function isCompactionCommandMessage(message: CompactionMessageFields): bo
497 );
498 }
499
500 +export type OrchestrationV2GoalCommand =
501 + | { readonly type: "show" }
502 + | { readonly type: "clear" }
503 + | { readonly type: "pause" }
504 + | { readonly type: "resume" }
505 + | { readonly type: "set"; readonly objective: string };
506 +
507 +/** Reads a `/goal` control message. Messages with attachments are ordinary prompts. */
508 +export function parseGoalCommand(message: {
509 + readonly text: string;
510 + readonly attachments?: ReadonlyArray<unknown> | undefined;
511 +}): OrchestrationV2GoalCommand | null {
512 + if ((message.attachments?.length ?? 0) > 0) return null;
513 + const match = /^\/goal(?:\s+([\s\S]*))?$/u.exec(message.text.trim());
514 + if (match === null) return null;
515 + const argument = (match[1] ?? "").trim();
516 + switch (argument.toLowerCase()) {
517 + case "":
518 + case "edit":
519 + return { type: "show" };
520 + case "clear":
521 + return { type: "clear" };
522 + case "pause":
523 + return { type: "pause" };
524 + case "resume":
525 + return { type: "resume" };
526 + default:
527 + return { type: "set", objective: argument };
528 + }
529 +}
530 +
531 /** Why T3 Code sent this `/compact` on its own, or undefined for one someone asked for. */
532 export function idleCompactionOf(
533 message: CompactionMessageFields,