Skip to content

Commit 3138f57

Browse files
Svykmaria-rcks
andauthored
fix(grok): emit task lifecycle for monitors and background shells (#9139)
Co-authored-by: maria-rcks <[email protected]>
1 parent 0c5771d commit 3138f57

5 files changed

Lines changed: 549 additions & 2 deletions

File tree

‎apps/server/scripts/acp-mock-agent.ts‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ const emitXAiAskUserQuestionThenHang =
3030
const emitContentThenHang = process.env.T3_ACP_EMIT_CONTENT_THEN_HANG === "1";
3131
const emitPlanThenHang = process.env.T3_ACP_EMIT_PLAN_THEN_HANG === "1";
3232
const emitActiveToolThenHang = process.env.T3_ACP_EMIT_ACTIVE_TOOL_THEN_HANG === "1";
33+
const emitGrokMonitorPostTurnPoll = process.env.T3_ACP_EMIT_GROK_MONITOR_POST_TURN_POLL === "1";
34+
const emitGrokBackgroundTaskStarted = process.env.T3_ACP_EMIT_GROK_BACKGROUND_TASK_STARTED === "1";
3335
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
3436
const waitForResumeRelease = process.env.T3_ACP_WAIT_FOR_RESUME_RELEASE === "1";
3537
const completeFirstPromptOnCancel = process.env.T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL === "1";
@@ -835,6 +837,108 @@ const program = Effect.gen(function* () {
835837
return yield* Effect.never;
836838
}
837839

840+
if (emitGrokMonitorPostTurnPoll) {
841+
const monitorCallId = "call-monitor-1";
842+
const pollCallId = "call-monitor-poll-1";
843+
const taskId = "01a05f41-5107-7550-821e-79e8d1cd7687";
844+
const description = "Watch count-sheet Typst unit until done";
845+
writeJsonRpcNotification("session/update", {
846+
sessionId: requestedSessionId,
847+
update: {
848+
sessionUpdate: "tool_call",
849+
toolCallId: monitorCallId,
850+
title: "monitor",
851+
kind: "other",
852+
status: "pending",
853+
rawInput: { description },
854+
_meta: {
855+
"x.ai/tool": { version: 1, name: "monitor", kind: "task", namespace: "grok_build" },
856+
},
857+
},
858+
});
859+
writeJsonRpcNotification("session/update", {
860+
sessionId: requestedSessionId,
861+
update: {
862+
sessionUpdate: "tool_call_update",
863+
toolCallId: monitorCallId,
864+
status: "completed",
865+
rawInput: { description },
866+
rawOutput: {
867+
type: "Monitor",
868+
taskId,
869+
timeoutMs: 36_000_000,
870+
},
871+
},
872+
});
873+
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
874+
sessionId: requestedSessionId,
875+
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
876+
stopReason: "end_turn",
877+
agentResult: null,
878+
});
879+
yield* Effect.sleep("120 millis");
880+
writeJsonRpcNotification("session/update", {
881+
sessionId: requestedSessionId,
882+
update: {
883+
sessionUpdate: "tool_call",
884+
toolCallId: pollCallId,
885+
title: "get_command_or_subagent_output",
886+
kind: "other",
887+
status: "completed",
888+
rawInput: { variant: "TaskOutput", task_ids: [taskId], timeout_ms: 0 },
889+
rawOutput: {
890+
type: "TaskOutput",
891+
Result: {
892+
task_id: taskId,
893+
command: `[monitor] ${description}`,
894+
status: "completed",
895+
exit_code: 0,
896+
output: "Monitor finished.",
897+
},
898+
},
899+
},
900+
});
901+
return yield* Effect.never;
902+
}
903+
904+
if (emitGrokBackgroundTaskStarted) {
905+
const toolCallId = "call-fb9d0000-0000-0000-0000-000000000026";
906+
const command = "sleep 40; echo done-a";
907+
writeJsonRpcNotification("session/update", {
908+
sessionId: requestedSessionId,
909+
update: {
910+
sessionUpdate: "tool_call",
911+
toolCallId,
912+
title: "run_terminal_command",
913+
kind: "execute",
914+
status: "in_progress",
915+
rawInput: { command },
916+
},
917+
});
918+
writeJsonRpcNotification("session/update", {
919+
sessionId: requestedSessionId,
920+
update: {
921+
sessionUpdate: "tool_call_update",
922+
toolCallId,
923+
status: "completed",
924+
rawOutput: {
925+
type: "BackgroundTaskStarted",
926+
task_id: toolCallId,
927+
task_type: "bash",
928+
status: "running",
929+
command,
930+
},
931+
},
932+
});
933+
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
934+
sessionId: requestedSessionId,
935+
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
936+
stopReason: "end_turn",
937+
agentResult: null,
938+
});
939+
return yield* Effect.never;
940+
}
941+
838942
if (emitInterleavedAssistantToolCalls) {
839943
const toolCallId = "tool-call-1";
840944

‎apps/server/src/provider/Layers/GrokAdapter.test.ts‎

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,18 @@ import {
2424
TurnId,
2525
type ProviderRuntimeEvent,
2626
} from "@t3tools/contracts";
27+
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
2728

2829
import { ServerConfig } from "../../config.ts";
30+
import { execScriptSource, writeFakeCli } from "../../testUtils/fakeCli.ts";
2931
import {
3032
grokPromptSettlementBelongsToContext,
3133
isGrokEnterPlanModeToolCall,
3234
makeGrokAdapter,
3335
nextGrokPlanModeActive,
3436
selectGrokPermissionOptionId,
3537
} from "./GrokAdapter.ts";
36-
import { execScriptSource, writeFakeCli } from "../../testUtils/fakeCli.ts";
37-
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
38+
3839
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
3940

4041
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
@@ -232,6 +233,65 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
232233
}),
233234
);
234235

