462 lines · 15.7 KB · TypeScript
RawDownload
import { expect, it, vi } from "vite-plus/test";import { it as effectIt } from "@effect/vitest";import {  CheckpointScopeId,  MessageId,  NodeId,  ProviderSessionId,  ProviderThreadId,  ProviderDriverKind,  ProviderInstanceId,  ProviderSetupError,  RunAttemptId,  RunId,  ThreadId,  ProjectId,  type OrchestrationV2ThreadProjection,  OrchestrationV2DomainEvent,} from "@t3tools/contracts";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Schema from "effect/Schema"; import * as GitWorkflow from "../git/GitWorkflowService.ts";import * as ProjectService from "../project/ProjectService.ts";import { ProviderAuthService } from "../provider/Services/ProviderAuthService.ts";import * as ContextHandoffService from "./ContextHandoffService.ts";import * as EventSink from "./EventSink.ts";import * as IdAllocator from "./IdAllocator.ts";import * as ProjectionStore from "./ProjectionStore.ts";import * as ProviderSessionManager from "./ProviderSessionManager.ts";import * as ProviderTurnStart from "./ProviderTurnStartService.ts";import * as RunExecutionService from "./RunExecutionService.ts";import * as RuntimePolicy from "./RuntimePolicy.ts"; const isDomainEvent = Schema.is(OrchestrationV2DomainEvent); it("does not commit running state when inherited background routing cannot be read", async () => {  const threadId = ThreadId.make("thread_provider_turn_start_projection_failure");  const runId = RunId.make("run_provider_turn_start_projection_failure");  const attemptId = RunAttemptId.make("attempt_provider_turn_start_projection_failure");  const rootNodeId = NodeId.make("node_provider_turn_start_projection_failure");  const providerThreadId = ProviderThreadId.make(    "provider_thread_provider_turn_start_projection_failure",  );  const providerSessionId = ProviderSessionId.make(    "provider_session_provider_turn_start_projection_failure",  );  const messageId = MessageId.make("message_provider_turn_start_projection_failure");  const checkpointScopeId = CheckpointScopeId.make(    "checkpoint_scope_provider_turn_start_projection_failure",  );  const projection = {    thread: {      id: threadId,      projectId: ProjectId.make("project_provider_turn_start_projection_failure"),      branch: "feature/restore",      worktreePath: "/tmp/missing-provider-turn-start-worktree",    },    runs: [      {        id: runId,        status: "starting",        rootNodeId,        activeAttemptId: attemptId,        providerThreadId,        userMessageId: messageId,        ordinal: 2,      },    ],    nodes: [{ id: rootNodeId, checkpointScopeId }],    attempts: [{ id: attemptId }],    providerThreads: [{ id: providerThreadId, providerSessionId }],    messages: [{ id: messageId, text: "Continue", attachments: [] }],    checkpointScopes: [{ id: checkpointScopeId }],    contextHandoffs: [],    contextTransfers: [],    turnItems: [],  } as unknown as OrchestrationV2ThreadProjection;  let projectionReadCount = 0;  const writeIfRunCurrent = vi.fn(() =>    Effect.succeed({ committed: true, storedEvents: [] } as never),  );  const startRootRun = vi.fn(() => Effect.void);  const pruneWorktrees = vi.fn(() => Effect.void);  const createWorktree = vi.fn(() => Effect.succeed({} as never));  const layer = ProviderTurnStart.layer.pipe(    Layer.provide(      Layer.mergeAll(        Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),        Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),        IdAllocator.layer,        Layer.succeed(FileSystem.FileSystem, { exists: () => Effect.succeed(false) } as never),        Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees, createWorktree }),        Layer.mock(ProjectService.ProjectService)({          getById: () =>            Effect.succeed(              Option.some({ workspaceRoot: "/tmp/provider-turn-start-project" } as never),            ),        }),        Layer.mock(ProjectionStore.ProjectionStoreV2)({          getThreadProjection: () => {            projectionReadCount += 1;            return projectionReadCount === 1              ? Effect.succeed(projection)              : Effect.fail(                  new ProjectionStore.ProjectionStoreReadError({                    threadId,                    cause: "simulated inherited-background projection failure",                  }),                );          },        }),        Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),        Layer.mock(ProviderAuthService)({ tryHandlePromptCommand: () => Effect.succeed(false) }),        Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),        Layer.mock(RuntimePolicy.RuntimePolicyV2)({}),      ),    ),  );   await Effect.gen(function* () {    const error = yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2)      .start({ threadId, runId })      .pipe(Effect.flip);     expect(error._tag).toBe("ProviderTurnStartError");    expect(projectionReadCount).toBe(2);    expect(pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" });    expect(createWorktree).toHaveBeenCalledWith({      cwd: "/tmp/provider-turn-start-project",      refName: "feature/restore",      path: "/tmp/missing-provider-turn-start-worktree",    });    expect(writeIfRunCurrent).not.toHaveBeenCalled();    expect(startRootRun).not.toHaveBeenCalled();  }).pipe(Effect.provide(layer), Effect.runPromise);}); function makeLocalCommandHarness(input: {  readonly text: string;  readonly previousNativeSession?: boolean;  readonly previousMessages?: ReadonlyArray<string>;  readonly logoutFailure?: string;}) {  const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");  const threadId = ThreadId.make("thread-native-account-command");  const runId = RunId.make("run-native-account-command");  const rootNodeId = NodeId.make("root-native-account-command");  const attemptId = RunAttemptId.make("attempt-native-account-command");  const providerThreadId = ProviderThreadId.make("new-provider-thread");  const providerSessionId = ProviderSessionId.make("new-provider-session");  const oldProviderThreadId = ProviderThreadId.make("existing-native-provider-thread");  const oldInstanceId = ProviderInstanceId.make("antigravity-personal");  const newInstanceId = ProviderInstanceId.make("codex-personal");  const checkpointScopeId = CheckpointScopeId.make("scope-native-account-command");  const messageId = MessageId.make("message-native-account-command");  const run: OrchestrationV2ThreadProjection["runs"][number] = {    id: runId,    threadId,    ordinal: 2,    providerInstanceId: newInstanceId,    modelSelection: { instanceId: newInstanceId, model: "gpt-5.4" },    providerThreadId,    userMessageId: messageId,    rootNodeId,    activeAttemptId: attemptId,    status: "starting",    requestedAt: now,    startedAt: null,    completedAt: null,    checkpointId: null,    contextHandoffId: null,  };  const providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] = {    id: providerThreadId,    driver: ProviderDriverKind.make("codex"),    providerInstanceId: newInstanceId,    providerSessionId,    appThreadId: threadId,    ownerNodeId: null,    nativeThreadRef: null,    nativeConversationHeadRef: null,    status: "not_loaded",    firstRunOrdinal: 2,    lastRunOrdinal: 2,    handoffIds: [],    forkedFrom: null,    createdAt: now,    updatedAt: now,  };  const message: OrchestrationV2ThreadProjection["messages"][number] = {    id: messageId,    threadId,    runId,    nodeId: rootNodeId,    role: "user",    text: input.text,    attachments: [],    streaming: false,    createdBy: "user",    creationSource: "web",    createdAt: now,    updatedAt: now,  };  let projection: OrchestrationV2ThreadProjection = {    thread: {      id: threadId,      activeProviderThreadId: providerThreadId,      branch: null,      worktreePath: null,    } as OrchestrationV2ThreadProjection["thread"],    runs: [      ...(input.previousNativeSession        ? [            {              ...run,              id: RunId.make("previous-native-run"),              ordinal: 1,              status: "completed" as const,              providerInstanceId: oldInstanceId,              providerThreadId: oldProviderThreadId,            },          ]        : []),      run,    ],    attempts: [      {        id: attemptId,        runId,        rootNodeId,        attemptOrdinal: 1,        providerInstanceId: newInstanceId,        providerThreadId,        providerTurnId: null,        reason: "initial",        status: "pending",        startedAt: null,        completedAt: null,      },    ],    nodes: [      {        id: rootNodeId,        threadId,        runId,        parentNodeId: null,        rootNodeId,        kind: "root_turn",        status: "pending",        countsForRun: true,        providerThreadId,        providerTurnId: null,        nativeItemRef: null,        runtimeRequestId: null,        checkpointScopeId,        startedAt: null,        completedAt: null,      },    ],    providerThreads: [      ...(input.previousNativeSession        ? [            {              ...providerThread,              id: oldProviderThreadId,              providerInstanceId: oldInstanceId,              driver: ProviderDriverKind.make("antigravity"),              lastRunOrdinal: 1,              nativeThreadRef: {                driver: ProviderDriverKind.make("antigravity"),                nativeId: "existing-session",                strength: "strong" as const,              },            },          ]        : []),      providerThread,    ],    messages: [      ...(input.previousMessages ?? []).map((text, index) => ({        ...message,        id: MessageId.make(`previous-message-${index}`),        text,      })),      message,    ],    checkpointScopes: [      {        id: checkpointScopeId,        threadId,        runId,        nodeId: rootNodeId,        parentScopeId: null,        providerThreadId,        kind: "root_run",        ordinalWithinParent: 0,        advancesAppRunCount: true,        cwd: "/tmp/native-account-command",        createdAt: now,      },    ],    providerSessions: [],    providerTurns: [],    contextHandoffs: [],    contextTransfers: [],    turnItems: [],    visibleTurnItems: [],    runtimeRequests: [],    subagents: [],    plans: [],    checkpoints: [],    updatedAt: now,  };  const events: Array<OrchestrationV2DomainEvent> = [];  const open = vi.fn(() => Effect.die("A local command must not open a native session."));  const startRootRun = vi.fn(() => Effect.die("A local command must not start a native turn."));  const tryHandlePromptCommand = vi.fn(() =>    input.logoutFailure === undefined      ? Effect.succeed(true)      : Effect.fail(          new ProviderSetupError({            instanceId: oldInstanceId,            operation: "logout",            detail: input.logoutFailure,          }),        ),  );  const layer = ProviderTurnStart.layer.pipe(    Layer.provide(      Layer.mergeAll(        Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),        Layer.mock(EventSink.EventSinkV2)({          writeIfRunCurrent: ({ events: incoming, activeAttemptId, expectedStatus }) =>            Effect.sync(() => {              const current = projection.runs.find((candidate) => candidate.id === runId);              const committed =                current?.activeAttemptId === activeAttemptId && current.status === expectedStatus;              if (committed) {                for (const event of incoming) {                  expect(isDomainEvent(event)).toBe(true);                  events.push(event);                  projection = ProjectionStore.applyToProjection(projection, event);                }              }              return { committed, storedEvents: [] };            }),        }),        IdAllocator.layer,        FileSystem.layerNoop({}),        Layer.mock(GitWorkflow.GitWorkflowService)({}),        Layer.mock(ProjectService.ProjectService)({}),        Layer.mock(ProjectionStore.ProjectionStoreV2)({          getThreadProjection: () => Effect.succeed(projection),        }),        Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }),        Layer.mock(ProviderAuthService)({ tryHandlePromptCommand }),        Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),        Layer.mock(RuntimePolicy.RuntimePolicyV2)({}),      ),    ),  );  return {    open,    startRootRun,    tryHandlePromptCommand,    events,    oldInstanceId,    newInstanceId,    projection: () => projection,    start: Effect.gen(function* () {      yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2).start({ threadId, runId });    }).pipe(Effect.provide(layer)),  };} effectIt.effect(  "signs out the existing native provider before opening the newly selected provider",  () =>    Effect.gen(function* () {      const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true });       yield* harness.start;      yield* harness.start;       expect(harness.tryHandlePromptCommand).toHaveBeenCalledExactlyOnceWith({        instanceId: harness.oldInstanceId,        text: "/logout",        hasAttachments: false,      });      expect(harness.open).not.toHaveBeenCalled();      expect(harness.startRootRun).not.toHaveBeenCalled();      const projection = harness.projection();      expect(projection.runs.at(-1)?.status).toBe("completed");      expect(projection.attempts[0]?.status).toBe("completed");      expect(projection.nodes[0]?.status).toBe("completed");      expect(projection.turnItems).toMatchObject([        {          type: "command_execution",          title: "Provider signed out",          output: "Provider signed out",          status: "completed",        },      ]);      expect(projection.providerTurns).toEqual([]);      expect(projection.checkpoints).toEqual([]);    }),); effectIt.effect("persists a failed sign-out without starting a provider turn", () =>  Effect.gen(function* () {    const harness = makeLocalCommandHarness({      text: "/logout",      logoutFailure: "Could not stop all sessions for this provider. Try again.",    });     yield* harness.start;     expect(harness.open).not.toHaveBeenCalled();    expect(harness.startRootRun).not.toHaveBeenCalled();    expect(harness.projection().runs.at(-1)?.status).toBe("failed");    expect(harness.projection().turnItems).toMatchObject([      {        type: "error",        title: "Provider sign-out failed",        failure: {          class: "permission_error",          message: "Could not stop all sessions for this provider. Try again.",        },      },    ]);  }),); for (const previousMessages of [[], ["/compact", " /COMPACT "]]) {  effectIt.effect(    `rejects compaction without conversation context after ${previousMessages.length} prior compactions`,    () =>      Effect.gen(function* () {        const harness = makeLocalCommandHarness({ text: "/compact", previousMessages });         yield* harness.start;         expect(harness.open).not.toHaveBeenCalled();        expect(harness.tryHandlePromptCommand).not.toHaveBeenCalled();        expect(harness.startRootRun).not.toHaveBeenCalled();        expect(harness.projection().runs.at(-1)?.status).toBe("failed");        expect(harness.projection().turnItems).toMatchObject([          {            type: "error",            failure: {              class: "validation_error",              message: "Start a conversation before compacting this thread.",            },          },        ]);      }),  );}

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t