Skip to content

Commit fce9e60

Browse files
committed
fix(acp): 重开会话时保留已投递指令记录
- 将指令摘要与原生会话标识保存到可选元数据,避免关闭后重开重复注入。 - 在完成事件前记录投递状态,并在压缩或回滚时失效,保留模式和工具变更的重新注入。 - 使用真实 mock 子进程验证重开、两类压缩和 ACP 工作状态时序;80 项测试及 check:changed 通过。
1 parent a0e0f8a commit fce9e60

4 files changed

Lines changed: 181 additions & 27 deletions

File tree

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -958,6 +958,15 @@ const program = Effect.gen(function* () {
958958
yield* agent.handlePrompt((request) =>
959959
Effect.gen(function* () {
960960
const requestedSessionId = String(request.sessionId ?? sessionId);
961+
if (process.env.T3_ACP_ECHO_ACCEPTED_PROMPT === "1") {
962+
yield* agent.client.sessionUpdate({
963+
sessionId: requestedSessionId,
964+
update: {
965+
sessionUpdate: "user_message_chunk",
966+
content: { type: "text", text: "Accepted test prompt" },
967+
},
968+
});
969+
}
961970
beginAcpMockPrompt(cancelledSessions, requestedSessionId);
962971
promptCount += 1;
963972
const idleError = process.env.T3_ACP_IDLE_ERROR;

‎apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts‎

Lines changed: 79 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,7 @@ const pollProtocolMethods = (events: Queue.Queue<EffectAcpProtocol.AcpProtocolLo
306306

307307
const makeInstructionCompactionHarness = Effect.fnUntraced(function* (
308308
environment: Readonly<Record<string, string>>,
309+
followAgentWorkState = false,
309310
) {
310311
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
311312
const path = yield* Path.Path;
@@ -331,6 +332,7 @@ const makeInstructionCompactionHarness = Effect.fnUntraced(function* (
331332
driver: ACP_TEST_DRIVER,
332333
capabilities: AcpProviderCapabilitiesV2,
333334
supportsCompaction: true,
335+
followAgentWorkState,
334336
makeRuntime: makeMockRuntime({
335337
childProcessSpawner,
336338
mockAgentPath,
@@ -345,23 +347,53 @@ const makeInstructionCompactionHarness = Effect.fnUntraced(function* (
345347
}),
346348
},
347349
selfInvocation,
350+
continuationRequests: { offer: () => Effect.void },
348351
});
349352
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
350353
runtimeMode: "full-access",
351354
interactionMode: "default",
352355
cwd: process.cwd(),
353356
});
354357
const modelSelection = { instanceId, model: "default" } as const;
355-
const runtime = yield* adapter.openSession({
358+
const open = Effect.fnUntraced(function* (initialNativeThreadId?: string) {
359+
const scope = yield* Scope.make();
360+
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
361+
const runtime = yield* adapter
362+
.openSession({
363+
threadId,
364+
providerSessionId: ProviderSessionId.make("provider-session-acp-instruction-compaction"),
365+
modelSelection,
366+
runtimePolicy,
367+
...(initialNativeThreadId === undefined ? {} : { initialNativeThreadId }),
368+
})
369+
.pipe(Effect.provideService(Scope.Scope, scope));
370+
return { runtime, scope };
371+
});
372+
let session = yield* open();
373+
let providerThread = yield* session.runtime.ensureThread({
356374
threadId,
357-
providerSessionId: ProviderSessionId.make("provider-session-acp-instruction-compaction"),
358375
modelSelection,
359376
runtimePolicy,
360377
});
361-
const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
362378
const now = yield* DateTime.now;
363379
let ordinal = 0;
364-
return Effect.fnUntraced(function* (messageText: string, expectedStatus = "completed") {
380+
return Effect.fnUntraced(function* (
381+
messageText: string,
382+
expectedStatus = "completed",
383+
reopen = false,
384+
) {
385+
if (reopen) {
386+
const nativeSessionId = providerThread.nativeThreadRef?.nativeId;
387+
if (nativeSessionId == null) return yield* Effect.die("Expected a persisted native session");
388+
yield* Scope.close(session.scope, Exit.void);
389+
session = yield* open(nativeSessionId);
390+
providerThread = yield* session.runtime.resumeThread({
391+
providerThread,
392+
modelSelection,
393+
runtimePolicy,
394+
});
395+
}
396+
const { runtime } = session;
365397
yield* runtime.startTurn(
366398
makeTurnInput({
367399
threadId,
@@ -374,6 +406,11 @@ const makeInstructionCompactionHarness = Effect.fnUntraced(function* (
374406
}),
375407
);
376408
const terminal = yield* runtime.events.pipe(
409+
Stream.tap((event) =>
410+
Effect.sync(() => {
411+
if (event.type === "provider_thread.updated") providerThread = event.providerThread;
412+
}),
413+
),
377414
Stream.filter((event) => event.type === "turn.terminal"),
378415
Stream.runHead,
379416
);
@@ -1010,6 +1047,44 @@ describe("AcpAdapterV2", () => {
10101047
}).pipe(Effect.provide(layerTest), Effect.scoped),
10111048
);
10121049

1050+
it.live("records instructions before ACP work-state completion ends the run", () =>
1051+
Effect.gen(function* () {
1052+
const runTurn = yield* makeInstructionCompactionHarness(
1053+
{ T3_ACP_ECHO_ACCEPTED_PROMPT: "1" },
1054+
true,
1055+
);
1056+
assertReinjectedInstructions(yield* runTurn("Start work."), "Start work.");
1057+
assert.equal(
1058+
(yield* runTurn("Continue work.", "completed", true))[0]?.text,
1059+
"Continue work.",
1060+
);
1061+
}).pipe(Effect.provide(layerTest), Effect.scoped),
1062+
);
1063+
1064+
it.live.each(["native", "protocol"] as const)(
1065+
"retains ACP instructions across reopen but reinjects after %s compaction",
1066+
(compaction) =>
1067+
Effect.gen(function* () {
1068+
const runTurn = yield* makeInstructionCompactionHarness(
1069+
compaction === "protocol"
1070+
? {
1071+
T3_ACP_COMPACTION_PROMPT_ORDINALS: "2",
1072+
}
1073+
: {},
1074+
);
1075+
assertReinjectedInstructions(yield* runTurn("Start work."), "Start work.");
1076+
assert.equal(
1077+
(yield* runTurn("Continue work.", "completed", true))[0]?.text,
1078+
"Continue work.",
1079+
);
1080+
yield* runTurn(compaction === "native" ? "/compact" : "Compact while working.");
1081+
assertReinjectedInstructions(
1082+
yield* runTurn("Continue after compact.", "completed", true),
1083+
"Continue after compact.",
1084+
);
1085+
}).pipe(Effect.provide(layerTest), Effect.scoped),
1086+
);
1087+
10131088
it.live(
10141089
"reinjects ACP instructions after protocol compaction, including during reinjection",
10151090
() =>

‎packages/contracts/src/orchestrationV2.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -908,6 +908,14 @@ export const OrchestrationV2PendingBackgroundTask = kindUnionWithFallback(
908908
export type OrchestrationV2PendingBackgroundTask = typeof OrchestrationV2PendingBackgroundTask.Type;
909909

910910
export const OrchestrationV2ProviderThreadNativeMetadata = Schema.Struct({
911+
acpInstructions: Schema.optional(
912+
Schema.NullOr(
913+
Schema.Struct({
914+
nativeSessionId: TrimmedNonEmptyString,
915+
digest: TrimmedNonEmptyString,
916+
}),
917+
),
918+
),
911919
modelSelection: Schema.optional(ModelSelection),
912920
title: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
913921
updatedAt: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),

‎packages/provider-acp/src/server/adapter.ts‎

Lines changed: 85 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import type * as Duration from "effect/Duration";
4646
import * as Effect from "effect/Effect";
4747
import * as Exit from "effect/Exit";
4848
import * as FileSystem from "effect/FileSystem";
49+
import * as Hex from "effect/encoding/Hex";
4950
import * as Fiber from "effect/Fiber";
5051
import * as Option from "effect/Option";
5152
import * as Queue from "effect/Queue";
@@ -1022,6 +1023,11 @@ interface AcpNativeBuildConfiguration {
10221023
}
10231024

10241025
interface ActiveAcpTurn {
1026+
readonly instructionDelivery?: {
1027+
readonly state: T3AcpInstructionState;
1028+
readonly digest: string;
1029+
readonly compactionMarker: symbol | undefined;
1030+
};
10251031
readonly input: ProviderAdapter.ProviderAdapterV2TurnInput;
10261032
readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
10271033
readonly nativeThreadId: string;
@@ -1922,6 +1928,31 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
19221928

19231929
const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) =>
19241930
Queue.offer(events, event).pipe(Effect.asVoid);
1931+
const recordInstructions = Effect.fnUntraced(function* (
1932+
context: ActiveAcpTurn,
1933+
receipt: NonNullable<
1934+
OrchestrationV2ProviderThreadNativeMetadata["acpInstructions"]
1935+
> | null,
1936+
) {
1937+
const metadata = { ...context.nativeMetadata, acpInstructions: receipt };
1938+
context.nativeMetadata = metadata;
1939+
yield* Ref.update(nativeMetadataBySessionId, (current) =>
1940+
new Map(current).set(context.nativeThreadId, metadata),
1941+
);
1942+
const known = (yield* Ref.get(providerThreadByNativeSessionId)).get(
1943+
context.nativeThreadId,
1944+
);
1945+
if (known === undefined) return;
1946+
const providerThread = {
1947+
...known,
1948+
nativeMetadata: metadata,
1949+
updatedAt: yield* DateTime.now,
1950+
};
1951+
yield* Ref.update(providerThreadByNativeSessionId, (current) =>
1952+
new Map(current).set(context.nativeThreadId, providerThread),
1953+
);
1954+
yield* emitProviderEvent({ type: "provider_thread.updated", driver, providerThread });
1955+
});
19251956
let scheduleDeferredFinalize: (context: ActiveAcpTurn) => Effect.Effect<void> = () =>
19261957
Effect.void;
19271958

@@ -3650,6 +3681,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
36503681
: { beforeTokenCount: context.contextUsage.usedTokens }),
36513682
};
36523683
if (status === "completed") {
3684+
yield* recordInstructions(context, null);
36533685
context.contextUsage = null;
36543686
yield* Ref.update(contextUsageBySessionId, (current) => {
36553687
const updated = new Map(current);
@@ -6914,13 +6946,34 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
69146946
yield* emitProviderRetry(context, settledStatus);
69156947
}
69166948
const now = yield* DateTime.now;
6949+
const delivery = context.instructionDelivery;
6950+
if (
6951+
settledStatus === "completed" &&
6952+
delivery !== undefined &&
6953+
(yield* Ref.get(compactionMarkers)).get(context.nativeThreadId) ===
6954+
delivery.compactionMarker
6955+
) {
6956+
yield* recordInstructions(context, {
6957+
nativeSessionId: context.nativeThreadId,
6958+
digest: delivery.digest,
6959+
});
6960+
yield* Ref.update(promptInstructionStates, (current) =>
6961+
new Map(current).set(context.nativeThreadId, delivery.state),
6962+
);
6963+
yield* Ref.update(compactionMarkers, (current) => {
6964+
const updated = new Map(current);
6965+
updated.delete(context.nativeThreadId);
6966+
return updated;
6967+
});
6968+
}
69176969
if (
69186970
flavor.supportsCompaction === true &&
69196971
context.input.message.text.trim() === "/compact" &&
69206972
context.input.message.attachments.length === 0 &&
69216973
settledStatus === "completed"
69226974
) {
69236975
const nativeItemId = `${context.nativeTurnId}:compaction`;
6976+
yield* recordInstructions(context, null);
69246977
yield* Ref.update(compactionMarkers, (current) => {
69256978
const updated = new Map(current);
69266979
updated.set(context.nativeThreadId, Symbol());
@@ -7092,7 +7145,27 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
70927145
interactionMode: turnInput.runtimePolicy.interactionMode,
70937146
hasT3Mcp: (yield* readMcpContext(turnInput.threadId)).servers.length > 0,
70947147
} satisfies T3AcpInstructionState;
7095-
const previousInstructionState = (yield* Ref.get(promptInstructionStates)).get(sessionId);
7148+
const instructionDigest = yield* crypto
7149+
.digest(
7150+
"SHA-256",
7151+
new TextEncoder().encode(
7152+
t3AcpPromptWithInstructions({ prompt: "", state: instructionState }),
7153+
),
7154+
)
7155+
.pipe(Effect.map(Hex.encode), Effect.orDie);
7156+
const rememberedInstructions = (yield* Ref.get(nativeMetadataBySessionId)).get(
7157+
sessionId,
7158+
)?.acpInstructions;
7159+
const recordedInstructions =
7160+
rememberedInstructions === undefined
7161+
? turnInput.providerThread.nativeMetadata?.acpInstructions
7162+
: rememberedInstructions;
7163+
const previousInstructionState =
7164+
(yield* Ref.get(promptInstructionStates)).get(sessionId) ??
7165+
(recordedInstructions?.nativeSessionId === sessionId &&
7166+
recordedInstructions.digest === instructionDigest
7167+
? instructionState
7168+
: undefined);
70967169
const compactionMarker = (yield* Ref.get(compactionMarkers)).get(sessionId);
70977170
const userText =
70987171
flavor.rewriteUserText === undefined
@@ -7173,6 +7246,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
71737246
return {
71747247
prompt,
71757248
instructionState: text === messageText ? undefined : instructionState,
7249+
instructionDigest,
71767250
compactionMarker,
71777251
};
71787252
});
@@ -7308,6 +7382,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
73087382
);
73097383
}
73107384
const context: ActiveAcpTurn = {
7385+
...(promptParts?.instructionState === undefined
7386+
? {}
7387+
: {
7388+
instructionDelivery: {
7389+
state: promptParts.instructionState,
7390+
digest: promptParts.instructionDigest,
7391+
compactionMarker: promptParts.compactionMarker,
7392+
},
7393+
}),
73117394
input: turnInput,
73127395
providerTurnId,
73137396
nativeThreadId: requestedSessionId,
@@ -7477,28 +7560,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
74777560
}
74787561
const promptGeneration = yield* Ref.get(runtimeCallbackGeneration);
74797562
yield* runtime.prompt({ prompt: promptParts!.prompt }).pipe(
7480-
Effect.tap(() =>
7481-
Ref.update(promptInstructionStates, (current) => {
7482-
if (promptParts?.instructionState === undefined) return current;
7483-
const updated = new Map(current);
7484-
updated.set(requestedSessionId, promptParts.instructionState);
7485-
return updated;
7486-
}),
7487-
),
7488-
Effect.tap(() =>
7489-
Ref.update(compactionMarkers, (current) => {
7490-
if (promptParts?.instructionState === undefined) return current;
7491-
const observedMarker = promptParts.compactionMarker;
7492-
if (
7493-
observedMarker === undefined ||
7494-
current.get(requestedSessionId) !== observedMarker
7495-
)
7496-
return current;
7497-
const updated = new Map(current);
7498-
updated.delete(requestedSessionId);
7499-
return updated;
7500-
}),
7501-
),
75027563
// Wire settlement precedes the completion callback's permit request so
75037564
// settled-soft classification can observe the native return even when
75047565
// the completion fiber has not yet set promptSettled under the permit.
@@ -8334,6 +8395,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
83348395
nativeConversationHeadRef: null,
83358396
nativeMetadata: {
83368397
...rollbackInput.providerThread.nativeMetadata,
8398+
acpInstructions: null,
83378399
itemIdentityVersion: 2 as const,
83388400
},
83398401
status: "idle" as const,

0 commit comments

Comments
 (0)