2655 lines · 85.4 KB · TypeScript
RawDownload
import { describe, expect, it } from "vite-plus/test";import { codexFeedbackMessage } from "@t3tools/client-runtime/state/threads"; import {  EventId,  MessageId,  ProjectId,  ProviderInstanceId,  ThreadId,  TurnId,  type OrchestrationThread,  type OrchestrationThreadActivity,} from "@t3tools/contracts"; import {  buildPendingUserInputAnswers,  buildThreadFeed,  derivePendingApprovals,  derivePendingUserInputs,  deriveThreadFeedPresentation,  isPendingUserInputOptionSelected,  setPendingUserInputCustomAnswer,  togglePendingUserInputOptionSelection,  type ThreadFeedActivity,  type ThreadFeedEntry,} from "./threadActivity"; describe("Codex feedback pseudo-messages", () => {  it("keeps pending and completed feedback messages in the mobile thread body", () => {    const pending = {      id: MessageId.make("feedback-command"),      command: "/feedback The agent stopped early.",      createdAt: "2026-08-23T00:00:00.000Z",      status: "uploading" as const,    };    const entries = [codexFeedbackMessage(pending), codexFeedbackMessage(pending, "assistant")].map(      (message) => ({        type: "message" as const,        id: message.id,        createdAt: message.createdAt,        message,      }),    );     expect(deriveThreadFeedPresentation(entries, null, new Set())).toEqual(entries);    expect(entries[1]?.message.text).toBe("Sending feedback to OpenAI...");     const completed = codexFeedbackMessage(      { ...pending, status: "sent", feedbackId: "codex-thread-1" },      "assistant",    );    expect(completed.text).toContain("codex-thread-1");  });}); const singleSelectQuestion = {  id: "runtime",  header: "Runtime",  question: "Which runtime should be used?",  options: [    { label: "Go", description: "One binary" },    { label: "Node.js", description: "Reuse TypeScript" },  ],  multiSelect: false,} as const; const multiSelectQuestion = {  id: "scope",  header: "Scope",  question: "Which data should be collected?",  options: [    { label: "Orders", description: "Receipts" },    { label: "Listings", description: "Inventory" },  ],  multiSelect: true,} as const; const nativeQuestion = {  id: "choice",  header: "File",  question: "Which file should be used?",  options: [    { label: "Use this", description: "First file", value: " choice " },    { label: "Use this", description: "Second file", value: "choice" },  ],  multiSelect: false,  allowCustomAnswer: false,} as const; describe("pending user input answers", () => {  it("accepts free-text answers to async questions without options", () => {    const question = {      id: "0",      header: "Question",      question: "What should it be named?",      options: [],      allowCustomAnswer: true,      multiSelect: false,    };    const requested = makeActivity({      id: EventId.make("async-question"),      kind: "user-input.requested",      summary: "User input requested",      createdAt: "2026-09-03T00:00:00.000Z",      payload: { requestId: "async-1", responseMode: "message", questions: [question] },    });    const questions = derivePendingUserInputs([requested])[0]?.questions;    expect(questions).toEqual([question]);    expect(buildPendingUserInputAnswers(questions!, { "0": { customAnswer: "Example" } })).toEqual({      "0": "Example",    });  });   it("preserves native choice values and custom-answer rules from activities", () => {    const requested = makeActivity({      id: EventId.make("native-question"),      kind: "user-input.requested",      summary: "User input requested",      createdAt: "2026-09-02T00:00:00.000Z",      payload: {        requestId: "interaction_1",        questions: [nativeQuestion, singleSelectQuestion],      },    });     expect(derivePendingUserInputs([requested])).toEqual([      {        requestId: "interaction_1",        createdAt: requested.createdAt,        questions: [nativeQuestion, singleSelectQuestion],      },    ]);  });   it("replaces single-select options and toggles multi-select options", () => {    expect(      togglePendingUserInputOptionSelection(        singleSelectQuestion,        { selectedOptionValues: ["Go"] },        "Node.js",      ),    ).toEqual({ customAnswer: "", selectedOptionValues: ["Node.js"] });     const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders");    const ordersAndListings = togglePendingUserInputOptionSelection(      multiSelectQuestion,      orders,      "Listings",    );    expect(ordersAndListings).toEqual({      customAnswer: "",      selectedOptionValues: ["Orders", "Listings"],    });    expect(      togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"),    ).toEqual({ customAnswer: "", selectedOptionValues: ["Listings"] });     const paddedOrders = togglePendingUserInputOptionSelection(      multiSelectQuestion,      undefined,      "  Orders  ",    );    expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionValues: ["Orders"] });    expect(      togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, "  Orders  "),    ).toEqual({ customAnswer: "" });  });   it("builds array answers for multi-select questions", () => {    expect(      buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], {        runtime: { selectedOptionValues: ["Go"] },        scope: { selectedOptionValues: ["Orders", "Listings"] },      }),    ).toEqual({      runtime: "Go",      scope: ["Orders", "Listings"],    });  });   it("clears selected options while a custom answer is active", () => {    expect(      setPendingUserInputCustomAnswer(        multiSelectQuestion,        { selectedOptionValues: ["Orders", "Listings"] },        "Orders first",      ),    ).toEqual({ customAnswer: "Orders first" });  });   it("matches selected options against normalized legacy labels", () => {    expect(      isPendingUserInputOptionSelected(        multiSelectQuestion,        { selectedOptionValues: ["Orders"] },        "  Orders  ",      ),    ).toBe(true);    expect(      isPendingUserInputOptionSelected(        multiSelectQuestion,        { selectedOptionValues: ["Orders"], customAnswer: "Orders first" },        "  Orders  ",      ),    ).toBe(false);  });   it("keeps custom answers enabled for legacy questions", () => {    expect(      buildPendingUserInputAnswers([singleSelectQuestion], {        runtime: { selectedOptionValues: ["Go"], customAnswer: "  Use Bun  " },      }),    ).toEqual({ runtime: "Use Bun" });  });   it("keeps duplicate labels and whitespace-sensitive native values separate", () => {    const first = togglePendingUserInputOptionSelection(nativeQuestion, undefined, " choice ");    expect(isPendingUserInputOptionSelected(nativeQuestion, first, " choice ")).toBe(true);    expect(isPendingUserInputOptionSelected(nativeQuestion, first, "choice")).toBe(false);    expect(buildPendingUserInputAnswers([nativeQuestion], { choice: first })).toEqual({      choice: " choice ",    });     const second = togglePendingUserInputOptionSelection(nativeQuestion, first, "choice");    expect(isPendingUserInputOptionSelected(nativeQuestion, second, " choice ")).toBe(false);    expect(isPendingUserInputOptionSelected(nativeQuestion, second, "choice")).toBe(true);    expect(buildPendingUserInputAnswers([nativeQuestion], { choice: second })).toEqual({      choice: "choice",    });  });   it("keeps exact native values in multi-select answers", () => {    const question = { ...nativeQuestion, multiSelect: true };    const first = togglePendingUserInputOptionSelection(question, undefined, " choice ");    const both = togglePendingUserInputOptionSelection(question, first, "choice");    expect(buildPendingUserInputAnswers([question], { choice: both })).toEqual({      choice: [" choice ", "choice"],    });     const second = togglePendingUserInputOptionSelection(question, both, " choice ");    expect(buildPendingUserInputAnswers([question], { choice: second })).toEqual({      choice: ["choice"],    });  });   it("ignores custom answers when a question only accepts choices", () => {    const draft = { selectedOptionValues: [" choice "], customAnswer: "Other" };    expect(setPendingUserInputCustomAnswer(nativeQuestion, draft, "Custom text")).toBe(draft);    expect(isPendingUserInputOptionSelected(nativeQuestion, draft, " choice ")).toBe(true);    expect(buildPendingUserInputAnswers([nativeQuestion], { choice: draft })).toEqual({      choice: " choice ",    });  });   it.each([    { customAnswer: "Other" },    { selectedOptionValues: ["Use this"] },    { selectedOptionValues: ["not offered"] },    { selectedOptionValues: ["  choice  "] },  ])("requires an offered value for a choice-only question: %j", (draft) => {    expect(buildPendingUserInputAnswers([nativeQuestion], { choice: draft })).toBeNull();  });}); describe("pending approvals", () => {  it.each([{}, { requestType: "unknown" }])(    "exposes legacy OpenCode approvals without a known request kind: %j",    (legacyPayload) => {      const requested = makeActivity({        id: EventId.make("approval-legacy"),        kind: "approval.requested",        summary: "Approval requested",        createdAt: "2026-08-24T00:00:00.000Z",        payload: { requestId: "per-legacy", detail: "*", ...legacyPayload },      });       expect(derivePendingApprovals([requested])).toEqual([        {          requestId: "per-legacy",          requestKind: "command",          createdAt: requested.createdAt,          detail: "*",        },      ]);    },  );   it.each(["tool_user_input", "auth_tokens_refresh"])(    "does not turn %s into an approval",    (requestType) => {      const activity = makeActivity({        id: EventId.make("approval-non-approval"),        kind: "approval.requested",        summary: "Approval requested",        createdAt: "2026-08-24T00:00:00.000Z",        payload: { requestId: "not-an-approval", requestType },      });       expect(derivePendingApprovals([activity])).toEqual([]);    },  );   it.each(["approval.resolved", "provider.approval.respond.failed"])(    "removes legacy approvals after %s",    (kind) => {      const requested = makeActivity({        id: EventId.make("approval-legacy-open"),        kind: "approval.requested",        summary: "Approval requested",        createdAt: "2026-08-24T00:00:00.000Z",        payload: { requestId: "per-legacy", requestType: "unknown" },      });      const resolved = makeActivity({        id: EventId.make("approval-legacy-resolved"),        kind,        summary: "Approval resolved",        createdAt: "2026-08-24T00:00:01.000Z",        payload: {          requestId: "per-legacy",          detail: "Unknown pending permission request: per-legacy",        },      });       expect(derivePendingApprovals([requested, resolved])).toEqual([]);    },  );   it("keeps app access approvals and persistence choices from remote environments", () => {    const options = [      { decision: "decline", label: "Decline" },      { decision: "acceptAlways", label: "Always allow Safari" },      { decision: "accept", label: "Approve" },    ];    const activity = makeActivity({      id: EventId.make("approval-safari"),      kind: "approval.requested",      summary: "App access approval requested",      createdAt: "2026-08-24T00:00:00.000Z",      payload: {        requestId: "req-safari",        requestType: "mcp_elicitation_approval",        detail: "Allow ChatGPT to use Safari?",        appName: "Safari",        options,      },    });     expect(derivePendingApprovals([activity])).toEqual([      {        requestId: "req-safari",        requestKind: "mcp-elicitation",        createdAt: "2026-08-24T00:00:00.000Z",        detail: "Allow ChatGPT to use Safari?",        appName: "Safari",        options,      },    ]);  });   it("removes an app access approval after a remote client rejects it", () => {    const requested = makeActivity({      id: EventId.make("approval-safari-open"),      kind: "approval.requested",      summary: "App access approval requested",      createdAt: "2026-08-24T00:00:00.000Z",      payload: { requestId: "req-safari", requestKind: "mcp-elicitation" },    });    const resolved = makeActivity({      id: EventId.make("approval-safari-resolved"),      kind: "approval.resolved",      summary: "Approval resolved",      createdAt: "2026-08-24T00:00:01.000Z",      payload: { requestId: "req-safari", decision: "decline" },    });     expect(derivePendingApprovals([requested, resolved])).toEqual([]);  });}); function makeActivity(  input: Partial<OrchestrationThreadActivity> &    Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,): OrchestrationThreadActivity {  return {    tone: "info",    payload: {},    turnId: null,    ...input,  };} function makeThread(  input: Partial<OrchestrationThread> & Pick<OrchestrationThread, "id" | "projectId" | "title">,): OrchestrationThread {  return {    modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },    runtimeMode: "full-access",    interactionMode: "default",    branch: null,    worktreePath: null,    latestTurn: null,    createdAt: "2026-04-01T00:00:00.000Z",    updatedAt: "2026-04-01T00:00:00.000Z",    archivedAt: null,    deletedAt: null,    messages: [],    proposedPlans: [],    activities: [],    checkpoints: [],    session: null,    ...input,    settledOverride: input.settledOverride ?? null,    settledAt: input.settledAt ?? null,  };} describe("buildThreadFeed", () => {  it("reuses unchanged feed and presentation rows during an assistant text update", () => {    const completedTurnId = TurnId.make("completed-turn");    const activeTurnId = TurnId.make("active-turn");    const thread = makeThread({      id: ThreadId.make("feed-reuse"),      projectId: ProjectId.make("project-1"),      title: "Feed reuse",      messages: [        {          id: MessageId.make("completed-message"),          role: "assistant",          text: "Completed response",          turnId: completedTurnId,          streaming: false,          createdAt: "2026-04-01T00:00:01.000Z",          updatedAt: "2026-04-01T00:00:01.000Z",        },        {          id: MessageId.make("streaming-message"),          role: "assistant",          text: "Current response",          turnId: activeTurnId,          streaming: true,          createdAt: "2026-04-01T00:00:04.000Z",          updatedAt: "2026-04-01T00:00:04.000Z",        },      ],      activities: [        makeActivity({          id: EventId.make("completed-tool"),          kind: "tool.completed",          summary: "Read files",          createdAt: "2026-04-01T00:00:02.000Z",          turnId: completedTurnId,          payload: { itemType: "file_read", status: "completed" },        }),        makeActivity({          id: EventId.make("active-tool"),          kind: "tool.updated",          summary: "Run checks",          createdAt: "2026-04-01T00:00:03.000Z",          turnId: activeTurnId,          payload: { itemType: "command_execution", command: "vp test", status: "inProgress" },        }),      ],    });    const latestTurn = {      turnId: activeTurnId,      state: "running" as const,      startedAt: "2026-04-01T00:00:03.000Z",      completedAt: null,    };    const expandedTurns = new Set([completedTurnId]);    const expandedGroups = new Set(["work-group:completed-tool", "work-group:active-tool"]);    const previousFeed = buildThreadFeed(thread);    const previousRows = deriveThreadFeedPresentation(      previousFeed,      latestTurn,      expandedTurns,      expandedGroups,      latestTurn.startedAt,    );    const updatedMessage = {      ...thread.messages[1]!,      text: "Current response with more text",      updatedAt: "2026-04-01T00:00:05.000Z",    };    const nextFeed = buildThreadFeed({      ...thread,      messages: [thread.messages[0]!, updatedMessage],    });    const nextRows = deriveThreadFeedPresentation(      nextFeed,      latestTurn,      expandedTurns,      expandedGroups,      latestTurn.startedAt,    );     expect(nextFeed).toHaveLength(previousFeed.length);    expect(nextRows).toHaveLength(previousRows.length);    for (const [before, after] of [      [previousFeed, nextFeed],

Lines 1–500 of 2655.