Skip to content

Commit 4010b23

Browse files
committed
fix(copilot): require complete replay provenance
1 parent 668e379 commit 4010b23

4 files changed

Lines changed: 63 additions & 8 deletions

File tree

‎extensions/copilot/src/attempt-finalize.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,9 @@ export async function completeCopilotAttempt(params: {
108108
lastToolError,
109109
journalValidated:
110110
transcript !== undefined &&
111+
!aborted &&
112+
!timedOut &&
113+
promptError === undefined &&
111114
!nativeSessionHistoryUnvalidated &&
112115
transcriptJournal?.hasFailed() !== true &&
113116
transcript?.replayInvalid !== true &&

‎extensions/copilot/src/attempt-transcript-journal.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -676,6 +676,7 @@ describe("Copilot attempt transcript journal", () => {
676676
idempotencyKey: "copilot-sdk:sdk-session:assistant-chunk-a",
677677
stopReason: "toolUse",
678678
});
679+
expect(rows[2]?.message).toMatchObject({ toolCallId: "call-a", toolName: "read" });
679680
expect(
680681
bridge.buildAssistantMessage({
681682
modelRef: { api: "openai-responses", id: "gpt-5", provider: "github-copilot" },
@@ -941,6 +942,37 @@ describe("Copilot attempt transcript journal", () => {
941942
expect(journal.snapshot().replayInvalid).toBe(true);
942943
});
943944

945+
it("preserves user-requested identity across an ephemeral completion", async () => {
946+
const { journal, session, target } = await createFixture();
947+
await journal.persistInitialUser();
948+
session.emit(
949+
event("tool.user_requested", "user-tool-request", {
950+
arguments: { path: "a" },
951+
toolCallId: "user-call",
952+
toolName: "read",
953+
}),
954+
);
955+
session.emit({
956+
...event("tool.execution_complete", "ephemeral-user-tool-result", {
957+
result: { content: "partial" },
958+
success: true,
959+
toolCallId: "user-call",
960+
}),
961+
ephemeral: true,
962+
} as SessionEvent);
963+
session.emit(
964+
event("tool.execution_complete", "durable-user-tool-result", {
965+
result: { content: "done" },
966+
success: true,
967+
toolCallId: "user-call",
968+
}),
969+
);
970+
await journal.barrier("user-requested completion");
971+
972+
expect(transcriptMessages(await readSessionTranscriptEvents(target))).toHaveLength(1);
973+
expect(journal.snapshot()).toMatchObject({ replayInvalid: true });
974+
});
975+
944976
it("hides autopilot users while preserving unknown SDK source provenance", async () => {
945977
initializeGlobalHookRunner(
946978
createMockPluginRegistry([

‎extensions/copilot/src/attempt.test.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2402,9 +2402,10 @@ describe("runCopilotAttempt", () => {
24022402
// the attempt as side-effect-safe.
24032403
const sdk = makeFakeSdk({
24042404
onCreateSession: (session) => {
2405-
session.sendAndWait.mockRejectedValueOnce(
2406-
new Error("Timeout after 60000ms waiting for session.idle"),
2407-
);
2405+
session.sendAndWait.mockImplementationOnce(async () => {
2406+
session.emit("user.message", { content: "hello" });
2407+
throw new Error("Timeout after 60000ms waiting for session.idle");
2408+
});
24082409
},
24092410
});
24102411
const pool = makeFakePool(sdk);
@@ -2423,6 +2424,9 @@ describe("runCopilotAttempt", () => {
24232424
// replay-shim incorrectly treated the attempt as side-effect-safe.
24242425
expect(result.replayMetadata?.hadPotentialSideEffects).toBe(true);
24252426
expect(result.replayMetadata?.replaySafe).toBe(false);
2427+
expect(
2428+
(result as AgentHarnessAttemptResult & { journalValidated?: boolean }).journalValidated,
2429+
).toBe(false);
24262430
sdk.sessions[0]?.emit("session.idle", {});
24272431
await vi.waitFor(() => {
24282432
expect(sdk.sessions[0]?.disconnect).toHaveBeenCalledTimes(1);
@@ -2572,7 +2576,10 @@ describe("runCopilotAttempt", () => {
25722576
const error = new Error("send failed");
25732577
const sdk = makeFakeSdk({
25742578
onCreateSession: (session) => {
2575-
session.sendAndWait.mockRejectedValueOnce(error);
2579+
session.sendAndWait.mockImplementationOnce(async () => {
2580+
session.emit("user.message", { content: "hello" });
2581+
throw error;
2582+
});
25762583
},
25772584
});
25782585
const pool = makeFakePool(sdk);
@@ -2581,6 +2588,9 @@ describe("runCopilotAttempt", () => {
25812588
const session = requireSession(sdk);
25822589

25832590
expect(projectAgentRunAttemptTerminal(result.terminal).promptError).toBe(error);
2591+
expect(
2592+
(result as AgentHarnessAttemptResult & { journalValidated?: boolean }).journalValidated,
2593+
).toBe(false);
25842594
expect(session.off).toHaveBeenCalledTimes(session.on.mock.calls.length);
25852595
expect(session.disconnect).toHaveBeenCalledTimes(1);
25862596
expect(pool["release"]).toHaveBeenCalledTimes(1);

‎extensions/copilot/src/event-bridge.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ export function attachEventBridge(
142142
let streamError: Error | undefined;
143143
const toolMetas: AgentHarnessAttemptResult["toolMetas"] = [];
144144
const toolMetaIndexByCallId = new Map<string, number>();
145+
const projectedToolNamesByCallId = new Map<string, string>();
145146
const userRequestedToolCallIds = new Set<string>();
146147
let startedCount = 0;
147148
let completedCount = 0;
@@ -349,12 +350,18 @@ export function attachEventBridge(
349350
};
350351
}
351352
const projection = options.transcriptProjection;
352-
const wasTrackedUserRequest = userRequestedToolCallIds.delete(event.data.toolCallId);
353+
const isDurableRootCompletion = isRootSessionEvent(event) && event.ephemeral !== true;
354+
const wasTrackedUserRequest = userRequestedToolCallIds.has(event.data.toolCallId);
353355
const isUserRequested = event.data.isUserRequested === true || wasTrackedUserRequest;
354-
if (projection && isRootSessionEvent(event) && event.ephemeral !== true && isUserRequested) {
356+
const projectedToolName = projectedToolNamesByCallId.get(event.data.toolCallId);
357+
if (isDurableRootCompletion) {
358+
userRequestedToolCallIds.delete(event.data.toolCallId);
359+
projectedToolNamesByCallId.delete(event.data.toolCallId);
360+
}
361+
if (projection && isDurableRootCompletion && isUserRequested) {
355362
projection.journal.markReplayIncomplete();
356363
}
357-
if (projection && isRootSessionEvent(event) && event.ephemeral !== true && !isUserRequested) {
364+
if (projection && isDurableRootCompletion && !isUserRequested) {
358365
const resultText = event.data.success
359366
? (event.data.result?.content ?? "")
360367
: (event.data.error?.message ?? "Tool execution failed");
@@ -368,7 +375,7 @@ export function attachEventBridge(
368375
message: {
369376
role: "toolResult",
370377
toolCallId: event.data.toolCallId,
371-
toolName: toolName ?? event.data.toolDescription?.name ?? "unknown",
378+
toolName: toolName ?? event.data.toolDescription?.name ?? projectedToolName ?? "unknown",
372379
content: [{ type: "text", text: sanitizeToolDetailText(resultText) }],
373380
...(hasOwnKeys(details) ? { details } : {}),
374381
isError: !event.data.success,
@@ -625,6 +632,9 @@ export function attachEventBridge(
625632
return;
626633
}
627634
handledAssistantEventIds.add(event.id);
635+
for (const request of event.data.toolRequests ?? []) {
636+
projectedToolNamesByCallId.set(request.toolCallId, request.name);
637+
}
628638
const entry = ensureMessageAccumulator(messagesById, messageOrder, event.data.messageId);
629639
if (typeof event.data.content === "string" && event.data.content.length >= entry.text.length) {
630640
entry.text = event.data.content;

0 commit comments

Comments
 (0)