@devries-cameron20 / t3code-1 / commits / 5b55036f8c
Fork 0

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

fix(server): a fork's first /compact compacts its inherited history (#24172)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 23, 2026 at 20:14 UTC 5b55036f8cf6090c83f835348525248e1f14b3b9
3 files changed +395 -8
apps/server/src/orchestration-v2/ProjectionStore.ts
+30 -7
@@ -351,6 +351,26 @@ const activeRunStatuses: ReadonlySet<ProjectionRun["status"]> = new Set([
351 "waiting",
352 ]);
353
354 +// A fork inherits its source's history before it has messages of its own,
355 +// unless a portable handoff's budget left none of that history to deliver.
356 +const inheritsForkConversation = ({
357 + thread,
358 + contextTransfers,
359 + contextHandoffs,
360 +}: Pick<OrchestrationV2ThreadProjection, "thread" | "contextTransfers" | "contextHandoffs">) => {
361 + if (thread.forkedFrom?.type !== "run") return false;
362 + const resolution = contextTransfers.find(
363 + (transfer) => transfer.type === "fork" && transfer.targetThreadId === thread.id,
364 + )?.resolution;
365 + return (
366 + resolution?.strategy !== "portable_context" ||
367 + contextHandoffs.some(
368 + (handoff) =>
369 + handoff.id === resolution.contextHandoffId && (handoff.history?.messages.length ?? 0) > 0,
370 + )
371 + );
372 +};
373 +
374 // In-memory twin of the omitSettledLeafNodes SQL clause in readCanonicalProjection.
375 const isSettledLeafNode = (node: ProjectionNode, runs: ReadonlyArray<ProjectionRun>) =>
376 settledLeafNodeKinds.has(node.kind) &&
@@ -4265,7 +4285,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4285 ) AS present
4286 `;
4287 return {
4268 - hasConversation: conversation[0]?.present === 1,
4288 + hasConversation:
4289 + conversation[0]?.present === 1 ||
4290 + inheritsForkConversation({ thread, contextTransfers, contextHandoffs }),
4291 thread,
4292 runs,
4293 attempts,
@@ -7249,12 +7271,13 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
7271 service.getThreadProjection(threadId).pipe(
7272 Effect.map((projection) => ({
7273 ...projection,
7252 - hasConversation: projection.messages.some(
7253 - (message) =>
7254 - message.role === "user" &&
7255 - (message.text.trim().toLowerCase() !== "/compact" ||
7256 - message.attachments.length > 0),
7257 - ),
7274 + hasConversation:
7275 + projection.messages.some(
7276 + (message) =>
7277 + message.role === "user" &&
7278 + (message.text.trim().toLowerCase() !== "/compact" ||
7279 + message.attachments.length > 0),
7280 + ) || inheritsForkConversation(projection),
7281 turnItems: projection.turnItems.filter((item) => item.runId === runId),
7282 })),
7283 ),
apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
+216 -1
@@ -20,11 +20,12 @@ import * as TestClock from "effect/testing/TestClock";
20
21 import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
22 import { ClaudeProviderCapabilitiesV2 } from "./Adapters/ClaudeAdapterV2.ts";
23 +import * as EffectWorker from "./EffectWorker.ts";
24 import * as EventSink from "./EventSink.ts";
25 import * as Orchestrator from "./Orchestrator.ts";
26 import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
27 import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
27 -import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
28 +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
29
30 const forkCases = (
31 [
@@ -395,3 +396,217 @@ it.effect.each(forkCases)(
396 assert.isNull(target.providerThreads[0]?.forkedFrom);
397 }).pipe(Effect.provide(layer)),
398 );
399 +
400 +it.effect.each([
401 + { execution: "portable_context", rejected: true },
402 + { execution: "native_fork", rejected: false },
403 +] as const)(
404 + "a $execution fork's first /compact is rejected only when no history reaches it: $rejected",
405 + ({ execution, rejected }) => {
406 + const opened: Array<ProviderInstanceId> = [];
407 + const adapter = (driverName: "claudeAgent" | "codex") => {
408 + const driver = ProviderDriverKind.make(driverName);
409 + const instanceId = ProviderInstanceId.make(driverName);
410 + return {
411 + instanceId,
412 + driver,
413 + getCapabilities: () =>
414 + Effect.succeed(
415 + driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
416 + ),
417 + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
418 + openSession: (input) =>
419 + Effect.sync(() => opened.push(instanceId)).pipe(
420 + Effect.andThen(
421 + new ProviderAdapter.ProviderAdapterOpenSessionError({
422 + driver,
423 + providerSessionId: input.providerSessionId,
424 + }),
425 + ),
426 + ),
427 + } satisfies ProviderAdapter.ProviderAdapterV2["Service"];
428 + };
429 + const claude = adapter("claudeAgent");
430 + const target = execution === "portable_context" ? adapter("codex") : claude;
431 + return Effect.gen(function* () {
432 + const orchestrator = yield* Orchestrator.OrchestratorV2;
433 + const eventSink = yield* EventSink.EventSinkV2;
434 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
435 + const now = yield* DateTime.now;
436 + const sourceThreadId = ThreadId.make("fork-compact-source");
437 + const targetThreadId = ThreadId.make("fork-compact-target");
438 + const providerThreadId = ProviderThreadId.make("fork-compact-native-thread");
439 + const sourceRunId = RunId.make("fork-compact-source-run");
440 + const userMessageId = MessageId.make("fork-compact-source-message");
441 + const sourceSelection = { instanceId: claude.instanceId, model: "test-model" };
442 +
443 + yield* orchestrator.dispatch({
444 + type: "thread.create",
445 + commandId: CommandId.make("fork-compact-create-source"),
446 + threadId: sourceThreadId,
447 + projectId: ProjectId.make("fork-compact-project"),
448 + title: "Fork compact source",
449 + modelSelection: sourceSelection,
450 + runtimeMode: "full-access",
451 + interactionMode: "default",
452 + branch: null,
453 + worktreePath: null,
454 + createdBy: "user",
455 + creationSource: "web",
456 + });
457 + const item = {
458 + threadId: sourceThreadId,
459 + runId: sourceRunId,
460 + nodeId: null,
461 + providerThreadId,
462 + providerTurnId: null,
463 + nativeItemRef: null,
464 + parentItemId: null,
465 + status: "completed",
466 + title: null,
467 + startedAt: now,
468 + completedAt: now,
469 + updatedAt: now,
470 + } as const;
471 + yield* eventSink.write({
472 + events: [
473 + {
474 + id: EventId.make("fork-compact-provider-thread"),
475 + type: "provider-thread.updated",
476 + threadId: sourceThreadId,
477 + occurredAt: now,
478 + payload: {
479 + id: providerThreadId,
480 + driver: claude.driver,
481 + providerInstanceId: claude.instanceId,
482 + providerSessionId: null,
483 + appThreadId: sourceThreadId,
484 + ownerNodeId: null,
485 + nativeThreadRef: {
486 + driver: claude.driver,
487 + nativeId: "native-fork-compact-source",
488 + strength: "strong",
489 + },
490 + nativeConversationHeadRef: null,
491 + status: "idle",
492 + firstRunOrdinal: 1,
493 + lastRunOrdinal: 1,
494 + handoffIds: [],
495 + forkedFrom: null,
496 + createdAt: now,
497 + updatedAt: now,
498 + },
499 + },
500 + {
501 + id: EventId.make("fork-compact-source-run"),
502 + type: "run.created",
503 + threadId: sourceThreadId,
504 + runId: sourceRunId,
505 + occurredAt: now,
506 + payload: {
507 + id: sourceRunId,
508 + threadId: sourceThreadId,
509 + ordinal: 1,
510 + providerInstanceId: claude.instanceId,
511 + modelSelection: sourceSelection,
512 + providerThreadId,
513 + userMessageId,
514 + rootNodeId: null,
515 + activeAttemptId: null,
516 + status: "completed",
517 + queuePosition: null,
518 + requestedAt: now,
519 + startedAt: now,
520 + completedAt: now,
521 + checkpointId: null,
522 + contextHandoffId: null,
523 + },
524 + },
525 + // Each message alone exceeds the default 16k handoff budget, so a
526 + // portable handoff omits both whole items.
527 + {
528 + id: EventId.make("fork-compact-user-item"),
529 + type: "turn-item.updated",
530 + threadId: sourceThreadId,
531 + runId: sourceRunId,
532 + occurredAt: now,
533 + payload: {
534 + ...item,
535 + id: TurnItemId.make("fork-compact-user-item"),
536 + ordinal: 1,
537 + type: "user_message",
538 + createdBy: "user",
539 + creationSource: "web",
540 + inputIntent: "turn_start",
541 + messageId: userMessageId,
542 + text: "u".repeat(17_000),
543 + attachments: [],
544 + },
545 + },
546 + {
547 + id: EventId.make("fork-compact-assistant-item"),
548 + type: "turn-item.updated",
549 + threadId: sourceThreadId,
550 + runId: sourceRunId,
551 + occurredAt: now,
552 + payload: {
553 + ...item,
554 + id: TurnItemId.make("fork-compact-assistant-item"),
555 + ordinal: 2,
556 + type: "assistant_message",
557 + messageId: MessageId.make("fork-compact-assistant-message"),
558 + text: "a".repeat(17_000),
559 + streaming: false,
560 + },
561 + },
562 + ],
563 + });
564 + yield* orchestrator.dispatch({
565 + type: "thread.fork",
566 + commandId: CommandId.make("fork-compact-fork"),
567 + sourceThreadId,
568 + targetThreadId,
569 + sourcePoint: { type: "run", runId: sourceRunId },
570 + createdBy: "user",
571 + creationSource: "web",
572 + });
573 + yield* orchestrator.dispatch({
574 + type: "message.dispatch",
575 + commandId: CommandId.make("fork-compact-compact"),
576 + threadId: targetThreadId,
577 + messageId: MessageId.make("fork-compact-compact"),
578 + text: "/compact",
579 + attachments: [],
580 + modelSelection: { instanceId: target.instanceId, model: "test-model" },
581 + dispatchMode: { type: "start_immediately" },
582 + createdBy: "user",
583 + creationSource: "web",
584 + });
585 + yield* worker.drain();
586 +
587 + const projection = yield* orchestrator.getThreadProjection(targetThreadId);
588 + if (execution === "portable_context") {
589 + assert.equal(projection.contextTransfers[0]?.resolution?.strategy, "portable_context");
590 + assert.deepEqual(projection.contextHandoffs[0]?.history?.messages, []);
591 + } else {
592 + assert.isEmpty(projection.contextHandoffs);
593 + }
594 + const emptyCompaction = projection.turnItems.some(
595 + (turnItem) =>
596 + turnItem.type === "error" &&
597 + turnItem.failure.message === "Start a conversation before compacting this thread.",
598 + );
599 + assert.equal(emptyCompaction, rejected);
600 + assert.deepEqual(opened, rejected ? [] : [target.instanceId]);
601 + }).pipe(
602 + Effect.provide(
603 + ProviderReplayHarness.layerWithRegistry(
604 + { name: `fork-compact-${execution}` },
605 + ProviderAdapterRegistry.layerFromAdapters(
606 + target === claude ? [claude] : [claude, target],
607 + ),
608 + ),
609 + ),
610 + );
611 + },
612 +);
apps/server/src/orchestration-v2/TurnStartReads.test.ts
+149
@@ -1,10 +1,12 @@
1 import { assert, it } from "@effect/vitest";
2 import {
3 CheckpointScopeId,
4 + ContextTransferId,
5 NodeId,
6 EventId,
7 MessageId,
8 ProjectId,
9 + ProviderDriverKind,
10 ProviderInstanceId,
11 RunId,
12 ThreadId,
@@ -366,3 +368,150 @@ it.effect.each(["sqlite", "memory"] as const)(
368 ),
369 ),
370 );
371 +
372 +it.effect.each(["sqlite", "memory"] as const)(
373 + "counts a native fork's inherited history as conversation for its first /compact in %s",
374 + (storage) =>
375 + Effect.gen(function* () {
376 + const store = yield* ProjectionStore.ProjectionStoreV2;
377 + const now = yield* DateTime.now;
378 + const instanceId = ProviderInstanceId.make("claudeAgent");
379 + const sourceId = ThreadId.make("thread:fork-source");
380 + const forkId = ThreadId.make("thread:fork-target");
381 + const sourceRunId = RunId.make("run:fork-source-third");
382 + const forkRunId = RunId.make("run:fork-compact");
383 + const source: OrchestrationV2AppThread = {
384 + id: sourceId,
385 + projectId: ProjectId.make("project:fork-compact"),
386 + title: "Source",
387 + providerInstanceId: instanceId,
388 + modelSelection: { instanceId, model: "claude-opus-5-5" },
389 + runtimeMode: "full-access",
390 + interactionMode: "default",
391 + branch: null,
392 + worktreePath: null,
393 + activeProviderThreadId: null,
394 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: sourceId },
395 + forkedFrom: null,
396 + createdBy: "user",
397 + creationSource: "web",
398 + createdAt: now,
399 + updatedAt: now,
400 + archivedAt: null,
401 + settledOverride: null,
402 + settledAt: null,
403 + lastVisitedAt: null,
404 + deletedAt: null,
405 + };
406 + const fork: OrchestrationV2AppThread = {
407 + ...source,
408 + id: forkId,
409 + title: "Fork",
410 + lineage: { parentThreadId: sourceId, relationshipToParent: "fork", rootThreadId: sourceId },
411 + forkedFrom: { type: "run", threadId: sourceId, runId: sourceRunId },
412 + };
413 + const run = (threadId: ThreadId, id: RunId, status: OrchestrationV2Run["status"]) =>
414 + ({
415 + id,
416 + threadId,
417 + ordinal: 1,
418 + providerInstanceId: instanceId,
419 + modelSelection: source.modelSelection,
420 + providerThreadId: null,
421 + userMessageId: MessageId.make(`message:${id}`),
422 + rootNodeId: NodeId.make(`node:${id}`),
423 + activeAttemptId: null,
424 + status,
425 + requestedAt: now,
426 + startedAt: null,
427 + completedAt: null,
428 + checkpointId: null,
429 + contextHandoffId: null,
430 + }) satisfies OrchestrationV2Run;
431 + const userMessage = (threadId: ThreadId, runId: RunId, text: string) =>
432 + store.apply({
433 + id: EventId.make(`event:message:${runId}`),
434 + type: "message.updated",
435 + threadId,
436 + runId,
437 + occurredAt: now,
438 + payload: {
439 + id: MessageId.make(`message:${runId}`),
440 + threadId,
441 + runId,
442 + nodeId: null,
443 + role: "user",
444 + text,
445 + attachments: [],
446 + streaming: false,
447 + createdBy: "user",
448 + creationSource: "web",
449 + createdAt: now,
450 + updatedAt: now,
451 + },
452 + });
453 + for (const thread of [source, fork]) {
454 + yield* store.apply({
455 + id: EventId.make(`event:thread:${thread.id}`),
456 + type: "thread.created",
457 + threadId: thread.id,
458 + occurredAt: now,
459 + payload: thread,
460 + });
461 + }
462 + for (const [threadId, value] of [
463 + [sourceId, run(sourceId, sourceRunId, "completed")],
464 + [forkId, run(forkId, forkRunId, "queued")],
465 + ] as const) {
466 + yield* store.apply({
467 + id: EventId.make(`event:run:${value.id}`),
468 + type: "run.updated",
469 + threadId,
470 + runId: value.id,
471 + occurredAt: now,
472 + payload: value,
473 + });
474 + }
475 + yield* userMessage(sourceId, sourceRunId, "THIRD");
476 + yield* store.apply({
477 + id: EventId.make("event:fork-transfer"),
478 + type: "context-transfer.created",
479 + threadId: forkId,
480 + occurredAt: now,
481 + payload: {
482 + id: ContextTransferId.make("transfer:fork-compact"),
483 + type: "fork",
484 + sourceThreadId: sourceId,
485 + targetThreadId: forkId,
486 + sourcePoint: { threadId: sourceId, runId: sourceRunId },
487 + basePoint: null,
488 + sourceProviderInstanceId: instanceId,
489 + targetProviderInstanceId: instanceId,
490 + targetRunId: forkRunId,
491 + status: "pending",
492 + resolution: {
493 + strategy: "native_fork",
494 + providerThreadRef: {
495 + driver: ProviderDriverKind.make("claudeAgent"),
496 + nativeId: "native-fork-source",
497 + strength: "strong",
498 + },
499 + },
500 + createdBy: "user",
501 + error: null,
502 + createdAt: now,
503 + updatedAt: now,
504 + consumedAt: null,
505 + },
506 + });
507 + yield* userMessage(forkId, forkRunId, "/compact");
508 +
509 + assert.isTrue((yield* store.getTurnStartContext(forkId, forkRunId)).hasConversation);
510 + }).pipe(
511 + Effect.provide(
512 + storage === "sqlite"
513 + ? layerDatabase
514 + : Layer.merge(SqlitePersistence.layerMemory, ProjectionStore.layerMemory),
515 + ),
516 + ),
517 +);