The best way to control Claude Code, Codex and more from any computer or phone
fix(server): imported ACP sessions show their native history (#22155)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Alan Justino da Silva <155623+alanjds@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Victor committed
Nov 11, 2026 at 04:46 UTC
75c7fb28af1d80d0941fa276d5d8f67c2f85c379
14 files changed
+1131
-231
apps/server/scripts/acp-mock-agent.ts
+4
@@ -28,6 +28,7 @@ const emitInterleavedAssistantToolCalls =
28
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
29
const emitV2Fidelity = process.env.T3_ACP_EMIT_V2_FIDELITY === "1";
30
const emitNotice = process.env.T3_ACP_EMIT_NOTICE === "1";
31
+const hangCloseSession = process.env.T3_ACP_HANG_CLOSE_SESSION === "1";
32
const vibeRetryOutcome = process.env.T3_ACP_VIBE_RETRY_OUTCOME;
33
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
34
const emitInTurnTaskOutputThenLateDuplicate =
@@ -731,6 +732,9 @@ const program = Effect.gen(function* () {
732
yield* agent.handleCloseSession(() =>
733
Effect.gen(function* () {
734
yield* requireAuthentication();
735
+ if (hangCloseSession) {
736
+ return yield* Effect.never;
737
+ }
738
return {};
739
}),
740
);
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+81
-1
@@ -2620,11 +2620,30 @@ describe("AcpAdapterV2", () => {
2620
content: { type: "text", text: "after plan" },
2621
},
2622
});
2623
+ yield* sessionUpdateHandler!({
2624
+ sessionId: "mock-session-1",
2625
+ update: {
2626
+ sessionUpdate: "agent_thought_chunk",
2627
+ content: { type: "text", text: "weighing it" },
2628
+ },
2629
+ });
2630
+ yield* sessionUpdateHandler!({
2631
+ sessionId: "mock-session-1",
2632
+ update: {
2633
+ sessionUpdate: "agent_thought",
2634
+ messageId: "whole-thought",
2635
+ content: [{ type: "text", text: "settled on it" }],
2636
+ },
2637
+ });
2638
2639
const snapshot = yield* runtime.readThreadSnapshot({ providerThread });
2640
assert.deepEqual(
2641
snapshot.messages.map((message) => message.text),
2627
- ["before plan", "after plan"],
2642
+ ["before plan", "after plan", "weighing it", "settled on it"],
2643
+ );
2644
+ assert.deepEqual(
2645
+ snapshot.reasoningMessageIds,
2646
+ snapshot.messages.slice(2).map((message) => message.id),
2647
);
2648
}).pipe(Effect.provide(layerTest), Effect.scoped),
2649
);
@@ -5453,6 +5472,67 @@ describe("AcpAdapterV2", () => {
5472
}).pipe(Effect.provide(layerTest), Effect.scoped),
5473
);
5474
5475
+ it.effect("closes the ACP runtime when the agent never answers session/close", () =>
5476
+ Effect.gen(function* () {
5477
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
5478
+ const path = yield* Path.Path;
5479
+ const selfInvocation = yield* resolveSelfInvocation();
5480
+ const mockAgentPath = yield* path.fromFileUrl(
5481
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
5482
+ );
5483
+ const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
5484
+ const makeRuntime = makeMockRuntime({
5485
+ childProcessSpawner,
5486
+ mockAgentPath,
5487
+ protocolEvents,
5488
+ environment: { T3_ACP_HANG_CLOSE_SESSION: "1" },
5489
+ });
5490
+ let runtimeClosed = false;
5491
+ const instanceId = ProviderInstanceId.make("acp-test");
5492
+ const adapter = yield* makeAcpAdapterV2({
5493
+ instanceId,
5494
+ flavor: {
5495
+ driver: ACP_TEST_DRIVER,
5496
+ capabilities: AcpProviderCapabilitiesV2,
5497
+ makeRuntime: (runtimeInput) =>
5498
+ Effect.addFinalizer(() =>
5499
+ Effect.sync(() => {
5500
+ runtimeClosed = true;
5501
+ }),
5502
+ ).pipe(Effect.andThen(makeRuntime(runtimeInput))),
5503
+ },
5504
+ selfInvocation,
5505
+ });
5506
+ const sessionScope = yield* Scope.make();
5507
+ yield* adapter
5508
+ .openSession({
5509
+ threadId: ThreadId.make("thread-acp-unanswered-close"),
5510
+ providerSessionId: ProviderSessionId.make("provider-session-acp-unanswered-close"),
5511
+ modelSelection: { instanceId, model: "default" },
5512
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
5513
+ runtimeMode: "full-access",
5514
+ interactionMode: "default",
5515
+ cwd: process.cwd(),
5516
+ }),
5517
+ })
5518
+ .pipe(Effect.provideService(Scope.Scope, sessionScope));
5519
+ const closing = yield* Scope.close(sessionScope, Exit.void).pipe(Effect.forkDetach);
5520
+ yield* Stream.fromQueue(protocolEvents).pipe(
5521
+ Stream.filter(
5522
+ (event) => event.direction === "outgoing" && rawProtocolMethod(event) === "session/close",
5523
+ ),
5524
+ Stream.runHead,
5525
+ );
5526
+ yield* TestClock.adjust("10 seconds");
5527
+ const closed = yield* Fiber.await(closing).pipe(
5528
+ Effect.timeoutOption("5 seconds"),
5529
+ TestClock.withLive,
5530
+ );
5531
+ assert.isTrue(Option.isSome(closed));
5532
+ assert.isTrue(runtimeClosed);
5533
+ }).pipe(Effect.provide(layerTest)),
5534
+ );
5535
+
5536
// Oracle: Grok incident frames. Command completion must release the turn even
5537
// when the CLI keeps the prompt RPC and process alive. Command polls stay visible.
5538
it.live(
apps/server/src/orchestration-v2/Orchestrator.migration.test.ts
+8
@@ -10,6 +10,14 @@ it("reissues imported context until a V2 run completes", () => {
10
legacyImportItemCount: 2,
11
}),
12
);
13
+ assert.isFalse(
14
+ shouldPrepareLegacyImportHandoff({
15
+ historyOrigin: "v1_import",
16
+ hasCompletedRun: false,
17
+ legacyImportItemCount: 2,
18
+ hasNativeHistory: true,
19
+ }),
20
+ );
21
assert.isFalse(
22
shouldPrepareLegacyImportHandoff({
23
historyOrigin: "v1_import",
apps/server/src/orchestration-v2/Orchestrator.ts
+8
-1
@@ -1048,12 +1048,16 @@ function latestContextTransfer(
1048
}
1049
1050
export function shouldPrepareLegacyImportHandoff(input: {
1051
+ readonly hasNativeHistory?: boolean;
1052
readonly hasCompletedRun: boolean;
1053
readonly historyOrigin: OrchestrationV2AppThread["historyOrigin"];
1054
readonly legacyImportItemCount: number;
1055
}): boolean {
1056
return (
1056
- input.historyOrigin === "v1_import" && !input.hasCompletedRun && input.legacyImportItemCount > 0
1057
+ input.historyOrigin === "v1_import" &&
1058
+ !input.hasNativeHistory &&
1059
+ !input.hasCompletedRun &&
1060
+ input.legacyImportItemCount > 0
1061
);
1062
}
1063
@@ -6958,6 +6962,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6962
nativeThreadId: `pending:${runId}`,
6963
});
6964
const legacyImportHandoff = shouldPrepareLegacyImportHandoff({
6965
+ hasNativeHistory:
6966
+ activeProviderThread?.driver === "acpRegistry" &&
6967
+ activeProviderThread.nativeThreadRef !== null,
6968
historyOrigin: projection.thread.historyOrigin,
6969
hasCompletedRun: latestCompletedRun !== undefined,
6970
legacyImportItemCount: legacyImportItems.length,
apps/server/src/orchestration-v2/runtimeLayer.ts
+2
@@ -244,6 +244,8 @@ const layerAgentSessionImporterProvided = AgentSessionImporter.layer.pipe(
244
layerEventSink,
245
IdAllocator.layer,
246
ProviderSessionRuntime.layer,
247
+ ProviderAdapterRegistry.layerFromProviderInstanceRegistry,
248
+ ThreadCommandExecutor.layer,
249
),
250
),
251
);
apps/server/src/project/AgentSessionImporter.test.ts
+340
-1
@@ -6,12 +6,18 @@ import {
6
ProjectId,
7
ProviderDriverKind,
8
ProviderInstanceId,
9
+ MessageId,
10
+ RunId,
11
ThreadId,
12
type ApplicationStoredEvent,
13
type OrchestrationV2AppThread,
14
+ type OrchestrationV2DomainEvent,
15
type OrchestrationV2ProviderThread,
16
} from "@t3tools/contracts";
17
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
18
+import * as KeyedLock from "@t3tools/shared/KeyedLock";
19
+import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator";
20
+import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
21
import * as Context from "effect/Context";
22
import * as DateTime from "effect/DateTime";
23
import * as Deferred from "effect/Deferred";
@@ -21,11 +27,14 @@ import * as Layer from "effect/Layer";
27
import * as Option from "effect/Option";
28
import * as Stream from "effect/Stream";
29
import * as SqlClient from "effect/sql/SqlClient";
30
+import * as TestClock from "effect/testing/TestClock";
31
32
import * as EventSink from "../orchestration-v2/EventSink.ts";
33
import * as EventStore from "../orchestration-v2/EventStore.ts";
34
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
35
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
36
+import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
37
+import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
38
import {
39
CLAUDE_MODEL_SELECTION,
40
CODEX_MODEL_SELECTION,
@@ -172,6 +181,8 @@ const seedOwner = Effect.fn(function* (
181
const makeImporter = Effect.fn(function* (
182
candidates: ReadonlyArray<ReturnType<typeof candidate>>,
183
beforeTransaction: Effect.Effect<void> = Effect.void,
184
+ getAdapter?: ProviderAdapterRegistry.ProviderAdapterRegistryV2Shape["get"],
185
+ threadCommands?: KeyedLock.KeyedLock<ThreadId>,
186
settings: Layer.Layer<
187
ServerSettings.ServerSettingsService,
188
ServerSettingsError
@@ -243,12 +254,23 @@ const makeImporter = Effect.fn(function* (
254
),
255
),
256
}),
257
+ Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)(
258
+ getAdapter === undefined ? {} : { get: getAdapter },
259
+ ),
260
+ Layer.succeed(
261
+ ThreadCommandExecutor.ThreadCommandExecutor,
262
+ threadCommands ?? (yield* KeyedLock.make<ThreadId>()),
263
+ ),
264
),
265
),
266
),
267
);
268
const importer = Context.get(context, AgentSessionImporter.AgentSessionImporter);
251
- return { run: importer.importRecentAgentThreads({ projectId }), published };
269
+ return {
270
+ run: importer.importRecentAgentThreads({ projectId }),
271
+ importNativeHistory: importer.importNativeHistory,
272
+ published,
273
+ };
274
});
275
276
it.effect(
@@ -424,6 +446,321 @@ it.effect(
446
}).pipe(Effect.scoped, Effect.provide(persistence)),
447
);
448
449
+it.effect(
450
+ "copies native session history into the imported thread once, retrying a failed read",
451
+ () =>
452
+ Effect.gen(function* () {
453
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
454
+ const source = candidate(CODEX_MODEL_SELECTION, "native-history");
455
+ const threadId = yield* seedOwner(source);
456
+ const resolved: Array<ProviderInstanceId> = [];
457
+ const opened: Array<ProviderAdapter.ProviderAdapterV2OpenSessionInput> = [];
458
+ let closed = false;
459
+ let failRead = true;
460
+ const replayed = (role: "user" | "assistant", text: string) => ({
461
+ createdBy: role === "user" ? ("user" as const) : ("agent" as const),
462
+ creationSource: "provider" as const,
463
+ id: MessageId.make(`replayed:${text}`),
464
+ threadId,
465
+ runId: null,
466
+ nodeId: null,
467
+ role,
468
+ text,
469
+ attachments: [],
470
+ streaming: false,
471
+ createdAt: now,
472
+ updatedAt: now,
473
+ });
474
+ const adapter = {
475
+ openSession: (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) =>
476
+ Effect.acquireRelease(
477
+ Effect.sync(() => {
478
+ opened.push(input);
479
+ return {
480
+ readThreadSnapshot: ({ providerThread }) =>
481
+ failRead
482
+ ? Effect.fail(
483
+ new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
484
+ driver: providerThread.driver,
485
+ providerThreadId: providerThread.id,
486
+ }),
487
+ )
488
+ : Effect.succeed({
489
+ providerThread,
490
+ providerTurns: [],
491
+ runtimeRequests: [],
492
+ reasoningMessageIds: [MessageId.make("replayed:Check the build log")],
493
+ messages: [
494
+ replayed("user", "Fix the build"),
495
+ replayed("assistant", "Check the build log"),
496
+ replayed("assistant", "Fixed it"),
497
+ replayed("assistant", " "),
498
+ ],
499
+ }),
500
+ } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">;
501
+ }),
502
+ () =>
503
+ Effect.sync(() => {
504
+ closed = true;
505
+ }),
506
+ ),
507
+ } as unknown as ProviderAdapter.ProviderAdapterV2["Service"];
508
+ const importer = yield* makeImporter([], Effect.void, (instanceId) =>
509
+ Effect.sync(() => {
510
+ resolved.push(instanceId);
511
+ return adapter;
512
+ }),
513
+ );
514
+
515
+ const importHistory = importer.importNativeHistory({
516
+ threadId,
517
+ workspaceRoot: "/workspace/project",
518
+ });
519
+
520
+ expect((yield* Effect.flip(importHistory))._tag).toBe(
521
+ "ProviderAdapterReadThreadSnapshotError",
522
+ );
523
+ expect(closed).toBe(true);
524
+ expect(
525
+ (yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin,
526
+ ).toBeUndefined();
527
+
528
+ failRead = false;
529
+ expect(yield* importHistory).toBe(3);
530
+ expect(resolved).toEqual([
531
+ CODEX_MODEL_SELECTION.instanceId,
532
+ CODEX_MODEL_SELECTION.instanceId,
533
+ ]);
534
+ expect(opened[1]).toMatchObject({
535
+ threadId,
536
+ initialNativeThreadId: source.source.providerSessionId,
537
+ runtimePolicy: { cwd: "/workspace/project" },
538
+ });
539
+ // Forks keep run-less history only for this origin.
540
+ expect((yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin).toBe(
541
+ "v1_import",
542
+ );
543
+ expect(yield* importHistory).toBe(0);
544
+ expect(opened).toHaveLength(2);
545
+ const page = yield* projections.getTimelinePage(threadId, { view: "activity", limit: 10 });
546
+ expect(
547
+ page.items.map(({ item }) => [
548
+ item.type,
549
+ item.runId,
550
+ "text" in item ? item.text : undefined,
551
+ ]),
552
+ ).toEqual([
553
+ ["user_message", null, "Fix the build"],
554
+ ["reasoning", null, "Check the build log"],
555
+ ["assistant_message", null, "Fixed it"],
556
+ ]);
557
+ }).pipe(Effect.scoped, Effect.provide(persistence)),
558
+);
559
+
560
+it.effect("releases the ACP import lock when a native session never answers", () =>
561
+ Effect.gen(function* () {
562
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
563
+ const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator;
564
+ const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, "native-history-hang"));
565
+ const opened = yield* Deferred.make<void>();
566
+ let closed = false;
567
+ // An agent that only resumes sessions and never answers its first session/resume.
568
+ const adapter = {
569
+ openSession: () =>
570
+ Effect.suspend(() => {
571
+ if (!closed) {
572
+ return Effect.addFinalizer(() =>
573
+ Effect.sync(() => {
574
+ closed = true;
575
+ }),
576
+ ).pipe(
577
+ Effect.andThen(Deferred.succeed(opened, undefined)),
578
+ Effect.andThen(Effect.never),
579
+ );
580
+ }
581
+ return Effect.succeed({
582
+ readThreadSnapshot: ({ providerThread }) =>
583
+ Effect.succeed({
584
+ providerThread,
585
+ providerTurns: [],
586
+ runtimeRequests: [],
587
+ messages: [
588
+ {
589
+ createdBy: "user",
590
+ creationSource: "provider",
591
+ id: MessageId.make("replayed:hang"),
592
+ threadId,
593
+ runId: null,
594
+ nodeId: null,
595
+ role: "user",
596
+ text: "Fix the build",
597
+ attachments: [],
598
+ streaming: false,
599
+ createdAt: now,
600
+ updatedAt: now,
601
+ },
602
+ ],
603
+ }),
604
+ } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">);
605
+ }),
606
+ } as unknown as ProviderAdapter.ProviderAdapterV2["Service"];
607
+ const importer = yield* makeImporter([], Effect.void, () => Effect.succeed(adapter));
608
+ const importHistory = coordinator.withSessionMutation(
609
+ importer.importNativeHistory({ threadId, workspaceRoot: "/workspace/project" }),
610
+ );
611
+
612
+ const importing = yield* importHistory.pipe(Effect.flip, Effect.forkChild);
613
+ yield* Deferred.await(opened);
614
+ // Any other ACP import or delete waits for the same lock.
615
+ const next = yield* coordinator
616
+ .withSessionMutation(Effect.succeed("next"))
617
+ .pipe(Effect.forkChild);
618
+ yield* TestClock.adjust("2 minutes");
619
+
620
+ expect((yield* Fiber.join(importing))._tag).toBe("TimeoutError");
621
+ expect(closed).toBe(true);
622
+ expect(yield* Fiber.join(next)).toBe("next");
623
+ expect(
624
+ (yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin,
625
+ ).toBeUndefined();
626
+ expect(yield* importHistory).toBe(1);
627
+ expect((yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin).toBe(
628
+ "v1_import",
629
+ );
630
+ }).pipe(
631
+ Effect.scoped,
632
+ Effect.provide(Layer.merge(persistence, AcpRegistryRuntimeCoordinator.layer)),
633
+ ),
634
+);
635
+
636
+/**
637
+ * Runs a thread command that read the thread before the history load ended and
638
+ * writes once the importer is about to commit, as an unserialized write would.
639
+ */
640
+const importDuringCommand = Effect.fn(function* (
641
+ name: string,
642
+ command: (thread: OrchestrationV2AppThread) => ReadonlyArray<OrchestrationV2DomainEvent>,
643
+) {
644
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
645
+ const sink = yield* EventSink.EventSinkV2;
646
+ const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, name));
647
+ const lock = yield* KeyedLock.make<ThreadId>();
648
+ const loaded = yield* Deferred.make<void>();
649
+ const importerCommitting = yield* Deferred.make<void>();
650
+ const commandWritten = yield* Deferred.make<void>();
651
+ const committing = Deferred.succeed(importerCommitting, undefined);
652
+ const adapter = {
653
+ openSession: () =>
654
+ Effect.succeed({
655
+ readThreadSnapshot: ({ providerThread }) =>
656
+ Deferred.await(loaded).pipe(
657
+ Effect.as({
658
+ providerThread,
659
+ providerTurns: [],
660
+ runtimeRequests: [],
661
+ messages: [
662
+ {
663
+ createdBy: "user" as const,
664
+ creationSource: "provider" as const,
665
+ id: MessageId.make(`replayed:${name}`),
666
+ threadId,
667
+ runId: null,
668
+ nodeId: null,
669
+ role: "user" as const,
670
+ text: "Fix the build",
671
+ attachments: [],
672
+ streaming: false,
673
+ createdAt: now,
674
+ updatedAt: now,
675
+ },
676
+ ],
677
+ }),
678
+ ),
679
+ } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">),
680
+ } as unknown as ProviderAdapter.ProviderAdapterV2["Service"];
681
+ const importer = yield* makeImporter(
682
+ [],
683
+ committing.pipe(Effect.andThen(Deferred.await(commandWritten))),
684
+ () => Effect.succeed(adapter),
685
+ {
686
+ ...lock,
687
+ withLock: (key, effect) => committing.pipe(Effect.andThen(lock.withLock(key, effect))),
688
+ },
689
+ );
690
+ const commanding = yield* Effect.forkScoped(
691
+ lock.withLock(
692
+ threadId,
693
+ Effect.gen(function* () {
694
+ const { thread } = yield* projections.getThreadRecords(threadId, []);
695
+ yield* Deferred.succeed(loaded, undefined);
696
+ yield* Deferred.await(importerCommitting);
697
+ yield* sink.write({ events: command(thread) });
698
+ yield* Deferred.succeed(commandWritten, undefined);
699
+ }),
700
+ ),
701
+ );
702
+ const imported = yield* importer.importNativeHistory({
703
+ threadId,
704
+ workspaceRoot: "/workspace/project",
705
+ });
706
+ yield* Fiber.join(commanding);
707
+ const records = yield* projections.getThreadRecords(threadId, ["runs"]);
708
+ const page = yield* projections.getTimelinePage(threadId, { view: "messages", limit: 10 });
709
+ return { imported, thread: records.thread, runs: records.runs, items: page.items };
710
+});
711
+
712
+it.effect("keeps a thread edit made while the native history loads", () =>
713
+ Effect.gen(function* () {
714
+ const result = yield* importDuringCommand("renamed-during-load", (thread) => [
715
+ {
716
+ id: EventId.make(`${thread.id}:renamed`),
717
+ type: "thread.metadata-updated",
718
+ threadId: thread.id,
719
+ occurredAt: now,
720
+ payload: { ...thread, title: "Renamed" },
721
+ },
722
+ ]);
723
+ expect(result.imported).toBe(1);
724
+ expect(result.thread.title).toBe("Renamed");
725
+ expect(result.thread.historyOrigin).toBe("v1_import");
726
+ expect(result.items).toHaveLength(1);
727
+ }).pipe(Effect.scoped, Effect.provide(persistence)),
728
+);
729
+
730
+it.effect("skips the native history when a run starts while it loads", () =>
731
+ Effect.gen(function* () {
732
+ const result = yield* importDuringCommand("run-during-load", (thread) => [
733
+ {
734
+ id: EventId.make(`${thread.id}:run`),
735
+ type: "run.updated",
736
+ threadId: thread.id,
737
+ occurredAt: now,
738
+ payload: {
739
+ id: RunId.make(`${thread.id}:run`),
740
+ threadId: thread.id,
741
+ ordinal: 1,
742
+ providerInstanceId: thread.providerInstanceId,
743
+ modelSelection: thread.modelSelection,
744
+ providerThreadId: null,
745
+ userMessageId: MessageId.make(`${thread.id}:prompt`),
746
+ rootNodeId: null,
747
+ activeAttemptId: null,
748
+ status: "queued",
749
+ requestedAt: now,
750
+ startedAt: null,
751
+ completedAt: null,
752
+ checkpointId: null,
753
+ contextHandoffId: null,
754
+ },
755
+ },
756
+ ]);
757
+ expect(result.imported).toBe(0);
758
+ expect(result.runs).toHaveLength(1);
759
+ expect(result.thread.historyOrigin).toBeUndefined();
760
+ expect(result.items).toEqual([]);
761
+ }).pipe(Effect.scoped, Effect.provide(persistence)),
762
+);
763
+
764
it.effect("imports under a policy ceiling in the project's default, kept under the ceiling", () =>
765
Effect.gen(function* () {
766
const projections = yield* ProjectionStore.ProjectionStoreV2;
@@ -433,6 +770,8 @@ it.effect("imports under a policy ceiling in the project's default, kept under t
770
const importer = yield* makeImporter(
771
[source],
772
Effect.void,
773
+ undefined,
774
+ undefined,
775
ServerSettings.layerTest(
776
{ defaultRuntimeMode: "full-access" },
777
{
apps/server/src/project/AgentSessionImporter.ts
+151
-23
@@ -36,6 +36,8 @@ import * as Stream from "effect/Stream";
36
import * as EventSink from "../orchestration-v2/EventSink.ts";
37
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
38
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
39
+import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
40
+import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
41
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
42
import * as ServerSettings from "../serverSettings.ts";
43
import * as AgentSessionScanner from "./AgentSessionScanner.ts";
@@ -85,14 +87,34 @@ class AgentSessionThreadModifiedError extends Schema.TaggedError<AgentSessionThr
87
}
88
}
89
90
+// ACP imports read the history while holding the session-mutation lock, and an agent can
91
+// leave session/resume or initialize unanswered. Longer than session/load's own deadline.
92
+const NATIVE_HISTORY_READ_TIMEOUT = "2 minutes";
93
+
94
+/**
95
+ * Whether a thread bound to a native session still lacks its native history.
96
+ * Once a turn has run, the native session also holds that turn's messages, so
97
+ * its history can no longer be imported as run-less items.
98
+ */
99
+export function isNativeHistoryPending(input: {
100
+ readonly historyOrigin: OrchestrationV2AppThread["historyOrigin"];
101
+ readonly hasRun: boolean;
102
+}): boolean {
103
+ return input.historyOrigin !== "v1_import" && !input.hasRun;
104
+}
105
+
106
function dateTime(value: string): DateTime.Utc {
107
return DateTime.makeUnsafe(value);
108
}
109
110
+type HistoryMessage = Omit<AgentSessionScanner.AgentSessionThreadMessage, "role"> & {
111
+ readonly role: AgentSessionScanner.AgentSessionThreadMessage["role"] | "reasoning";
112
+};
113
+
114
function messageEvents(input: {
115
readonly threadId: ThreadId;
116
readonly index: number;
95
- readonly message: AgentSessionScanner.AgentSessionThreadMessage;
117
+ readonly message: HistoryMessage;
118
}): ReadonlyArray<OrchestrationV2DomainEvent> {
119
const ordinal = input.index + 1;
120
const suffix = String(input.index).padStart(6, "0");
@@ -101,20 +123,6 @@ function messageEvents(input: {
123
`${IMPORT_EVENT_PREFIX}:turn-item:${input.threadId}:${suffix}`,
124
);
125
const at = dateTime(input.message.createdAt);
104
- const message: OrchestrationV2ConversationMessage = {
105
- createdBy: input.message.role === "user" ? "user" : "agent",
106
- creationSource: "server",
107
- id: messageId,
108
- threadId: input.threadId,
109
- runId: null,
110
- nodeId: null,
111
- role: input.message.role,
112
- text: input.message.text,
113
- attachments: [],
114
- streaming: false,
115
- createdAt: at,
116
- updatedAt: at,
117
- };
126
const common = {
127
id: turnItemId,
128
threadId: input.threadId,
@@ -131,6 +139,32 @@ function messageEvents(input: {
139
completedAt: at,
140
updatedAt: at,
141
};
142
+ const turnItemEvent = (payload: OrchestrationV2TurnItem): OrchestrationV2DomainEvent => ({
143
+ id: EventId.make(turnItemId),
144
+ type: "turn-item.updated",
145
+ threadId: input.threadId,
146
+ occurredAt: at,
147
+ payload,
148
+ });
149
+ if (input.message.role === "reasoning") {
150
+ return [
151
+ turnItemEvent({ ...common, type: "reasoning", text: input.message.text, streaming: false }),
152
+ ];
153
+ }
154
+ const message: OrchestrationV2ConversationMessage = {
155
+ createdBy: input.message.role === "user" ? "user" : "agent",
156
+ creationSource: "server",
157
+ id: messageId,
158
+ threadId: input.threadId,
159
+ runId: null,
160
+ nodeId: null,
161
+ role: input.message.role,
162
+ text: input.message.text,
163
+ attachments: [],
164
+ streaming: false,
165
+ createdAt: at,
166
+ updatedAt: at,
167
+ };
168
const turnItem: OrchestrationV2TurnItem =
169
input.message.role === "user"
170
? {
@@ -158,13 +192,7 @@ function messageEvents(input: {
192
occurredAt: at,
193
payload: message,
194
},
161
- {
162
- id: EventId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${input.threadId}:${suffix}`),
163
- type: "turn-item.updated",
164
- threadId: input.threadId,
165
- occurredAt: at,
166
- payload: turnItem,
167
- },
195
+ turnItemEvent(turnItem),
196
];
197
}
198
@@ -175,6 +203,8 @@ const make = Effect.gen(function* () {
203
const eventSink = yield* EventSink.EventSinkV2;
204
const idAllocator = yield* IdAllocator.IdAllocatorV2;
205
const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
206
+ const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2;
207
+ const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
208
const settingsService = yield* ServerSettings.ServerSettingsService;
209
const ceiling = settingsService.managedPolicy?.limits?.maxRuntimeMode;
210
const importRecentAgentThreads = Effect.fn("importRecentAgentThreadsV2")(function* (
@@ -452,7 +482,105 @@ const make = Effect.gen(function* () {
482
return { importedCount, skippedCount } satisfies AgentSessionImportResult;
483
});
484
455
- return { importRecentAgentThreads };
485
+ /**
486
+ * Loading a native session replays its history only into the adapter's own
487
+ * snapshot, so copy that snapshot into the thread as run-less history. The
488
+ * `v1_import` origin keeps it in forks and marks the import done, so a call
489
+ * after a failed read repairs the thread and any later call does nothing.
490
+ */
491
+ const importNativeHistory = Effect.fn("importNativeHistoryV2")(function* (input: {
492
+ readonly threadId: ThreadId;
493
+ readonly workspaceRoot: string;
494
+ }) {
495
+ const pendingThread = Effect.map(
496
+ orchestrator.getThreadRecords(input.threadId, ["providerThreads", "runs"]),
497
+ (records) =>
498
+ isNativeHistoryPending({
499
+ historyOrigin: records.thread.historyOrigin,
500
+ hasRun: records.runs.length > 0,
501
+ })
502
+ ? records
503
+ : null,
504
+ );
505
+ // Thread commands write whole thread rows, so hold their lock from the
506
+ // re-read through the write to keep both this marker and their changes.
507
+ const commit = (messages: ReadonlyArray<HistoryMessage>) =>
508
+ threadCommands.withLock(
509
+ input.threadId,
510
+ Effect.gen(function* () {
511
+ const current = yield* pendingThread;
512
+ if (current === null) return 0;
513
+ yield* eventSink.write({
514
+ events: [
515
+ ...messages.flatMap((message, index) =>
516
+ messageEvents({ threadId: input.threadId, index, message }),
517
+ ),
518
+ {
519
+ id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${input.threadId}:native-history`),
520
+ type: "thread.metadata-updated",
521
+ threadId: input.threadId,
522
+ providerInstanceId: current.thread.providerInstanceId,
523
+ occurredAt: yield* DateTime.now,
524
+ payload: { ...current.thread, historyOrigin: "v1_import" },
525
+ },
526
+ ],
527
+ });
528
+ return messages.length;
529
+ }),
530
+ );
531
+ const records = yield* pendingThread;
532
+ if (records === null) return 0;
533
+ const { thread, providerThreads } = records;
534
+ const providerThread = providerThreads.find(
535
+ (candidate) => candidate.appThreadId === input.threadId && candidate.nativeThreadRef !== null,
536
+ );
537
+ const nativeThreadId = providerThread?.nativeThreadRef?.nativeId;
538
+ if (providerThread === undefined || nativeThreadId == null) return 0;
539
+ const providerSessionId = yield* idAllocator.allocate.providerSession({
540
+ providerInstanceId: providerThread.providerInstanceId,
541
+ threadId: input.threadId,
542
+ });
543
+ // The registry admits this open against sign-in changes, like any other open.
544
+ const adapter = yield* registry.get(thread.modelSelection.instanceId);
545
+ const snapshot = yield* adapter
546
+ .openSession({
547
+ threadId: input.threadId,
548
+ providerSessionId,
549
+ modelSelection: thread.modelSelection,
550
+ runtimePolicy: {
551
+ runtimeMode: thread.runtimeMode,
552
+ interactionMode: thread.interactionMode,
553
+ cwd: thread.worktreePath ?? input.workspaceRoot,
554
+ },
555
+ initialNativeThreadId: nativeThreadId,
556
+ ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
557
+ ? {}
558
+ : {
559
+ initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
560
+ }),
561
+ })
562
+ .pipe(
563
+ Effect.flatMap((session) => session.readThreadSnapshot({ providerThread })),
564
+ Effect.timeout(NATIVE_HISTORY_READ_TIMEOUT),
565
+ Effect.scoped,
566
+ );
567
+ const reasoningIds = new Set(snapshot.reasoningMessageIds);
568
+ const messages = snapshot.messages.flatMap((message) =>
569
+ (message.role === "user" || message.role === "assistant") && message.text.trim() !== ""
570
+ ? [
571
+ {
572
+ role: reasoningIds.has(message.id) ? ("reasoning" as const) : message.role,
573
+ text: message.text,
574
+ createdAt: DateTime.formatIso(message.createdAt),
575
+ },
576
+ ]
577
+ : [],
578
+ );
579
+ // Loading the session can take a while, and the thread is usable meanwhile.
580
+ return yield* commit(messages);
581
+ });
582
+
583
+ return { importRecentAgentThreads, importNativeHistory };
584
});
585
586
type AgentSessionImporterShape = Effect.Success<typeof make>;
apps/server/src/provider/AcpRegistrySessions.ts
new
+229
@@ -0,0 +1,229 @@
1
+import {
2
+ AcpRegistryOperationError,
3
+ CommandId,
4
+ type AcpRegistryImportSessionInput,
5
+ type AcpRegistryImportSessionResult,
6
+ type Project,
7
+ type ProjectId,
8
+ type ProviderDriverKind,
9
+ type ProviderInstanceId,
10
+} from "@t3tools/contracts";
11
+import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator";
12
+import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
13
+import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
14
+import * as Context from "effect/Context";
15
+import * as SecureRandom from "effect/crypto/SecureRandom";
16
+import * as Effect from "effect/Effect";
17
+import * as Layer from "effect/Layer";
18
+import * as Result from "effect/Result";
19
+
20
+import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
21
+import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
22
+import * as AgentSessionImporter from "../project/AgentSessionImporter.ts";
23
+import * as ProjectService from "../project/ProjectService.ts";
24
+import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts";
25
+import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
26
+import * as ProviderRegistry from "./ProviderRegistry.ts";
27
+
28
+export const importedThreadId = (input: {
29
+ readonly driver: ProviderDriverKind;
30
+ readonly instanceId: ProviderInstanceId;
31
+ readonly sessionId: string;
32
+}) =>
33
+ IdAllocator.deriveThreadFromProviderThread({
34
+ driver: input.driver,
35
+ providerInstanceId: input.instanceId,
36
+ nativeThreadId: input.sessionId,
37
+ });
38
+
39
+export class AcpRegistrySessions extends Context.Service<
40
+ AcpRegistrySessions,
41
+ {
42
+ readonly project: (projectId: ProjectId) => Effect.Effect<Project, AcpRegistryOperationError>;
43
+ readonly sessionManager: (instanceId: ProviderInstanceId) => Effect.Effect<
44
+ {
45
+ readonly instance: ProviderInstance;
46
+ readonly manager: NonNullable<ProviderInstance["acpSessionManagement"]>;
47
+ },
48
+ AcpRegistryOperationError
49
+ >;
50
+ /**
51
+ * Binds a native ACP session to a T3 thread and copies its history in. Importing a
52
+ * session whose thread still lacks its history repairs that thread instead.
53
+ */
54
+ readonly importSession: (
55
+ input: AcpRegistryImportSessionInput,
56
+ ) => Effect.Effect<AcpRegistryImportSessionResult, AcpRegistryOperationError>;
57
+ }
58
+>()("t3/provider/AcpRegistrySessions") {}
59
+
60
+const make = Effect.gen(function* () {
61
+ const projectService = yield* ProjectService.ProjectService;
62
+ const providerInstances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
63
+ const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
64
+ const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator;
65
+ const threadManagement = yield* ThreadManagementService.ThreadManagementService;
66
+ const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
67
+ const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
68
+ const agentSessionImporter = yield* AgentSessionImporter.AgentSessionImporter;
69
+ const random = yield* SecureRandom.SecureRandom;
70
+
71
+ const project = Effect.fn("AcpRegistrySessions.project")(function* (projectId: ProjectId) {
72
+ const found = yield* projectService.getById(projectId).pipe(
73
+ Effect.mapError(
74
+ (cause) =>
75
+ new AcpRegistryOperationError({
76
+ reason: "project_not_found",
77
+ message: `Project ${projectId} is unavailable.`,
78
+ cause,
79
+ }),
80
+ ),
81
+ );
82
+ return yield* Effect.fromOption(
83
+ found,
84
+ () =>
85
+ new AcpRegistryOperationError({
86
+ reason: "project_not_found",
87
+ message: `Project ${projectId} was not found.`,
88
+ }),
89
+ );
90
+ });
91
+
92
+ const sessionManager = Effect.fn("AcpRegistrySessions.sessionManager")(function* (
93
+ instanceId: ProviderInstanceId,
94
+ ) {
95
+ const instance = yield* providerInstances.getInstance(instanceId);
96
+ if (instance === undefined) {
97
+ return yield* new AcpRegistryOperationError({
98
+ reason: "instance_not_found",
99
+ message: `Provider instance ${instanceId} was not found.`,
100
+ });
101
+ }
102
+ if (instance.acpSessionManagement === undefined) {
103
+ return yield* new AcpRegistryOperationError({
104
+ reason: "session_list_unsupported",
105
+ message: `Provider instance ${instanceId} does not expose ACP session management.`,
106
+ });
107
+ }
108
+ return { instance, manager: instance.acpSessionManagement };
109
+ });
110
+
111
+ const importSession = Effect.fn("AcpRegistrySessions.importSession")(function* (
112
+ input: AcpRegistryImportSessionInput,
113
+ ) {
114
+ const { workspaceRoot } = yield* project(input.projectId);
115
+ const { instance } = yield* sessionManager(input.instanceId);
116
+ const providerSnapshot = yield* instance.snapshot.getSnapshot;
117
+ if (
118
+ providerSnapshot.nativeSessions?.canLoad !== true &&
119
+ providerSnapshot.nativeSessions?.canResume !== true
120
+ ) {
121
+ return yield* new AcpRegistryOperationError({
122
+ reason: "session_resume_unsupported",
123
+ message: "The ACP agent cannot load or resume native sessions.",
124
+ });
125
+ }
126
+ const threadId = importedThreadId({
127
+ driver: instance.driverKind,
128
+ instanceId: input.instanceId,
129
+ sessionId: input.sessionId,
130
+ });
131
+ const existing = yield* threadManagement.getThreadShell(threadId).pipe(
132
+ Effect.mapError(
133
+ (cause) =>
134
+ new AcpRegistryOperationError({
135
+ reason: "session_import_failed",
136
+ message: "Could not inspect the imported ACP session mapping.",
137
+ cause,
138
+ }),
139
+ ),
140
+ );
141
+ if (existing !== null) {
142
+ const repairing = AgentSessionImporter.isNativeHistoryPending({
143
+ historyOrigin: existing.historyOrigin,
144
+ hasRun: existing.latestRunId !== null,
145
+ });
146
+ yield* agentSessionImporter.importNativeHistory({ threadId, workspaceRoot }).pipe(
147
+ Effect.mapError(
148
+ (cause) =>
149
+ new AcpRegistryOperationError({
150
+ reason: "session_import_failed",
151
+ message: "Could not import the ACP session history.",
152
+ cause,
153
+ }),
154
+ ),
155
+ );
156
+ return { threadId, imported: repairing } as const;
157
+ }
158
+
159
+ const provider = (yield* providerRegistry.getProviders).find(
160
+ (candidate) => candidate.instanceId === input.instanceId,
161
+ );
162
+ const model =
163
+ provider?.models.find((candidate) => candidate.isDefault)?.slug ??
164
+ provider?.models[0]?.slug ??
165
+ "default";
166
+ const commandId = CommandId.make(yield* random.uuidV4());
167
+ const launched = yield* Effect.result(
168
+ startup.enqueueCommand(
169
+ threadLaunch.launch({
170
+ commandId,
171
+ threadId,
172
+ projectId: input.projectId,
173
+ title: input.title ?? "Imported ACP session",
174
+ modelSelection: { instanceId: input.instanceId, model },
175
+ runtimeMode: "approval-required",
176
+ interactionMode: "default",
177
+ workspaceStrategy: { type: "root" },
178
+ importedNativeThread: {
179
+ ref: {
180
+ driver: instance.driverKind,
181
+ nativeId: input.sessionId,
182
+ strength: "strong",
183
+ },
184
+ metadata: {
185
+ itemIdentityVersion: 2,
186
+ ...(input.title === undefined ? {} : { title: input.title }),
187
+ ...(input.updatedAt === undefined ? {} : { updatedAt: input.updatedAt }),
188
+ },
189
+ },
190
+ createdBy: "user",
191
+ creationSource: "web",
192
+ }),
193
+ ),
194
+ );
195
+ if (Result.isFailure(launched)) {
196
+ const racedImport = yield* threadManagement.getThreadShell(threadId).pipe(
197
+ Effect.mapError(
198
+ (cause) =>
199
+ new AcpRegistryOperationError({
200
+ reason: "session_import_failed",
201
+ message: "Could not inspect the imported ACP session after launch failed.",
202
+ cause,
203
+ }),
204
+ ),
205
+ );
206
+ if (racedImport !== null) return { threadId, imported: false } as const;
207
+ return yield* new AcpRegistryOperationError({
208
+ reason: "session_import_failed",
209
+ message: "Could not create a T3 thread for the ACP session.",
210
+ cause: launched.failure,
211
+ });
212
+ }
213
+ // The thread is usable without its history, so a failed read only logs.
214
+ yield* agentSessionImporter.importNativeHistory({ threadId, workspaceRoot }).pipe(
215
+ Effect.catch((cause) =>
216
+ Effect.logWarning("Could not import ACP session history", {
217
+ instanceId: input.instanceId,
218
+ sessionId: input.sessionId,
219
+ cause,
220
+ }),
221
+ ),
222
+ );
223
+ return { threadId, imported: true } as const;
224
+ }, coordinator.withSessionMutation);
225
+
226
+ return AcpRegistrySessions.of({ project, sessionManager, importSession });
227
+});
228
+
229
+export const layer = Layer.effect(AcpRegistrySessions, make);
apps/server/src/ws.test.ts
+243
@@ -3,6 +3,8 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3
import * as NodeServices from "@effect/platform-node/NodeServices";
4
import { assert, it } from "@effect/vitest";
5
import {
6
+ AuthOrchestrationOperateScope,
7
+ AuthOrchestrationReadScope,
8
AuthSessionId,
9
AuthSourceControlWriteScope,
10
EnvironmentId,
@@ -13,11 +15,14 @@ import {
15
TurnItemId,
16
ProviderDriverKind,
17
ProviderInstanceId,
18
+ RunId,
19
SourceControlRepositoryError,
20
WS_METHODS,
21
WsRpcGroup,
22
WsServerRefreshProvidersRpc,
23
WsSubscribeServerConfigRpc,
24
+ type OrchestrationV2AppThread,
25
+ type OrchestrationV2DomainEvent,
26
type OrchestrationV2StoredEvent,
27
type OrchestrationV2ThreadShell,
28
type OrchestrationProjectShell,
@@ -26,6 +31,7 @@ import {
31
type ServerProvider,
32
} from "@t3tools/contracts";
33
import * as Deferred from "effect/Deferred";
34
+import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
35
import * as DateTime from "effect/DateTime";
36
import * as Effect from "effect/Effect";
37
import * as Exit from "effect/Exit";
@@ -40,6 +46,7 @@ import * as Stream from "effect/Stream";
46
import * as TestClock from "effect/testing/TestClock";
47
import { Headers } from "effect/http";
48
import { RpcGroup, RpcMessage, RpcServer } from "effect/rpc";
49
+import * as RpcTest from "effect/rpc/RpcTest";
50
import * as SqlClient from "effect/sql/SqlClient";
51
import * as Statement from "effect/sql/Statement";
52
import { vi } from "vite-plus/test";
@@ -83,6 +90,7 @@ import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts
90
import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts";
91
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
92
import * as ProviderAuthService from "./provider/ProviderAuthService.ts";
93
+import * as AcpRegistrySessions from "./provider/AcpRegistrySessions.ts";
94
import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts";
95
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
96
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
@@ -132,6 +140,7 @@ import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";
140
import * as ServerSettings from "./serverSettings.ts";
141
import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
142
143
+import * as EventStore from "./orchestration-v2/EventStore.ts";
144
import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
145
import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
146
import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
@@ -782,6 +791,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
791
Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}),
792
Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({}),
793
Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({}),
794
+ Layer.mock(AcpRegistrySessions.AcpRegistrySessions)({}),
795
Layer.mock(AgentSessionImporter.AgentSessionImporter)({}),
796
Layer.mock(AgentSessionScanner.AgentSessionScanner)({}),
797
Layer.mock(AnalyticsService.AnalyticsService)({}),
@@ -1808,3 +1818,236 @@ it.effect("thread resume at its own high-water below the pruned boundary skips t
1818
assert.isTrue(Exit.isSuccess(exit));
1819
}).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
1820
);
1821
+
1822
+const acpDriver = ProviderDriverKind.make("acpRegistry");
1823
+const acpInstanceId = ProviderInstanceId.make("acpRegistry_test");
1824
+const acpProjectId = ProjectId.make("project:acp");
1825
+const acpThreadId = (sessionId: string) =>
1826
+ IdAllocator.deriveThreadFromProviderThread({
1827
+ driver: acpDriver,
1828
+ providerInstanceId: acpInstanceId,
1829
+ nativeThreadId: sessionId,
1830
+ });
1831
+const acpSessionTags = [
1832
+ WS_METHODS.serverListAcpRegistrySessions,
1833
+ WS_METHODS.serverImportAcpRegistrySession,
1834
+] as const;
1835
+const acpSessionRpcs = WsRpcGroup.omit(
1836
+ ...[...WsRpcGroup.requests.keys()].filter(
1837
+ (
1838
+ tag,
1839
+ ): tag is Exclude<
1840
+ keyof typeof RpcAuthorization.RPC_REQUIRED_SCOPES,
1841
+ (typeof acpSessionTags)[number]
1842
+ > => !(acpSessionTags as ReadonlyArray<string>).includes(tag),
1843
+ ),
1844
+);
1845
+const acpStores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe(
1846
+ Layer.provideMerge(SqlitePersistence.layerMemory),
1847
+);
1848
+
1849
+const seedAcpThread = Effect.fn(function* (
1850
+ sessionId: string,
1851
+ state: { readonly imported: boolean; readonly ran: boolean },
1852
+) {
1853
+ const sink = yield* EventSink.EventSinkV2;
1854
+ const now = DateTime.makeUnsafe("2026-10-23T00:00:00.000Z");
1855
+ const threadId = acpThreadId(sessionId);
1856
+ const thread: OrchestrationV2AppThread = {
1857
+ createdBy: "user",
1858
+ creationSource: "web",
1859
+ id: threadId,
1860
+ projectId: acpProjectId,
1861
+ title: sessionId,
1862
+ providerInstanceId: acpInstanceId,
1863
+ modelSelection: { instanceId: acpInstanceId, model: "default" },
1864
+ runtimeMode: "approval-required",
1865
+ interactionMode: "default",
1866
+ branch: null,
1867
+ worktreePath: null,
1868
+ activeProviderThreadId: null,
1869
+ ...(state.imported ? { historyOrigin: "v1_import" as const } : {}),
1870
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1871
+ forkedFrom: null,
1872
+ createdAt: now,
1873
+ updatedAt: now,
1874
+ archivedAt: null,
1875
+ deletedAt: null,
1876
+ settledOverride: null,
1877
+ settledAt: null,
1878
+ lastVisitedAt: null,
1879
+ };
1880
+ const events: Array<OrchestrationV2DomainEvent> = [
1881
+ {
1882
+ id: EventId.make(`${threadId}:created`),
1883
+ type: "thread.created",
1884
+ threadId,
1885
+ occurredAt: now,
1886
+ payload: thread,
1887
+ },
1888
+ ];
1889
+ if (state.ran) {
1890
+ events.push({
1891
+ id: EventId.make(`${threadId}:run`),
1892
+ type: "run.updated",
1893
+ threadId,
1894
+ occurredAt: now,
1895
+ payload: {
1896
+ id: RunId.make(`${threadId}:run`),
1897
+ threadId,
1898
+ ordinal: 1,
1899
+ providerInstanceId: acpInstanceId,
1900
+ modelSelection: thread.modelSelection,
1901
+ providerThreadId: null,
1902
+ userMessageId: MessageId.make(`${threadId}:prompt`),
1903
+ rootNodeId: null,
1904
+ activeAttemptId: null,
1905
+ status: "completed",
1906
+ requestedAt: now,
1907
+ startedAt: now,
1908
+ completedAt: now,
1909
+ checkpointId: null,
1910
+ contextHandoffId: null,
1911
+ },
1912
+ });
1913
+ }
1914
+ yield* sink.write({ events });
1915
+ return threadId;
1916
+});
1917
+
1918
+it.effect("ACP session RPCs list a thread missing its history and repair it on import", () =>
1919
+ Effect.gen(function* () {
1920
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
1921
+ const pending = yield* seedAcpThread("pending", { imported: false, ran: false });
1922
+ const complete = yield* seedAcpThread("complete", { imported: true, ran: false });
1923
+ const ran = yield* seedAcpThread("ran", { imported: false, ran: true });
1924
+ const repaired: Array<ThreadId> = [];
1925
+ const session = (sessionId: string) => ({
1926
+ sessionId,
1927
+ cwd: "/workspace/acp",
1928
+ additionalDirectories: [],
1929
+ title: null,
1930
+ updatedAt: null,
1931
+ importedThreadId: null,
1932
+ });
1933
+ const instance = {
1934
+ driverKind: acpDriver,
1935
+ snapshot: { getSnapshot: Effect.succeed({ nativeSessions: { canLoad: true } }) },
1936
+ acpSessionManagement: {
1937
+ listSessions: () =>
1938
+ Effect.succeed({
1939
+ sessions: ["new", "pending", "complete", "ran"].map(session),
1940
+ nextCursor: null,
1941
+ canLoad: true,
1942
+ canResume: true,
1943
+ canDelete: true,
1944
+ }),
1945
+ },
1946
+ } as unknown as ProviderInstance;
1947
+ const dependencies = Layer.mergeAll(
1948
+ layerUnusedConfigRpcServices,
1949
+ Layer.fresh(layerConfigSources),
1950
+ Layer.mock(ExternalLauncher.ExternalLauncher)({}),
1951
+ Layer.mock(ProviderRegistry.ProviderRegistry)({}),
1952
+ Layer.mock(UsageLimitSources.UsageLimitSources)({}),
1953
+ Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}),
1954
+ Layer.mock(DirectEndpoints.DirectEndpoints)({}),
1955
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }),
1956
+ Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
1957
+ Layer.mock(ServerEnvironment.ServerEnvironment)({}),
1958
+ Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
1959
+ Layer.mock(ProjectService.ProjectService)({
1960
+ getById: () =>
1961
+ Effect.succeedSome({
1962
+ id: acpProjectId,
1963
+ title: "ACP",
1964
+ workspaceRoot: "/workspace/acp",
1965
+ defaultModelSelection: null,
1966
+ scripts: [],
1967
+ createdAt: "2026-10-23T00:00:00.000Z",
1968
+ updatedAt: "2026-10-23T00:00:00.000Z",
1969
+ deletedAt: null,
1970
+ }),
1971
+ }),
1972
+ Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
1973
+ getInstance: () => Effect.succeed(instance),
1974
+ }),
1975
+ Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({
1976
+ withSessionMutation: (effect) => effect,
1977
+ }),
1978
+ Layer.mock(ThreadManagement.ThreadManagementService)({
1979
+ getThreadShell: (threadId) =>
1980
+ projections
1981
+ .getThreadShell(threadId)
1982
+ .pipe(
1983
+ Effect.mapError(
1984
+ (cause) => new Orchestrator.OrchestratorProjectionError({ threadId, cause }),
1985
+ ),
1986
+ ),
1987
+ }),
1988
+ // Repairing an existing thread must not launch another one.
1989
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
1990
+ Layer.mock(AgentSessionImporter.AgentSessionImporter)({
1991
+ importNativeHistory: ({ threadId }) =>
1992
+ Effect.sync(() => repaired.push(threadId)).pipe(Effect.as(1)),
1993
+ }),
1994
+ );
1995
+ const services = AcpRegistrySessions.layer.pipe(Layer.provideMerge(dependencies));
1996
+ const client = yield* RpcTest.makeClient(acpSessionRpcs).pipe(
1997
+ Effect.provide(
1998
+ layerWsRpc(
1999
+ {
2000
+ sessionId: AuthSessionId.make("acp-test"),
2001
+ subject: "acp-test",
2002
+ method: "browser-session-cookie",
2003
+ scopes: [],
2004
+ },
2005
+ {},
2006
+ yield* ServerBrowser.ServerBrowser,
2007
+ () => Effect.void,
2008
+ { secretReferences: true },
2009
+ ).pipe(
2010
+ Layer.provide(services),
2011
+ Layer.merge(
2012
+ RpcAuthorization.layer([AuthOrchestrationReadScope, AuthOrchestrationOperateScope]),
2013
+ ),
2014
+ ),
2015
+ ),
2016
+ );
2017
+
2018
+ const listed = yield* client[WS_METHODS.serverListAcpRegistrySessions]({
2019
+ instanceId: acpInstanceId,
2020
+ projectId: acpProjectId,
2021
+ });
2022
+ assert.deepEqual(
2023
+ listed.sessions.map(({ sessionId, importedThreadId, nativeHistoryPending }) => [
2024
+ sessionId,
2025
+ importedThreadId,
2026
+ nativeHistoryPending,
2027
+ ]),
2028
+ [
2029
+ ["new", null, undefined],
2030
+ ["pending", pending, true],
2031
+ ["complete", complete, undefined],
2032
+ ["ran", ran, undefined],
2033
+ ],
2034
+ );
2035
+
2036
+ const imported = yield* client[WS_METHODS.serverImportAcpRegistrySession]({
2037
+ instanceId: acpInstanceId,
2038
+ projectId: acpProjectId,
2039
+ sessionId: "pending",
2040
+ });
2041
+ assert.deepEqual(imported, { threadId: pending, imported: true });
2042
+ assert.deepEqual(repaired, [pending]);
2043
+ }).pipe(
2044
+ Effect.provide(
2045
+ Layer.mergeAll(
2046
+ EventSink.layer.pipe(Layer.provideMerge(acpStores)),
2047
+ Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}),
2048
+ Layer.mock(ServerBrowser.ServerBrowser)({}),
2049
+ ),
2050
+ ),
2051
+ Effect.scoped,
2052
+ ),
2053
+);
apps/server/src/ws.ts
+28
-166
@@ -17,7 +17,6 @@ import * as Path from "effect/Path";
17
import * as Queue from "effect/Queue";
18
import * as Ref from "effect/Ref";
19
import * as Schema from "effect/Schema";
20
-import * as Result from "effect/Result";
20
import * as Stream from "effect/Stream";
21
import { rpcInitialItems } from "./rpcInitialItems.ts";
22
import { subscribeChatGptHandoff } from "./provider/CodexChatGptHandoff.ts";
@@ -43,7 +42,6 @@ import {
42
type GitActionProgressEvent,
43
type GitManagerServiceError,
44
type MessageId,
46
- type AcpRegistryImportSessionInput,
45
type AcpRegistryDeleteSessionInput,
46
type AcpRegistryDisableProviderInput,
47
type AcpRegistryListProvidersInput,
@@ -94,9 +92,6 @@ import {
92
PersistChatAttachmentsError,
93
RpcClientId,
94
EnvironmentAuthorizationError,
97
- type ProjectId,
98
- type ProviderDriverKind,
99
- type ProviderInstanceId,
95
ThreadId,
96
type TerminalMetadataStreamEvent,
97
type PullRequestRef,
@@ -124,7 +119,6 @@ import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManag
119
import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts";
120
import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts";
121
import * as DocumentText from "./provider/DocumentText.ts";
127
-import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
122
import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";
123
import * as SecretRequests from "./secrets/SecretRequests.ts";
124
import * as GuestShareService from "./guest/GuestShareService.ts";
@@ -174,6 +168,7 @@ import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts";
168
import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts";
169
import { userFacingDispatchErrorMessage } from "./orchestration-v2/UserFacingErrors.ts";
170
import * as ProviderRegistry from "./provider/ProviderRegistry.ts";
171
+import * as AcpRegistrySessions from "./provider/AcpRegistrySessions.ts";
172
import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts";
173
import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
174
import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator";
@@ -1503,6 +1498,7 @@ export const layerWsRpc = (
1498
const acpRegistryCatalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
1499
const acpRegistryRuntimeCoordinator =
1500
yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator;
1501
+ const acpRegistrySessions = yield* AcpRegistrySessions.AcpRegistrySessions;
1502
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
1503
const providerAuth = yield* ProviderAuthService.ProviderAuthService;
1504
const providerInstallation = yield* ProviderInstallation.ProviderInstallation;
@@ -1568,64 +1564,11 @@ export const layerWsRpc = (
1564
? effect
1565
: Effect.fail(rpcAuthorizationError(requiredScope));
1566
1571
- const acpRegistryProject = Effect.fn("ws.acpRegistry.project")(function* (
1572
- projectId: ProjectId,
1573
- ) {
1574
- const project = yield* projectService.getById(projectId).pipe(
1575
- Effect.mapError(
1576
- (cause) =>
1577
- new AcpRegistryOperationError({
1578
- reason: "project_not_found",
1579
- message: `Project ${projectId} is unavailable.`,
1580
- cause,
1581
- }),
1582
- ),
1583
- );
1584
- return yield* Effect.fromOption(
1585
- project,
1586
- () =>
1587
- new AcpRegistryOperationError({
1588
- reason: "project_not_found",
1589
- message: `Project ${projectId} was not found.`,
1590
- }),
1591
- );
1592
- });
1593
-
1594
- const acpSessionManager = Effect.fn("ws.acpRegistry.sessionManager")(function* (
1595
- instanceId: ProviderInstanceId,
1596
- ) {
1597
- const instance = yield* providerInstances.getInstance(instanceId);
1598
- if (instance === undefined) {
1599
- return yield* new AcpRegistryOperationError({
1600
- reason: "instance_not_found",
1601
- message: `Provider instance ${instanceId} was not found.`,
1602
- });
1603
- }
1604
- if (instance.acpSessionManagement === undefined) {
1605
- return yield* new AcpRegistryOperationError({
1606
- reason: "session_list_unsupported",
1607
- message: `Provider instance ${instanceId} does not expose ACP session management.`,
1608
- });
1609
- }
1610
- return { instance, manager: instance.acpSessionManagement };
1611
- });
1612
-
1613
- const importedAcpThreadId = (input: {
1614
- readonly driver: ProviderDriverKind;
1615
- readonly instanceId: ProviderInstanceId;
1616
- readonly sessionId: string;
1617
- }) =>
1618
- IdAllocator.deriveThreadFromProviderThread({
1619
- driver: input.driver,
1620
- providerInstanceId: input.instanceId,
1621
- nativeThreadId: input.sessionId,
1622
- });
1623
-
1567
const listAcpRegistrySessions = Effect.fn("ws.acpRegistry.listSessions")(function* (
1568
input: AcpRegistryListSessionsInput,
1569
) {
1627
- const project = yield* acpRegistryProject(input.projectId);
1628
- const { instance, manager } = yield* acpSessionManager(input.instanceId);
1570
+ const project = yield* acpRegistrySessions.project(input.projectId);
1571
+ const { instance, manager } = yield* acpRegistrySessions.sessionManager(input.instanceId);
1572
const listed = yield* manager.listSessions({
1573
cwd: project.workspaceRoot,
1574
...(input.cursor === undefined ? {} : { cursor: input.cursor }),
@@ -1633,7 +1576,7 @@ export const layerWsRpc = (
1576
const sessions = yield* Effect.forEach(
1577
listed.sessions,
1578
(session) => {
1636
- const threadId = importedAcpThreadId({
1579
+ const threadId = AcpRegistrySessions.importedThreadId({
1580
driver: instance.driverKind,
1581
instanceId: input.instanceId,
1582
sessionId: session.sessionId,
@@ -1642,6 +1585,13 @@ export const layerWsRpc = (
1585
Effect.map((thread) => ({
1586
...session,
1587
importedThreadId: thread === null ? null : threadId,
1588
+ ...(thread !== null &&
1589
+ AgentSessionImporter.isNativeHistoryPending({
1590
+ historyOrigin: thread.historyOrigin,
1591
+ hasRun: thread.latestRunId !== null,
1592
+ })
1593
+ ? { nativeHistoryPending: true }
1594
+ : {}),
1595
})),
1596
Effect.mapError(
1597
(cause) =>
@@ -1658,106 +1608,15 @@ export const layerWsRpc = (
1608
return { ...listed, sessions };
1609
});
1610
1661
- const importAcpRegistrySession = Effect.fn("ws.acpRegistry.importSession")(function* (
1662
- input: AcpRegistryImportSessionInput,
1663
- ) {
1664
- return yield* acpRegistryRuntimeCoordinator.withSessionMutation(
1665
- Effect.gen(function* () {
1666
- yield* acpRegistryProject(input.projectId);
1667
- const { instance } = yield* acpSessionManager(input.instanceId);
1668
- const providerSnapshot = yield* instance.snapshot.getSnapshot;
1669
- if (
1670
- providerSnapshot.nativeSessions?.canLoad !== true &&
1671
- providerSnapshot.nativeSessions?.canResume !== true
1672
- ) {
1673
- return yield* new AcpRegistryOperationError({
1674
- reason: "session_resume_unsupported",
1675
- message: "The ACP agent cannot load or resume native sessions.",
1676
- });
1677
- }
1678
- const threadId = importedAcpThreadId({
1679
- driver: instance.driverKind,
1680
- instanceId: input.instanceId,
1681
- sessionId: input.sessionId,
1682
- });
1683
- const existing = yield* threadManagement.getThreadShell(threadId).pipe(
1684
- Effect.mapError(
1685
- (cause) =>
1686
- new AcpRegistryOperationError({
1687
- reason: "session_import_failed",
1688
- message: "Could not inspect the imported ACP session mapping.",
1689
- cause,
1690
- }),
1691
- ),
1692
- );
1693
- if (existing !== null) return { threadId, imported: false } as const;
1694
-
1695
- const provider = (yield* providerRegistry.getProviders).find(
1696
- (candidate) => candidate.instanceId === input.instanceId,
1697
- );
1698
- const model =
1699
- provider?.models.find((candidate) => candidate.isDefault)?.slug ??
1700
- provider?.models[0]?.slug ??
1701
- "default";
1702
- const commandId = CommandId.make(yield* random.uuidV4());
1703
- const launched = yield* Effect.result(
1704
- startup.enqueueCommand(
1705
- threadLaunch.launch({
1706
- commandId,
1707
- threadId,
1708
- projectId: input.projectId,
1709
- title: input.title ?? "Imported ACP session",
1710
- modelSelection: { instanceId: input.instanceId, model },
1711
- runtimeMode: "approval-required",
1712
- interactionMode: "default",
1713
- workspaceStrategy: { type: "root" },
1714
- importedNativeThread: {
1715
- ref: {
1716
- driver: instance.driverKind,
1717
- nativeId: input.sessionId,
1718
- strength: "strong",
1719
- },
1720
- metadata: {
1721
- itemIdentityVersion: 2,
1722
- ...(input.title === undefined ? {} : { title: input.title }),
1723
- ...(input.updatedAt === undefined ? {} : { updatedAt: input.updatedAt }),
1724
- },
1725
- },
1726
- createdBy: "user",
1727
- creationSource: "web",
1728
- }),
1729
- ),
1730
- );
1731
- if (Result.isFailure(launched)) {
1732
- const racedImport = yield* threadManagement.getThreadShell(threadId).pipe(
1733
- Effect.mapError(
1734
- (cause) =>
1735
- new AcpRegistryOperationError({
1736
- reason: "session_import_failed",
1737
- message: "Could not inspect the imported ACP session after launch failed.",
1738
- cause,
1739
- }),
1740
- ),
1741
- );
1742
- if (racedImport !== null) return { threadId, imported: false } as const;
1743
- return yield* new AcpRegistryOperationError({
1744
- reason: "session_import_failed",
1745
- message: "Could not create a T3 thread for the ACP session.",
1746
- cause: launched.failure,
1747
- });
1748
- }
1749
- return { threadId, imported: true } as const;
1750
- }),
1751
- );
1752
- });
1753
-
1611
const deleteAcpRegistrySession = Effect.fn("ws.acpRegistry.deleteSession")(function* (
1612
input: AcpRegistryDeleteSessionInput,
1613
) {
1614
return yield* acpRegistryRuntimeCoordinator.withSessionMutation(
1615
Effect.gen(function* () {
1759
- const project = yield* acpRegistryProject(input.projectId);
1760
- const { instance, manager } = yield* acpSessionManager(input.instanceId);
1616
+ const project = yield* acpRegistrySessions.project(input.projectId);
1617
+ const { instance, manager } = yield* acpRegistrySessions.sessionManager(
1618
+ input.instanceId,
1619
+ );
1620
const snapshot = yield* instance.snapshot.getSnapshot;
1621
if (snapshot.nativeSessions?.canDelete !== true) {
1622
return yield* new AcpRegistryOperationError({
@@ -1765,7 +1624,7 @@ export const layerWsRpc = (
1624
message: "The ACP agent does not advertise session deletion.",
1625
});
1626
}
1768
- const threadId = importedAcpThreadId({
1627
+ const threadId = AcpRegistrySessions.importedThreadId({
1628
driver: instance.driverKind,
1629
instanceId: input.instanceId,
1630
sessionId: input.sessionId,
@@ -1798,8 +1657,8 @@ export const layerWsRpc = (
1657
const listAcpRegistryProviders = Effect.fn("ws.acpRegistry.listProviders")(function* (
1658
input: AcpRegistryListProvidersInput,
1659
) {
1801
- const project = yield* acpRegistryProject(input.projectId);
1802
- const { instance, manager } = yield* acpSessionManager(input.instanceId);
1660
+ const project = yield* acpRegistrySessions.project(input.projectId);
1661
+ const { instance, manager } = yield* acpRegistrySessions.sessionManager(input.instanceId);
1662
const snapshot = yield* instance.snapshot.getSnapshot;
1663
if (snapshot.configurableProviders !== true) {
1664
return yield* new AcpRegistryOperationError({
@@ -1813,8 +1672,8 @@ export const layerWsRpc = (
1672
const setAcpRegistryProvider = Effect.fn("ws.acpRegistry.setProvider")(function* (
1673
input: AcpRegistrySetProviderInput,
1674
) {
1816
- const project = yield* acpRegistryProject(input.projectId);
1817
- const { manager } = yield* acpSessionManager(input.instanceId);
1675
+ const project = yield* acpRegistrySessions.project(input.projectId);
1676
+ const { manager } = yield* acpRegistrySessions.sessionManager(input.instanceId);
1677
if (input.headers !== undefined && Object.keys(input.headers).length > 32) {
1678
return yield* new AcpRegistryOperationError({
1679
reason: "provider_configuration_failed",
@@ -1855,8 +1714,8 @@ export const layerWsRpc = (
1714
const disableAcpRegistryProvider = Effect.fn("ws.acpRegistry.disableProvider")(function* (
1715
input: AcpRegistryDisableProviderInput,
1716
) {
1858
- const project = yield* acpRegistryProject(input.projectId);
1859
- const { manager } = yield* acpSessionManager(input.instanceId);
1717
+ const project = yield* acpRegistrySessions.project(input.projectId);
1718
+ const { manager } = yield* acpRegistrySessions.sessionManager(input.instanceId);
1719
const listed = yield* manager.listProviders(project.workspaceRoot);
1720
const provider = listed.providers.find(
1721
(candidate) => candidate.providerId === input.providerId,
@@ -2430,7 +2289,7 @@ export const layerWsRpc = (
2289
Effect.annotateCurrentSpan({
2290
"provider.instance_id": input.instanceId,
2291
"project.id": input.projectId,
2433
- }).pipe(Effect.andThen(importAcpRegistrySession(input))),
2292
+ }).pipe(Effect.andThen(acpRegistrySessions.importSession(input))),
2293
[WS_METHODS.serverDeleteAcpRegistrySession]: (input) =>
2294
Effect.annotateCurrentSpan({
2295
"provider.instance_id": input.instanceId,
@@ -2455,7 +2314,9 @@ export const layerWsRpc = (
2314
Effect.annotateCurrentSpan({ "provider.instance_id": input.instanceId }).pipe(
2315
Effect.andThen(
2316
Effect.gen(function* () {
2458
- const { instance, manager } = yield* acpSessionManager(input.instanceId);
2317
+ const { instance, manager } = yield* acpRegistrySessions.sessionManager(
2318
+ input.instanceId,
2319
+ );
2320
const snapshot = yield* instance.snapshot.getSnapshot;
2321
if (snapshot.auth.canLogout !== true) {
2322
return yield* new AcpRegistryOperationError({
@@ -3612,6 +3473,7 @@ export const layer = Layer.unwrap(
3473
Layer.provide(DefectReporter.layer),
3474
Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)),
3475
Layer.provide(AgentSessionScanner.layer),
3476
+ Layer.provide(AcpRegistrySessions.layer),
3477
Layer.provide(ProviderMaintenanceRunner.layer),
3478
Layer.provide(Layer.succeed(NpmRelease.NpmRelease, npmRelease)),
3479
Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),
apps/web/src/components/settings/AcpSessionManagementSection.tsx
+7
-3
@@ -34,6 +34,10 @@ interface AcpSessionProject {
34
readonly workspaceRoot: string;
35
}
36
37
+function needsImport(session: AcpRegistrySession) {
38
+ return session.importedThreadId === null || session.nativeHistoryPending === true;
39
+}
40
+
41
function reportFailure(title: string, result: AtomCommandResult<unknown, unknown>) {
42
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
43
const error = squashAtomCommandFailure(result);
@@ -223,7 +227,7 @@ function InstanceSessionManagement(
227
setSessions((current) =>
228
current.map((candidate) =>
229
candidate.sessionId === session.sessionId
226
- ? { ...candidate, importedThreadId: result.value.threadId }
230
+ ? { ...candidate, importedThreadId: result.value.threadId, nativeHistoryPending: false }
231
: candidate,
232
),
233
);
@@ -472,12 +476,12 @@ function InstanceSessionManagement(
476
disabled={
477
!canOperate ||
478
!canImport ||
475
- session.importedThreadId !== null ||
479
+ !needsImport(session) ||
480
importingSessionId !== null
481
}
482
onClick={() => void importNativeSession(session)}
483
>
480
- {session.importedThreadId !== null
484
+ {!needsImport(session)
485
? "Imported"
486
: importingSessionId === session.sessionId
487
? "Importing"
packages/contracts/src/acpRegistry.ts
+2
@@ -149,6 +149,8 @@ export const AcpRegistrySession = Schema.Struct({
149
title: Schema.NullOr(Schema.String.check(Schema.isMaxLength(1_024))),
150
updatedAt: Schema.NullOr(Schema.String.check(Schema.isMaxLength(128))),
151
importedThreadId: Schema.NullOr(ThreadId),
152
+ /** The imported thread still lacks the session's history, so importing again copies it. */
153
+ nativeHistoryPending: Schema.optionalKey(Schema.Boolean),
154
});
155
export type AcpRegistrySession = typeof AcpRegistrySession.Type;
156
packages/provider-acp/src/server/adapter.ts
+26
-36
@@ -1641,11 +1641,22 @@ type PendingRuntimeRequest = {
1641
interface SnapshotMessageState {
1642
readonly order: Array<string>;
1643
readonly messages: Map<string, OrchestrationV2ConversationMessage>;
1644
+ /** Messages loaded from thought chunks; `messages` stores them as assistant text. */
1645
+ readonly reasoningIds: ReadonlySet<OrchestrationV2ConversationMessage["id"]>;
1646
loadingRole: "user" | "assistant" | "thought" | null;
1647
loadingMessageId: string | null;
1648
loadingIndex: number;
1649
}
1650
1651
+const emptySnapshotState = (): SnapshotMessageState => ({
1652
+ order: [],
1653
+ messages: new Map(),
1654
+ reasoningIds: new Set(),
1655
+ loadingRole: null,
1656
+ loadingMessageId: null,
1657
+ loadingIndex: 0,
1658
+});
1659
+
1660
/** How long a Stop waits for the agent to confirm before the user is offered Force stop. */
1661
const ACP_STOP_CONFIRM_TIMEOUT_MS = 10_000;
1662
const TOOL_UPDATE_PERSIST_EVERY = 10;
@@ -1962,13 +1973,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1973
options.testHooks?.onNativeResponseLifecycle ?? (() => Effect.void);
1974
const nextElicitationOrdinal = yield* Ref.make(0);
1975
const providerTurns = yield* Ref.make(new Map<string, OrchestrationV2ProviderTurn>());
1965
- const snapshot = yield* Ref.make<SnapshotMessageState>({
1966
- order: [],
1967
- messages: new Map(),
1968
- loadingRole: null,
1969
- loadingMessageId: null,
1970
- loadingIndex: 0,
1971
- });
1976
+ const snapshot = yield* Ref.make(emptySnapshotState());
1977
1978
const awaitRuntimeTeardown = Effect.fnUntraced(function* () {
1979
const state = yield* Ref.get(runtimeTeardownState);
@@ -4548,6 +4553,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4553
return {
4554
order: current.order.includes(key) ? current.order : [...current.order, key],
4555
messages,
4556
+ reasoningIds:
4557
+ role === "thought" && !current.reasoningIds.has(messageId)
4558
+ ? new Set(current.reasoningIds).add(messageId)
4559
+ : current.reasoningIds,
4560
loadingRole: role,
4561
loadingMessageId: sourceMessageId ?? (startsNew ? null : current.loadingMessageId),
4562
loadingIndex,
@@ -7105,13 +7114,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7114
yield* Ref.set(promptInstructionStates, new Map());
7115
yield* Ref.set(compactionMarkers, new Map());
7116
yield* Ref.set(providerTurns, new Map());
7108
- yield* Ref.set(snapshot, {
7109
- order: [],
7110
- messages: new Map(),
7111
- loadingRole: null,
7112
- loadingMessageId: null,
7113
- loadingIndex: 0,
7114
- });
7117
+ yield* Ref.set(snapshot, emptySnapshotState());
7118
yield* continuationPermit.withPermit(
7119
Effect.gen(function* () {
7120
yield* Ref.update(continuationGeneration, (value) => value + 1);
@@ -8049,13 +8052,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8052
yield* Ref.set(activeSessionSetup, null);
8053
yield* Ref.set(activeSelection, null);
8054
yield* Ref.set(activeInteractionMode, null);
8052
- yield* Ref.set(snapshot, {
8053
- order: [],
8054
- messages: new Map(),
8055
- loadingRole: null,
8056
- loadingMessageId: null,
8057
- loadingIndex: 0,
8058
- });
8055
+ yield* Ref.set(snapshot, emptySnapshotState());
8056
return true;
8057
});
8058
@@ -8575,7 +8572,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8572
!restartRequired &&
8573
!transportHadOutstandingResponses
8574
) {
8578
- yield* runtime.closeSession().pipe(Effect.ignore);
8575
+ // Finalizers can't be interrupted, so an agent that never
8576
+ // answers would keep its process and this scope open.
8577
+ yield* runtime
8578
+ .closeSession()
8579
+ .pipe(Effect.timeoutOption("10 seconds"), Effect.ignore);
8580
}
8581
}),
8582
);
@@ -8733,13 +8734,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8734
threadInput.providerThread.appThreadId,
8735
).pipe(Effect.tapError(() => restorePreviousItemIdentity));
8736
if ((yield* Ref.get(activeSessionId)) !== sessionId || restartAfterInterrupt) {
8736
- yield* Ref.set(snapshot, {
8737
- order: [],
8738
- messages: new Map(),
8739
- loadingRole: null,
8740
- loadingMessageId: null,
8741
- loadingIndex: 0,
8742
- });
8737
+ yield* Ref.set(snapshot, emptySnapshotState());
8738
const activated = yield* activateSession(
8739
sessionId,
8740
threadInput.providerThread.appThreadId,
@@ -9237,13 +9232,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9232
detail: "ACP driver does not support session/load snapshots",
9233
});
9234
}
9240
- yield* Ref.set(snapshot, {
9241
- order: [],
9242
- messages: new Map(),
9243
- loadingRole: null,
9244
- loadingMessageId: null,
9245
- loadingIndex: 0,
9246
- });
9235
+ yield* Ref.set(snapshot, emptySnapshotState());
9236
const mcpContext = yield* readMcpContext(
9237
snapshotInput.providerThread.appThreadId,
9238
);
@@ -9275,6 +9264,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9264
const message = state.messages.get(key);
9265
return message === undefined ? [] : [message];
9266
}),
9267
+ reasoningMessageIds: [...state.reasoningIds],
9268
runtimeRequests: [],
9269
providerPayload: { protocol: ACP_PROTOCOL, sessionId },
9270
};
packages/provider-core/src/server/ProviderAdapter.ts
+2
@@ -540,6 +540,8 @@ export interface ProviderAdapterV2ThreadSnapshot {
540
readonly providerThread: OrchestrationV2ProviderThread;
541
readonly providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
542
readonly messages: ReadonlyArray<OrchestrationV2ConversationMessage>;
543
+ /** Ids in `messages` that hold the agent's reasoning, not its reply. */
544
+ readonly reasoningMessageIds?: ReadonlyArray<OrchestrationV2ConversationMessage["id"]>;
545
readonly runtimeRequests: ReadonlyArray<OrchestrationV2RuntimeRequest>;
546
readonly providerPayload?: unknown;
547
}