sailfork / t3code-github / apps/ mobile/ src/ state/ thread-provider-switching.test.ts

import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";

import { threadAllowsProviderSwitch } from "./thread-provider-switching";

const startedThread = {
  latestRun: { id: "run-1" },
  latestUserMessageAt: "2026-06-01T00:00:00.000Z",
  runtime: { status: "idle" },
} as never;

function projectionWithSession(supportsProviderSwitchingViaHandoff: boolean) {
  return {
    thread: { id: "thread", activeProviderThreadId: "provider-thread" },
    runs: [],
    providerThreads: [
      { id: "provider-thread", appThreadId: "thread", providerSessionId: "provider-session" },
    ],
    providerSessions: [
      {
        id: "provider-session",
        status: "running",
        capabilities: { sessions: { supportsProviderSwitchingViaHandoff } },
      },
    ],
  } as unknown as OrchestrationV2ThreadProjection;
}

describe("threadAllowsProviderSwitch", () => {
  it("keeps a started thread on its provider when the session cannot hand off", () => {
    expect(
      threadAllowsProviderSwitch({
        thread: startedThread,
        projection: projectionWithSession(false),
      }),
    ).toBe(false);
  });

  it("allows an imported thread to hand off before opening a provider session", () => {
    expect(
      threadAllowsProviderSwitch({
        thread: startedThread,
        projection: {
          thread: { id: "thread", activeProviderThreadId: null, historyOrigin: "v1_import" },
          runs: [],
          providerThreads: [],
          providerSessions: [],
        } as unknown as OrchestrationV2ThreadProjection,
      }),
    ).toBe(true);
  });

  it("keeps a preparing turn bound before its provider session appears", () => {
    expect(
      threadAllowsProviderSwitch({
        thread: startedThread,
        projection: {
          thread: { id: "thread", activeProviderThreadId: null, historyOrigin: "v1_import" },
          runs: [{ status: "preparing", providerThreadId: "provider-thread" }],
          providerThreads: [],
          providerSessions: [],
        } as unknown as OrchestrationV2ThreadProjection,
      }),
    ).toBe(false);
  });

  it("keeps a started thread bound until its projection resolves a session", () => {
    expect(threadAllowsProviderSwitch({ thread: startedThread, projection: null })).toBe(false);
  });
});