236+
for (const taskType of ["monitor", "shell"] as const) {
237+
it.effect(`emits the ${taskType} background lifecycle`, () =>
238+
Effect.gen(function* () {
239+
const threadId = ThreadId.make(`grok-background-${taskType}`);
240+
const wrapperPath = yield* Effect.promise(() =>
241+
makeMockGrokWrapper({
242+
[taskType === "monitor"
243+
? "T3_ACP_EMIT_GROK_MONITOR_POST_TURN_POLL"
244+
: "T3_ACP_EMIT_GROK_BACKGROUND_TASK_STARTED"]: "1",
245+
}),
246+
);
247+
const adapter = yield* makeTestAdapter(wrapperPath);
248+
const events: ProviderRuntimeEvent[] = [];
249+
const finished = yield* Deferred.make<void>();
250+
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
251+
Effect.gen(function* () {
252+
events.push(event);
253+
if (event.type === (taskType === "monitor" ? "task.completed" : "turn.completed")) {
254+
yield* Deferred.succeed(finished, undefined);
255+
}
256+
}),
257+
).pipe(Effect.forkChild);
258+
yield* adapter.startSession({ threadId, cwd: process.cwd(), runtimeMode: "full-access" });
259+
yield* adapter.sendTurn({ threadId, input: "watch the unit" });
260+
yield* Deferred.await(finished).pipe(Effect.timeout("3 seconds"));
261+
262+
const started = events.find((event) => event.type === "task.started");
263+
const taskId =
264+
taskType === "monitor"
265+
? "01a05f41-5107-7550-821e-79e8d1cd7687"
266+
: "call-fb9d0000-0000-0000-0000-000000000026";
267+
assert.equal(started?.payload.taskType, taskType);
268+
assert.equal(started?.payload.taskId, taskId);
269+
if (taskType === "monitor") {
270+
const completed = events.find((event) => event.type === "task.completed");
271+
const turnEnd = events.findIndex((event) => event.type === "turn.completed");
272+
assert.equal(completed?.payload.status, "completed");
273+
assert.equal(completed?.payload.taskId, taskId);
274+
assert.equal(completed?.turnId, undefined);
275+
assert.isAtLeast(turnEnd, 0);
276+
assert.isAbove(
277+
events.findIndex((event) => event.type === "task.completed"),
278+
turnEnd,
279+
);
280+
assert.deepEqual(
281+
events
282+
.slice(turnEnd + 1)
283+
.filter((event) => event.type === "item.updated" || event.type === "item.completed"),
284+
[],
285+
);
286+
} else {
287+
assert.equal(started?.payload.description, "sleep 40; echo done-a");
288+
}
289+
yield* Fiber.interrupt(eventsFiber);
290+
yield* adapter.stopSession(threadId);
291+
}).pipe(TestClock.withLive),
292+
);
293+
}
294+
235295
it.effect("sends runtime context with the current model without changing saved prompts", () =>
236296
Effect.gen(function* () {
237297
const threadId = ThreadId.make("grok-runtime-context");

‎apps/server/src/provider/Layers/GrokAdapter.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ import {
6868
normalizeGrokReasoningEffort,
6969
resolveGrokAcpBaseModelId,
7070
} from "../acp/GrokAcpSupport.ts";
71+
import {
72+
buildGrokBackgroundTaskEvents,
73+
type GrokBackgroundTaskRecord,
74+
} from "../acp/XAiBackgroundTasks.ts";
7175
import {
7276
extractGrokPlanMarkdownFromToolCallData,
7377
extractXAiAskUserQuestions,
@@ -171,6 +175,8 @@ interface GrokSessionContext {
171175
currentModelId: string | undefined;
172176
currentReasoningEffort: string | undefined;
173177
stopped: boolean;
178+
/** Live monitor/shell identities and their originating turns. */
179+
readonly backgroundTasks: Map<string, GrokBackgroundTaskRecord>;
174180
}
175181

176182
function settlePendingApprovalsAsCancelled(
@@ -1309,6 +1315,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
13091315
? normalizeGrokReasoningEffort(requestedStartReasoningEffort)
13101316
: currentStartReasoningEffort,
13111317
stopped: false,
1318+
backgroundTasks: new Map(),
13121319
};
13131320

13141321
const nf = yield* Stream.runDrain(
@@ -1331,6 +1338,24 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
13311338
}
13321339

13331340
const notificationTurnId = resolveNotificationTurnId(ctx);
1341+
if (event._tag === "ToolCallUpdated" && !ctx.stopped) {
1342+
for (const taskEvent of buildGrokBackgroundTaskEvents({
1343+
tasks: ctx.backgroundTasks,
1344+
toolCallId: event.toolCall.toolCallId,
1345+
rawInput: event.toolCall.data.rawInput,
1346+
rawOutput: event.toolCall.data.rawOutput,
1347+
toolCallStatus: event.toolCall.status,
1348+
turnId: notificationTurnId,
1349+
})) {
1350+
yield* offerRuntimeEvent({
1351+
...taskEvent,
1352+
...(yield* makeEventStamp()),
1353+
provider: PROVIDER,
1354+
threadId: ctx.threadId,
1355+
});
1356+
}
1357+
}
1358+
13341359
if (
13351360
notificationTurnId === undefined ||
13361361
ctx.interruptedTurnIds.has(notificationTurnId)

0 commit comments

Comments
 (0)