@devries-cameron20 / t3code-1 / commits / 2c4622efb4
Fork 0

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

fix(server): the first message on an imported conversation sends its history once (#38575)

Julius Marminge committed Nov 18, 2026 at 04:06 UTC 2c4622efb429dfe68c9dc1ef3cd08668803f874b
6 files changed +250 -4
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+9
@@ -1880,6 +1880,15 @@ describe("ClaudeAdapterV2 resumeThread", () => {
1880 },
1881 });
1882 assert.equal(missing.nativeThreadRef?.nativeId, "native-thread-missing");
1883 +
1884 + // An imported session's history lives only in its transcript.
1885 + const missingImport = yield* Effect.flip(
1886 + runtime.resumeThread({
1887 + providerThread: { ...missing, id: providerThread.id },
1888 + importedNativeSession: true,
1889 + }),
1890 + );
1891 + assert.equal(missingImport._tag, "ProviderAdapterResumeThreadError");
1892 }),
1893 ).pipe(
1894 Effect.provide(
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+9 -2
@@ -14078,7 +14078,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
14078 ),
14079 ),
14080 resumeThread: Effect.fn("ClaudeAdapterV2.resumeThread")(
14081 - function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) {
14081 + function* (threadInput: {
14082 + readonly providerThread: OrchestrationV2ProviderThread;
14083 + readonly importedNativeSession?: boolean;
14084 + }) {
14085 const nativeThreadId = threadInput.providerThread.nativeThreadRef?.nativeId;
14086 if (nativeThreadId !== undefined && nativeThreadId !== null) {
14087 const recordedTitle = threadInput.providerThread.nativeMetadata?.title;
@@ -14102,7 +14105,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
14105 const transcript = yield* claudeTranscriptState(nativeThreadId).pipe(
14106 Effect.orElseSucceed(() => "missing" as const),
14107 );
14105 - if (transcript === "empty") {
14108 + // Opening a missing imported session would start an empty one under its id.
14109 + if (
14110 + transcript === "empty" ||
14111 + (transcript === "missing" && threadInput.importedNativeSession === true)
14112 + ) {
14113 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
14114 driver: CLAUDE_PROVIDER,
14115 detail: `Claude session ${nativeThreadId} has no conversation to resume.`,
apps/server/src/orchestration-v2/Orchestrator.ts
+2 -2
@@ -8087,8 +8087,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8087 });
8088 const legacyImportHandoff = shouldPrepareLegacyImportHandoff({
8089 hasNativeHistory:
8090 - activeProviderThread?.driver === "acpRegistry" &&
8091 - activeProviderThread.nativeThreadRef !== null,
8090 + activeProviderThread !== undefined && activeProviderThread.nativeThreadRef !== null,
8091 historyOrigin: projection.thread.historyOrigin,
8092 hasCompletedRun: latestCompletedRun !== undefined,
8093 legacyImportItemCount: legacyImportItems.length,
@@ -8797,6 +8796,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8796 const legacyImportRecoveryHandoff =
8797 isProviderSwitch &&
8798 !canResumeAcrossInstances &&
8799 + ensuredProviderThread.nativeThreadRef === null &&
8800 latestCompletedRun === undefined &&
8801 legacyImportItems.length > 0
8802 ? yield* contextHandoffService
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+10
@@ -1420,6 +1420,15 @@ export const layer: Layer.Layer<
1420 const nativeSessionLacksKeptTurns =
1421 !session.providerSession.capabilities.checkpointing.providerCanRollbackConversation &&
1422 nativeSessionMissesKeptTurns(projection, providerThread, run);
1423 + // Dispatch prepares no import handoff for a session import: its history is in the native session.
1424 + const importedNativeSession =
1425 + projection.thread.historyOrigin === "v1_import" &&
1426 + !projection.providerTurns.some((turn) => turn.providerThreadId === providerThread.id) &&
1427 + !projection.contextHandoffs.some(
1428 + (handoff) =>
1429 + handoff.toProviderThreadId === providerThread.id &&
1430 + handoff.strategy === "manual_context",
1431 + );
1432 const resumed = yield* Effect.result(
1433 uncertainDelivery || nativeSessionLacksKeptTurns
1434 ? Effect.fail(
@@ -1438,6 +1447,7 @@ export const layer: Layer.Layer<
1447 threadId: projection.thread.id,
1448 modelSelection: run.modelSelection,
1449 runtimePolicy: resolvedRuntimePolicy,
1450 + importedNativeSession,
1451 }),
1452 );
1453 if (resumed._tag === "Success") {
apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+218
@@ -1390,6 +1390,224 @@ describe("orchestration v2 provider switching", () => {
1390 }),
1391 );
1392
1393 + const importedNativeSessionScenario = (
1394 + scenario: "first-send" | "after-failed-switch" | "resume-fails",
1395 + ) =>
1396 + Effect.gen(function* () {
1397 + const cwd = yield* checkpointWorkspace(`imported-native-session-${scenario}`);
1398 + const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1399 + const claudeOrdinal = scenario === "after-failed-switch" ? 2 : 1;
1400 + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
1401 + makeTestAdapter({
1402 + instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1403 + driver: CLAUDE_DRIVER,
1404 + capabilities: ClaudeProviderCapabilitiesV2,
1405 + modelSelection: CLAUDE_MODEL_SELECTION,
1406 + responseByRunOrdinal: { [claudeOrdinal]: "PELICAN" },
1407 + capturedTurns,
1408 + failResume: scenario === "resume-fails",
1409 + }),
1410 + makeTestAdapter({
1411 + instanceId: CODEX_MODEL_SELECTION.instanceId,
1412 + driver: CODEX_DRIVER,
1413 + capabilities: CodexProviderCapabilitiesV2,
1414 + modelSelection: CODEX_MODEL_SELECTION,
1415 + responseByRunOrdinal: {},
1416 + capturedTurns,
1417 + failedRunOrdinals: new Set([1]),
1418 + }),
1419 + ]);
1420 + yield* Effect.gen(function* () {
1421 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1422 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1423 + yield* orchestrator.dispatch({
1424 + type: "thread.create",
1425 + commandId: CommandId.make("imported-native:create"),
1426 + threadId,
1427 + projectId,
1428 + createdBy: "system",
1429 + creationSource: "server",
1430 + title: "Imported Claude Code session",
1431 + modelSelection: CLAUDE_MODEL_SELECTION,
1432 + runtimeMode: "full-access",
1433 + interactionMode: "default",
1434 + branch: null,
1435 + worktreePath: null,
1436 + });
1437 + // The rows AgentSessionImporter writes: imported messages without a run,
1438 + // bound to the strong native session they came from.
1439 + const created = yield* orchestrator.getThreadProjection(threadId);
1440 + const at = created.thread.createdAt;
1441 + const providerThread: OrchestrationV2ProviderThread = {
1442 + id: ProviderThreadId.make("provider-thread:imported-native"),
1443 + driver: CLAUDE_DRIVER,
1444 + providerInstanceId: CLAUDE_MODEL_SELECTION.instanceId,
1445 + providerSessionId: null,
1446 + appThreadId: threadId,
1447 + ownerNodeId: null,
1448 + nativeThreadRef: {
1449 + driver: CLAUDE_DRIVER,
1450 + nativeId: "native-session",
1451 + strength: "strong",
1452 + },
1453 + nativeConversationHeadRef: null,
1454 + status: "idle",
1455 + firstRunOrdinal: null,
1456 + lastRunOrdinal: null,
1457 + handoffIds: [],
1458 + forkedFrom: null,
1459 + createdAt: at,
1460 + updatedAt: at,
1461 + };
1462 + const common = {
1463 + threadId,
1464 + runId: null,
1465 + nodeId: null,
1466 + providerThreadId: null,
1467 + providerTurnId: null,
1468 + nativeItemRef: null,
1469 + parentItemId: null,
1470 + status: "completed" as const,
1471 + title: null,
1472 + startedAt: at,
1473 + completedAt: at,
1474 + updatedAt: at,
1475 + };
1476 + yield* (yield* EventSink.EventSinkV2).write({
1477 + events: [
1478 + {
1479 + id: EventId.make("imported-native:thread"),
1480 + type: "thread.metadata-updated",
1481 + threadId,
1482 + providerInstanceId: CLAUDE_MODEL_SELECTION.instanceId,
1483 + occurredAt: at,
1484 + payload: {
1485 + ...created.thread,
1486 + historyOrigin: "v1_import",
1487 + activeProviderThreadId: providerThread.id,
1488 + },
1489 + },
1490 + {
1491 + id: EventId.make("imported-native:user"),
1492 + type: "turn-item.updated",
1493 + threadId,
1494 + occurredAt: at,
1495 + payload: {
1496 + ...common,
1497 + id: TurnItemId.make("imported-native:user"),
1498 + ordinal: 1,
1499 + createdBy: "user",
1500 + creationSource: "server",
1501 + type: "user_message",
1502 + messageId: MessageId.make("imported-native:user"),
1503 + inputIntent: "turn_start",
1504 + text: "Remember the code word PELICAN.",
1505 + attachments: [],
1506 + },
1507 + },
1508 + {
1509 + id: EventId.make("imported-native:assistant"),
1510 + type: "turn-item.updated",
1511 + threadId,
1512 + occurredAt: at,
1513 + payload: {
1514 + ...common,
1515 + id: TurnItemId.make("imported-native:assistant"),
1516 + ordinal: 2,
1517 + type: "assistant_message",
1518 + messageId: MessageId.make("imported-native:assistant"),
1519 + text: "OK",
1520 + streaming: false,
1521 + },
1522 + },
1523 + {
1524 + id: EventId.make("imported-native:provider-thread"),
1525 + type: "provider-thread.updated",
1526 + threadId,
1527 + driver: CLAUDE_DRIVER,
1528 + providerInstanceId: CLAUDE_MODEL_SELECTION.instanceId,
1529 + occurredAt: at,
1530 + payload: providerThread,
1531 + },
1532 + ],
1533 + });
1534 + const send = (ordinal: number, modelSelection: ModelSelection) =>
1535 + Effect.gen(function* () {
1536 + yield* orchestrator.dispatch({
1537 + type: "message.dispatch",
1538 + commandId: CommandId.make(`imported-native:${ordinal}`),
1539 + threadId,
1540 + messageId: MessageId.make(`imported-native:${ordinal}`),
1541 + createdBy: "user",
1542 + creationSource: "web",
1543 + text: "What was the code word?",
1544 + attachments: [],
1545 + modelSelection,
1546 + dispatchMode: { type: "start_immediately" },
1547 + });
1548 + yield* orchestrator.streamStoredEvents.pipe(
1549 + Stream.filter(
1550 + ({ event }) =>
1551 + event.type === "run.updated" &&
1552 + event.payload.ordinal === ordinal &&
1553 + (event.payload.status === "completed" || event.payload.status === "failed"),
1554 + ),
1555 + Stream.runHead,
1556 + );
1557 + yield* worker.drain();
1558 + });
1559 + if (scenario === "after-failed-switch") yield* send(1, CODEX_MODEL_SELECTION);
1560 + yield* send(claudeOrdinal, CLAUDE_MODEL_SELECTION);
1561 +
1562 + const projection = yield* orchestrator.getThreadProjection(threadId);
1563 + assert.equal(projection.runs.at(-1)?.status, "completed");
1564 + const claudeTurn = (yield* Ref.get(capturedTurns)).findLast(
1565 + (turn) => turn.driver === CLAUDE_DRIVER,
1566 + );
1567 + const importHandoffTargets = projection.contextHandoffs
1568 + .filter((handoff) => handoff.strategy === "manual_context")
1569 + .map((handoff) => handoff.toProviderThreadId);
1570 + if (scenario === "resume-fails") {
1571 + // The replacement session is empty, so the recovery summary carries the import.
1572 + assert.notEqual(claudeTurn?.nativeThreadId, "native-session");
1573 + assert.deepEqual(
1574 + projection.contextHandoffs.map((handoff) => handoff.strategy),
1575 + ["full_thread_summary"],
1576 + );
1577 + assert.include(claudeTurn?.text ?? "", "Remember the code word PELICAN.");
1578 + return;
1579 + }
1580 + assert.equal(claudeTurn?.nativeThreadId, "native-session");
1581 + assert.notInclude(importHandoffTargets, providerThread.id);
1582 + assert.lengthOf(importHandoffTargets, scenario === "after-failed-switch" ? 1 : 0);
1583 + if (scenario === "first-send") assert.deepEqual(projection.contextHandoffs, []);
1584 + assert.notInclude(claudeTurn?.text ?? "", "Remember the code word PELICAN.");
1585 + }).pipe(
1586 + Effect.provide(
1587 + ProviderReplayHarness.layerWithRegistry(
1588 + {
1589 + name: `imported-native-session-${scenario}`,
1590 + runtimePolicyOverride: {
1591 + cwd,
1592 + approvalPolicy: "never",
1593 + sandboxPolicy: { type: "readOnly" },
1594 + },
1595 + },
1596 + layerRegistry,
1597 + ),
1598 + ),
1599 + );
1600 + });
1601 + it.live("resumes an imported native session without resending its history", () =>
1602 + importedNativeSessionScenario("first-send"),
1603 + );
1604 + it.live("returns to an imported native session without resending its history", () =>
1605 + importedNativeSessionScenario("after-failed-switch"),
1606 + );
1607 + it.live("recovers an imported native session's history when its resume fails", () =>
1608 + importedNativeSessionScenario("resume-fails"),
1609 + );
1610 +
1611 it.live.each(["native", "legacy"] as const)(
1612 "starts a replacement native thread as new after the resume fallback with %s attempts",
1613 (attempts) =>
packages/provider-core/src/server/ProviderAdapter.ts
+2
@@ -734,6 +734,8 @@ export interface ProviderAdapterV2SessionRuntime {
734 readonly threadId?: ThreadId;
735 readonly modelSelection?: ModelSelection;
736 readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy;
737 + /** The native session is the only copy of the thread's imported history: fail when it is gone. */
738 + readonly importedNativeSession?: boolean;
739 }) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
740 /** False means the native protocol explicitly does not support history injection. */
741 readonly injectHistory?: (