Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d1604932b | ||
|
|
e0d4388c77 | ||
|
|
7984a23fbd | ||
|
|
1040a2a624 | ||
|
|
cc7245e770 | ||
|
|
6348bea7c3 | ||
|
|
2cadee4050 | ||
|
|
3003850f37 | ||
|
|
c44d17f174 | ||
|
|
e12d2903f2 | ||
|
|
8cb3995a9c | ||
|
|
96d6160ea5 | ||
|
|
97ff0ac4a9 | ||
|
|
07e86e938b | ||
|
|
71ff626e3e | ||
|
|
8cad01a57b | ||
|
|
340634eeee | ||
|
|
fa0a1c1567 | ||
|
|
01358d1006 |
No files matched your search
@@ -141,9 +141,9 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'info',
|
||||
'runtime.warning',
|
||||
'Runtime warning',
|
||||
'{"message":"provider started"}',
|
||||
'runtime.note',
|
||||
'provider started',
|
||||
'{"stage":"start"}',
|
||||
'2026-02-24T00:00:06.000Z'
|
||||
)
|
||||
`;
|
||||
@@ -306,9 +306,9 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
{
|
||||
id: asEventId("activity-1"),
|
||||
tone: "info",
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
payload: { message: "provider started" },
|
||||
kind: "runtime.note",
|
||||
summary: "provider started",
|
||||
payload: { stage: "start" },
|
||||
turnId: asTurnId("turn-1"),
|
||||
createdAt: "2026-02-24T00:00:06.000Z",
|
||||
},
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationThreadActivity,
|
||||
ProjectScript,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
@@ -17,6 +16,7 @@ import {
|
||||
type OrchestrationProject,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
ModelSelection,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
@@ -460,18 +460,16 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
for (const row of activityRows) {
|
||||
updatedAt = maxIso(updatedAt, row.createdAt);
|
||||
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
|
||||
threadActivities.push(
|
||||
Schema.decodeUnknownSync(OrchestrationThreadActivity)({
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
}),
|
||||
);
|
||||
threadActivities.push({
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
});
|
||||
activitiesByThread.set(row.threadId, threadActivities);
|
||||
}
|
||||
|
||||
|
||||
@@ -94,7 +94,6 @@ describe("ProviderCommandReactor", () => {
|
||||
async function createHarness(input?: {
|
||||
readonly baseDir?: string;
|
||||
readonly threadModelSelection?: ModelSelection;
|
||||
readonly sessionModelSwitch?: "unsupported" | "in-session";
|
||||
}) {
|
||||
const now = new Date().toISOString();
|
||||
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||
@@ -193,9 +192,9 @@ describe("ProviderCommandReactor", () => {
|
||||
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
|
||||
stopSession: stopSession as ProviderServiceShape["stopSession"],
|
||||
listSessions: () => Effect.succeed(runtimeSessions),
|
||||
getCapabilities: (_provider) =>
|
||||
getCapabilities: (provider) =>
|
||||
Effect.succeed({
|
||||
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
|
||||
sessionModelSwitch: provider === "codex" ? "in-session" : "in-session",
|
||||
}),
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
@@ -505,9 +504,7 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
|
||||
});
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -558,53 +555,45 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the active session model when in-session model switching is unsupported", async () => {
|
||||
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
|
||||
it("allows custom model strings on the thread's explicit provider", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-custom-model"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-1"),
|
||||
messageId: asMessageId("user-message-custom-model"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
type RuntimeMode,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
@@ -160,7 +160,8 @@ const make = Effect.gen(function* () {
|
||||
| "provider.turn.start.failed"
|
||||
| "provider.turn.interrupt.failed"
|
||||
| "provider.approval.respond.failed"
|
||||
| "provider.user-input.respond.failed";
|
||||
| "provider.user-input.respond.failed"
|
||||
| "provider.session.stop.failed";
|
||||
readonly summary: string;
|
||||
readonly detail: string;
|
||||
readonly turnId: TurnId | null;
|
||||
@@ -300,7 +301,7 @@ const make = Effect.gen(function* () {
|
||||
const shouldRestartForModelSelectionChange =
|
||||
currentProvider === "claudeAgent" &&
|
||||
requestedModelSelection !== undefined &&
|
||||
!Equal.equals(previousModelSelection, requestedModelSelection);
|
||||
JSON.stringify(previousModelSelection) !== JSON.stringify(requestedModelSelection);
|
||||
|
||||
if (
|
||||
!runtimeModeChanged &&
|
||||
@@ -382,16 +383,14 @@ const make = Effect.gen(function* () {
|
||||
activeSession === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
|
||||
const requestedModelSelection =
|
||||
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
|
||||
const modelForTurn =
|
||||
sessionModelSwitch === "unsupported"
|
||||
? activeSession?.model !== undefined
|
||||
? input.modelSelection
|
||||
? {
|
||||
...requestedModelSelection,
|
||||
model: activeSession.model,
|
||||
...input.modelSelection,
|
||||
model: activeSession?.model ?? input.modelSelection.model,
|
||||
}
|
||||
: requestedModelSelection
|
||||
: undefined
|
||||
: input.modelSelection;
|
||||
|
||||
yield* providerService.sendTurn({
|
||||
|
||||
@@ -1830,9 +1830,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
status: "in_progress",
|
||||
title: "Run tests",
|
||||
detail: "bun test",
|
||||
data: {
|
||||
kind: "generic",
|
||||
},
|
||||
data: { pid: 123 },
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type AssistantDeliveryMode,
|
||||
type CanonicalJsonValue,
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
@@ -103,16 +102,6 @@ function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function toCanonicalJsonValue(value: unknown): CanonicalJsonValue | undefined {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = JSON.parse(
|
||||
JSON.stringify(value, (_key, nestedValue) => (nestedValue === undefined ? null : nestedValue)),
|
||||
) as CanonicalJsonValue | null;
|
||||
return normalized ?? undefined;
|
||||
}
|
||||
|
||||
function buildContextWindowActivityPayload(
|
||||
event: ProviderRuntimeEvent,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
@@ -294,9 +283,7 @@ function runtimeEventToActivities(
|
||||
summary: "Runtime warning",
|
||||
payload: {
|
||||
message: truncateDetail(event.payload.message),
|
||||
...(event.payload.detail !== undefined
|
||||
? { detail: toCanonicalJsonValue(event.payload.detail) }
|
||||
: {}),
|
||||
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
@@ -446,9 +433,7 @@ function runtimeEventToActivities(
|
||||
summary: "Context compacted",
|
||||
payload: {
|
||||
state: event.payload.state,
|
||||
...(event.payload.detail !== undefined
|
||||
? { detail: toCanonicalJsonValue(event.payload.detail) }
|
||||
: {}),
|
||||
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import { Effect, Layer, Option, Schema, Struct } from "effect";
|
||||
|
||||
import { ModelSelection, ProjectScript } from "@t3tools/contracts";
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
@@ -114,11 +114,35 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
const getById: ProjectionProjectRepositoryShape["getById"] = (input) =>
|
||||
getProjectionProjectRow(input).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.getById:query")),
|
||||
Effect.map(
|
||||
Option.map((row) => ({
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
const listAll: ProjectionProjectRepositoryShape["listAll"] = () =>
|
||||
listProjectionProjectRows().pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.listAll:query")),
|
||||
Effect.map((rows) =>
|
||||
rows.map((row) => ({
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteById: ProjectionProjectRepositoryShape["deleteById"] = (input) =>
|
||||
|
||||
@@ -67,7 +67,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stores JSON for thread model options", () =>
|
||||
it.effect("stores SQL NULL for missing thread model options", () =>
|
||||
Effect.gen(function* () {
|
||||
const threads = yield* ProjectionThreadRepository;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import { Effect, Layer, Option, Schema, Struct } from "effect";
|
||||
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
@@ -135,11 +135,13 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
const getById: ProjectionThreadRepositoryShape["getById"] = (input) =>
|
||||
getProjectionThreadRow(input).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.getById:query")),
|
||||
Effect.map(Option.map((row) => row)),
|
||||
);
|
||||
|
||||
const listByProjectId: ProjectionThreadRepositoryShape["listByProjectId"] = (input) =>
|
||||
listProjectionThreadRows(input).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.listByProjectId:query")),
|
||||
Effect.map((rows) => rows),
|
||||
);
|
||||
|
||||
const deleteById: ProjectionThreadRepositoryShape["deleteById"] = (input) =>
|
||||
|
||||
@@ -90,15 +90,9 @@ export interface RunMigrationsOptions {
|
||||
*/
|
||||
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.log(
|
||||
toMigrationInclusive === undefined
|
||||
? "Running all migrations..."
|
||||
: `Running migrations 1 through ${toMigrationInclusive}...`,
|
||||
);
|
||||
yield* Effect.log(`Running migrations 1 through ${toMigrationInclusive}...`);
|
||||
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
|
||||
yield* Effect.log("Migrations ran successfully").pipe(
|
||||
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
|
||||
);
|
||||
yield* Effect.log("Migrations ran successfully");
|
||||
return executedMigrations;
|
||||
});
|
||||
|
||||
|
||||
@@ -114,20 +114,6 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
'{"projectId":"project-1","title":"Project","workspaceRoot":"/tmp/project","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"high"},"claudeAgent":{"effort":"max"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-project-created-fallback',
|
||||
'project',
|
||||
'project-2',
|
||||
1,
|
||||
'project.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-project-created-fallback',
|
||||
NULL,
|
||||
'correlation-project-created-fallback',
|
||||
'user',
|
||||
'{"projectId":"project-2","title":"Fallback Project","workspaceRoot":"/tmp/project-2","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"low"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-created',
|
||||
'thread',
|
||||
@@ -142,20 +128,6 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
'{"threadId":"thread-1","projectId":"project-1","title":"Thread","model":"claude-opus-4-6","modelOptions":{"codex":{"reasoningEffort":"high"},"claudeAgent":{"effort":"max","thinking":false}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-created-fallback',
|
||||
'thread',
|
||||
'thread-2',
|
||||
1,
|
||||
'thread.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-thread-created-fallback',
|
||||
NULL,
|
||||
'correlation-thread-created-fallback',
|
||||
'user',
|
||||
'{"threadId":"thread-2","projectId":"project-1","title":"Fallback Thread","model":"gpt-5.4","modelOptions":{"claudeAgent":{"effort":"max"}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-turn-start-requested',
|
||||
'thread',
|
||||
@@ -169,20 +141,6 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
'user',
|
||||
'{"threadId":"thread-1","turnId":"turn-1","input":"hi","model":"gpt-5.4","modelOptions":{"codex":{"fastMode":true},"claudeAgent":{"effort":"max"}},"deliveryMode":"buffered"}',
|
||||
'{}'
|
||||
),
|
||||
(
|
||||
'event-thread-created-no-model',
|
||||
'thread',
|
||||
'thread-3',
|
||||
1,
|
||||
'thread.created',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'command-thread-created-no-model',
|
||||
NULL,
|
||||
'correlation-thread-created-no-model',
|
||||
'user',
|
||||
'{"threadId":"thread-3","projectId":"project-1","title":"Ancient Thread","runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
|
||||
'{}'
|
||||
)
|
||||
`;
|
||||
}
|
||||
@@ -268,22 +226,6 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[1]!.payloadJson), {
|
||||
projectId: "project-2",
|
||||
title: "Fallback Project",
|
||||
workspaceRoot: "/tmp/project-2",
|
||||
defaultModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
},
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
@@ -303,26 +245,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), {
|
||||
threadId: "thread-2",
|
||||
projectId: "project-1",
|
||||
title: "Fallback Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), {
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
input: "hi",
|
||||
@@ -335,22 +258,6 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
},
|
||||
deliveryMode: "buffered",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
|
||||
threadId: "thread-3",
|
||||
projectId: "project-1",
|
||||
title: "Ancient Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -89,47 +89,29 @@ export default Effect.gen(function* () {
|
||||
'model',
|
||||
json_extract(payload_json, '$.defaultModel')
|
||||
),
|
||||
CASE
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions') IS NULL THEN '{}'
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
|
||||
OR json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
|
||||
THEN CASE
|
||||
WHEN (
|
||||
CASE
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions') IS NULL THEN '{}'
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
|
||||
OR json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
|
||||
THEN CASE
|
||||
WHEN (
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL
|
||||
THEN json_extract(payload_json, '$.defaultProvider')
|
||||
WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%'
|
||||
THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END
|
||||
) = 'claudeAgent'
|
||||
THEN CASE
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.codex'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
ELSE CASE
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.codex'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
END
|
||||
) = 'claudeAgent'
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))
|
||||
)
|
||||
ELSE json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.codex'))
|
||||
)
|
||||
END
|
||||
ELSE json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions'))
|
||||
@@ -178,34 +160,16 @@ export default Effect.gen(function* () {
|
||||
WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'
|
||||
THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END
|
||||
END
|
||||
) = 'claudeAgent'
|
||||
THEN CASE
|
||||
WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.claudeAgent'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.codex'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
ELSE CASE
|
||||
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.codex'))
|
||||
)
|
||||
WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.claudeAgent'))
|
||||
)
|
||||
ELSE '{}'
|
||||
END
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.claudeAgent'))
|
||||
)
|
||||
ELSE json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.codex'))
|
||||
)
|
||||
END
|
||||
ELSE json_object('options', json(json_extract(payload_json, '$.modelOptions')))
|
||||
END
|
||||
@@ -219,17 +183,4 @@ export default Effect.gen(function* () {
|
||||
AND json_type(payload_json, '$.modelSelection') IS NULL
|
||||
AND json_type(payload_json, '$.model') IS NOT NULL
|
||||
`;
|
||||
|
||||
// Backfill thread.created events that predate the model field entirely
|
||||
yield* sql`
|
||||
UPDATE orchestration_events
|
||||
SET payload_json = json_set(
|
||||
payload_json,
|
||||
'$.modelSelection',
|
||||
json(json_object('provider', 'codex', 'model', 'gpt-5.4'))
|
||||
)
|
||||
WHERE event_type = 'thread.created'
|
||||
AND json_type(payload_json, '$.modelSelection') IS NULL
|
||||
AND json_type(payload_json, '$.model') IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -614,7 +614,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 10).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -731,6 +731,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -742,7 +743,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
],
|
||||
);
|
||||
|
||||
const turnStarted = runtimeEvents[2];
|
||||
const turnStarted = runtimeEvents[3];
|
||||
assert.equal(turnStarted?.type, "turn.started");
|
||||
if (turnStarted?.type === "turn.started") {
|
||||
assert.equal(String(turnStarted.turnId), String(turn.turnId));
|
||||
@@ -790,7 +791,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 10).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 11).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -896,6 +897,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -926,13 +928,12 @@ describe("ClaudeAdapterLive", () => {
|
||||
const toolInputUpdated = runtimeEvents.find(
|
||||
(event) =>
|
||||
event.type === "item.updated" &&
|
||||
event.payload.data?.kind === "generic" &&
|
||||
event.payload.data.input?.pattern === "foo",
|
||||
(event.payload.data as { input?: { pattern?: string; path?: string } } | undefined)?.input
|
||||
?.pattern === "foo",
|
||||
);
|
||||
assert.equal(toolInputUpdated?.type, "item.updated");
|
||||
if (toolInputUpdated?.type === "item.updated") {
|
||||
assert.deepEqual(toolInputUpdated.payload.data, {
|
||||
kind: "generic",
|
||||
toolName: "Grep",
|
||||
input: {
|
||||
pattern: "foo",
|
||||
@@ -944,25 +945,17 @@ describe("ClaudeAdapterLive", () => {
|
||||
const toolResultUpdated = runtimeEvents.find(
|
||||
(event) =>
|
||||
event.type === "item.updated" &&
|
||||
event.payload.data?.kind === "generic" &&
|
||||
event.payload.data.result !== undefined &&
|
||||
event.payload.data.result !== null &&
|
||||
typeof event.payload.data.result === "object" &&
|
||||
!Array.isArray(event.payload.data.result) &&
|
||||
"tool_use_id" in event.payload.data.result &&
|
||||
event.payload.data.result.tool_use_id === "tool-grep-1",
|
||||
(event.payload.data as { result?: { tool_use_id?: string } } | undefined)?.result
|
||||
?.tool_use_id === "tool-grep-1",
|
||||
);
|
||||
assert.equal(toolResultUpdated?.type, "item.updated");
|
||||
if (toolResultUpdated?.type === "item.updated") {
|
||||
assert.equal(
|
||||
toolResultUpdated.payload.data?.kind === "generic" &&
|
||||
toolResultUpdated.payload.data.result !== undefined &&
|
||||
toolResultUpdated.payload.data.result !== null &&
|
||||
typeof toolResultUpdated.payload.data.result === "object" &&
|
||||
!Array.isArray(toolResultUpdated.payload.data.result) &&
|
||||
"content" in toolResultUpdated.payload.data.result
|
||||
? toolResultUpdated.payload.data.result.content
|
||||
: undefined,
|
||||
(
|
||||
toolResultUpdated.payload.data as {
|
||||
result?: { content?: string };
|
||||
}
|
||||
).result?.content,
|
||||
"src/example.ts:1:foo",
|
||||
);
|
||||
}
|
||||
@@ -977,7 +970,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 8).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1053,7 +1046,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 5).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1085,6 +1078,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -1142,6 +1136,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"turn.completed",
|
||||
@@ -1149,7 +1144,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
],
|
||||
);
|
||||
|
||||
const turnCompleted = runtimeEvents.find((event) => event.type === "turn.completed");
|
||||
const turnCompleted = runtimeEvents[4];
|
||||
assert.equal(turnCompleted?.type, "turn.completed");
|
||||
if (turnCompleted?.type === "turn.completed") {
|
||||
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
|
||||
@@ -1157,7 +1152,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
assert.equal(turnCompleted.payload.errorMessage, "Claude runtime interrupted.");
|
||||
}
|
||||
|
||||
const sessionExited = runtimeEvents.find((event) => event.type === "session.exited");
|
||||
const sessionExited = runtimeEvents[5];
|
||||
assert.equal(sessionExited?.type, "session.exited");
|
||||
|
||||
assert.equal(yield* adapter.hasSession(THREAD_ID), false);
|
||||
@@ -1242,7 +1237,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 5).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1289,7 +1284,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 5).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1343,7 +1338,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1412,7 +1407,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 8).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1471,6 +1466,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -1615,6 +1611,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -1622,7 +1619,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
"item.completed",
|
||||
"content.delta",
|
||||
"item.completed",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1668,7 +1664,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 8).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1710,6 +1706,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -1736,7 +1733,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 12).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 13).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1897,6 +1894,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -2003,10 +2001,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2016,7 +2014,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
assert.equal(sessionStarted.threadId, THREAD_ID);
|
||||
}
|
||||
|
||||
const threadStarted = runtimeEvents.find((event) => event.type === "thread.started");
|
||||
const threadStarted = runtimeEvents[4];
|
||||
assert.equal(threadStarted?.type, "thread.started");
|
||||
if (threadStarted?.type === "thread.started") {
|
||||
assert.equal(threadStarted.threadId, THREAD_ID);
|
||||
@@ -2041,7 +2039,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 2).pipe(Stream.runDrain);
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
@@ -2150,7 +2148,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 2).pipe(Stream.runDrain);
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
const canUseTool = createInput?.options.canUseTool;
|
||||
@@ -2498,7 +2496,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 2).pipe(Stream.runDrain);
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
@@ -2564,7 +2562,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 2).pipe(Stream.runDrain);
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
@@ -2636,8 +2634,8 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
// Drain the session startup events (started, state.changed).
|
||||
yield* Stream.take(adapter.streamEvents, 2).pipe(Stream.runDrain);
|
||||
// Drain the session startup events (started, configured, state.changed).
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
@@ -2761,7 +2759,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 2).pipe(Stream.runDrain);
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
const canUseTool = createInput?.options.canUseTool;
|
||||
@@ -2829,7 +2827,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 2).pipe(Stream.runDrain);
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
const canUseTool = createInput?.options.canUseTool;
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type CanonicalItemType,
|
||||
type CanonicalToolLifecycleData,
|
||||
type CanonicalRequestType,
|
||||
EventId,
|
||||
type ProviderApprovalDecision,
|
||||
@@ -39,13 +38,15 @@ import {
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type UserInputQuestion,
|
||||
ClaudeCodeEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
hasEffortLevel,
|
||||
applyClaudePromptEffortPrefix,
|
||||
getModelCapabilities,
|
||||
trimOrNull,
|
||||
getEffectiveClaudeCodeEffort,
|
||||
getReasoningEffortOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
} from "@t3tools/shared/model";
|
||||
import {
|
||||
Cause,
|
||||
@@ -157,7 +158,6 @@ interface ClaudeSessionContext {
|
||||
readonly inFlightTools: Map<number, ToolInFlight>;
|
||||
turnState: ClaudeTurnState | undefined;
|
||||
lastKnownContextWindow: number | undefined;
|
||||
lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;
|
||||
lastAssistantUuid: string | undefined;
|
||||
lastThreadStartedId: string | undefined;
|
||||
stopped: boolean;
|
||||
@@ -211,15 +211,6 @@ function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray
|
||||
return squashed.length > 0 ? [squashed] : [];
|
||||
}
|
||||
|
||||
function getEffectiveClaudeCodeEffort(
|
||||
effort: ClaudeCodeEffort | null | undefined,
|
||||
): Exclude<ClaudeCodeEffort, "ultrathink"> | null {
|
||||
if (!effort) {
|
||||
return null;
|
||||
}
|
||||
return effort === "ultrathink" ? null : effort;
|
||||
}
|
||||
|
||||
function isClaudeInterruptedMessage(message: string): boolean {
|
||||
const normalized = message.toLowerCase();
|
||||
return (
|
||||
@@ -521,16 +512,21 @@ const CLAUDE_SETTING_SOURCES = [
|
||||
] as const satisfies ReadonlyArray<SettingSource>;
|
||||
|
||||
function buildPromptText(input: ProviderSendTurnInput): string {
|
||||
const rawEffort =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null;
|
||||
const requestedEffort = trimOrNull(rawEffort);
|
||||
const claudeModel =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined;
|
||||
const caps = getModelCapabilities("claudeAgent", claudeModel);
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null,
|
||||
);
|
||||
const supportedEffortOptions = getReasoningEffortOptions(
|
||||
"claudeAgent",
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined,
|
||||
);
|
||||
const promptEffort =
|
||||
requestedEffort === "ultrathink" && caps.reasoningEffortLevels.length > 0
|
||||
requestedEffort === "ultrathink" &&
|
||||
supportsClaudeUltrathinkKeyword(
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined,
|
||||
)
|
||||
? "ultrathink"
|
||||
: requestedEffort && hasEffortLevel(caps, requestedEffort)
|
||||
: requestedEffort && supportedEffortOptions.includes(requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort);
|
||||
@@ -756,116 +752,6 @@ function tryParseJsonRecord(value: string): Record<string, unknown> | undefined
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeCommandValue(value: unknown): string | undefined {
|
||||
if (typeof value === "string") {
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const parts = value
|
||||
.map((entry) => (typeof entry === "string" ? entry.trim() : ""))
|
||||
.filter((entry) => entry.length > 0);
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {
|
||||
if (typeof value !== "string") {
|
||||
return;
|
||||
}
|
||||
const normalized = value.trim();
|
||||
if (normalized.length === 0 || seen.has(normalized)) {
|
||||
return;
|
||||
}
|
||||
seen.add(normalized);
|
||||
target.push(normalized);
|
||||
}
|
||||
|
||||
function collectChangedFiles(value: unknown, target: string[], seen: Set<string>, depth: number) {
|
||||
if (depth > 4 || target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
collectChangedFiles(entry, target, seen, depth + 1);
|
||||
if (target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!value || typeof value !== "object") {
|
||||
return;
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
pushChangedFile(target, seen, record.path);
|
||||
pushChangedFile(target, seen, record.filePath);
|
||||
pushChangedFile(target, seen, record.relativePath);
|
||||
pushChangedFile(target, seen, record.filename);
|
||||
pushChangedFile(target, seen, record.newPath);
|
||||
pushChangedFile(target, seen, record.oldPath);
|
||||
for (const nestedKey of ["result", "input", "content", "files", "edits", "changes"]) {
|
||||
if (nestedKey in record) {
|
||||
collectChangedFiles(record[nestedKey], target, seen, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function canonicalToolLifecycleData(input: {
|
||||
itemType?: CanonicalItemType | undefined;
|
||||
toolName?: string | undefined;
|
||||
input?: Record<string, unknown> | undefined;
|
||||
result?: unknown;
|
||||
}): CanonicalToolLifecycleData | undefined {
|
||||
const command = normalizeCommandValue(input.input?.command);
|
||||
const changedFiles: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
collectChangedFiles(input.input, changedFiles, seen, 0);
|
||||
collectChangedFiles(input.result, changedFiles, seen, 0);
|
||||
if (input.itemType === "command_execution" && command) {
|
||||
const resultRecord =
|
||||
input.result && typeof input.result === "object" && !Array.isArray(input.result)
|
||||
? (input.result as Record<string, unknown>)
|
||||
: undefined;
|
||||
return {
|
||||
kind: "command_execution",
|
||||
command,
|
||||
...(input.toolName ? { toolName: input.toolName } : {}),
|
||||
...(input.input ? { input: input.input as CanonicalToolLifecycleData["input"] } : {}),
|
||||
...(typeof resultRecord?.content === "string" ? { output: resultRecord.content } : {}),
|
||||
...(typeof resultRecord?.is_error === "boolean" && resultRecord.is_error === false
|
||||
? { exitCode: 0 }
|
||||
: {}),
|
||||
...(input.result !== undefined
|
||||
? { result: input.result as CanonicalToolLifecycleData["result"] }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
if (input.itemType === "file_change" && changedFiles.length > 0) {
|
||||
return {
|
||||
kind: "file_change",
|
||||
changedFiles,
|
||||
...(input.toolName ? { toolName: input.toolName } : {}),
|
||||
...(input.input ? { input: input.input as CanonicalToolLifecycleData["input"] } : {}),
|
||||
...(input.result !== undefined
|
||||
? { result: input.result as CanonicalToolLifecycleData["result"] }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
if (input.toolName || input.input || input.result !== undefined) {
|
||||
return {
|
||||
kind: "generic",
|
||||
...(input.toolName ? { toolName: input.toolName } : {}),
|
||||
...(input.input ? { input: input.input as CanonicalToolLifecycleData["input"] } : {}),
|
||||
...(input.result !== undefined
|
||||
? { result: input.result as CanonicalToolLifecycleData["result"] }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function toolInputFingerprint(input: Record<string, unknown>): string | undefined {
|
||||
try {
|
||||
return JSON.stringify(input);
|
||||
@@ -1488,32 +1374,13 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
const resultUsage =
|
||||
result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined;
|
||||
const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);
|
||||
if (resultContextWindow !== undefined) {
|
||||
context.lastKnownContextWindow = resultContextWindow;
|
||||
}
|
||||
|
||||
// The SDK result.usage contains *accumulated* totals across all API calls
|
||||
// (input_tokens, cache_read_input_tokens, etc. summed over every request).
|
||||
// This does NOT represent the current context window size.
|
||||
// Instead, use the last known context-window-accurate usage from task_progress
|
||||
// events and treat the accumulated total as totalProcessedTokens.
|
||||
const accumulatedSnapshot = normalizeClaudeTokenUsage(
|
||||
const usageSnapshot = normalizeClaudeTokenUsage(
|
||||
resultUsage,
|
||||
resultContextWindow ?? context.lastKnownContextWindow,
|
||||
);
|
||||
const lastGoodUsage = context.lastKnownTokenUsage;
|
||||
const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
|
||||
const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage
|
||||
? {
|
||||
...lastGoodUsage,
|
||||
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
|
||||
? { maxTokens }
|
||||
: {}),
|
||||
...(accumulatedSnapshot && accumulatedSnapshot.usedTokens > lastGoodUsage.usedTokens
|
||||
? { totalProcessedTokens: accumulatedSnapshot.usedTokens }
|
||||
: {}),
|
||||
}
|
||||
: accumulatedSnapshot;
|
||||
if (resultContextWindow !== undefined) {
|
||||
context.lastKnownContextWindow = resultContextWindow;
|
||||
}
|
||||
|
||||
const turnState = context.turnState;
|
||||
if (!turnState) {
|
||||
@@ -1542,7 +1409,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
payload: {
|
||||
state: status,
|
||||
...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),
|
||||
...(usageSnapshot ? { usage: usageSnapshot } : {}),
|
||||
...(result?.usage ? { usage: result.usage } : {}),
|
||||
...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),
|
||||
...(typeof result?.total_cost_usd === "number"
|
||||
? { totalCostUsd: result.total_cost_usd }
|
||||
: {}),
|
||||
@@ -1568,19 +1436,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
status: status === "completed" ? "completed" : "failed",
|
||||
title: tool.title,
|
||||
...(tool.detail ? { detail: tool.detail } : {}),
|
||||
...(canonicalToolLifecycleData({
|
||||
itemType: tool.itemType,
|
||||
data: {
|
||||
toolName: tool.toolName,
|
||||
input: tool.input,
|
||||
})
|
||||
? {
|
||||
data: canonicalToolLifecycleData({
|
||||
itemType: tool.itemType,
|
||||
toolName: tool.toolName,
|
||||
input: tool.input,
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
|
||||
raw: {
|
||||
@@ -1634,7 +1493,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
payload: {
|
||||
state: status,
|
||||
...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),
|
||||
...(usageSnapshot ? { usage: usageSnapshot } : {}),
|
||||
...(result?.usage ? { usage: result.usage } : {}),
|
||||
...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),
|
||||
...(typeof result?.total_cost_usd === "number"
|
||||
? { totalCostUsd: result.total_cost_usd }
|
||||
: {}),
|
||||
@@ -1772,19 +1632,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
status: "inProgress",
|
||||
title: nextTool.title,
|
||||
...(nextTool.detail ? { detail: nextTool.detail } : {}),
|
||||
...(canonicalToolLifecycleData({
|
||||
itemType: nextTool.itemType,
|
||||
data: {
|
||||
toolName: nextTool.toolName,
|
||||
input: nextTool.input,
|
||||
})
|
||||
? {
|
||||
data: canonicalToolLifecycleData({
|
||||
itemType: nextTool.itemType,
|
||||
toolName: nextTool.toolName,
|
||||
input: nextTool.input,
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: nextTool.itemId }),
|
||||
raw: {
|
||||
@@ -1850,19 +1701,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
status: "inProgress",
|
||||
title: tool.title,
|
||||
...(tool.detail ? { detail: tool.detail } : {}),
|
||||
...(canonicalToolLifecycleData({
|
||||
itemType: tool.itemType,
|
||||
data: {
|
||||
toolName: tool.toolName,
|
||||
input: toolInput,
|
||||
})
|
||||
? {
|
||||
data: canonicalToolLifecycleData({
|
||||
itemType: tool.itemType,
|
||||
toolName: tool.toolName,
|
||||
input: toolInput,
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
|
||||
raw: {
|
||||
@@ -1915,12 +1757,11 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
|
||||
const [index, tool] = toolEntry;
|
||||
const itemStatus = toolResult.isError ? "failed" : "completed";
|
||||
const toolData = canonicalToolLifecycleData({
|
||||
itemType: tool.itemType,
|
||||
const toolData = {
|
||||
toolName: tool.toolName,
|
||||
input: tool.input,
|
||||
result: toolResult.block,
|
||||
});
|
||||
};
|
||||
|
||||
const updatedStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
@@ -1936,7 +1777,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
status: toolResult.isError ? "failed" : "inProgress",
|
||||
title: tool.title,
|
||||
...(tool.detail ? { detail: tool.detail } : {}),
|
||||
...(toolData ? { data: toolData } : {}),
|
||||
data: toolData,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
|
||||
raw: {
|
||||
@@ -1984,7 +1825,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
status: itemStatus,
|
||||
title: tool.title,
|
||||
...(tool.detail ? { detail: tool.detail } : {}),
|
||||
...(toolData ? { data: toolData } : {}),
|
||||
data: toolData,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
|
||||
raw: {
|
||||
@@ -2131,6 +1972,15 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
};
|
||||
|
||||
switch (message.subtype) {
|
||||
case "init":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "session.configured",
|
||||
payload: {
|
||||
config: message as Record<string, unknown>,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "status":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
@@ -2152,6 +2002,43 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "hook_started":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "hook.started",
|
||||
payload: {
|
||||
hookId: message.hook_id,
|
||||
hookName: message.hook_name,
|
||||
hookEvent: message.hook_event,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "hook_progress":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "hook.progress",
|
||||
payload: {
|
||||
hookId: message.hook_id,
|
||||
output: message.output,
|
||||
stdout: message.stdout,
|
||||
stderr: message.stderr,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "hook_response":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "hook.completed",
|
||||
payload: {
|
||||
hookId: message.hook_id,
|
||||
outcome: message.outcome,
|
||||
output: message.output,
|
||||
stdout: message.stdout,
|
||||
stderr: message.stderr,
|
||||
...(typeof message.exit_code === "number" ? { exitCode: message.exit_code } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "task_started":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
@@ -2163,22 +2050,24 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "task_progress": {
|
||||
const normalizedUsage = message.usage
|
||||
? normalizeClaudeTokenUsage(message.usage, context.lastKnownContextWindow)
|
||||
: undefined;
|
||||
if (normalizedUsage) {
|
||||
context.lastKnownTokenUsage = normalizedUsage;
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: usageStamp.eventId,
|
||||
createdAt: usageStamp.createdAt,
|
||||
type: "thread.token-usage.updated",
|
||||
payload: {
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
});
|
||||
case "task_progress":
|
||||
if (message.usage) {
|
||||
const normalizedUsage = normalizeClaudeTokenUsage(
|
||||
message.usage,
|
||||
context.lastKnownContextWindow,
|
||||
);
|
||||
if (normalizedUsage) {
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: usageStamp.eventId,
|
||||
createdAt: usageStamp.createdAt,
|
||||
type: "thread.token-usage.updated",
|
||||
payload: {
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
@@ -2187,28 +2076,29 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
taskId: RuntimeTaskId.makeUnsafe(message.task_id),
|
||||
description: message.description,
|
||||
...(message.summary ? { summary: message.summary } : {}),
|
||||
...(normalizedUsage ? { usage: normalizedUsage } : {}),
|
||||
...(message.usage ? { usage: message.usage } : {}),
|
||||
...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "task_notification": {
|
||||
const normalizedUsage = message.usage
|
||||
? normalizeClaudeTokenUsage(message.usage, context.lastKnownContextWindow)
|
||||
: undefined;
|
||||
if (normalizedUsage) {
|
||||
context.lastKnownTokenUsage = normalizedUsage;
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: usageStamp.eventId,
|
||||
createdAt: usageStamp.createdAt,
|
||||
type: "thread.token-usage.updated",
|
||||
payload: {
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
});
|
||||
case "task_notification":
|
||||
if (message.usage) {
|
||||
const normalizedUsage = normalizeClaudeTokenUsage(
|
||||
message.usage,
|
||||
context.lastKnownContextWindow,
|
||||
);
|
||||
if (normalizedUsage) {
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: usageStamp.eventId,
|
||||
createdAt: usageStamp.createdAt,
|
||||
type: "thread.token-usage.updated",
|
||||
payload: {
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
@@ -2217,11 +2107,32 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
taskId: RuntimeTaskId.makeUnsafe(message.task_id),
|
||||
status: message.status,
|
||||
...(message.summary ? { summary: message.summary } : {}),
|
||||
...(normalizedUsage ? { usage: normalizedUsage } : {}),
|
||||
...(message.usage ? { usage: message.usage } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "files_persisted":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "files.persisted",
|
||||
payload: {
|
||||
files: Array.isArray(message.files)
|
||||
? message.files.map((file: { filename: string; file_id: string }) => ({
|
||||
filename: file.filename,
|
||||
fileId: file.file_id,
|
||||
}))
|
||||
: [],
|
||||
...(Array.isArray(message.failed)
|
||||
? {
|
||||
failed: message.failed.map((entry: { filename: string; error: string }) => ({
|
||||
filename: entry.filename,
|
||||
error: entry.error,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
default:
|
||||
yield* emitRuntimeWarning(
|
||||
context,
|
||||
@@ -2233,9 +2144,78 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
});
|
||||
|
||||
const handleSdkTelemetryMessage = (
|
||||
_context: ClaudeSessionContext,
|
||||
_message: SDKMessage,
|
||||
): Effect.Effect<void> => Effect.void;
|
||||
context: ClaudeSessionContext,
|
||||
message: SDKMessage,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
const stamp = yield* makeEventStamp();
|
||||
const base = {
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
providerRefs: nativeProviderRefs(context),
|
||||
raw: {
|
||||
source: "claude.sdk.message" as const,
|
||||
method: sdkNativeMethod(message),
|
||||
messageType: message.type,
|
||||
payload: message,
|
||||
},
|
||||
};
|
||||
|
||||
if (message.type === "tool_progress") {
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "tool.progress",
|
||||
payload: {
|
||||
toolUseId: message.tool_use_id,
|
||||
toolName: message.tool_name,
|
||||
elapsedSeconds: message.elapsed_time_seconds,
|
||||
...(message.task_id ? { summary: `task:${message.task_id}` } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "tool_use_summary") {
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "tool.summary",
|
||||
payload: {
|
||||
summary: message.summary,
|
||||
...(message.preceding_tool_use_ids.length > 0
|
||||
? { precedingToolUseIds: message.preceding_tool_use_ids }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "auth_status") {
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "auth.status",
|
||||
payload: {
|
||||
isAuthenticating: message.isAuthenticating,
|
||||
output: message.output,
|
||||
...(message.error ? { error: message.error } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "rate_limit_event") {
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "account.rate-limits.updated",
|
||||
payload: {
|
||||
rateLimits: message,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const handleSdkMessage = (
|
||||
context: ClaudeSessionContext,
|
||||
@@ -2726,13 +2706,24 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
const providerOptions = input.providerOptions?.claudeAgent;
|
||||
const modelSelection =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
|
||||
const requestedEffort = trimOrNull(modelSelection?.options?.effort ?? null);
|
||||
const caps = getModelCapabilities("claudeAgent", modelSelection?.model);
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
modelSelection?.options?.effort ?? null,
|
||||
);
|
||||
const supportedEffortOptions = getReasoningEffortOptions(
|
||||
"claudeAgent",
|
||||
modelSelection?.model,
|
||||
);
|
||||
const effort =
|
||||
requestedEffort && hasEffortLevel(caps, requestedEffort) ? requestedEffort : null;
|
||||
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
|
||||
requestedEffort && supportedEffortOptions.includes(requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
const fastMode =
|
||||
modelSelection?.options?.fastMode === true &&
|
||||
supportsClaudeFastMode(modelSelection?.model);
|
||||
const thinking =
|
||||
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
|
||||
typeof modelSelection?.options?.thinking === "boolean" &&
|
||||
supportsClaudeThinkingToggle(modelSelection?.model)
|
||||
? modelSelection.options.thinking
|
||||
: undefined;
|
||||
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
|
||||
@@ -2815,7 +2806,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
inFlightTools,
|
||||
turnState: undefined,
|
||||
lastKnownContextWindow: undefined,
|
||||
lastKnownTokenUsage: undefined,
|
||||
lastAssistantUuid: resumeState?.resumeSessionAt,
|
||||
lastThreadStartedId: undefined,
|
||||
stopped: false,
|
||||
@@ -2834,6 +2824,28 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
providerRefs: {},
|
||||
});
|
||||
|
||||
const configuredStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.configured",
|
||||
eventId: configuredStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: configuredStamp.createdAt,
|
||||
threadId,
|
||||
payload: {
|
||||
config: {
|
||||
...(modelSelection?.model ? { model: modelSelection.model } : {}),
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(effectiveEffort ? { effort: effectiveEffort } : {}),
|
||||
...(permissionMode ? { permissionMode } : {}),
|
||||
...(providerOptions?.maxThinkingTokens !== undefined
|
||||
? { maxThinkingTokens: providerOptions.maxThinkingTokens }
|
||||
: {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
},
|
||||
},
|
||||
providerRefs: {},
|
||||
});
|
||||
|
||||
const readyStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.state.changed",
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
*/
|
||||
import {
|
||||
type CanonicalItemType,
|
||||
type CanonicalToolLifecycleData,
|
||||
type CanonicalRequestType,
|
||||
type ProviderEvent,
|
||||
type ProviderRuntimeEvent,
|
||||
@@ -111,111 +110,6 @@ function asNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function normalizeCommandValue(value: unknown): string | undefined {
|
||||
if (typeof value === "string") {
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const parts = value
|
||||
.map((entry) => (typeof entry === "string" ? entry.trim() : ""))
|
||||
.filter((entry) => entry.length > 0);
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {
|
||||
if (typeof value !== "string") {
|
||||
return;
|
||||
}
|
||||
const normalized = value.trim();
|
||||
if (normalized.length === 0 || seen.has(normalized)) {
|
||||
return;
|
||||
}
|
||||
seen.add(normalized);
|
||||
target.push(normalized);
|
||||
}
|
||||
|
||||
function collectChangedFiles(value: unknown, target: string[], seen: Set<string>, depth: number) {
|
||||
if (depth > 4 || target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
collectChangedFiles(entry, target, seen, depth + 1);
|
||||
if (target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const record = asObject(value);
|
||||
if (!record) {
|
||||
return;
|
||||
}
|
||||
|
||||
pushChangedFile(target, seen, record.path);
|
||||
pushChangedFile(target, seen, record.filePath);
|
||||
pushChangedFile(target, seen, record.relativePath);
|
||||
pushChangedFile(target, seen, record.filename);
|
||||
pushChangedFile(target, seen, record.newPath);
|
||||
pushChangedFile(target, seen, record.oldPath);
|
||||
|
||||
for (const nestedKey of ["item", "result", "input", "changes", "files", "edits", "patches"]) {
|
||||
if (!(nestedKey in record)) {
|
||||
continue;
|
||||
}
|
||||
collectChangedFiles(record[nestedKey], target, seen, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
function buildCanonicalToolLifecycleData(
|
||||
itemType: CanonicalItemType,
|
||||
source: Record<string, unknown>,
|
||||
payload: Record<string, unknown>,
|
||||
): CanonicalToolLifecycleData | undefined {
|
||||
const result = asObject(source.result);
|
||||
const input = asObject(source.input);
|
||||
const command = [
|
||||
normalizeCommandValue(source.command),
|
||||
normalizeCommandValue(input?.command),
|
||||
normalizeCommandValue(result?.command),
|
||||
normalizeCommandValue(payload.command),
|
||||
].find((candidate) => candidate !== undefined);
|
||||
const changedFiles: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
collectChangedFiles(source, changedFiles, seen, 0);
|
||||
collectChangedFiles(payload, changedFiles, seen, 0);
|
||||
if (itemType === "command_execution" && command) {
|
||||
return {
|
||||
kind: "command_execution",
|
||||
command,
|
||||
...(input ? { input: input as CanonicalToolLifecycleData["input"] } : {}),
|
||||
...(result ? { result: result as CanonicalToolLifecycleData["result"] } : {}),
|
||||
...(typeof result?.content === "string" ? { output: result.content } : {}),
|
||||
...(asNumber(result?.exitCode) !== undefined ? { exitCode: asNumber(result?.exitCode) } : {}),
|
||||
};
|
||||
}
|
||||
if (itemType === "file_change" && changedFiles.length > 0) {
|
||||
return {
|
||||
kind: "file_change",
|
||||
changedFiles,
|
||||
...(input ? { input: input as CanonicalToolLifecycleData["input"] } : {}),
|
||||
...(result ? { result: result as CanonicalToolLifecycleData["result"] } : {}),
|
||||
};
|
||||
}
|
||||
if (input || result) {
|
||||
return {
|
||||
kind: "generic",
|
||||
...(input ? { input: input as CanonicalToolLifecycleData["input"] } : {}),
|
||||
...(result ? { result: result as CanonicalToolLifecycleData["result"] } : {}),
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined {
|
||||
const usage = asObject(value);
|
||||
const totalUsage = asObject(usage?.total_token_usage ?? usage?.total);
|
||||
@@ -423,29 +317,27 @@ function toCanonicalUserInputAnswers(
|
||||
return {};
|
||||
}
|
||||
|
||||
const normalized: Record<string, string | readonly string[]> = {};
|
||||
for (const [questionId, value] of Object.entries(answers)) {
|
||||
if (typeof value === "string") {
|
||||
normalized[questionId] = value;
|
||||
continue;
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(answers).flatMap(([questionId, value]) => {
|
||||
if (typeof value === "string") {
|
||||
return [[questionId, value] as const];
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const entries = value.filter((entry): entry is string => typeof entry === "string");
|
||||
normalized[questionId] = entries.length === 1 ? (entries[0] ?? entries) : entries;
|
||||
continue;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
const normalized = value.filter((entry): entry is string => typeof entry === "string");
|
||||
return [[questionId, normalized.length === 1 ? normalized[0] : normalized] as const];
|
||||
}
|
||||
|
||||
const answerObject = asObject(value);
|
||||
const answerList = asArray(answerObject?.answers)?.filter(
|
||||
(entry): entry is string => typeof entry === "string",
|
||||
);
|
||||
if (answerList) {
|
||||
normalized[questionId] = answerList.length === 1 ? (answerList[0] ?? answerList) : answerList;
|
||||
}
|
||||
}
|
||||
|
||||
return normalized;
|
||||
const answerObject = asObject(value);
|
||||
const answerList = asArray(answerObject?.answers)?.filter(
|
||||
(entry): entry is string => typeof entry === "string",
|
||||
);
|
||||
if (!answerList) {
|
||||
return [];
|
||||
}
|
||||
return [[questionId, answerList.length === 1 ? answerList[0] : answerList] as const];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function toUserInputQuestions(payload: Record<string, unknown> | undefined) {
|
||||
@@ -670,9 +562,7 @@ function mapItemLifecycle(
|
||||
...(status ? { status } : {}),
|
||||
...(itemTitle(itemType) ? { title: itemTitle(itemType) } : {}),
|
||||
...(detail ? { detail } : {}),
|
||||
...(buildCanonicalToolLifecycleData(itemType, source, payload ?? {})
|
||||
? { data: buildCanonicalToolLifecycleData(itemType, source, payload ?? {}) }
|
||||
: {}),
|
||||
...(event.payload !== undefined ? { data: event.payload } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -904,9 +794,8 @@ function mapToRuntimeEvents(
|
||||
payload: {
|
||||
state: toTurnStatus(turn?.status),
|
||||
...(asString(turn?.stopReason) ? { stopReason: asString(turn?.stopReason) } : {}),
|
||||
...(normalizeCodexTokenUsage(turn?.usage)
|
||||
? { usage: normalizeCodexTokenUsage(turn?.usage) }
|
||||
: {}),
|
||||
...(turn?.usage !== undefined ? { usage: turn.usage } : {}),
|
||||
...(asObject(turn?.modelUsage) ? { modelUsage: asObject(turn?.modelUsage) } : {}),
|
||||
...(asNumber(turn?.totalCostUsd) !== undefined
|
||||
? { totalCostUsd: asNumber(turn?.totalCostUsd) }
|
||||
: {}),
|
||||
@@ -916,6 +805,18 @@ function mapToRuntimeEvents(
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "turn/aborted") {
|
||||
return [
|
||||
{
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
type: "turn.aborted",
|
||||
payload: {
|
||||
reason: event.message ?? "Turn aborted",
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "turn/plan/updated") {
|
||||
const steps = Array.isArray(payload?.plan) ? payload.plan : [];
|
||||
return [
|
||||
@@ -1050,6 +951,23 @@ function mapToRuntimeEvents(
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "item/mcpToolCall/progress") {
|
||||
return [
|
||||
{
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
type: "tool.progress",
|
||||
payload: {
|
||||
...(asString(payload?.toolUseId) ? { toolUseId: asString(payload?.toolUseId) } : {}),
|
||||
...(asString(payload?.toolName) ? { toolName: asString(payload?.toolName) } : {}),
|
||||
...(asString(payload?.summary) ? { summary: asString(payload?.summary) } : {}),
|
||||
...(asNumber(payload?.elapsedSeconds) !== undefined
|
||||
? { elapsedSeconds: asNumber(payload?.elapsedSeconds) }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "serverRequest/resolved") {
|
||||
const requestType =
|
||||
toRequestTypeFromResolvedPayload(payload) !== "unknown"
|
||||
@@ -1189,6 +1107,148 @@ function mapToRuntimeEvents(
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "model/rerouted") {
|
||||
return [
|
||||
{
|
||||
type: "model.rerouted",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
fromModel: asString(payload?.fromModel) ?? "unknown",
|
||||
toModel: asString(payload?.toModel) ?? "unknown",
|
||||
reason: asString(payload?.reason) ?? "unknown",
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "deprecationNotice") {
|
||||
return [
|
||||
{
|
||||
type: "deprecation.notice",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
summary: asString(payload?.summary) ?? "Deprecation notice",
|
||||
...(asString(payload?.details) ? { details: asString(payload?.details) } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "configWarning") {
|
||||
return [
|
||||
{
|
||||
type: "config.warning",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
summary: asString(payload?.summary) ?? "Configuration warning",
|
||||
...(asString(payload?.details) ? { details: asString(payload?.details) } : {}),
|
||||
...(asString(payload?.path) ? { path: asString(payload?.path) } : {}),
|
||||
...(payload?.range !== undefined ? { range: payload.range } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "account/updated") {
|
||||
return [
|
||||
{
|
||||
type: "account.updated",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
account: event.payload ?? {},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "account/rateLimits/updated") {
|
||||
return [
|
||||
{
|
||||
type: "account.rate-limits.updated",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
rateLimits: event.payload ?? {},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "mcpServer/oauthLogin/completed") {
|
||||
return [
|
||||
{
|
||||
type: "mcp.oauth.completed",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
success: payload?.success === true,
|
||||
...(asString(payload?.name) ? { name: asString(payload?.name) } : {}),
|
||||
...(asString(payload?.error) ? { error: asString(payload?.error) } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "thread/realtime/started") {
|
||||
const realtimeSessionId = asString(payload?.realtimeSessionId);
|
||||
return [
|
||||
{
|
||||
type: "thread.realtime.started",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
realtimeSessionId,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "thread/realtime/itemAdded") {
|
||||
return [
|
||||
{
|
||||
type: "thread.realtime.item-added",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
item: event.payload ?? {},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "thread/realtime/outputAudio/delta") {
|
||||
return [
|
||||
{
|
||||
type: "thread.realtime.audio.delta",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
audio: event.payload ?? {},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "thread/realtime/error") {
|
||||
const message = asString(payload?.message) ?? event.message ?? "Realtime error";
|
||||
return [
|
||||
{
|
||||
type: "thread.realtime.error",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
message,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "thread/realtime/closed") {
|
||||
return [
|
||||
{
|
||||
type: "thread.realtime.closed",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
reason: event.message,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "error") {
|
||||
const message =
|
||||
asString(asObject(payload?.error)?.message) ?? event.message ?? "Provider runtime error";
|
||||
|
||||
@@ -90,7 +90,6 @@ interface UserRowMeasurement {
|
||||
}
|
||||
|
||||
interface MountedChatView {
|
||||
[Symbol.asyncDispose]: () => Promise<void>;
|
||||
cleanup: () => Promise<void>;
|
||||
measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
|
||||
setViewport: (viewport: ViewportSpec) => Promise<void>;
|
||||
@@ -766,14 +765,11 @@ async function mountChatView(options: {
|
||||
|
||||
await waitForLayout();
|
||||
|
||||
const cleanup = async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
};
|
||||
|
||||
return {
|
||||
[Symbol.asyncDispose]: cleanup,
|
||||
cleanup,
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }),
|
||||
setViewport: async (viewport: ViewportSpec) => {
|
||||
await setViewport(viewport);
|
||||
@@ -830,8 +826,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
stickyModelSelection: null,
|
||||
});
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
@@ -1496,17 +1491,14 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("snapshots sticky codex settings into a new draft thread", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "codex",
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -1531,16 +1523,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const newThreadId = newThreadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
@@ -1549,17 +1538,14 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("hydrates the provider alongside a sticky claude model", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelectionByProvider: {
|
||||
claudeAgent: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
stickyModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "claudeAgent",
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -1584,18 +1570,16 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const newThreadId = newThreadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
|
||||
modelSelectionByProvider: {
|
||||
claudeAgent: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
activeProvider: "claudeAgent",
|
||||
});
|
||||
await expect.element(page.getByText("Claude Opus 4.6")).toBeInTheDocument();
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
@@ -1631,17 +1615,14 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("prefers draft state over sticky composer settings and defaults", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "codex",
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -1666,16 +1647,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const threadId = threadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
});
|
||||
|
||||
useComposerDraftStore.getState().setModelSelection(threadId, {
|
||||
@@ -1695,17 +1673,14 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
"New-thread should reuse the existing project draft thread.",
|
||||
);
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
type ProjectScript,
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
type ProviderUserInputAnswers,
|
||||
type ProjectEntry,
|
||||
type ProjectId,
|
||||
type ProviderApprovalDecision,
|
||||
@@ -25,8 +24,9 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getModelCapabilities,
|
||||
getDefaultModel,
|
||||
normalizeModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
@@ -134,7 +134,6 @@ import {
|
||||
type DraftThreadEnvMode,
|
||||
type PersistedComposerImageAttachment,
|
||||
useComposerDraftStore,
|
||||
useEffectiveComposerModelState,
|
||||
useComposerThreadDraft,
|
||||
} from "../composerDraftStore";
|
||||
import {
|
||||
@@ -198,12 +197,10 @@ const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnsw
|
||||
|
||||
function formatOutgoingPrompt(params: {
|
||||
provider: ProviderKind;
|
||||
model: string | null;
|
||||
effort: string | null;
|
||||
text: string;
|
||||
}): string {
|
||||
const caps = getModelCapabilities(params.provider, params.model);
|
||||
if (params.effort && caps.promptInjectedEffortLevels.includes(params.effort)) {
|
||||
if (params.provider === "claudeAgent" && params.effort === "ultrathink") {
|
||||
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeCodeEffort | null);
|
||||
}
|
||||
return params.text;
|
||||
@@ -598,7 +595,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
]);
|
||||
|
||||
const sessionProvider = activeThread?.session?.provider ?? null;
|
||||
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
|
||||
const selectedProviderByThreadId = composerDraft.modelSelection?.provider ?? null;
|
||||
const threadProvider =
|
||||
activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null;
|
||||
const hasThreadStarted = Boolean(
|
||||
@@ -612,23 +609,34 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
: null;
|
||||
const selectedProvider: ProviderKind =
|
||||
lockedProvider ?? selectedProviderByThreadId ?? threadProvider ?? "codex";
|
||||
const customModelsByProvider = useMemo(() => getCustomModelsByProvider(settings), [settings]);
|
||||
const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({
|
||||
threadId,
|
||||
const baseThreadModel = resolveModelSlugForProvider(
|
||||
selectedProvider,
|
||||
threadModelSelection: activeThread?.modelSelection,
|
||||
projectModelSelection: activeProject?.defaultModelSelection,
|
||||
activeThread?.modelSelection.model ??
|
||||
activeProject?.defaultModelSelection?.model ??
|
||||
getDefaultModel(selectedProvider),
|
||||
);
|
||||
const customModelsByProvider = useMemo(() => getCustomModelsByProvider(settings), [settings]);
|
||||
const selectedModel = useMemo(() => {
|
||||
const draftModel = composerDraft.modelSelection?.model;
|
||||
if (!draftModel) {
|
||||
return baseThreadModel;
|
||||
}
|
||||
return resolveAppModelSelection(selectedProvider, customModelsByProvider, draftModel);
|
||||
}, [
|
||||
baseThreadModel,
|
||||
composerDraft.modelSelection?.model,
|
||||
customModelsByProvider,
|
||||
});
|
||||
selectedProvider,
|
||||
]);
|
||||
const composerProviderState = useMemo(
|
||||
() =>
|
||||
getComposerProviderState({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
prompt,
|
||||
modelOptions: composerModelOptions,
|
||||
modelOptions: composerDraft.modelSelection?.options,
|
||||
}),
|
||||
[composerModelOptions, prompt, selectedModel, selectedProvider],
|
||||
[composerDraft.modelSelection?.options, prompt, selectedModel, selectedProvider],
|
||||
);
|
||||
const selectedPromptEffort = composerProviderState.promptEffort;
|
||||
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
|
||||
@@ -2461,7 +2469,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
const outgoingMessageText = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
effort: selectedPromptEffort,
|
||||
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
});
|
||||
@@ -2736,7 +2743,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
|
||||
const onRespondToUserInput = useCallback(
|
||||
async (requestId: ApprovalRequestId, answers: ProviderUserInputAnswers) => {
|
||||
async (requestId: ApprovalRequestId, answers: Record<string, unknown>) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId) return;
|
||||
|
||||
@@ -2884,7 +2891,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
const outgoingMessageText = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
effort: selectedPromptEffort,
|
||||
text: trimmed,
|
||||
});
|
||||
@@ -2981,7 +2987,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setComposerDraftInteractionMode,
|
||||
setThreadError,
|
||||
settings.enableAssistantStreaming,
|
||||
selectedModel,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -3006,7 +3011,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const implementationPrompt = buildPlanImplementationPrompt(planMarkdown);
|
||||
const outgoingImplementationPrompt = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
effort: selectedPromptEffort,
|
||||
text: implementationPrompt,
|
||||
});
|
||||
@@ -3102,7 +3106,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
selectedProvider,
|
||||
settings.enableAssistantStreaming,
|
||||
syncServerReadModel,
|
||||
selectedModel,
|
||||
]);
|
||||
|
||||
const onProviderModelSelect = useCallback(
|
||||
@@ -3113,9 +3116,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
const resolvedModel = resolveAppModelSelection(provider, customModelsByProvider, model);
|
||||
const existingModelSelection = composerDraft.modelSelection;
|
||||
const preserveOptions =
|
||||
existingModelSelection?.provider === provider &&
|
||||
existingModelSelection.options !== undefined;
|
||||
const nextModelSelection: ModelSelection = {
|
||||
provider,
|
||||
model: resolvedModel,
|
||||
...(preserveOptions ? { options: existingModelSelection.options } : {}),
|
||||
};
|
||||
setComposerDraftModelSelection(activeThread.id, nextModelSelection);
|
||||
setStickyComposerModelSelection(nextModelSelection);
|
||||
@@ -3123,6 +3131,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
composerDraft.modelSelection,
|
||||
lockedProvider,
|
||||
scheduleComposerFocus,
|
||||
setComposerDraftModelSelection,
|
||||
@@ -3150,16 +3159,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
provider: selectedProvider,
|
||||
threadId,
|
||||
model: selectedModel,
|
||||
modelOptions: composerModelOptions?.[selectedProvider],
|
||||
prompt,
|
||||
onPromptChange: setPromptFromTraits,
|
||||
});
|
||||
const providerTraitsPicker = renderProviderTraitsPicker({
|
||||
provider: selectedProvider,
|
||||
threadId,
|
||||
model: selectedModel,
|
||||
modelOptions: composerModelOptions?.[selectedProvider],
|
||||
prompt,
|
||||
onPromptChange: setPromptFromTraits,
|
||||
});
|
||||
const onEnvModeChange = useCallback(
|
||||
|
||||
@@ -347,16 +347,13 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "action_finished":
|
||||
// Don't clear timestamps here — the HTTP response handler (line 496)
|
||||
// sets activeGitActionProgressRef to null and shows the success toast.
|
||||
// Clearing timestamps early causes the "Running for Xs" description
|
||||
// to disappear before the success state renders, leaving a bare
|
||||
// "Pushing..." toast in the gap between the WS event and HTTP response.
|
||||
return;
|
||||
progress.phaseStartedAtMs = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
break;
|
||||
case "action_failed":
|
||||
// Same reasoning as action_finished — let the HTTP error handler
|
||||
// manage the final toast state to avoid a flash of bare title.
|
||||
return;
|
||||
progress.phaseStartedAtMs = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
break;
|
||||
}
|
||||
|
||||
updateActiveProgressToast();
|
||||
|
||||
@@ -343,7 +343,6 @@ describe("getVisibleThreadsForProject", () => {
|
||||
});
|
||||
|
||||
function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
const { defaultModelSelection, ...rest } = overrides;
|
||||
return {
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Project",
|
||||
@@ -351,13 +350,13 @@ function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
...defaultModelSelection,
|
||||
...overrides?.defaultModelSelection,
|
||||
},
|
||||
expanded: true,
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
scripts: [],
|
||||
...rest,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import "../../index.css";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { ClaudeTraitsPicker } from "./ClaudeTraitsPicker";
|
||||
import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
|
||||
async function mountPicker(props?: {
|
||||
model?: string;
|
||||
prompt?: string;
|
||||
effort?: "low" | "medium" | "high" | "max" | "ultrathink" | null;
|
||||
thinkingEnabled?: boolean | null;
|
||||
fastModeEnabled?: boolean;
|
||||
}) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-claude-traits");
|
||||
const draftsByThreadId = {} as ReturnType<
|
||||
typeof useComposerDraftStore.getState
|
||||
>["draftsByThreadId"];
|
||||
draftsByThreadId[threadId] = {
|
||||
prompt: props?.prompt ?? "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
options: {
|
||||
...(props?.effort ? { effort: props.effort } : {}),
|
||||
...(props?.thinkingEnabled === false ? { thinking: false } : {}),
|
||||
...(props?.fastModeEnabled ? { fastMode: true } : {}),
|
||||
},
|
||||
},
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const onPromptChange = vi.fn();
|
||||
const screen = await render(
|
||||
<ClaudeTraitsPicker
|
||||
threadId={threadId}
|
||||
model={props?.model ?? "claude-opus-4-6"}
|
||||
onPromptChange={onPromptChange}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
return {
|
||||
onPromptChange,
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("ClaudeTraitsPicker", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls for Opus", async () => {
|
||||
const mounted = await mountPicker();
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-Opus models", async () => {
|
||||
const mounted = await mountPicker({ model: "claude-sonnet-4-6" });
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
const mounted = await mountPicker({
|
||||
model: "claude-sonnet-4-6",
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Max");
|
||||
expect(text).toContain("Ultrathink");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a thinking on/off dropdown for Haiku", async () => {
|
||||
const mounted = await mountPicker({
|
||||
model: "claude-haiku-4-5",
|
||||
thinkingEnabled: true,
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Thinking On");
|
||||
});
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Thinking");
|
||||
expect(text).toContain("On (default)");
|
||||
expect(text).toContain("Off");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows prompt-controlled Ultrathink state with disabled effort controls", async () => {
|
||||
const mounted = await mountPicker({
|
||||
effort: "high",
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "Ultrathink:\nInvestigate this",
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Ultrathink");
|
||||
expect(document.body.textContent ?? "").not.toContain("Ultrathink · Prompt");
|
||||
});
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("persists sticky claude model options when traits change", async () => {
|
||||
const mounted = await mountPicker({
|
||||
model: "claude-opus-4-6",
|
||||
effort: "medium",
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "Max" }).click();
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import {
|
||||
ProviderKind,
|
||||
type ClaudeCodeEffort,
|
||||
type ClaudeModelOptions,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
normalizeClaudeModelOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
isClaudeUltrathinkPrompt,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator as MenuDivider,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
|
||||
|
||||
const PROVIDER = "claudeAgent" as const satisfies ProviderKind;
|
||||
|
||||
const CLAUDE_EFFORT_LABELS: Record<ClaudeCodeEffort, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
max: "Max",
|
||||
ultrathink: "Ultrathink",
|
||||
};
|
||||
|
||||
const ULTRATHINK_PROMPT_PREFIX = "Ultrathink:\n";
|
||||
|
||||
function getSelectedClaudeTraits(
|
||||
model: string | null | undefined,
|
||||
prompt: string,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): {
|
||||
effort: Exclude<ClaudeCodeEffort, "ultrathink"> | null;
|
||||
thinkingEnabled: boolean | null;
|
||||
fastModeEnabled: boolean;
|
||||
options: ReadonlyArray<ClaudeCodeEffort>;
|
||||
ultrathinkPromptControlled: boolean;
|
||||
supportsFastMode: boolean;
|
||||
} {
|
||||
const options = getReasoningEffortOptions(PROVIDER, model);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER) as Exclude<
|
||||
ClaudeCodeEffort,
|
||||
"ultrathink"
|
||||
>;
|
||||
const resolvedEffort = resolveReasoningEffortForProvider(PROVIDER, modelOptions?.effort);
|
||||
const effort =
|
||||
resolvedEffort && resolvedEffort !== "ultrathink" && options.includes(resolvedEffort)
|
||||
? resolvedEffort
|
||||
: options.includes(defaultReasoningEffort)
|
||||
? defaultReasoningEffort
|
||||
: null;
|
||||
const thinkingEnabled = supportsClaudeThinkingToggle(model)
|
||||
? (modelOptions?.thinking ?? true)
|
||||
: null;
|
||||
const supportsFastMode = supportsClaudeFastMode(model);
|
||||
return {
|
||||
effort,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled: supportsFastMode && modelOptions?.fastMode === true,
|
||||
options,
|
||||
ultrathinkPromptControlled:
|
||||
supportsClaudeUltrathinkKeyword(model) && isClaudeUltrathinkPrompt(prompt),
|
||||
supportsFastMode,
|
||||
};
|
||||
}
|
||||
|
||||
interface ClaudeTraitsMenuContentProps {
|
||||
threadId: ThreadId;
|
||||
model: string | null | undefined;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}
|
||||
|
||||
export const ClaudeTraitsMenuContent = memo(function ClaudeTraitsMenuContentImpl({
|
||||
threadId,
|
||||
model,
|
||||
onPromptChange,
|
||||
}: ClaudeTraitsMenuContentProps) {
|
||||
const draft = useComposerThreadDraft(threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions =
|
||||
draft.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const {
|
||||
effort,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
options,
|
||||
ultrathinkPromptControlled,
|
||||
supportsFastMode,
|
||||
} = getSelectedClaudeTraits(model, prompt, modelOptions);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER);
|
||||
|
||||
const handleEffortChange = useCallback(
|
||||
(value: ClaudeCodeEffort) => {
|
||||
if (ultrathinkPromptControlled) return;
|
||||
if (!value) return;
|
||||
const nextEffort = options.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
if (nextEffort === "ultrathink") {
|
||||
const nextPrompt =
|
||||
prompt.trim().length === 0
|
||||
? ULTRATHINK_PROMPT_PREFIX
|
||||
: applyClaudePromptEffortPrefix(prompt, "ultrathink");
|
||||
onPromptChange(nextPrompt);
|
||||
return;
|
||||
}
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
PROVIDER,
|
||||
normalizeClaudeModelOptions(model, {
|
||||
...modelOptions,
|
||||
effort: nextEffort,
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
},
|
||||
[
|
||||
ultrathinkPromptControlled,
|
||||
model,
|
||||
modelOptions,
|
||||
onPromptChange,
|
||||
threadId,
|
||||
setProviderModelOptions,
|
||||
options,
|
||||
prompt,
|
||||
],
|
||||
);
|
||||
|
||||
if (effort === null && thinkingEnabled === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{effort ? (
|
||||
<>
|
||||
<MenuGroup>
|
||||
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">Effort</div>
|
||||
{ultrathinkPromptControlled ? (
|
||||
<div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
|
||||
Remove Ultrathink from the prompt to change effort.
|
||||
</div>
|
||||
) : null}
|
||||
<MenuRadioGroup value={effort} onValueChange={handleEffortChange}>
|
||||
{options.map((option) => (
|
||||
<MenuRadioItem key={option} value={option} disabled={ultrathinkPromptControlled}>
|
||||
{CLAUDE_EFFORT_LABELS[option]}
|
||||
{option === defaultReasoningEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : thinkingEnabled !== null ? (
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Thinking</div>
|
||||
<MenuRadioGroup
|
||||
value={thinkingEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
PROVIDER,
|
||||
normalizeClaudeModelOptions(model, {
|
||||
...modelOptions,
|
||||
thinking: value === "on",
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="on">On (default)</MenuRadioItem>
|
||||
<MenuRadioItem value="off">Off</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
) : null}
|
||||
{supportsFastMode ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
PROVIDER,
|
||||
normalizeClaudeModelOptions(model, {
|
||||
...modelOptions,
|
||||
fastMode: value === "on",
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export const ClaudeTraitsPicker = memo(function ClaudeTraitsPicker({
|
||||
threadId,
|
||||
model,
|
||||
onPromptChange,
|
||||
}: ClaudeTraitsMenuContentProps) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const draft = useComposerThreadDraft(threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions =
|
||||
draft.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
const { effort, thinkingEnabled, fastModeEnabled, ultrathinkPromptControlled, supportsFastMode } =
|
||||
getSelectedClaudeTraits(model, prompt, modelOptions);
|
||||
const triggerLabel = [
|
||||
ultrathinkPromptControlled
|
||||
? "Ultrathink"
|
||||
: effort
|
||||
? CLAUDE_EFFORT_LABELS[effort]
|
||||
: thinkingEnabled === null
|
||||
? null
|
||||
: `Thinking ${thinkingEnabled ? "On" : "Off"}`,
|
||||
...(supportsFastMode && fastModeEnabled ? ["Fast"] : []),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsMenuOpen(open);
|
||||
}}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
<ClaudeTraitsMenuContent
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import "../../index.css";
|
||||
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { CodexTraitsPicker } from "./CodexTraitsPicker";
|
||||
import { COMPOSER_DRAFT_STORAGE_KEY, useComposerDraftStore } from "../../composerDraftStore";
|
||||
|
||||
async function mountPicker(props: {
|
||||
reasoningEffort?: "low" | "medium" | "high" | "xhigh";
|
||||
fastModeEnabled: boolean;
|
||||
}) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-codex-traits");
|
||||
const draftsByThreadId = {} as ReturnType<
|
||||
typeof useComposerDraftStore.getState
|
||||
>["draftsByThreadId"];
|
||||
draftsByThreadId[threadId] = {
|
||||
prompt: "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
...(props.reasoningEffort ? { reasoningEffort: props.reasoningEffort } : {}),
|
||||
...(props.fastModeEnabled ? { fastMode: true } : {}),
|
||||
},
|
||||
},
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[ProjectId.makeUnsafe("project-codex-traits")]: threadId,
|
||||
},
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const screen = await render(<CodexTraitsPicker threadId={threadId} />, { container: host });
|
||||
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("CodexTraitsPicker", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows Fast in the trigger label when fast mode is active", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: true,
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("High · Fast");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).toContain("Extra High");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("persists sticky codex model options when traits change", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "on" }).click();
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toMatchObject({
|
||||
provider: "codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hydrates legacy codex persisted state into modelOptions through the picker", async () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-codex-legacy");
|
||||
localStorage.setItem(
|
||||
COMPOSER_DRAFT_STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
state: {
|
||||
draftsByThreadId: {
|
||||
[threadId]: {
|
||||
prompt: "",
|
||||
attachments: [],
|
||||
modelSelection: null,
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "xhigh",
|
||||
codexFastMode: true,
|
||||
serviceTier: "fast",
|
||||
},
|
||||
},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
},
|
||||
version: 1,
|
||||
}),
|
||||
);
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const screen = await render(<CodexTraitsPicker threadId={threadId} />, { container: host });
|
||||
|
||||
try {
|
||||
await useComposerDraftStore.persist.rehydrate();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Extra High · Fast");
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
{
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
import type {
|
||||
CodexModelOptions,
|
||||
CodexReasoningEffort,
|
||||
ProviderKind,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
normalizeCodexModelOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator as MenuDivider,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
|
||||
const PROVIDER = "codex" as const satisfies ProviderKind;
|
||||
|
||||
const CODEX_REASONING_LABELS: Record<CodexReasoningEffort, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
xhigh: "Extra High",
|
||||
};
|
||||
|
||||
function getSelectedCodexTraits(modelOptions: CodexModelOptions | null | undefined): {
|
||||
effort: CodexReasoningEffort;
|
||||
fastModeEnabled: boolean;
|
||||
} {
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER);
|
||||
return {
|
||||
effort:
|
||||
resolveReasoningEffortForProvider(PROVIDER, modelOptions?.reasoningEffort) ??
|
||||
defaultReasoningEffort,
|
||||
fastModeEnabled: modelOptions?.fastMode === true,
|
||||
};
|
||||
}
|
||||
|
||||
function CodexTraitsMenuContentImpl(props: { threadId: ThreadId }) {
|
||||
const draft = useComposerThreadDraft(props.threadId);
|
||||
const modelOptions =
|
||||
draft.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const options = getReasoningEffortOptions(PROVIDER);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER);
|
||||
const { effort, fastModeEnabled } = getSelectedCodexTraits(modelOptions);
|
||||
|
||||
return (
|
||||
<>
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Reasoning</div>
|
||||
<MenuRadioGroup
|
||||
value={effort}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
const nextEffort = options.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
setProviderModelOptions(
|
||||
props.threadId,
|
||||
PROVIDER,
|
||||
normalizeCodexModelOptions({
|
||||
...modelOptions,
|
||||
reasoningEffort: nextEffort,
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
{options.map((option) => (
|
||||
<MenuRadioItem key={option} value={option}>
|
||||
{CODEX_REASONING_LABELS[option]}
|
||||
{option === defaultReasoningEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setProviderModelOptions(
|
||||
props.threadId,
|
||||
PROVIDER,
|
||||
normalizeCodexModelOptions({
|
||||
...modelOptions,
|
||||
fastMode: value === "on",
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const CodexTraitsMenuContent = memo(CodexTraitsMenuContentImpl);
|
||||
|
||||
export const CodexTraitsPicker = memo(function CodexTraitsPicker(props: { threadId: ThreadId }) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const draft = useComposerThreadDraft(props.threadId);
|
||||
const modelOptions =
|
||||
draft.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
const { effort, fastModeEnabled } = getSelectedCodexTraits(modelOptions);
|
||||
const triggerLabel = [CODEX_REASONING_LABELS[effort], ...(fastModeEnabled ? ["Fast"] : [])]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsMenuOpen(open);
|
||||
}}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:max-w-48 sm:px-3 [&_svg]:mx-0"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
|
||||
{triggerLabel}
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
<CodexTraitsMenuContent threadId={props.threadId} />
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DEFAULT_MODEL_BY_PROVIDER, ModelSelection, ThreadId } from "@t3tools/contracts";
|
||||
import { type ProviderModelOptions, ThreadId } from "@t3tools/contracts";
|
||||
import "../../index.css";
|
||||
|
||||
import { page } from "vitest/browser";
|
||||
@@ -6,31 +6,37 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
|
||||
import { TraitsMenuContent } from "./TraitsPicker";
|
||||
import { ClaudeTraitsMenuContent } from "./ClaudeTraitsPicker";
|
||||
import { CodexTraitsMenuContent } from "./CodexTraitsPicker";
|
||||
import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
|
||||
async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: string }) {
|
||||
async function mountMenu(props?: {
|
||||
model?: string;
|
||||
prompt?: string;
|
||||
provider?: "codex" | "claudeAgent";
|
||||
modelOptions?: ProviderModelOptions | null;
|
||||
}) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-compact-menu");
|
||||
const provider = props?.modelSelection?.provider ?? "claudeAgent";
|
||||
const provider = props?.provider ?? "claudeAgent";
|
||||
const draftsByThreadId = {} as ReturnType<
|
||||
typeof useComposerDraftStore.getState
|
||||
>["draftsByThreadId"];
|
||||
const model = props?.modelSelection?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
|
||||
draftsByThreadId[threadId] = {
|
||||
prompt: props?.prompt ?? "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelectionByProvider: {
|
||||
[provider]: {
|
||||
provider,
|
||||
model,
|
||||
...(props?.modelSelection?.options ? { options: props.modelSelection.options } : {}),
|
||||
},
|
||||
modelSelection: {
|
||||
provider,
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
...(props?.modelOptions
|
||||
? {
|
||||
options:
|
||||
provider === "codex" ? props.modelOptions.codex : props.modelOptions.claudeAgent,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
activeProvider: provider,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
@@ -42,7 +48,6 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const onPromptChange = vi.fn();
|
||||
const providerOptions = props?.modelSelection?.options;
|
||||
const screen = await render(
|
||||
<CompactComposerControlsMenu
|
||||
activePlan={false}
|
||||
@@ -50,14 +55,15 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
planSidebarOpen={false}
|
||||
runtimeMode="approval-required"
|
||||
traitsMenuContent={
|
||||
<TraitsMenuContent
|
||||
provider={provider}
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
prompt={props?.prompt ?? ""}
|
||||
modelOptions={providerOptions}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
provider === "codex" ? (
|
||||
<CodexTraitsMenuContent threadId={threadId} />
|
||||
) : (
|
||||
<ClaudeTraitsMenuContent
|
||||
threadId={threadId}
|
||||
model={props?.model ?? "claude-opus-4-6"}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
)
|
||||
}
|
||||
onToggleInteractionMode={vi.fn()}
|
||||
onTogglePlanSidebar={vi.fn()}
|
||||
@@ -66,14 +72,11 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
const cleanup = async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
};
|
||||
|
||||
return {
|
||||
[Symbol.asyncDispose]: cleanup,
|
||||
cleanup,
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -84,90 +87,107 @@ describe("CompactComposerControlsMenu", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls for Opus", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
||||
});
|
||||
const mounted = await mountMenu();
|
||||
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-Opus Claude models", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||
});
|
||||
const mounted = await mountMenu({ model: "claude-sonnet-4-6" });
|
||||
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||
const mounted = await mountMenu({
|
||||
model: "claude-sonnet-4-6",
|
||||
});
|
||||
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Max");
|
||||
expect(text).toContain("Ultrathink");
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Max");
|
||||
expect(text).toContain("Ultrathink");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a Claude thinking on/off section for Haiku", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: { thinking: true },
|
||||
const mounted = await mountMenu({
|
||||
model: "claude-haiku-4-5",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
thinking: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Thinking");
|
||||
expect(text).toContain("On (default)");
|
||||
expect(text).toContain("Off");
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Thinking");
|
||||
expect(text).toContain("On (default)");
|
||||
expect(text).toContain("Off");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows prompt-controlled Ultrathink messaging with disabled effort controls", async () => {
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: { effort: "high" },
|
||||
},
|
||||
const mounted = await mountMenu({
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "Ultrathink:\nInvestigate this",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PROVIDER_DISPLAY_NAMES, type ServerProviderStatus } from "@t3tools/contracts";
|
||||
import { type ServerProviderStatus } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
|
||||
import { CircleAlertIcon } from "lucide-react";
|
||||
@@ -12,7 +12,12 @@ export const ProviderHealthBanner = memo(function ProviderHealthBanner({
|
||||
return null;
|
||||
}
|
||||
|
||||
const providerLabel = PROVIDER_DISPLAY_NAMES[status.provider] ?? status.provider;
|
||||
const providerLabel =
|
||||
status.provider === "codex"
|
||||
? "Codex"
|
||||
: status.provider === "claudeAgent"
|
||||
? "Claude"
|
||||
: status.provider;
|
||||
const defaultMessage =
|
||||
status.status === "error"
|
||||
? `${providerLabel} provider is unavailable.`
|
||||
|
||||
@@ -1,362 +0,0 @@
|
||||
import "../../index.css";
|
||||
|
||||
import {
|
||||
type ModelSelection,
|
||||
ClaudeModelOptions,
|
||||
CodexModelOptions,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { useCallback } from "react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { TraitsPicker } from "./TraitsPicker";
|
||||
import {
|
||||
COMPOSER_DRAFT_STORAGE_KEY,
|
||||
ComposerThreadDraftState,
|
||||
useComposerDraftStore,
|
||||
useComposerThreadDraft,
|
||||
useEffectiveComposerModelState,
|
||||
} from "../../composerDraftStore";
|
||||
|
||||
// ── Claude TraitsPicker tests ─────────────────────────────────────────
|
||||
|
||||
const CLAUDE_THREAD_ID = ThreadId.makeUnsafe("thread-claude-traits");
|
||||
|
||||
function ClaudeTraitsPickerHarness(props: {
|
||||
model: string;
|
||||
fallbackModelSelection: ModelSelection | null;
|
||||
}) {
|
||||
const prompt = useComposerThreadDraft(CLAUDE_THREAD_ID).prompt;
|
||||
const setPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
const { modelOptions, selectedModel } = useEffectiveComposerModelState({
|
||||
threadId: CLAUDE_THREAD_ID,
|
||||
selectedProvider: "claudeAgent",
|
||||
threadModelSelection: props.fallbackModelSelection,
|
||||
projectModelSelection: null,
|
||||
customModelsByProvider: { codex: [], claudeAgent: [] },
|
||||
});
|
||||
const handlePromptChange = useCallback(
|
||||
(nextPrompt: string) => {
|
||||
setPrompt(CLAUDE_THREAD_ID, nextPrompt);
|
||||
},
|
||||
[setPrompt],
|
||||
);
|
||||
|
||||
return (
|
||||
<TraitsPicker
|
||||
provider="claudeAgent"
|
||||
threadId={CLAUDE_THREAD_ID}
|
||||
model={selectedModel ?? props.model}
|
||||
prompt={prompt}
|
||||
modelOptions={modelOptions?.claudeAgent}
|
||||
onPromptChange={handlePromptChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
async function mountClaudePicker(props?: {
|
||||
model?: string;
|
||||
prompt?: string;
|
||||
options?: ClaudeModelOptions;
|
||||
fallbackModelOptions?: {
|
||||
effort?: "low" | "medium" | "high" | "max" | "ultrathink";
|
||||
thinking?: boolean;
|
||||
fastMode?: boolean;
|
||||
} | null;
|
||||
skipDraftModelOptions?: boolean;
|
||||
}) {
|
||||
const model = props?.model ?? "claude-opus-4-6";
|
||||
const claudeOptions = !props?.skipDraftModelOptions ? props?.options : undefined;
|
||||
const draftsByThreadId: Record<ThreadId, ComposerThreadDraftState> = {
|
||||
[CLAUDE_THREAD_ID]: {
|
||||
prompt: props?.prompt ?? "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelectionByProvider: props?.skipDraftModelOptions
|
||||
? {}
|
||||
: {
|
||||
claudeAgent: {
|
||||
provider: "claudeAgent",
|
||||
model,
|
||||
...(claudeOptions && Object.keys(claudeOptions).length > 0
|
||||
? { options: claudeOptions }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
activeProvider: "claudeAgent",
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
},
|
||||
};
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const fallbackModelSelection =
|
||||
props?.fallbackModelOptions !== undefined
|
||||
? ({
|
||||
provider: "claudeAgent",
|
||||
model,
|
||||
options: props.fallbackModelOptions ?? undefined,
|
||||
} satisfies ModelSelection)
|
||||
: null;
|
||||
const screen = await render(
|
||||
<ClaudeTraitsPickerHarness model={model} fallbackModelSelection={fallbackModelSelection} />,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
const cleanup = async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
};
|
||||
|
||||
return {
|
||||
[Symbol.asyncDispose]: cleanup,
|
||||
cleanup,
|
||||
};
|
||||
}
|
||||
|
||||
describe("TraitsPicker (Claude)", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls for Opus", async () => {
|
||||
await using _ = await mountClaudePicker();
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-Opus models", async () => {
|
||||
await using _ = await mountClaudePicker({ model: "claude-sonnet-4-6" });
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
await using _ = await mountClaudePicker({
|
||||
model: "claude-sonnet-4-6",
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Max");
|
||||
expect(text).toContain("Ultrathink");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a th inking on/off dropdown for Haiku", async () => {
|
||||
await using _ = await mountClaudePicker({
|
||||
model: "claude-haiku-4-5",
|
||||
options: { thinking: true },
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Thinking On");
|
||||
});
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Thinking");
|
||||
expect(text).toContain("On (default)");
|
||||
expect(text).toContain("Off");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows prompt-controlled Ultrathink state with disabled effort controls", async () => {
|
||||
await using _ = await mountClaudePicker({
|
||||
model: "claude-opus-4-6",
|
||||
options: { effort: "high" },
|
||||
prompt: "Ultrathink:\nInvestigate this",
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Ultrathink");
|
||||
expect(document.body.textContent ?? "").not.toContain("Ultrathink · Prompt");
|
||||
});
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
});
|
||||
|
||||
it("persists sticky claude model options when traits change", async () => {
|
||||
await using _ = await mountClaudePicker({
|
||||
model: "claude-opus-4-6",
|
||||
options: { effort: "medium", fastMode: false },
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "Max" }).click();
|
||||
|
||||
expect(
|
||||
useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent,
|
||||
).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ── Codex TraitsPicker tests ──────────────────────────────────────────
|
||||
|
||||
async function mountCodexPicker(props: { model?: string; options?: CodexModelOptions }) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-codex-traits");
|
||||
const model = props.model ?? DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
const draftsByThreadId: Record<ThreadId, ComposerThreadDraftState> = {
|
||||
[threadId]: {
|
||||
prompt: "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model,
|
||||
...(props.options ? { options: props.options } : {}),
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
},
|
||||
};
|
||||
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[ProjectId.makeUnsafe("project-codex-traits")]: threadId,
|
||||
},
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const screen = await render(
|
||||
<TraitsPicker
|
||||
provider="codex"
|
||||
threadId={threadId}
|
||||
model={props.model ?? DEFAULT_MODEL_BY_PROVIDER.codex}
|
||||
prompt=""
|
||||
modelOptions={props.options}
|
||||
onPromptChange={() => {}}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
const cleanup = async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
};
|
||||
|
||||
return {
|
||||
[Symbol.asyncDispose]: cleanup,
|
||||
cleanup,
|
||||
};
|
||||
}
|
||||
|
||||
describe("TraitsPicker (Codex)", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls", async () => {
|
||||
await using _ = await mountCodexPicker({
|
||||
options: { fastMode: false },
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows Fast in the trigger label when fast mode is active", async () => {
|
||||
await using _ = await mountCodexPicker({
|
||||
options: { fastMode: true },
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("High · Fast");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
await using _ = await mountCodexPicker({
|
||||
options: { fastMode: false },
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).toContain("Extra High");
|
||||
});
|
||||
});
|
||||
|
||||
it("persists sticky codex model options when traits change", async () => {
|
||||
await using _ = await mountCodexPicker({
|
||||
options: { fastMode: false },
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "on" }).click();
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toMatchObject({
|
||||
provider: "codex",
|
||||
options: { fastMode: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,320 +0,0 @@
|
||||
import {
|
||||
type ClaudeModelOptions,
|
||||
type CodexModelOptions,
|
||||
type ProviderKind,
|
||||
type ProviderModelOptions,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getModelCapabilities,
|
||||
isClaudeUltrathinkPrompt,
|
||||
trimOrNull,
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator as MenuDivider,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
|
||||
type ProviderOptions = ProviderModelOptions[ProviderKind];
|
||||
|
||||
const ULTRATHINK_PROMPT_PREFIX = "Ultrathink:\n";
|
||||
|
||||
function getRawEffort(
|
||||
provider: ProviderKind,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
): string | null {
|
||||
if (provider === "codex") {
|
||||
return trimOrNull((modelOptions as CodexModelOptions | undefined)?.reasoningEffort);
|
||||
}
|
||||
return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.effort);
|
||||
}
|
||||
|
||||
function buildNextOptions(
|
||||
provider: ProviderKind,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
patch: Record<string, unknown>,
|
||||
): ProviderOptions {
|
||||
if (provider === "codex") {
|
||||
return { ...(modelOptions as CodexModelOptions | undefined), ...patch } as CodexModelOptions;
|
||||
}
|
||||
return { ...(modelOptions as ClaudeModelOptions | undefined), ...patch } as ClaudeModelOptions;
|
||||
}
|
||||
|
||||
function getSelectedTraits(
|
||||
provider: ProviderKind,
|
||||
model: string | null | undefined,
|
||||
prompt: string,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
) {
|
||||
const caps = getModelCapabilities(provider, model);
|
||||
const effortLevels = caps.reasoningEffortLevels;
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
|
||||
// Resolve effort from options (provider-specific key)
|
||||
const resolvedEffort = getRawEffort(provider, modelOptions);
|
||||
|
||||
// Filter out prompt-injected efforts from the "current effort" display
|
||||
const isPromptInjected = resolvedEffort
|
||||
? caps.promptInjectedEffortLevels.includes(resolvedEffort)
|
||||
: false;
|
||||
const effort =
|
||||
resolvedEffort && !isPromptInjected && hasEffortLevel(caps, resolvedEffort)
|
||||
? resolvedEffort
|
||||
: defaultEffort && hasEffortLevel(caps, defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
|
||||
// Thinking toggle (only for models that support it)
|
||||
const thinkingEnabled = caps.supportsThinkingToggle
|
||||
? ((modelOptions as ClaudeModelOptions | undefined)?.thinking ?? true)
|
||||
: null;
|
||||
|
||||
// Fast mode
|
||||
const fastModeEnabled =
|
||||
caps.supportsFastMode &&
|
||||
(modelOptions as { fastMode?: boolean } | undefined)?.fastMode === true;
|
||||
|
||||
// Prompt-controlled effort (e.g. ultrathink in prompt text)
|
||||
const ultrathinkPromptControlled =
|
||||
caps.promptInjectedEffortLevels.length > 0 && isClaudeUltrathinkPrompt(prompt);
|
||||
|
||||
return {
|
||||
caps,
|
||||
effort,
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
ultrathinkPromptControlled,
|
||||
};
|
||||
}
|
||||
|
||||
export interface TraitsMenuContentProps {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: string | null | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
modelOptions?: ProviderOptions | null | undefined;
|
||||
}
|
||||
|
||||
export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
provider,
|
||||
threadId,
|
||||
model,
|
||||
prompt,
|
||||
onPromptChange,
|
||||
modelOptions,
|
||||
}: TraitsMenuContentProps) {
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const {
|
||||
caps,
|
||||
effort,
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
ultrathinkPromptControlled,
|
||||
} = getSelectedTraits(provider, model, prompt, modelOptions);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
|
||||
const handleEffortChange = useCallback(
|
||||
(value: string) => {
|
||||
if (ultrathinkPromptControlled) return;
|
||||
if (!value) return;
|
||||
const nextOption = effortLevels.find((option) => option.value === value);
|
||||
if (!nextOption) return;
|
||||
if (caps.promptInjectedEffortLevels.includes(nextOption.value)) {
|
||||
const nextPrompt =
|
||||
prompt.trim().length === 0
|
||||
? ULTRATHINK_PROMPT_PREFIX
|
||||
: applyClaudePromptEffortPrefix(prompt, "ultrathink");
|
||||
onPromptChange(nextPrompt);
|
||||
return;
|
||||
}
|
||||
const effortKey = provider === "codex" ? "reasoningEffort" : "effort";
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
provider,
|
||||
buildNextOptions(provider, modelOptions, { [effortKey]: nextOption.value }),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
},
|
||||
[
|
||||
ultrathinkPromptControlled,
|
||||
modelOptions,
|
||||
onPromptChange,
|
||||
threadId,
|
||||
setProviderModelOptions,
|
||||
effortLevels,
|
||||
prompt,
|
||||
caps.promptInjectedEffortLevels,
|
||||
provider,
|
||||
],
|
||||
);
|
||||
|
||||
if (effort === null && thinkingEnabled === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{effort ? (
|
||||
<>
|
||||
<MenuGroup>
|
||||
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">Effort</div>
|
||||
{ultrathinkPromptControlled ? (
|
||||
<div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
|
||||
Remove Ultrathink from the prompt to change effort.
|
||||
</div>
|
||||
) : null}
|
||||
<MenuRadioGroup value={effort} onValueChange={handleEffortChange}>
|
||||
{effortLevels.map((option) => (
|
||||
<MenuRadioItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
disabled={ultrathinkPromptControlled}
|
||||
>
|
||||
{option.label}
|
||||
{option.value === defaultEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : thinkingEnabled !== null ? (
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Thinking</div>
|
||||
<MenuRadioGroup
|
||||
value={thinkingEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
provider,
|
||||
buildNextOptions(provider, modelOptions, { thinking: value === "on" }),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="on">On (default)</MenuRadioItem>
|
||||
<MenuRadioItem value="off">Off</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
) : null}
|
||||
{caps.supportsFastMode ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
provider,
|
||||
buildNextOptions(provider, modelOptions, { fastMode: value === "on" }),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export const TraitsPicker = memo(function TraitsPicker({
|
||||
provider,
|
||||
threadId,
|
||||
model,
|
||||
prompt,
|
||||
onPromptChange,
|
||||
modelOptions,
|
||||
}: TraitsMenuContentProps) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const {
|
||||
caps,
|
||||
effort,
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
ultrathinkPromptControlled,
|
||||
} = getSelectedTraits(provider, model, prompt, modelOptions);
|
||||
|
||||
const effortLabel = effort
|
||||
? (effortLevels.find((l) => l.value === effort)?.label ?? effort)
|
||||
: null;
|
||||
const triggerLabel = [
|
||||
ultrathinkPromptControlled
|
||||
? "Ultrathink"
|
||||
: effortLabel
|
||||
? effortLabel
|
||||
: thinkingEnabled === null
|
||||
? null
|
||||
: `Thinking ${thinkingEnabled ? "On" : "Off"}`,
|
||||
...(caps.supportsFastMode && fastModeEnabled ? ["Fast"] : []),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
const isCodexStyle = provider === "codex";
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsMenuOpen(open);
|
||||
}}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className={
|
||||
isCodexStyle
|
||||
? "min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:max-w-48 sm:px-3 [&_svg]:mx-0"
|
||||
: "shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{isCodexStyle ? (
|
||||
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
|
||||
{triggerLabel}
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</>
|
||||
)}
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
<TraitsMenuContent
|
||||
provider={provider}
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
prompt={prompt}
|
||||
onPromptChange={onPromptChange}
|
||||
modelOptions={modelOptions}
|
||||
/>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
@@ -23,10 +23,8 @@ describe("getComposerProviderState", () => {
|
||||
model: "gpt-5.4",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -40,47 +38,6 @@ describe("getComposerProviderState", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves codex fast mode when it is the only active option", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("drops explicit codex default/off overrides from dispatch while keeping the selected effort label", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns Claude defaults for effort-capable models", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
@@ -102,9 +59,7 @@ describe("getComposerProviderState", () => {
|
||||
model: "claude-sonnet-4-6",
|
||||
prompt: "Ultrathink:\nInvestigate this failure",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "medium",
|
||||
},
|
||||
effort: "medium",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -126,10 +81,8 @@ describe("getComposerProviderState", () => {
|
||||
model: "claude-haiku-4-5",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
thinking: false,
|
||||
},
|
||||
effort: "max",
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -141,45 +94,4 @@ describe("getComposerProviderState", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves Claude fast mode when it is the only active option", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("drops explicit Claude default/off overrides from dispatch while keeping the selected effort label", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "high",
|
||||
fastMode: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,32 +1,35 @@
|
||||
import {
|
||||
type ClaudeModelOptions,
|
||||
type CodexModelOptions,
|
||||
type ModelSlug,
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
type ProviderModelOptions,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getModelCapabilities,
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptions,
|
||||
normalizeCodexModelOptions,
|
||||
trimOrNull,
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
resolveReasoningEffortForProvider,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
} from "@t3tools/shared/model";
|
||||
import type { ReactNode } from "react";
|
||||
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
|
||||
import { ClaudeTraitsMenuContent, ClaudeTraitsPicker } from "./ClaudeTraitsPicker";
|
||||
import { CodexTraitsMenuContent, CodexTraitsPicker } from "./CodexTraitsPicker";
|
||||
|
||||
export type ComposerProviderStateInput = {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
prompt: string;
|
||||
modelOptions: ProviderModelOptions | null | undefined;
|
||||
modelOptions: ModelSelection["options"] | null | undefined;
|
||||
};
|
||||
|
||||
export type ComposerProviderState = {
|
||||
provider: ProviderKind;
|
||||
promptEffort: string | null;
|
||||
modelOptionsForDispatch: ProviderModelOptions[ProviderKind] | undefined;
|
||||
modelOptionsForDispatch: ModelSelection["options"] | undefined;
|
||||
composerFrameClassName?: string;
|
||||
composerSurfaceClassName?: string;
|
||||
modelPickerIconClassName?: string;
|
||||
@@ -37,114 +40,82 @@ type ProviderRegistryEntry = {
|
||||
renderTraitsMenuContent: (input: {
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}) => ReactNode;
|
||||
renderTraitsPicker: (input: {
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}) => ReactNode;
|
||||
};
|
||||
|
||||
function getProviderStateFromCapabilities(
|
||||
input: ComposerProviderStateInput,
|
||||
): ComposerProviderState {
|
||||
const { provider, model, prompt, modelOptions } = input;
|
||||
const caps = getModelCapabilities(provider, model);
|
||||
const providerOptions = modelOptions?.[provider];
|
||||
function asCodexModelOptions(
|
||||
modelOptions: ModelSelection["options"] | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
return modelOptions && "reasoningEffort" in modelOptions ? modelOptions : undefined;
|
||||
}
|
||||
|
||||
// Resolve effort
|
||||
const rawEffort = providerOptions
|
||||
? "effort" in providerOptions
|
||||
? providerOptions.effort
|
||||
: "reasoningEffort" in providerOptions
|
||||
? providerOptions.reasoningEffort
|
||||
: null
|
||||
: null;
|
||||
|
||||
const draftEffort = trimOrNull(rawEffort);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
const isPromptInjected = draftEffort
|
||||
? caps.promptInjectedEffortLevels.includes(draftEffort)
|
||||
: false;
|
||||
const promptEffort =
|
||||
draftEffort && !isPromptInjected && hasEffortLevel(caps, draftEffort)
|
||||
? draftEffort
|
||||
: defaultEffort && hasEffortLevel(caps, defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
|
||||
// Normalize options for dispatch
|
||||
const normalizedOptions =
|
||||
provider === "codex"
|
||||
? normalizeCodexModelOptions(model, providerOptions)
|
||||
: normalizeClaudeModelOptions(model, providerOptions);
|
||||
|
||||
// Ultrathink styling (driven by capabilities data, not provider identity)
|
||||
const ultrathinkActive =
|
||||
caps.promptInjectedEffortLevels.length > 0 && isClaudeUltrathinkPrompt(prompt);
|
||||
|
||||
return {
|
||||
provider,
|
||||
promptEffort,
|
||||
modelOptionsForDispatch: normalizedOptions,
|
||||
...(ultrathinkActive ? { composerFrameClassName: "ultrathink-frame" } : {}),
|
||||
...(ultrathinkActive
|
||||
? { composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]" }
|
||||
: {}),
|
||||
...(ultrathinkActive ? { modelPickerIconClassName: "ultrathink-chroma" } : {}),
|
||||
};
|
||||
function asClaudeModelOptions(
|
||||
modelOptions: ModelSelection["options"] | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
return modelOptions && ("effort" in modelOptions || "thinking" in modelOptions)
|
||||
? modelOptions
|
||||
: undefined;
|
||||
}
|
||||
|
||||
const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
|
||||
codex: {
|
||||
getState: (input) => getProviderStateFromCapabilities(input),
|
||||
renderTraitsMenuContent: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
<TraitsMenuContent
|
||||
provider="codex"
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
prompt={prompt}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
),
|
||||
renderTraitsPicker: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
<TraitsPicker
|
||||
provider="codex"
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
prompt={prompt}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
),
|
||||
getState: ({ modelOptions }) => {
|
||||
const codexModelOptions = asCodexModelOptions(modelOptions);
|
||||
const promptEffort =
|
||||
resolveReasoningEffortForProvider("codex", codexModelOptions?.reasoningEffort) ??
|
||||
getDefaultReasoningEffort("codex");
|
||||
const normalizedCodexOptions = normalizeCodexModelOptions(codexModelOptions);
|
||||
|
||||
return {
|
||||
provider: "codex",
|
||||
promptEffort,
|
||||
modelOptionsForDispatch: normalizedCodexOptions,
|
||||
};
|
||||
},
|
||||
renderTraitsMenuContent: ({ threadId }) => <CodexTraitsMenuContent threadId={threadId} />,
|
||||
renderTraitsPicker: ({ threadId }) => <CodexTraitsPicker threadId={threadId} />,
|
||||
},
|
||||
claudeAgent: {
|
||||
getState: (input) => getProviderStateFromCapabilities(input),
|
||||
renderTraitsMenuContent: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
<TraitsMenuContent
|
||||
provider="claudeAgent"
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
prompt={prompt}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
getState: ({ model, prompt, modelOptions }) => {
|
||||
const claudeModelOptions = asClaudeModelOptions(modelOptions);
|
||||
const reasoningOptions = getReasoningEffortOptions("claudeAgent", model);
|
||||
const draftEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
claudeModelOptions?.effort,
|
||||
);
|
||||
const defaultEffort = getDefaultReasoningEffort("claudeAgent");
|
||||
const promptEffort =
|
||||
draftEffort && draftEffort !== "ultrathink" && reasoningOptions.includes(draftEffort)
|
||||
? draftEffort
|
||||
: reasoningOptions.includes(defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
const normalizedClaudeOptions = normalizeClaudeModelOptions(model, claudeModelOptions);
|
||||
const ultrathinkActive =
|
||||
supportsClaudeUltrathinkKeyword(model) && isClaudeUltrathinkPrompt(prompt);
|
||||
|
||||
return {
|
||||
provider: "claudeAgent",
|
||||
promptEffort,
|
||||
modelOptionsForDispatch: normalizedClaudeOptions,
|
||||
...(ultrathinkActive ? { composerFrameClassName: "ultrathink-frame" } : {}),
|
||||
...(ultrathinkActive
|
||||
? { composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]" }
|
||||
: {}),
|
||||
...(ultrathinkActive ? { modelPickerIconClassName: "ultrathink-chroma" } : {}),
|
||||
};
|
||||
},
|
||||
renderTraitsMenuContent: ({ threadId, model, onPromptChange }) => (
|
||||
<ClaudeTraitsMenuContent threadId={threadId} model={model} onPromptChange={onPromptChange} />
|
||||
),
|
||||
renderTraitsPicker: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
<TraitsPicker
|
||||
provider="claudeAgent"
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
prompt={prompt}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
renderTraitsPicker: ({ threadId, model, onPromptChange }) => (
|
||||
<ClaudeTraitsPicker threadId={threadId} model={model} onPromptChange={onPromptChange} />
|
||||
),
|
||||
},
|
||||
};
|
||||
@@ -157,15 +128,11 @@ export function renderProviderTraitsMenuContent(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}): ReactNode {
|
||||
return composerProviderRegistry[input.provider].renderTraitsMenuContent({
|
||||
threadId: input.threadId,
|
||||
model: input.model,
|
||||
modelOptions: input.modelOptions,
|
||||
prompt: input.prompt,
|
||||
onPromptChange: input.onPromptChange,
|
||||
});
|
||||
}
|
||||
@@ -174,15 +141,11 @@ export function renderProviderTraitsPicker(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}): ReactNode {
|
||||
return composerProviderRegistry[input.provider].renderTraitsPicker({
|
||||
threadId: input.threadId,
|
||||
model: input.model,
|
||||
modelOptions: input.modelOptions,
|
||||
prompt: input.prompt,
|
||||
onPromptChange: input.onPromptChange,
|
||||
});
|
||||
}
|
||||
@@ -1,10 +1,5 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type ModelSelection,
|
||||
type ProviderModelOptions,
|
||||
} from "@t3tools/contracts";
|
||||
import { ProjectId, ThreadId, type ModelSelection } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -72,8 +67,7 @@ function resetComposerDraftStore() {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
stickyModelSelection: null,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -89,10 +83,6 @@ function modelSelection(
|
||||
} as ModelSelection;
|
||||
}
|
||||
|
||||
function providerModelOptions(options: ProviderModelOptions): ProviderModelOptions {
|
||||
return options;
|
||||
}
|
||||
|
||||
describe("composerDraftStore addImages", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-dedupe");
|
||||
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
|
||||
@@ -218,8 +208,6 @@ describe("composerDraftStore syncPersistedAttachments", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -276,8 +264,6 @@ describe("composerDraftStore terminal contexts", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -637,9 +623,7 @@ describe("composerDraftStore modelSelection", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
@@ -651,9 +635,9 @@ describe("composerDraftStore modelSelection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.4"));
|
||||
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(modelSelection("codex", "gpt-5.4"));
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.4"),
|
||||
);
|
||||
});
|
||||
|
||||
it("replaces only the targeted provider options on the current model selection", () => {
|
||||
@@ -682,22 +666,19 @@ describe("composerDraftStore modelSelection", () => {
|
||||
{ persistSticky: true },
|
||||
);
|
||||
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent).toEqual(
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps explicit default-state overrides on the selection", () => {
|
||||
it("removes selection options when the patched provider options normalize empty", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelSelection(
|
||||
@@ -711,18 +692,13 @@ describe("composerDraftStore modelSelection", () => {
|
||||
thinking: true,
|
||||
});
|
||||
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: true,
|
||||
}),
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6"),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider).toEqual({});
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps explicit off/default codex overrides on the selection", () => {
|
||||
it("removes model options entirely when the last provider entry normalizes empty", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.4", { fastMode: true }));
|
||||
@@ -732,13 +708,8 @@ describe("composerDraftStore modelSelection", () => {
|
||||
fastMode: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(
|
||||
modelSelection("codex", "gpt-5.4", {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
}),
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.4"),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -757,60 +728,16 @@ describe("composerDraftStore modelSelection", () => {
|
||||
thinking: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent).toEqual(
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not clear other provider options when setting options for a single provider", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
// Set options for both providers
|
||||
store.setModelOptions(
|
||||
threadId,
|
||||
providerModelOptions({
|
||||
codex: { fastMode: true },
|
||||
claudeAgent: { effort: "max" },
|
||||
}),
|
||||
);
|
||||
|
||||
// Now set options for only codex — claudeAgent should be untouched
|
||||
store.setModelOptions(threadId, providerModelOptions({ codex: { reasoningEffort: "xhigh" } }));
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.modelSelectionByProvider.codex?.options).toEqual({ reasoningEffort: "xhigh" });
|
||||
expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual({ effort: "max" });
|
||||
});
|
||||
|
||||
it("preserves other provider options when switching the active model selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelOptions(
|
||||
threadId,
|
||||
providerModelOptions({
|
||||
codex: { fastMode: true },
|
||||
claudeAgent: { effort: "max" },
|
||||
}),
|
||||
);
|
||||
|
||||
store.setModelSelection(threadId, modelSelection("claudeAgent", "claude-opus-4-6"));
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.modelSelectionByProvider.claudeAgent).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
expect(draft?.modelSelectionByProvider.codex?.options).toEqual({ fastMode: true });
|
||||
expect(draft?.activeProvider).toBe("claudeAgent");
|
||||
});
|
||||
|
||||
it("creates the first sticky snapshot from provider option changes", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
@@ -825,7 +752,7 @@ describe("composerDraftStore modelSelection", () => {
|
||||
{ persistSticky: true },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toEqual(
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.4", {
|
||||
fastMode: true,
|
||||
}),
|
||||
@@ -852,15 +779,12 @@ describe("composerDraftStore modelSelection", () => {
|
||||
{ persistSticky: false },
|
||||
);
|
||||
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent).toEqual(
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
});
|
||||
@@ -878,9 +802,9 @@ describe("composerDraftStore setModelSelection", () => {
|
||||
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.3-codex"));
|
||||
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(modelSelection("codex", "gpt-5.3-codex"));
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -899,13 +823,16 @@ describe("composerDraftStore sticky composer settings", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyActiveProvider).toBe("codex");
|
||||
expect(useComposerDraftStore.getState()).toMatchObject({
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes empty sticky model options by dropping selection options", () => {
|
||||
@@ -913,25 +840,9 @@ describe("composerDraftStore sticky composer settings", () => {
|
||||
|
||||
store.setStickyModelSelection(modelSelection("codex", "gpt-5.4"));
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toEqual(
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.4"),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyActiveProvider).toBe("codex");
|
||||
});
|
||||
|
||||
it("applies sticky activeProvider to new drafts", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
const threadId = ThreadId.makeUnsafe("thread-sticky-active-provider");
|
||||
|
||||
store.setStickyModelSelection(modelSelection("claudeAgent", "claude-opus-4-6"));
|
||||
store.applyStickyState(threadId);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
modelSelectionByProvider: {
|
||||
claudeAgent: modelSelection("claudeAgent", "claude-opus-4-6"),
|
||||
},
|
||||
activeProvider: "claudeAgent",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -942,7 +853,7 @@ describe("composerDraftStore provider-scoped option updates", () => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("retains off-provider option memory without changing the active selection", () => {
|
||||
it("does not patch provider options when the draft selection is on another provider", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
@@ -951,12 +862,11 @@ describe("composerDraftStore provider-scoped option updates", () => {
|
||||
}),
|
||||
);
|
||||
store.setProviderModelOptions(threadId, "claudeAgent", { effort: "max" });
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.modelSelectionByProvider.codex).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", { reasoningEffort: "medium" }),
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "medium",
|
||||
}),
|
||||
);
|
||||
expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual({ effort: "max" });
|
||||
expect(draft?.activeProvider).toBe("codex");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+113
-574
@@ -2,8 +2,8 @@ import {
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
type ClaudeCodeEffort,
|
||||
type CodexReasoningEffort,
|
||||
type ModelSlug,
|
||||
ModelSelection,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
type ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
ProviderKind,
|
||||
@@ -14,14 +14,8 @@ import {
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Equal from "effect/Equal";
|
||||
import { DeepMutable } from "effect/Types";
|
||||
import {
|
||||
getDefaultModel,
|
||||
normalizeModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import { useMemo } from "react";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { getLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
import { resolveAppModelSelection } from "./appSettings";
|
||||
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";
|
||||
import {
|
||||
type TerminalContextDraft,
|
||||
@@ -33,7 +27,7 @@ import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import { createDebouncedStorage, createMemoryStorage } from "./lib/storage";
|
||||
|
||||
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
|
||||
const COMPOSER_DRAFT_STORAGE_VERSION = 3;
|
||||
const COMPOSER_DRAFT_STORAGE_VERSION = 2;
|
||||
const DraftThreadEnvModeSchema = Schema.Literals(["local", "worktree"]);
|
||||
export type DraftThreadEnvMode = typeof DraftThreadEnvModeSchema.Type;
|
||||
|
||||
@@ -80,10 +74,7 @@ const PersistedComposerThreadDraftState = Schema.Struct({
|
||||
prompt: Schema.String,
|
||||
attachments: Schema.Array(PersistedComposerImageAttachment),
|
||||
terminalContexts: Schema.optionalKey(Schema.Array(PersistedTerminalContextDraft)),
|
||||
modelSelectionByProvider: Schema.optionalKey(
|
||||
Schema.Record(ProviderKind, Schema.optionalKey(ModelSelection)),
|
||||
),
|
||||
activeProvider: Schema.optionalKey(Schema.NullOr(ProviderKind)),
|
||||
modelSelection: Schema.optionalKey(Schema.NullOr(Schema.Unknown)),
|
||||
runtimeMode: Schema.optionalKey(RuntimeMode),
|
||||
interactionMode: Schema.optionalKey(ProviderInteractionMode),
|
||||
});
|
||||
@@ -96,39 +87,13 @@ const LegacyCodexFields = Schema.Struct({
|
||||
});
|
||||
type LegacyCodexFields = typeof LegacyCodexFields.Type;
|
||||
|
||||
const LegacyThreadModelFields = Schema.Struct({
|
||||
provider: Schema.optionalKey(ProviderKind),
|
||||
model: Schema.optionalKey(Schema.String),
|
||||
modelOptions: Schema.optionalKey(Schema.NullOr(ProviderModelOptions)),
|
||||
});
|
||||
type LegacyThreadModelFields = typeof LegacyThreadModelFields.Type;
|
||||
|
||||
type LegacyV2ThreadDraftFields = {
|
||||
modelSelection?: ModelSelection | null;
|
||||
type LegacyPersistedCodexThreadDraftState = PersistedComposerThreadDraftState & LegacyCodexFields;
|
||||
type LegacyPersistedComposerThreadDraftState = LegacyPersistedCodexThreadDraftState & {
|
||||
provider?: ProviderKind;
|
||||
model?: string;
|
||||
modelOptions?: ProviderModelOptions | null;
|
||||
};
|
||||
|
||||
type LegacyPersistedComposerThreadDraftState = PersistedComposerThreadDraftState &
|
||||
LegacyCodexFields &
|
||||
LegacyThreadModelFields &
|
||||
LegacyV2ThreadDraftFields;
|
||||
|
||||
const LegacyStickyModelFields = Schema.Struct({
|
||||
stickyProvider: Schema.optionalKey(ProviderKind),
|
||||
stickyModel: Schema.optionalKey(Schema.String),
|
||||
stickyModelOptions: Schema.optionalKey(Schema.NullOr(ProviderModelOptions)),
|
||||
});
|
||||
type LegacyStickyModelFields = typeof LegacyStickyModelFields.Type;
|
||||
|
||||
type LegacyV2StoreFields = {
|
||||
stickyModelSelection?: ModelSelection | null;
|
||||
stickyModelOptions?: ProviderModelOptions | null;
|
||||
};
|
||||
|
||||
type LegacyPersistedComposerDraftStoreState = PersistedComposerDraftStoreState &
|
||||
LegacyStickyModelFields &
|
||||
LegacyV2StoreFields;
|
||||
|
||||
const PersistedDraftThreadState = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
createdAt: Schema.String,
|
||||
@@ -144,10 +109,7 @@ const PersistedComposerDraftStoreState = Schema.Struct({
|
||||
draftsByThreadId: Schema.Record(ThreadId, PersistedComposerThreadDraftState),
|
||||
draftThreadsByThreadId: Schema.Record(ThreadId, PersistedDraftThreadState),
|
||||
projectDraftThreadIdByProjectId: Schema.Record(ProjectId, ThreadId),
|
||||
stickyModelSelectionByProvider: Schema.optionalKey(
|
||||
Schema.Record(ProviderKind, Schema.optionalKey(ModelSelection)),
|
||||
),
|
||||
stickyActiveProvider: Schema.optionalKey(Schema.NullOr(ProviderKind)),
|
||||
stickyModelSelection: Schema.NullOr(Schema.Unknown),
|
||||
});
|
||||
type PersistedComposerDraftStoreState = typeof PersistedComposerDraftStoreState.Type;
|
||||
|
||||
@@ -156,14 +118,13 @@ const PersistedComposerDraftStoreStorage = Schema.Struct({
|
||||
state: PersistedComposerDraftStoreState,
|
||||
});
|
||||
|
||||
export interface ComposerThreadDraftState {
|
||||
interface ComposerThreadDraftState {
|
||||
prompt: string;
|
||||
images: ComposerImageAttachment[];
|
||||
nonPersistedImageIds: string[];
|
||||
persistedAttachments: PersistedComposerImageAttachment[];
|
||||
terminalContexts: TerminalContextDraft[];
|
||||
modelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>>;
|
||||
activeProvider: ProviderKind | null;
|
||||
modelSelection: ModelSelection | null;
|
||||
runtimeMode: RuntimeMode | null;
|
||||
interactionMode: ProviderInteractionMode | null;
|
||||
}
|
||||
@@ -186,8 +147,7 @@ interface ComposerDraftStoreState {
|
||||
draftsByThreadId: Record<ThreadId, ComposerThreadDraftState>;
|
||||
draftThreadsByThreadId: Record<ThreadId, DraftThreadState>;
|
||||
projectDraftThreadIdByProjectId: Record<ProjectId, ThreadId>;
|
||||
stickyModelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>>;
|
||||
stickyActiveProvider: ProviderKind | null;
|
||||
stickyModelSelection: ModelSelection | null;
|
||||
getDraftThreadByProjectId: (projectId: ProjectId) => ProjectDraftThread | null;
|
||||
getDraftThread: (threadId: ThreadId) => DraftThreadState | null;
|
||||
setProjectDraftThreadId: (
|
||||
@@ -224,11 +184,6 @@ interface ComposerDraftStoreState {
|
||||
threadId: ThreadId,
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
) => void;
|
||||
setModelOptions: (
|
||||
threadId: ThreadId,
|
||||
modelOptions: ProviderModelOptions | null | undefined,
|
||||
) => void;
|
||||
applyStickyState: (threadId: ThreadId) => void;
|
||||
setProviderModelOptions: (
|
||||
threadId: ThreadId,
|
||||
provider: ProviderKind,
|
||||
@@ -263,42 +218,11 @@ interface ComposerDraftStoreState {
|
||||
clearComposerContent: (threadId: ThreadId) => void;
|
||||
}
|
||||
|
||||
export interface EffectiveComposerModelState {
|
||||
selectedModel: ModelSlug;
|
||||
modelOptions: ProviderModelOptions | null;
|
||||
}
|
||||
|
||||
function providerModelOptionsFromSelection(
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
): ProviderModelOptions | null {
|
||||
if (!modelSelection?.options) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
[modelSelection.provider]: modelSelection.options,
|
||||
};
|
||||
}
|
||||
|
||||
function modelSelectionByProviderToOptions(
|
||||
map: Partial<Record<ProviderKind, ModelSelection>> | null | undefined,
|
||||
): ProviderModelOptions | null {
|
||||
if (!map) return null;
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [provider, selection] of Object.entries(map)) {
|
||||
if (selection?.options) {
|
||||
result[provider] = selection.options;
|
||||
}
|
||||
}
|
||||
return Object.keys(result).length > 0 ? (result as ProviderModelOptions) : null;
|
||||
}
|
||||
|
||||
const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftStoreState>({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
stickyModelSelection: null,
|
||||
});
|
||||
|
||||
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
|
||||
@@ -308,17 +232,13 @@ const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
|
||||
Object.freeze(EMPTY_IMAGES);
|
||||
Object.freeze(EMPTY_IDS);
|
||||
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
|
||||
const EMPTY_MODEL_SELECTION_BY_PROVIDER: Partial<Record<ProviderKind, ModelSelection>> =
|
||||
Object.freeze({});
|
||||
|
||||
const EMPTY_THREAD_DRAFT = Object.freeze<ComposerThreadDraftState>({
|
||||
prompt: "",
|
||||
images: EMPTY_IMAGES,
|
||||
nonPersistedImageIds: EMPTY_IDS,
|
||||
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
|
||||
terminalContexts: EMPTY_TERMINAL_CONTEXTS,
|
||||
modelSelectionByProvider: EMPTY_MODEL_SELECTION_BY_PROVIDER,
|
||||
activeProvider: null,
|
||||
modelSelection: null,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
});
|
||||
@@ -330,8 +250,7 @@ function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelectionByProvider: {},
|
||||
activeProvider: null,
|
||||
modelSelection: null,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
@@ -400,8 +319,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
draft.images.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
Object.keys(draft.modelSelectionByProvider).length === 0 &&
|
||||
draft.activeProvider === null &&
|
||||
draft.modelSelection === null &&
|
||||
draft.runtimeMode === null &&
|
||||
draft.interactionMode === null
|
||||
);
|
||||
@@ -440,28 +358,20 @@ function normalizeProviderModelOptions(
|
||||
? legacy.effort
|
||||
: undefined;
|
||||
const codexFastMode =
|
||||
codexCandidate?.fastMode === true
|
||||
? true
|
||||
: codexCandidate?.fastMode === false
|
||||
? false
|
||||
: (provider === "codex" && legacy?.codexFastMode === true) ||
|
||||
(typeof legacy?.serviceTier === "string" && legacy.serviceTier === "fast")
|
||||
? true
|
||||
: undefined;
|
||||
codexCandidate?.fastMode === true ||
|
||||
(provider === "codex" && legacy?.codexFastMode === true) ||
|
||||
(typeof legacy?.serviceTier === "string" && legacy.serviceTier === "fast");
|
||||
const codex =
|
||||
codexReasoningEffort !== undefined || codexFastMode !== undefined
|
||||
codexReasoningEffort && codexReasoningEffort !== DEFAULT_REASONING_EFFORT_BY_PROVIDER.codex
|
||||
? {
|
||||
...(codexReasoningEffort !== undefined ? { reasoningEffort: codexReasoningEffort } : {}),
|
||||
...(codexFastMode !== undefined ? { fastMode: codexFastMode } : {}),
|
||||
reasoningEffort: codexReasoningEffort,
|
||||
...(codexFastMode ? { fastMode: true } : {}),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const claudeThinking =
|
||||
claudeCandidate?.thinking === true
|
||||
? true
|
||||
: claudeCandidate?.thinking === false
|
||||
? false
|
||||
: codexFastMode
|
||||
? { fastMode: true }
|
||||
: undefined;
|
||||
|
||||
const claudeThinking = claudeCandidate?.thinking === false ? false : undefined;
|
||||
const claudeEffort: ClaudeCodeEffort | undefined =
|
||||
claudeCandidate?.effort === "low" ||
|
||||
claudeCandidate?.effort === "medium" ||
|
||||
@@ -470,18 +380,17 @@ function normalizeProviderModelOptions(
|
||||
claudeCandidate?.effort === "ultrathink"
|
||||
? claudeCandidate.effort
|
||||
: undefined;
|
||||
const claudeFastMode =
|
||||
claudeCandidate?.fastMode === true
|
||||
? true
|
||||
: claudeCandidate?.fastMode === false
|
||||
? false
|
||||
: undefined;
|
||||
const claudeFastMode = claudeCandidate?.fastMode === true;
|
||||
const claude =
|
||||
claudeThinking !== undefined || claudeEffort !== undefined || claudeFastMode !== undefined
|
||||
claudeThinking === false ||
|
||||
(claudeEffort && claudeEffort !== DEFAULT_REASONING_EFFORT_BY_PROVIDER.claudeAgent) ||
|
||||
claudeFastMode
|
||||
? {
|
||||
...(claudeThinking !== undefined ? { thinking: claudeThinking } : {}),
|
||||
...(claudeEffort !== undefined ? { effort: claudeEffort } : {}),
|
||||
...(claudeFastMode !== undefined ? { fastMode: claudeFastMode } : {}),
|
||||
...(claudeThinking === false ? { thinking: false } : {}),
|
||||
...(claudeEffort && claudeEffort !== DEFAULT_REASONING_EFFORT_BY_PROVIDER.claudeAgent
|
||||
? { effort: claudeEffort }
|
||||
: {}),
|
||||
...(claudeFastMode ? { fastMode: true } : {}),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
@@ -529,38 +438,7 @@ function normalizeModelSelection(
|
||||
};
|
||||
}
|
||||
|
||||
// ── Legacy sync helpers (used only during migration from v2 storage) ──
|
||||
|
||||
function legacySyncModelSelectionOptions(
|
||||
modelSelection: ModelSelection | null,
|
||||
modelOptions: ProviderModelOptions | null | undefined,
|
||||
): ModelSelection | null {
|
||||
if (modelSelection === null) {
|
||||
return null;
|
||||
}
|
||||
const options = modelOptions?.[modelSelection.provider];
|
||||
return {
|
||||
provider: modelSelection.provider,
|
||||
model: modelSelection.model,
|
||||
...(options ? { options } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function legacyMergeModelSelectionIntoProviderModelOptions(
|
||||
modelSelection: ModelSelection | null,
|
||||
currentModelOptions: ProviderModelOptions | null | undefined,
|
||||
): ProviderModelOptions | null {
|
||||
if (modelSelection?.options === undefined) {
|
||||
return normalizeProviderModelOptions(currentModelOptions);
|
||||
}
|
||||
return legacyReplaceProviderModelOptions(
|
||||
normalizeProviderModelOptions(currentModelOptions),
|
||||
modelSelection.provider,
|
||||
modelSelection.options,
|
||||
);
|
||||
}
|
||||
|
||||
function legacyReplaceProviderModelOptions(
|
||||
function replaceProviderModelOptions(
|
||||
currentModelOptions: ProviderModelOptions | null | undefined,
|
||||
provider: ProviderKind,
|
||||
nextProviderOptions: ProviderModelOptions[ProviderKind] | null | undefined,
|
||||
@@ -578,72 +456,6 @@ function legacyReplaceProviderModelOptions(
|
||||
});
|
||||
}
|
||||
|
||||
// ── New helpers for the consolidated representation ────────────────────
|
||||
|
||||
function legacyToModelSelectionByProvider(
|
||||
modelSelection: ModelSelection | null,
|
||||
modelOptions: ProviderModelOptions | null | undefined,
|
||||
): Partial<Record<ProviderKind, ModelSelection>> {
|
||||
const result: Partial<Record<ProviderKind, ModelSelection>> = {};
|
||||
// Add entries from the options bag (for non-active providers)
|
||||
if (modelOptions) {
|
||||
for (const provider of ["codex", "claudeAgent"] as const) {
|
||||
const options = modelOptions[provider];
|
||||
if (options && Object.keys(options).length > 0) {
|
||||
result[provider] = {
|
||||
provider,
|
||||
model:
|
||||
modelSelection?.provider === provider
|
||||
? modelSelection.model
|
||||
: getDefaultModel(provider),
|
||||
options,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
// Add/overwrite the active selection (it's authoritative for its provider)
|
||||
if (modelSelection) {
|
||||
result[modelSelection.provider] = modelSelection;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function deriveEffectiveComposerModelState(input: {
|
||||
draft:
|
||||
| Pick<ComposerThreadDraftState, "modelSelectionByProvider" | "activeProvider">
|
||||
| null
|
||||
| undefined;
|
||||
selectedProvider: ProviderKind;
|
||||
threadModelSelection: ModelSelection | null | undefined;
|
||||
projectModelSelection: ModelSelection | null | undefined;
|
||||
customModelsByProvider: Record<ProviderKind, readonly string[]>;
|
||||
}): EffectiveComposerModelState {
|
||||
const baseModel = resolveModelSlugForProvider(
|
||||
input.selectedProvider,
|
||||
input.threadModelSelection?.model ??
|
||||
input.projectModelSelection?.model ??
|
||||
getDefaultModel(input.selectedProvider),
|
||||
);
|
||||
const activeSelection = input.draft?.modelSelectionByProvider?.[input.selectedProvider];
|
||||
const selectedModel = activeSelection?.model
|
||||
? resolveAppModelSelection(
|
||||
input.selectedProvider,
|
||||
input.customModelsByProvider,
|
||||
activeSelection.model,
|
||||
)
|
||||
: baseModel;
|
||||
const modelOptions =
|
||||
modelSelectionByProviderToOptions(input.draft?.modelSelectionByProvider) ??
|
||||
providerModelOptionsFromSelection(input.threadModelSelection) ??
|
||||
providerModelOptionsFromSelection(input.projectModelSelection) ??
|
||||
null;
|
||||
|
||||
return {
|
||||
selectedModel,
|
||||
modelOptions,
|
||||
};
|
||||
}
|
||||
|
||||
function revokeObjectPreviewUrl(previewUrl: string): void {
|
||||
if (typeof URL === "undefined") {
|
||||
return;
|
||||
@@ -844,7 +656,9 @@ function normalizePersistedDraftsByThreadId(
|
||||
if (!draftValue || typeof draftValue !== "object") {
|
||||
continue;
|
||||
}
|
||||
const draftCandidate = draftValue as PersistedComposerThreadDraftState;
|
||||
const draftCandidate = draftValue as
|
||||
| PersistedComposerThreadDraftState
|
||||
| LegacyPersistedCodexThreadDraftState;
|
||||
const promptCandidate = typeof draftCandidate.prompt === "string" ? draftCandidate.prompt : "";
|
||||
const attachments = Array.isArray(draftCandidate.attachments)
|
||||
? draftCandidate.attachments.flatMap((entry) => {
|
||||
@@ -871,59 +685,18 @@ function normalizePersistedDraftsByThreadId(
|
||||
promptCandidate,
|
||||
terminalContexts.length,
|
||||
);
|
||||
// If the draft already has the v3 shape, use it directly
|
||||
const legacyDraftCandidate = draftValue as LegacyPersistedComposerThreadDraftState;
|
||||
let modelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>> = {};
|
||||
let activeProvider: ProviderKind | null = null;
|
||||
|
||||
if (
|
||||
draftCandidate.modelSelectionByProvider &&
|
||||
typeof draftCandidate.modelSelectionByProvider === "object"
|
||||
) {
|
||||
// v3 format
|
||||
modelSelectionByProvider = draftCandidate.modelSelectionByProvider as Partial<
|
||||
Record<ProviderKind, ModelSelection>
|
||||
>;
|
||||
activeProvider = normalizeProviderKind(draftCandidate.activeProvider);
|
||||
} else {
|
||||
// v2 or legacy format: migrate
|
||||
const normalizedModelOptions =
|
||||
normalizeProviderModelOptions(
|
||||
legacyDraftCandidate.modelOptions,
|
||||
undefined,
|
||||
legacyDraftCandidate,
|
||||
) ?? null;
|
||||
const normalizedModelSelection = normalizeModelSelection(
|
||||
legacyDraftCandidate.modelSelection,
|
||||
{
|
||||
provider: legacyDraftCandidate.provider,
|
||||
model: legacyDraftCandidate.model,
|
||||
modelOptions: normalizedModelOptions ?? legacyDraftCandidate.modelOptions,
|
||||
legacyCodex: legacyDraftCandidate,
|
||||
},
|
||||
);
|
||||
const mergedModelOptions = legacyMergeModelSelectionIntoProviderModelOptions(
|
||||
normalizedModelSelection,
|
||||
normalizedModelOptions,
|
||||
);
|
||||
const modelSelection = legacySyncModelSelectionOptions(
|
||||
normalizedModelSelection,
|
||||
mergedModelOptions,
|
||||
);
|
||||
modelSelectionByProvider = legacyToModelSelectionByProvider(
|
||||
modelSelection,
|
||||
mergedModelOptions,
|
||||
);
|
||||
activeProvider = modelSelection?.provider ?? null;
|
||||
}
|
||||
|
||||
const hasModelData =
|
||||
Object.keys(modelSelectionByProvider).length > 0 || activeProvider !== null;
|
||||
const legacyDraftCandidate = draftCandidate as LegacyPersistedComposerThreadDraftState;
|
||||
const modelSelection = normalizeModelSelection(draftCandidate.modelSelection, {
|
||||
provider: legacyDraftCandidate.provider,
|
||||
model: legacyDraftCandidate.model,
|
||||
modelOptions: legacyDraftCandidate.modelOptions,
|
||||
legacyCodex: legacyDraftCandidate,
|
||||
});
|
||||
if (
|
||||
promptCandidate.length === 0 &&
|
||||
attachments.length === 0 &&
|
||||
terminalContexts.length === 0 &&
|
||||
!hasModelData &&
|
||||
modelSelection === null &&
|
||||
!runtimeMode &&
|
||||
!interactionMode
|
||||
) {
|
||||
@@ -933,7 +706,7 @@ function normalizePersistedDraftsByThreadId(
|
||||
prompt,
|
||||
attachments,
|
||||
...(terminalContexts.length > 0 ? { terminalContexts } : {}),
|
||||
...(hasModelData ? { modelSelectionByProvider, activeProvider } : {}),
|
||||
...(modelSelection ? { modelSelection } : {}),
|
||||
...(runtimeMode ? { runtimeMode } : {}),
|
||||
...(interactionMode ? { interactionMode } : {}),
|
||||
};
|
||||
@@ -948,32 +721,15 @@ function migratePersistedComposerDraftStoreState(
|
||||
if (!persistedState || typeof persistedState !== "object") {
|
||||
return EMPTY_PERSISTED_DRAFT_STORE_STATE;
|
||||
}
|
||||
const candidate = persistedState as LegacyPersistedComposerDraftStoreState;
|
||||
const candidate = persistedState as Record<string, unknown>;
|
||||
const rawDraftMap = candidate.draftsByThreadId;
|
||||
const rawDraftThreadsByThreadId = candidate.draftThreadsByThreadId;
|
||||
const rawProjectDraftThreadIdByProjectId = candidate.projectDraftThreadIdByProjectId;
|
||||
|
||||
// Migrate sticky state from v2 (dual) to v3 (consolidated)
|
||||
const stickyModelOptions = normalizeProviderModelOptions(candidate.stickyModelOptions) ?? {};
|
||||
const normalizedStickyModelSelection = normalizeModelSelection(candidate.stickyModelSelection, {
|
||||
const stickyModelSelection = normalizeModelSelection(candidate.stickyModelSelection, {
|
||||
provider: candidate.stickyProvider ?? "codex",
|
||||
model: candidate.stickyModel,
|
||||
modelOptions: stickyModelOptions,
|
||||
modelOptions: candidate.stickyModelOptions,
|
||||
});
|
||||
const nextStickyModelOptions = legacyMergeModelSelectionIntoProviderModelOptions(
|
||||
normalizedStickyModelSelection,
|
||||
stickyModelOptions,
|
||||
);
|
||||
const stickyModelSelection = legacySyncModelSelectionOptions(
|
||||
normalizedStickyModelSelection,
|
||||
nextStickyModelOptions,
|
||||
);
|
||||
const stickyModelSelectionByProvider = legacyToModelSelectionByProvider(
|
||||
stickyModelSelection,
|
||||
nextStickyModelOptions,
|
||||
);
|
||||
const stickyActiveProvider = normalizeProviderKind(candidate.stickyProvider) ?? null;
|
||||
|
||||
const { draftThreadsByThreadId, projectDraftThreadIdByProjectId } =
|
||||
normalizePersistedDraftThreads(rawDraftThreadsByThreadId, rawProjectDraftThreadIdByProjectId);
|
||||
const draftsByThreadId = normalizePersistedDraftsByThreadId(rawDraftMap);
|
||||
@@ -981,8 +737,7 @@ function migratePersistedComposerDraftStoreState(
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId,
|
||||
stickyModelSelectionByProvider,
|
||||
stickyActiveProvider,
|
||||
stickyModelSelection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -996,13 +751,11 @@ function partializeComposerDraftStoreState(
|
||||
if (typeof threadId !== "string" || threadId.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const hasModelData =
|
||||
Object.keys(draft.modelSelectionByProvider).length > 0 || draft.activeProvider !== null;
|
||||
if (
|
||||
draft.prompt.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
!hasModelData &&
|
||||
draft.modelSelection === null &&
|
||||
draft.runtimeMode === null &&
|
||||
draft.interactionMode === null
|
||||
) {
|
||||
@@ -1024,12 +777,7 @@ function partializeComposerDraftStoreState(
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
...(hasModelData
|
||||
? {
|
||||
modelSelectionByProvider: draft.modelSelectionByProvider,
|
||||
activeProvider: draft.activeProvider,
|
||||
}
|
||||
: {}),
|
||||
...(draft.modelSelection ? { modelSelection: draft.modelSelection } : {}),
|
||||
...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}),
|
||||
...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}),
|
||||
};
|
||||
@@ -1039,8 +787,7 @@ function partializeComposerDraftStoreState(
|
||||
draftsByThreadId: persistedDraftsByThreadId,
|
||||
draftThreadsByThreadId: state.draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: state.projectDraftThreadIdByProjectId,
|
||||
stickyModelSelectionByProvider: state.stickyModelSelectionByProvider,
|
||||
stickyActiveProvider: state.stickyActiveProvider,
|
||||
stickyModelSelection: state.stickyModelSelection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1050,58 +797,25 @@ function normalizeCurrentPersistedComposerDraftStoreState(
|
||||
if (!persistedState || typeof persistedState !== "object") {
|
||||
return EMPTY_PERSISTED_DRAFT_STORE_STATE;
|
||||
}
|
||||
const normalizedPersistedState = persistedState as LegacyPersistedComposerDraftStoreState;
|
||||
const normalizedPersistedState = persistedState as Record<string, unknown>;
|
||||
const { draftThreadsByThreadId, projectDraftThreadIdByProjectId } =
|
||||
normalizePersistedDraftThreads(
|
||||
normalizedPersistedState.draftThreadsByThreadId,
|
||||
normalizedPersistedState.projectDraftThreadIdByProjectId,
|
||||
);
|
||||
|
||||
// Handle both v3 (modelSelectionByProvider) and v2/legacy formats
|
||||
let stickyModelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>> = {};
|
||||
let stickyActiveProvider: ProviderKind | null = null;
|
||||
if (
|
||||
normalizedPersistedState.stickyModelSelectionByProvider &&
|
||||
typeof normalizedPersistedState.stickyModelSelectionByProvider === "object"
|
||||
) {
|
||||
stickyModelSelectionByProvider =
|
||||
normalizedPersistedState.stickyModelSelectionByProvider as Partial<
|
||||
Record<ProviderKind, ModelSelection>
|
||||
>;
|
||||
stickyActiveProvider = normalizeProviderKind(normalizedPersistedState.stickyActiveProvider);
|
||||
} else {
|
||||
// Legacy migration path
|
||||
const stickyModelOptions =
|
||||
normalizeProviderModelOptions(normalizedPersistedState.stickyModelOptions) ?? {};
|
||||
const normalizedStickyModelSelection = normalizeModelSelection(
|
||||
normalizedPersistedState.stickyModelSelection,
|
||||
{
|
||||
provider: normalizedPersistedState.stickyProvider,
|
||||
model: normalizedPersistedState.stickyModel,
|
||||
modelOptions: stickyModelOptions,
|
||||
},
|
||||
);
|
||||
const nextStickyModelOptions = legacyMergeModelSelectionIntoProviderModelOptions(
|
||||
normalizedStickyModelSelection,
|
||||
stickyModelOptions,
|
||||
);
|
||||
const stickyModelSelection = legacySyncModelSelectionOptions(
|
||||
normalizedStickyModelSelection,
|
||||
nextStickyModelOptions,
|
||||
);
|
||||
stickyModelSelectionByProvider = legacyToModelSelectionByProvider(
|
||||
stickyModelSelection,
|
||||
nextStickyModelOptions,
|
||||
);
|
||||
stickyActiveProvider = normalizeProviderKind(normalizedPersistedState.stickyProvider);
|
||||
}
|
||||
|
||||
const stickyModelSelection = normalizeModelSelection(
|
||||
normalizedPersistedState.stickyModelSelection,
|
||||
{
|
||||
provider: normalizedPersistedState.stickyProvider,
|
||||
model: normalizedPersistedState.stickyModel,
|
||||
modelOptions: normalizedPersistedState.stickyModelOptions,
|
||||
},
|
||||
);
|
||||
return {
|
||||
draftsByThreadId: normalizePersistedDraftsByThreadId(normalizedPersistedState.draftsByThreadId),
|
||||
draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId,
|
||||
stickyModelSelectionByProvider,
|
||||
stickyActiveProvider,
|
||||
stickyModelSelection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1228,11 +942,6 @@ function hydrateImagesFromPersisted(
|
||||
function toHydratedThreadDraft(
|
||||
persistedDraft: PersistedComposerThreadDraftState,
|
||||
): ComposerThreadDraftState {
|
||||
// The persisted draft is already in v3 shape (migration handles older formats)
|
||||
const modelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>> =
|
||||
persistedDraft.modelSelectionByProvider ?? {};
|
||||
const activeProvider = normalizeProviderKind(persistedDraft.activeProvider) ?? null;
|
||||
|
||||
return {
|
||||
prompt: persistedDraft.prompt,
|
||||
images: hydrateImagesFromPersisted(persistedDraft.attachments),
|
||||
@@ -1243,8 +952,12 @@ function toHydratedThreadDraft(
|
||||
...context,
|
||||
text: "",
|
||||
})) ?? [],
|
||||
modelSelectionByProvider,
|
||||
activeProvider,
|
||||
modelSelection: normalizeModelSelection(persistedDraft.modelSelection, {
|
||||
provider: (persistedDraft as LegacyPersistedComposerThreadDraftState).provider,
|
||||
model: (persistedDraft as LegacyPersistedComposerThreadDraftState).model,
|
||||
modelOptions: (persistedDraft as LegacyPersistedComposerThreadDraftState).modelOptions,
|
||||
legacyCodex: persistedDraft as LegacyPersistedComposerThreadDraftState,
|
||||
}),
|
||||
runtimeMode: persistedDraft.runtimeMode ?? null,
|
||||
interactionMode: persistedDraft.interactionMode ?? null,
|
||||
};
|
||||
@@ -1256,8 +969,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
stickyModelSelection: null,
|
||||
getDraftThreadByProjectId: (projectId) => {
|
||||
if (projectId.length === 0) {
|
||||
return null;
|
||||
@@ -1504,67 +1216,12 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
});
|
||||
},
|
||||
setStickyModelSelection: (modelSelection) => {
|
||||
const normalized = normalizeModelSelection(modelSelection);
|
||||
set((state) => {
|
||||
if (!normalized) {
|
||||
return state;
|
||||
}
|
||||
const nextMap: Partial<Record<ProviderKind, ModelSelection>> = {
|
||||
...state.stickyModelSelectionByProvider,
|
||||
[normalized.provider]: normalized,
|
||||
};
|
||||
if (Equal.equals(state.stickyModelSelectionByProvider, nextMap)) {
|
||||
return state.stickyActiveProvider === normalized.provider
|
||||
? state
|
||||
: { stickyActiveProvider: normalized.provider };
|
||||
}
|
||||
return {
|
||||
stickyModelSelectionByProvider: nextMap,
|
||||
stickyActiveProvider: normalized.provider,
|
||||
};
|
||||
});
|
||||
},
|
||||
applyStickyState: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const stickyMap = state.stickyModelSelectionByProvider;
|
||||
const stickyActiveProvider = state.stickyActiveProvider;
|
||||
if (Object.keys(stickyMap).length === 0 && stickyActiveProvider === null) {
|
||||
return state;
|
||||
}
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
for (const [provider, selection] of Object.entries(stickyMap)) {
|
||||
if (selection) {
|
||||
const current = nextMap[provider as ProviderKind];
|
||||
nextMap[provider as ProviderKind] = {
|
||||
...selection,
|
||||
model: current?.model ?? selection.model,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (
|
||||
Equal.equals(base.modelSelectionByProvider, nextMap) &&
|
||||
base.activeProvider === stickyActiveProvider
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelectionByProvider: nextMap,
|
||||
activeProvider: stickyActiveProvider,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
const normalizedModelSelection = normalizeModelSelection(modelSelection);
|
||||
set((state) =>
|
||||
Equal.equals(state.stickyModelSelection, normalizedModelSelection)
|
||||
? state
|
||||
: { stickyModelSelection: normalizedModelSelection },
|
||||
);
|
||||
},
|
||||
setPrompt: (threadId, prompt) => {
|
||||
if (threadId.length === 0) {
|
||||
@@ -1613,84 +1270,19 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalized = normalizeModelSelection(modelSelection);
|
||||
const normalizedModelSelection = normalizeModelSelection(modelSelection);
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && normalized === null) {
|
||||
if (!existing && normalizedModelSelection === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
if (normalized) {
|
||||
const current = nextMap[normalized.provider];
|
||||
if (normalized.options !== undefined) {
|
||||
// Explicit options provided → use them
|
||||
nextMap[normalized.provider] = normalized;
|
||||
} else {
|
||||
// No options in selection → preserve existing options, update provider+model
|
||||
nextMap[normalized.provider] = {
|
||||
provider: normalized.provider,
|
||||
model: normalized.model,
|
||||
...(current?.options ? { options: current.options } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
const nextActiveProvider = normalized?.provider ?? base.activeProvider;
|
||||
if (
|
||||
Equal.equals(base.modelSelectionByProvider, nextMap) &&
|
||||
base.activeProvider === nextActiveProvider
|
||||
) {
|
||||
if (Equal.equals(base.modelSelection, normalizedModelSelection)) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelectionByProvider: nextMap,
|
||||
activeProvider: nextActiveProvider,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setModelOptions: (threadId, modelOptions) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedOpts = normalizeProviderModelOptions(modelOptions);
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && normalizedOpts === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
for (const provider of ["codex", "claudeAgent"] as const) {
|
||||
// Only touch providers explicitly present in the input
|
||||
if (!normalizedOpts || !(provider in normalizedOpts)) continue;
|
||||
const opts = normalizedOpts[provider];
|
||||
const current = nextMap[provider];
|
||||
if (opts) {
|
||||
nextMap[provider] = {
|
||||
provider,
|
||||
model: current?.model ?? getDefaultModel(provider),
|
||||
options: opts,
|
||||
};
|
||||
} else if (current?.options) {
|
||||
// Remove options but keep the selection
|
||||
const { options: _, ...rest } = current;
|
||||
nextMap[provider] = rest as ModelSelection;
|
||||
}
|
||||
}
|
||||
if (Equal.equals(base.modelSelectionByProvider, nextMap)) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelectionByProvider: nextMap,
|
||||
modelSelection: normalizedModelSelection,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
@@ -1709,67 +1301,46 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (normalizedProvider === null) {
|
||||
return;
|
||||
}
|
||||
// Normalize just this provider's options
|
||||
const normalizedOpts = normalizeProviderModelOptions(
|
||||
{ [normalizedProvider]: nextProviderOptions },
|
||||
normalizedProvider,
|
||||
);
|
||||
const providerOpts = normalizedOpts?.[normalizedProvider];
|
||||
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
|
||||
// Update the map entry for this provider
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
const currentForProvider = nextMap[normalizedProvider];
|
||||
if (providerOpts) {
|
||||
nextMap[normalizedProvider] = {
|
||||
provider: normalizedProvider,
|
||||
model: currentForProvider?.model ?? getDefaultModel(normalizedProvider),
|
||||
options: providerOpts,
|
||||
};
|
||||
} else if (currentForProvider?.options) {
|
||||
const { options: _, ...rest } = currentForProvider;
|
||||
nextMap[normalizedProvider] = rest as ModelSelection;
|
||||
}
|
||||
|
||||
// Handle sticky persistence
|
||||
let nextStickyMap = state.stickyModelSelectionByProvider;
|
||||
let nextStickyActiveProvider = state.stickyActiveProvider;
|
||||
if (options?.persistSticky === true) {
|
||||
nextStickyMap = { ...state.stickyModelSelectionByProvider };
|
||||
const stickyBase =
|
||||
nextStickyMap[normalizedProvider] ??
|
||||
base.modelSelectionByProvider[normalizedProvider] ??
|
||||
({
|
||||
provider: normalizedProvider,
|
||||
model: getDefaultModel(normalizedProvider),
|
||||
} as ModelSelection);
|
||||
if (providerOpts) {
|
||||
nextStickyMap[normalizedProvider] = {
|
||||
...stickyBase,
|
||||
provider: normalizedProvider,
|
||||
options: providerOpts,
|
||||
};
|
||||
} else if (stickyBase.options) {
|
||||
const { options: _, ...rest } = stickyBase;
|
||||
nextStickyMap[normalizedProvider] = rest as ModelSelection;
|
||||
}
|
||||
nextStickyActiveProvider = base.activeProvider ?? normalizedProvider;
|
||||
if (base.modelSelection?.provider !== normalizedProvider) {
|
||||
return state;
|
||||
}
|
||||
const nextProviderModelOptions = replaceProviderModelOptions(
|
||||
base.modelSelection?.options
|
||||
? { [normalizedProvider]: base.modelSelection.options }
|
||||
: null,
|
||||
normalizedProvider,
|
||||
nextProviderOptions,
|
||||
);
|
||||
const nextOptions =
|
||||
normalizedProvider === "codex"
|
||||
? nextProviderModelOptions?.codex
|
||||
: nextProviderModelOptions?.claudeAgent;
|
||||
const nextModelSelection =
|
||||
base.modelSelection === null
|
||||
? null
|
||||
: {
|
||||
provider: base.modelSelection.provider,
|
||||
model: base.modelSelection.model,
|
||||
...(nextOptions ? { options: nextOptions } : {}),
|
||||
};
|
||||
const nextStickyModelSelection =
|
||||
options?.persistSticky === true && nextModelSelection !== null
|
||||
? nextModelSelection
|
||||
: state.stickyModelSelection;
|
||||
|
||||
if (
|
||||
Equal.equals(base.modelSelectionByProvider, nextMap) &&
|
||||
Equal.equals(state.stickyModelSelectionByProvider, nextStickyMap) &&
|
||||
state.stickyActiveProvider === nextStickyActiveProvider
|
||||
Equal.equals(base.modelSelection, nextModelSelection) &&
|
||||
Equal.equals(state.stickyModelSelection, nextStickyModelSelection)
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelectionByProvider: nextMap,
|
||||
modelSelection: nextModelSelection,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
@@ -1781,10 +1352,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return {
|
||||
draftsByThreadId: nextDraftsByThreadId,
|
||||
...(options?.persistSticky === true
|
||||
? {
|
||||
stickyModelSelectionByProvider: nextStickyMap,
|
||||
stickyActiveProvider: nextStickyActiveProvider,
|
||||
}
|
||||
? { stickyModelSelection: nextStickyModelSelection }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
@@ -2143,8 +1711,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: normalizedPersisted.draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: normalizedPersisted.projectDraftThreadIdByProjectId,
|
||||
stickyModelSelectionByProvider: normalizedPersisted.stickyModelSelectionByProvider ?? {},
|
||||
stickyActiveProvider: normalizedPersisted.stickyActiveProvider ?? null,
|
||||
stickyModelSelection: normalizedPersisted.stickyModelSelection as ModelSelection | null,
|
||||
};
|
||||
},
|
||||
},
|
||||
@@ -2155,34 +1722,6 @@ export function useComposerThreadDraft(threadId: ThreadId): ComposerThreadDraftS
|
||||
return useComposerDraftStore((state) => state.draftsByThreadId[threadId] ?? EMPTY_THREAD_DRAFT);
|
||||
}
|
||||
|
||||
export function useEffectiveComposerModelState(input: {
|
||||
threadId: ThreadId;
|
||||
selectedProvider: ProviderKind;
|
||||
threadModelSelection: ModelSelection | null | undefined;
|
||||
projectModelSelection: ModelSelection | null | undefined;
|
||||
customModelsByProvider: Record<ProviderKind, readonly string[]>;
|
||||
}): EffectiveComposerModelState {
|
||||
const draft = useComposerThreadDraft(input.threadId);
|
||||
|
||||
return useMemo(
|
||||
() =>
|
||||
deriveEffectiveComposerModelState({
|
||||
draft,
|
||||
selectedProvider: input.selectedProvider,
|
||||
threadModelSelection: input.threadModelSelection,
|
||||
projectModelSelection: input.projectModelSelection,
|
||||
customModelsByProvider: input.customModelsByProvider,
|
||||
}),
|
||||
[
|
||||
draft,
|
||||
input.customModelsByProvider,
|
||||
input.projectModelSelection,
|
||||
input.selectedProvider,
|
||||
input.threadModelSelection,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear draft threads that have been promoted to server threads.
|
||||
*
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useStore } from "../store";
|
||||
export function useHandleNewThread() {
|
||||
const projects = useStore((store) => store.projects);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const stickyModelSelection = useComposerDraftStore((store) => store.stickyModelSelection);
|
||||
const navigate = useNavigate();
|
||||
const routeThreadId = useParams({
|
||||
strict: false,
|
||||
@@ -38,7 +39,7 @@ export function useHandleNewThread() {
|
||||
clearProjectDraftThreadId,
|
||||
getDraftThread,
|
||||
getDraftThreadByProjectId,
|
||||
applyStickyState,
|
||||
setModelSelection,
|
||||
setDraftThreadContext,
|
||||
setProjectDraftThreadId,
|
||||
} = useComposerDraftStore.getState();
|
||||
@@ -97,7 +98,9 @@ export function useHandleNewThread() {
|
||||
envMode: options?.envMode ?? "local",
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
});
|
||||
applyStickyState(threadId);
|
||||
if (stickyModelSelection) {
|
||||
setModelSelection(threadId, stickyModelSelection);
|
||||
}
|
||||
|
||||
await navigate({
|
||||
to: "/$threadId",
|
||||
@@ -105,7 +108,7 @@ export function useHandleNewThread() {
|
||||
});
|
||||
})();
|
||||
},
|
||||
[navigate, routeThreadId],
|
||||
[navigate, routeThreadId, stickyModelSelection],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,27 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
EventId,
|
||||
type OrchestrationThreadActivity,
|
||||
type OrchestrationThreadActivityKind,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { EventId, type OrchestrationThreadActivity, TurnId } from "@t3tools/contracts";
|
||||
|
||||
import { deriveLatestContextWindowSnapshot, formatContextWindowTokens } from "./contextWindow";
|
||||
|
||||
function makeActivity(
|
||||
id: string,
|
||||
kind: OrchestrationThreadActivityKind,
|
||||
payload: unknown,
|
||||
): OrchestrationThreadActivity {
|
||||
function makeActivity(id: string, kind: string, payload: unknown): OrchestrationThreadActivity {
|
||||
return {
|
||||
id: EventId.makeUnsafe(id),
|
||||
tone: kind.startsWith("tool.") ? "tool" : "info",
|
||||
tone: "info",
|
||||
kind,
|
||||
summary: kind,
|
||||
payload,
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
createdAt: "2026-03-23T00:00:00.000Z",
|
||||
} as OrchestrationThreadActivity;
|
||||
};
|
||||
}
|
||||
|
||||
describe("contextWindow", () => {
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
import type { OrchestrationThreadActivity, ThreadTokenUsageSnapshot } from "@t3tools/contracts";
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
|
||||
}
|
||||
|
||||
function asFiniteNumber(value: unknown): number | null {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
function asBoolean(value: unknown): boolean | null {
|
||||
return typeof value === "boolean" ? value : null;
|
||||
}
|
||||
|
||||
type NullableContextWindowUsage = {
|
||||
readonly [Key in keyof ThreadTokenUsageSnapshot]: undefined extends ThreadTokenUsageSnapshot[Key]
|
||||
? Exclude<ThreadTokenUsageSnapshot[Key], undefined> | null
|
||||
@@ -22,56 +34,38 @@ export function deriveLatestContextWindowSnapshot(
|
||||
continue;
|
||||
}
|
||||
|
||||
const {
|
||||
payload: {
|
||||
usedTokens,
|
||||
totalProcessedTokens,
|
||||
maxTokens,
|
||||
inputTokens,
|
||||
cachedInputTokens,
|
||||
outputTokens,
|
||||
reasoningOutputTokens,
|
||||
lastUsedTokens,
|
||||
lastInputTokens,
|
||||
lastCachedInputTokens,
|
||||
lastOutputTokens,
|
||||
lastReasoningOutputTokens,
|
||||
toolUses,
|
||||
durationMs,
|
||||
compactsAutomatically,
|
||||
},
|
||||
} = activity;
|
||||
if (!Number.isFinite(usedTokens) || usedTokens <= 0) {
|
||||
const payload = asRecord(activity.payload);
|
||||
const usedTokens = asFiniteNumber(payload?.usedTokens);
|
||||
if (usedTokens === null || usedTokens <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const maxTokens = asFiniteNumber(payload?.maxTokens);
|
||||
const usedPercentage =
|
||||
maxTokens !== undefined && maxTokens > 0
|
||||
? Math.min(100, (usedTokens / maxTokens) * 100)
|
||||
: null;
|
||||
maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null;
|
||||
const remainingTokens =
|
||||
maxTokens !== undefined ? Math.max(0, Math.round(maxTokens - usedTokens)) : null;
|
||||
maxTokens !== null ? Math.max(0, Math.round(maxTokens - usedTokens)) : null;
|
||||
const remainingPercentage = usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null;
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
totalProcessedTokens: totalProcessedTokens ?? null,
|
||||
maxTokens: maxTokens ?? null,
|
||||
totalProcessedTokens: asFiniteNumber(payload?.totalProcessedTokens),
|
||||
maxTokens,
|
||||
remainingTokens,
|
||||
usedPercentage,
|
||||
remainingPercentage,
|
||||
inputTokens: inputTokens ?? null,
|
||||
cachedInputTokens: cachedInputTokens ?? null,
|
||||
outputTokens: outputTokens ?? null,
|
||||
reasoningOutputTokens: reasoningOutputTokens ?? null,
|
||||
lastUsedTokens: lastUsedTokens ?? null,
|
||||
lastInputTokens: lastInputTokens ?? null,
|
||||
lastCachedInputTokens: lastCachedInputTokens ?? null,
|
||||
lastOutputTokens: lastOutputTokens ?? null,
|
||||
lastReasoningOutputTokens: lastReasoningOutputTokens ?? null,
|
||||
toolUses: toolUses ?? null,
|
||||
durationMs: durationMs ?? null,
|
||||
compactsAutomatically: compactsAutomatically ?? false,
|
||||
inputTokens: asFiniteNumber(payload?.inputTokens),
|
||||
cachedInputTokens: asFiniteNumber(payload?.cachedInputTokens),
|
||||
outputTokens: asFiniteNumber(payload?.outputTokens),
|
||||
reasoningOutputTokens: asFiniteNumber(payload?.reasoningOutputTokens),
|
||||
lastUsedTokens: asFiniteNumber(payload?.lastUsedTokens),
|
||||
lastInputTokens: asFiniteNumber(payload?.lastInputTokens),
|
||||
lastCachedInputTokens: asFiniteNumber(payload?.lastCachedInputTokens),
|
||||
lastOutputTokens: asFiniteNumber(payload?.lastOutputTokens),
|
||||
lastReasoningOutputTokens: asFiniteNumber(payload?.lastReasoningOutputTokens),
|
||||
toolUses: asFiniteNumber(payload?.toolUses),
|
||||
durationMs: asFiniteNumber(payload?.durationMs),
|
||||
compactsAutomatically: asBoolean(payload?.compactsAutomatically) ?? false,
|
||||
updatedAt: activity.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
|
||||
import type { UserInputQuestion } from "@t3tools/contracts";
|
||||
|
||||
export interface PendingUserInputDraftAnswer {
|
||||
selectedOptionLabel?: string;
|
||||
@@ -55,7 +55,7 @@ export function setPendingUserInputCustomAnswer(
|
||||
export function buildPendingUserInputAnswers(
|
||||
questions: ReadonlyArray<UserInputQuestion>,
|
||||
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
|
||||
): ProviderUserInputAnswers | null {
|
||||
): Record<string, string> | null {
|
||||
const answers: Record<string, string> = {};
|
||||
|
||||
for (const question of questions) {
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
MessageId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThreadActivityKind,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
@@ -26,7 +25,7 @@ import {
|
||||
function makeActivity(overrides: {
|
||||
id?: string;
|
||||
createdAt?: string;
|
||||
kind?: OrchestrationThreadActivityKind;
|
||||
kind?: string;
|
||||
summary?: string;
|
||||
tone?: OrchestrationThreadActivity["tone"];
|
||||
payload?: Record<string, unknown>;
|
||||
@@ -43,7 +42,7 @@ function makeActivity(overrides: {
|
||||
payload,
|
||||
turnId: overrides.turnId ? TurnId.makeUnsafe(overrides.turnId) : null,
|
||||
...(overrides.sequence !== undefined ? { sequence: overrides.sequence } : {}),
|
||||
} as OrchestrationThreadActivity;
|
||||
};
|
||||
}
|
||||
|
||||
describe("derivePendingApprovals", () => {
|
||||
@@ -697,8 +696,9 @@ describe("deriveWorkLogEntries", () => {
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
data: {
|
||||
kind: "command_execution",
|
||||
command: "bun run lint",
|
||||
item: {
|
||||
command: ["bun", "run", "lint"],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -720,11 +720,12 @@ describe("deriveWorkLogEntries", () => {
|
||||
status: "completed",
|
||||
detail: '{ "dev": "vite dev --port 3000" } <exited with exit code 0>',
|
||||
data: {
|
||||
kind: "command_execution",
|
||||
command: "bun run dev",
|
||||
result: {
|
||||
content: '{ "dev": "vite dev --port 3000" } <exited with exit code 0>',
|
||||
exitCode: 0,
|
||||
item: {
|
||||
command: ["bun", "run", "dev"],
|
||||
result: {
|
||||
content: '{ "dev": "vite dev --port 3000" } <exited with exit code 0>',
|
||||
exitCode: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -749,8 +750,12 @@ describe("deriveWorkLogEntries", () => {
|
||||
payload: {
|
||||
itemType: "file_change",
|
||||
data: {
|
||||
kind: "file_change",
|
||||
changedFiles: ["apps/web/src/components/ChatView.tsx", "apps/web/src/session-logic.ts"],
|
||||
item: {
|
||||
changes: [
|
||||
{ path: "apps/web/src/components/ChatView.tsx" },
|
||||
{ filename: "apps/web/src/session-logic.ts" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -786,7 +791,9 @@ describe("deriveWorkLogEntries", () => {
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
data: {
|
||||
kind: "generic",
|
||||
item: {
|
||||
command: ["sed", "-n", "1,40p", "/tmp/app.ts"],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -811,6 +818,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
createdAt: "2026-02-23T00:00:03.000Z",
|
||||
label: "Tool call completed",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
command: "sed -n 1,40p /tmp/app.ts",
|
||||
itemType: "dynamic_tool_call",
|
||||
toolTitle: "Tool call",
|
||||
});
|
||||
@@ -1016,7 +1024,7 @@ describe("hasToolActivityForTurn", () => {
|
||||
it("returns true only for matching tool activity in the target turn", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
|
||||
makeActivity({ id: "info-1", turnId: "turn-2", kind: "task.completed", tone: "info" }),
|
||||
makeActivity({ id: "info-1", turnId: "turn-2", kind: "turn.completed", tone: "info" }),
|
||||
];
|
||||
|
||||
expect(hasToolActivityForTurn(activities, TurnId.makeUnsafe("turn-1"))).toBe(true);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type CanonicalToolLifecycleData,
|
||||
isToolLifecycleItemType,
|
||||
type OrchestrationLatestTurn,
|
||||
type OrchestrationThreadActivity,
|
||||
@@ -477,10 +476,22 @@ function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): bool
|
||||
if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") {
|
||||
return false;
|
||||
}
|
||||
return activity.payload.detail?.startsWith("ExitPlanMode:") ?? false;
|
||||
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
|
||||
}
|
||||
|
||||
function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const command = extractToolCommand(payload);
|
||||
const changedFiles = extractChangedFiles(payload);
|
||||
const title = extractToolTitle(payload);
|
||||
const entry: DerivedWorkLogEntry = {
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
@@ -488,24 +499,12 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
tone: activity.tone === "approval" ? "info" : activity.tone,
|
||||
activityKind: activity.kind,
|
||||
};
|
||||
const toolPayload = toolLifecyclePayloadFromActivity(activity);
|
||||
const detail =
|
||||
"detail" in activity.payload && typeof activity.payload.detail === "string"
|
||||
? activity.payload.detail
|
||||
: undefined;
|
||||
const toolData = toolPayload && "data" in toolPayload ? toolPayload.data : undefined;
|
||||
const command = extractToolCommand(toolData);
|
||||
const changedFiles = extractChangedFiles(toolData);
|
||||
const title =
|
||||
"title" in activity.payload && typeof activity.payload.title === "string"
|
||||
? extractToolTitle(activity.payload.title)
|
||||
: null;
|
||||
const itemType = extractWorkLogItemType(toolPayload);
|
||||
const requestKind = extractWorkLogRequestKind(activity);
|
||||
if (detail && detail.length > 0) {
|
||||
const normalizedDetail = stripTrailingExitCode(detail).output;
|
||||
if (normalizedDetail) {
|
||||
entry.detail = normalizedDetail;
|
||||
const itemType = extractWorkLogItemType(payload);
|
||||
const requestKind = extractWorkLogRequestKind(payload);
|
||||
if (payload && typeof payload.detail === "string" && payload.detail.length > 0) {
|
||||
const detail = stripTrailingExitCode(payload.detail).output;
|
||||
if (detail) {
|
||||
entry.detail = detail;
|
||||
}
|
||||
}
|
||||
if (command) {
|
||||
@@ -625,6 +624,10 @@ function toLatestProposedPlanState(proposedPlan: ProposedPlan): LatestProposedPl
|
||||
};
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
|
||||
}
|
||||
|
||||
function asTrimmedString(value: unknown): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
@@ -647,37 +650,22 @@ function normalizeCommandValue(value: unknown): string | null {
|
||||
return parts.length > 0 ? parts.join(" ") : null;
|
||||
}
|
||||
|
||||
function toolLifecyclePayloadFromActivity(
|
||||
activity: OrchestrationThreadActivity,
|
||||
):
|
||||
| Extract<
|
||||
OrchestrationThreadActivity,
|
||||
{ kind: "tool.started" | "tool.updated" | "tool.completed" }
|
||||
>["payload"]
|
||||
| null {
|
||||
switch (activity.kind) {
|
||||
case "tool.started":
|
||||
case "tool.updated":
|
||||
case "tool.completed":
|
||||
return activity.payload;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function extractToolCommand(data: CanonicalToolLifecycleData | undefined): string | null {
|
||||
if (data?.kind !== "command_execution") {
|
||||
return null;
|
||||
}
|
||||
function extractToolCommand(payload: Record<string, unknown> | null): string | null {
|
||||
const data = asRecord(payload?.data);
|
||||
const item = asRecord(data?.item);
|
||||
const itemResult = asRecord(item?.result);
|
||||
const itemInput = asRecord(item?.input);
|
||||
const candidates = [
|
||||
normalizeCommandValue(data.command),
|
||||
normalizeCommandValue(data.input?.command),
|
||||
normalizeCommandValue(item?.command),
|
||||
normalizeCommandValue(itemInput?.command),
|
||||
normalizeCommandValue(itemResult?.command),
|
||||
normalizeCommandValue(data?.command),
|
||||
];
|
||||
return candidates.find((candidate) => candidate !== null) ?? null;
|
||||
}
|
||||
|
||||
function extractToolTitle(value: string | undefined): string | null {
|
||||
return asTrimmedString(value);
|
||||
function extractToolTitle(payload: Record<string, unknown> | null): string | null {
|
||||
return asTrimmedString(payload?.title);
|
||||
}
|
||||
|
||||
function stripTrailingExitCode(value: string): {
|
||||
@@ -702,36 +690,28 @@ function stripTrailingExitCode(value: string): {
|
||||
}
|
||||
|
||||
function extractWorkLogItemType(
|
||||
payload:
|
||||
| Extract<
|
||||
OrchestrationThreadActivity,
|
||||
{ kind: "tool.started" | "tool.updated" | "tool.completed" }
|
||||
>["payload"]
|
||||
| null,
|
||||
payload: Record<string, unknown> | null,
|
||||
): WorkLogEntry["itemType"] | undefined {
|
||||
if (payload && isToolLifecycleItemType(payload.itemType)) {
|
||||
if (typeof payload?.itemType === "string" && isToolLifecycleItemType(payload.itemType)) {
|
||||
return payload.itemType;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function extractWorkLogRequestKind(
|
||||
activity: OrchestrationThreadActivity,
|
||||
payload: Record<string, unknown> | null,
|
||||
): WorkLogEntry["requestKind"] | undefined {
|
||||
if (activity.kind !== "approval.requested" && activity.kind !== "approval.resolved") {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
activity.payload.requestKind === "command" ||
|
||||
activity.payload.requestKind === "file-read" ||
|
||||
activity.payload.requestKind === "file-change"
|
||||
payload?.requestKind === "command" ||
|
||||
payload?.requestKind === "file-read" ||
|
||||
payload?.requestKind === "file-change"
|
||||
) {
|
||||
return activity.payload.requestKind;
|
||||
return payload.requestKind;
|
||||
}
|
||||
return requestKindFromRequestType(activity.payload.requestType) ?? undefined;
|
||||
return requestKindFromRequestType(payload?.requestType) ?? undefined;
|
||||
}
|
||||
|
||||
function pushChangedFile(target: string[], seen: Set<string>, value: string | undefined) {
|
||||
function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {
|
||||
const normalized = asTrimmedString(value);
|
||||
if (!normalized || seen.has(normalized)) {
|
||||
return;
|
||||
@@ -740,16 +720,58 @@ function pushChangedFile(target: string[], seen: Set<string>, value: string | un
|
||||
target.push(normalized);
|
||||
}
|
||||
|
||||
function extractChangedFiles(data: CanonicalToolLifecycleData | undefined): string[] {
|
||||
const changedFiles: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
const files = data?.kind === "file_change" ? data.changedFiles : [];
|
||||
for (const file of files) {
|
||||
pushChangedFile(changedFiles, seen, file);
|
||||
if (changedFiles.length >= 12) {
|
||||
break;
|
||||
function collectChangedFiles(value: unknown, target: string[], seen: Set<string>, depth: number) {
|
||||
if (depth > 4 || target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
collectChangedFiles(entry, target, seen, depth + 1);
|
||||
if (target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const record = asRecord(value);
|
||||
if (!record) {
|
||||
return;
|
||||
}
|
||||
|
||||
pushChangedFile(target, seen, record.path);
|
||||
pushChangedFile(target, seen, record.filePath);
|
||||
pushChangedFile(target, seen, record.relativePath);
|
||||
pushChangedFile(target, seen, record.filename);
|
||||
pushChangedFile(target, seen, record.newPath);
|
||||
pushChangedFile(target, seen, record.oldPath);
|
||||
|
||||
for (const nestedKey of [
|
||||
"item",
|
||||
"result",
|
||||
"input",
|
||||
"data",
|
||||
"changes",
|
||||
"files",
|
||||
"edits",
|
||||
"patch",
|
||||
"patches",
|
||||
"operations",
|
||||
]) {
|
||||
if (!(nestedKey in record)) {
|
||||
continue;
|
||||
}
|
||||
collectChangedFiles(record[nestedKey], target, seen, depth + 1);
|
||||
if (target.length >= 12) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function extractChangedFiles(payload: Record<string, unknown> | null): string[] {
|
||||
const changedFiles: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
collectChangedFiles(asRecord(payload?.data), changedFiles, seen, 0);
|
||||
return changedFiles;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Fragment, type ReactNode, createElement, useEffect } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
@@ -324,6 +326,26 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveModelSelection(
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
fallbackProvider: ProviderKind,
|
||||
fallbackModel?: string | null,
|
||||
): ModelSelection {
|
||||
if (modelSelection) {
|
||||
return {
|
||||
...modelSelection,
|
||||
model: resolveModelSlugForProvider(modelSelection.provider, modelSelection.model),
|
||||
};
|
||||
}
|
||||
return {
|
||||
provider: fallbackProvider,
|
||||
model: resolveModelSlugForProvider(
|
||||
fallbackProvider,
|
||||
fallbackModel ?? DEFAULT_MODEL_BY_PROVIDER[fallbackProvider],
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function markThreadVisited(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
|
||||
@@ -3,15 +3,11 @@ export * from "./ipc";
|
||||
export * from "./terminal";
|
||||
export * from "./provider";
|
||||
export * from "./providerRuntime";
|
||||
export * from "./threadUsage";
|
||||
export * from "./model";
|
||||
export * from "./ws";
|
||||
export * from "./keybindings";
|
||||
export * from "./server";
|
||||
export * from "./git";
|
||||
export * from "./jsonValue";
|
||||
export * from "./orchestration";
|
||||
export * from "./toolLifecycle";
|
||||
export * from "./userInput";
|
||||
export * from "./editor";
|
||||
export * from "./project";
|
||||
@@ -1,7 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
export const CanonicalJsonValueSchema = Schema.Json;
|
||||
export type CanonicalJsonValue = typeof CanonicalJsonValueSchema.Type;
|
||||
|
||||
export const CanonicalJsonObjectSchema = Schema.Record(Schema.String, CanonicalJsonValueSchema);
|
||||
export type CanonicalJsonObject = typeof CanonicalJsonObjectSchema.Type;
|
||||
+19
-165
@@ -26,166 +26,26 @@ export const ProviderModelOptions = Schema.Struct({
|
||||
});
|
||||
export type ProviderModelOptions = typeof ProviderModelOptions.Type;
|
||||
|
||||
export type EffortOption = {
|
||||
readonly value: string;
|
||||
readonly label: string;
|
||||
readonly isDefault?: true;
|
||||
};
|
||||
|
||||
export type ModelCapabilities = {
|
||||
readonly reasoningEffortLevels: readonly EffortOption[];
|
||||
readonly supportsFastMode: boolean;
|
||||
readonly supportsThinkingToggle: boolean;
|
||||
readonly promptInjectedEffortLevels: readonly string[];
|
||||
};
|
||||
|
||||
type ModelDefinition = {
|
||||
type ModelOption = {
|
||||
readonly slug: string;
|
||||
readonly name: string;
|
||||
readonly capabilities: ModelCapabilities;
|
||||
};
|
||||
|
||||
/**
|
||||
* TODO: This should not be a static array, each provider
|
||||
* should return its own model list over the WS API.
|
||||
*/
|
||||
export const MODEL_OPTIONS_BY_PROVIDER = {
|
||||
codex: [
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.4-mini",
|
||||
name: "GPT-5.4 Mini",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex",
|
||||
name: "GPT-5.3 Codex",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex-spark",
|
||||
name: "GPT-5.3 Codex Spark",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.2-codex",
|
||||
name: "GPT-5.2 Codex",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.2",
|
||||
name: "GPT-5.2",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ slug: "gpt-5.4-mini", name: "GPT-5.4 Mini" },
|
||||
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
|
||||
{ slug: "gpt-5.3-codex-spark", name: "GPT-5.3 Codex Spark" },
|
||||
{ slug: "gpt-5.2-codex", name: "GPT-5.2 Codex" },
|
||||
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
||||
],
|
||||
claudeAgent: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Claude Opus 4.6",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
name: "Claude Sonnet 4.6",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-haiku-4-5",
|
||||
name: "Claude Haiku 4.5",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{ slug: "claude-opus-4-6", name: "Claude Opus 4.6" },
|
||||
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
|
||||
{ slug: "claude-haiku-4-5", name: "Claude Haiku 4.5" },
|
||||
],
|
||||
} as const satisfies Record<ProviderKind, readonly ModelDefinition[]>;
|
||||
} as const satisfies Record<ProviderKind, readonly ModelOption[]>;
|
||||
export type ModelOptionsByProvider = typeof MODEL_OPTIONS_BY_PROVIDER;
|
||||
|
||||
type BuiltInModelSlug = (typeof MODEL_OPTIONS_BY_PROVIDER)[ProviderKind][number]["slug"];
|
||||
@@ -225,18 +85,12 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,
|
||||
},
|
||||
};
|
||||
|
||||
// ── Model capabilities index ──────────────────────────────────────────
|
||||
export const REASONING_EFFORT_OPTIONS_BY_PROVIDER = {
|
||||
codex: CODEX_REASONING_EFFORT_OPTIONS,
|
||||
claudeAgent: CLAUDE_CODE_EFFORT_OPTIONS,
|
||||
} as const satisfies Record<ProviderKind, readonly ProviderReasoningEffort[]>;
|
||||
|
||||
export const MODEL_CAPABILITIES_INDEX = Object.fromEntries(
|
||||
Object.entries(MODEL_OPTIONS_BY_PROVIDER).map(([provider, models]) => [
|
||||
provider,
|
||||
Object.fromEntries(models.map((m) => [m.slug, m.capabilities])),
|
||||
]),
|
||||
) as unknown as Record<ProviderKind, Record<string, ModelCapabilities>>;
|
||||
|
||||
// ── Provider display names ────────────────────────────────────────────
|
||||
|
||||
export const PROVIDER_DISPLAY_NAMES: Record<ProviderKind, string> = {
|
||||
codex: "Codex",
|
||||
claudeAgent: "Claude",
|
||||
};
|
||||
export const DEFAULT_REASONING_EFFORT_BY_PROVIDER = {
|
||||
codex: "high",
|
||||
claudeAgent: "high",
|
||||
} as const satisfies Record<ProviderKind, ProviderReasoningEffort>;
|
||||
@@ -116,6 +116,24 @@ it.effect("decodes historical project.created payloads with a default provider",
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy project.created payloads into defaultModelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeProjectCreatedPayload({
|
||||
projectId: "project-legacy-1",
|
||||
title: "Project Title",
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
defaultModel: "gpt-5.4",
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.defaultModelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes project.meta-updated payloads with explicit default provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeProjectMetaUpdatedPayload({
|
||||
@@ -130,6 +148,21 @@ it.effect("decodes project.meta-updated payloads with explicit default provider"
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy project.meta-updated payloads into defaultModelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeProjectMetaUpdatedPayload({
|
||||
projectId: "project-legacy-2",
|
||||
defaultProvider: "claudeAgent",
|
||||
defaultModel: "claude-opus-4-6",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.defaultModelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects command fields that become empty after trim", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Effect.exit(
|
||||
@@ -213,6 +246,29 @@ it.effect("decodes thread.created runtime mode for historical events", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy thread.created payloads into modelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadCreatedPayload({
|
||||
threadId: "thread-legacy-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread title",
|
||||
model: "claude-opus-4-6",
|
||||
provider: "claudeAgent",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(parsed.modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
});
|
||||
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes thread.meta-updated payloads with explicit provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadMetaUpdatedPayload({
|
||||
@@ -227,6 +283,20 @@ it.effect("decodes thread.meta-updated payloads with explicit provider", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy thread.meta-updated payloads into modelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadMetaUpdatedPayload({
|
||||
threadId: "thread-legacy-2",
|
||||
model: "gpt-5.4",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.modelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts provider-scoped model options in thread.turn.start", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadTurnStartCommand({
|
||||
@@ -314,6 +384,21 @@ it.effect("decodes thread.turn-start-requested source proposed plan metadata whe
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy thread.turn-start-requested payloads into modelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadTurnStartRequestedPayload({
|
||||
threadId: "thread-legacy-3",
|
||||
messageId: "msg-legacy-3",
|
||||
model: "gpt-5.4",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.modelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes latest turn source proposed plan metadata when present", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeOrchestrationLatestTurn({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Option, Schema, SchemaIssue, Struct } from "effect";
|
||||
import { Effect, Option, Schema, SchemaIssue, SchemaTransformation, Struct } from "effect";
|
||||
import { ClaudeModelOptions, CodexModelOptions } from "./model";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -14,10 +14,6 @@ import {
|
||||
TrimmedNonEmptyString,
|
||||
TurnId,
|
||||
} from "./baseSchemas";
|
||||
import { CanonicalJsonValueSchema } from "./jsonValue";
|
||||
import { CanonicalToolLifecycleData } from "./toolLifecycle";
|
||||
import { ThreadTokenUsageSnapshot } from "./threadUsage";
|
||||
import { ProviderUserInputAnswers, UserInputQuestion } from "./userInput";
|
||||
|
||||
export const ORCHESTRATION_WS_METHODS = {
|
||||
getSnapshot: "orchestration.getSnapshot",
|
||||
@@ -64,6 +60,96 @@ export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
|
||||
|
||||
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]);
|
||||
export type ModelSelection = typeof ModelSelection.Type;
|
||||
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
|
||||
|
||||
const LegacyDefaultModelSelectionFields = {
|
||||
defaultProvider: Schema.optional(ProviderKind),
|
||||
defaultModel: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
defaultModelOptions: Schema.optional(Schema.NullOr(Schema.Unknown)),
|
||||
} as const;
|
||||
|
||||
const LegacyThreadModelSelectionFields = {
|
||||
provider: Schema.optional(ProviderKind),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
modelOptions: Schema.optional(Schema.NullOr(Schema.Unknown)),
|
||||
} as const;
|
||||
|
||||
function invalidLegacyModelSelectionIssue(
|
||||
value: unknown,
|
||||
title: string,
|
||||
cause: unknown,
|
||||
): SchemaIssue.InvalidValue {
|
||||
return new SchemaIssue.InvalidValue(Option.some(value), {
|
||||
title,
|
||||
...(Schema.isSchemaError(cause)
|
||||
? { description: SchemaIssue.makeFormatterDefault()(cause.issue) }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
type LegacyDefaultModelSelectionInput = {
|
||||
readonly defaultModelSelection?: ModelSelection | null | undefined;
|
||||
readonly defaultProvider?: ProviderKind | undefined;
|
||||
readonly defaultModel?: string | null | undefined;
|
||||
readonly defaultModelOptions?: unknown | null | undefined;
|
||||
};
|
||||
|
||||
type LegacyThreadModelSelectionInput = {
|
||||
readonly modelSelection?: ModelSelection | undefined;
|
||||
readonly provider?: ProviderKind | undefined;
|
||||
readonly model?: string | undefined;
|
||||
readonly modelOptions?: unknown | null | undefined;
|
||||
};
|
||||
|
||||
function normalizeLegacyDefaultModelSelection(
|
||||
input: LegacyDefaultModelSelectionInput,
|
||||
): Effect.Effect<ModelSelection | null, SchemaIssue.InvalidValue> {
|
||||
if (input.defaultModelSelection !== undefined) {
|
||||
return Effect.succeed(input.defaultModelSelection);
|
||||
}
|
||||
if (input.defaultModel === undefined || input.defaultModel === null) {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
return Effect.try({
|
||||
try: () =>
|
||||
decodeModelSelectionSync({
|
||||
provider: input.defaultProvider ?? DEFAULT_PROVIDER_KIND,
|
||||
model: input.defaultModel,
|
||||
...(input.defaultModelOptions != null ? { options: input.defaultModelOptions } : {}),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
invalidLegacyModelSelectionIssue(
|
||||
input,
|
||||
"Invalid legacy default model selection payload",
|
||||
cause,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeLegacyThreadModelSelection(
|
||||
input: LegacyThreadModelSelectionInput,
|
||||
): Effect.Effect<ModelSelection | undefined, SchemaIssue.InvalidValue> {
|
||||
if (input.modelSelection !== undefined) {
|
||||
return Effect.succeed(input.modelSelection);
|
||||
}
|
||||
if (input.model === undefined) {
|
||||
return Effect.succeed<ModelSelection | undefined>(undefined);
|
||||
}
|
||||
return Effect.try({
|
||||
try: () =>
|
||||
decodeModelSelectionSync({
|
||||
provider: input.provider ?? DEFAULT_PROVIDER_KIND,
|
||||
model: input.model,
|
||||
...(input.modelOptions != null ? { options: input.modelOptions } : {}),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
invalidLegacyModelSelectionIssue(
|
||||
input,
|
||||
"Invalid legacy thread model selection payload",
|
||||
cause,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export const CodexProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -99,6 +185,9 @@ export const ProviderApprovalDecision = Schema.Literals([
|
||||
"cancel",
|
||||
]);
|
||||
export type ProviderApprovalDecision = typeof ProviderApprovalDecision.Type;
|
||||
export const ProviderUserInputAnswers = Schema.Record(Schema.String, Schema.Unknown);
|
||||
export type ProviderUserInputAnswers = typeof ProviderUserInputAnswers.Type;
|
||||
|
||||
export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;
|
||||
export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;
|
||||
export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
||||
@@ -256,199 +345,16 @@ export const OrchestrationThreadActivityTone = Schema.Literals([
|
||||
]);
|
||||
export type OrchestrationThreadActivityTone = typeof OrchestrationThreadActivityTone.Type;
|
||||
|
||||
export const OrchestrationThreadActivityKind = Schema.Literals([
|
||||
"approval.requested",
|
||||
"approval.resolved",
|
||||
"runtime.error",
|
||||
"runtime.warning",
|
||||
"turn.plan.updated",
|
||||
"user-input.requested",
|
||||
"user-input.resolved",
|
||||
"task.started",
|
||||
"task.progress",
|
||||
"task.completed",
|
||||
"context-compaction",
|
||||
"context-window.updated",
|
||||
"tool.updated",
|
||||
"tool.completed",
|
||||
"tool.started",
|
||||
"checkpoint.revert.failed",
|
||||
"checkpoint.capture.failed",
|
||||
"checkpoint.captured",
|
||||
"provider.turn.start.failed",
|
||||
"provider.turn.interrupt.failed",
|
||||
"provider.approval.respond.failed",
|
||||
"provider.user-input.respond.failed",
|
||||
]);
|
||||
export type OrchestrationThreadActivityKind = typeof OrchestrationThreadActivityKind.Type;
|
||||
|
||||
const OrchestrationThreadActivityBaseFields = {
|
||||
export const OrchestrationThreadActivity = Schema.Struct({
|
||||
id: EventId,
|
||||
tone: OrchestrationThreadActivityTone,
|
||||
kind: TrimmedNonEmptyString,
|
||||
summary: TrimmedNonEmptyString,
|
||||
payload: Schema.Unknown,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
sequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
} as const;
|
||||
|
||||
const ApprovalRequestedActivityPayload = Schema.Struct({
|
||||
requestId: Schema.optional(TrimmedNonEmptyString),
|
||||
requestKind: Schema.optional(ProviderRequestKind),
|
||||
requestType: Schema.optional(TrimmedNonEmptyString),
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const ApprovalResolvedActivityPayload = Schema.Struct({
|
||||
requestId: Schema.optional(TrimmedNonEmptyString),
|
||||
requestKind: Schema.optional(ProviderRequestKind),
|
||||
requestType: Schema.optional(TrimmedNonEmptyString),
|
||||
decision: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const RuntimeErrorActivityPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const RuntimeWarningActivityPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyString,
|
||||
detail: Schema.optional(CanonicalJsonValueSchema),
|
||||
});
|
||||
|
||||
const RuntimePlanStep = Schema.Struct({
|
||||
step: TrimmedNonEmptyString,
|
||||
status: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const TurnPlanUpdatedActivityPayload = Schema.Struct({
|
||||
plan: Schema.Array(RuntimePlanStep),
|
||||
explanation: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
});
|
||||
|
||||
const UserInputRequestedActivityPayload = Schema.Struct({
|
||||
requestId: Schema.optional(TrimmedNonEmptyString),
|
||||
questions: Schema.Array(UserInputQuestion),
|
||||
});
|
||||
|
||||
const UserInputResolvedActivityPayload = Schema.Struct({
|
||||
requestId: Schema.optional(TrimmedNonEmptyString),
|
||||
answers: ProviderUserInputAnswers,
|
||||
});
|
||||
|
||||
const TaskStartedActivityPayload = Schema.Struct({
|
||||
taskId: TrimmedNonEmptyString,
|
||||
taskType: Schema.optional(TrimmedNonEmptyString),
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const TaskProgressActivityPayload = Schema.Struct({
|
||||
taskId: TrimmedNonEmptyString,
|
||||
detail: TrimmedNonEmptyString,
|
||||
summary: Schema.optional(TrimmedNonEmptyString),
|
||||
lastToolName: Schema.optional(TrimmedNonEmptyString),
|
||||
usage: Schema.optional(ThreadTokenUsageSnapshot),
|
||||
});
|
||||
|
||||
const TaskCompletedActivityPayload = Schema.Struct({
|
||||
taskId: TrimmedNonEmptyString,
|
||||
status: TrimmedNonEmptyString,
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
usage: Schema.optional(ThreadTokenUsageSnapshot),
|
||||
});
|
||||
|
||||
const ContextCompactionActivityPayload = Schema.Struct({
|
||||
state: Schema.Literal("compacted"),
|
||||
detail: Schema.optional(CanonicalJsonValueSchema),
|
||||
});
|
||||
|
||||
const ToolStartedOrCompletedActivityPayload = Schema.Struct({
|
||||
itemType: TrimmedNonEmptyString,
|
||||
status: Schema.optional(TrimmedNonEmptyString),
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
data: Schema.optional(CanonicalToolLifecycleData),
|
||||
});
|
||||
|
||||
const ToolUpdatedActivityPayload = Schema.Struct({
|
||||
itemType: TrimmedNonEmptyString,
|
||||
status: Schema.optional(TrimmedNonEmptyString),
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
data: Schema.optional(CanonicalToolLifecycleData),
|
||||
});
|
||||
|
||||
const CheckpointRevertFailedActivityPayload = Schema.Struct({
|
||||
turnCount: NonNegativeInt,
|
||||
detail: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const CheckpointCaptureFailedActivityPayload = Schema.Struct({
|
||||
detail: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const CheckpointCapturedActivityPayload = Schema.Struct({
|
||||
turnCount: NonNegativeInt,
|
||||
status: OrchestrationCheckpointStatus,
|
||||
});
|
||||
|
||||
const ProviderFailureActivityPayload = Schema.Struct({
|
||||
detail: TrimmedNonEmptyString,
|
||||
requestId: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
function makeThreadActivitySchema<
|
||||
Kind extends OrchestrationThreadActivityKind,
|
||||
Payload extends Schema.Schema<any>,
|
||||
>(kind: Kind, tone: OrchestrationThreadActivityTone, payload: Payload) {
|
||||
return Schema.Struct({
|
||||
...OrchestrationThreadActivityBaseFields,
|
||||
tone: Schema.Literal(tone),
|
||||
kind: Schema.Literal(kind),
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
export const OrchestrationThreadActivity = Schema.Union([
|
||||
makeThreadActivitySchema("approval.requested", "approval", ApprovalRequestedActivityPayload),
|
||||
makeThreadActivitySchema("approval.resolved", "approval", ApprovalResolvedActivityPayload),
|
||||
makeThreadActivitySchema("runtime.error", "error", RuntimeErrorActivityPayload),
|
||||
makeThreadActivitySchema("runtime.warning", "info", RuntimeWarningActivityPayload),
|
||||
makeThreadActivitySchema("turn.plan.updated", "info", TurnPlanUpdatedActivityPayload),
|
||||
makeThreadActivitySchema("user-input.requested", "info", UserInputRequestedActivityPayload),
|
||||
makeThreadActivitySchema("user-input.resolved", "info", UserInputResolvedActivityPayload),
|
||||
makeThreadActivitySchema("task.started", "info", TaskStartedActivityPayload),
|
||||
makeThreadActivitySchema("task.progress", "info", TaskProgressActivityPayload),
|
||||
makeThreadActivitySchema("task.completed", "info", TaskCompletedActivityPayload),
|
||||
makeThreadActivitySchema("context-compaction", "info", ContextCompactionActivityPayload),
|
||||
makeThreadActivitySchema("context-window.updated", "info", ThreadTokenUsageSnapshot),
|
||||
makeThreadActivitySchema("tool.updated", "tool", ToolUpdatedActivityPayload),
|
||||
makeThreadActivitySchema("tool.completed", "tool", ToolStartedOrCompletedActivityPayload),
|
||||
makeThreadActivitySchema("tool.started", "tool", ToolStartedOrCompletedActivityPayload),
|
||||
makeThreadActivitySchema(
|
||||
"checkpoint.revert.failed",
|
||||
"error",
|
||||
CheckpointRevertFailedActivityPayload,
|
||||
),
|
||||
makeThreadActivitySchema(
|
||||
"checkpoint.capture.failed",
|
||||
"error",
|
||||
CheckpointCaptureFailedActivityPayload,
|
||||
),
|
||||
makeThreadActivitySchema("checkpoint.captured", "info", CheckpointCapturedActivityPayload),
|
||||
makeThreadActivitySchema("provider.turn.start.failed", "error", ProviderFailureActivityPayload),
|
||||
makeThreadActivitySchema(
|
||||
"provider.turn.interrupt.failed",
|
||||
"error",
|
||||
ProviderFailureActivityPayload,
|
||||
),
|
||||
makeThreadActivitySchema(
|
||||
"provider.approval.respond.failed",
|
||||
"error",
|
||||
ProviderFailureActivityPayload,
|
||||
),
|
||||
makeThreadActivitySchema(
|
||||
"provider.user-input.respond.failed",
|
||||
"error",
|
||||
ProviderFailureActivityPayload,
|
||||
),
|
||||
]);
|
||||
export type OrchestrationThreadActivity = typeof OrchestrationThreadActivity.Type;
|
||||
|
||||
const OrchestrationLatestTurnState = Schema.Literals([
|
||||
@@ -803,7 +709,7 @@ export const OrchestrationAggregateKind = Schema.Literals(["project", "thread"])
|
||||
export type OrchestrationAggregateKind = typeof OrchestrationAggregateKind.Type;
|
||||
export const OrchestrationActorKind = Schema.Literals(["client", "server", "provider"]);
|
||||
|
||||
export const ProjectCreatedPayload = Schema.Struct({
|
||||
const ProjectCreatedPayloadCanonical = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
@@ -812,8 +718,48 @@ export const ProjectCreatedPayload = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
const ProjectCreatedPayloadSource = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
|
||||
...LegacyDefaultModelSelectionFields,
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ProjectCreatedPayloadSource = typeof ProjectCreatedPayloadSource.Type;
|
||||
export const ProjectCreatedPayload = ProjectCreatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ProjectCreatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input) =>
|
||||
normalizeLegacyDefaultModelSelection(input).pipe(
|
||||
Effect.map((defaultModelSelection) => ({
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
defaultModelSelection,
|
||||
scripts: input.scripts,
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.updatedAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical) =>
|
||||
Effect.succeed({
|
||||
projectId: canonical.projectId,
|
||||
title: canonical.title,
|
||||
workspaceRoot: canonical.workspaceRoot,
|
||||
defaultModelSelection: canonical.defaultModelSelection,
|
||||
scripts: canonical.scripts,
|
||||
createdAt: canonical.createdAt,
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ProjectCreatedPayloadSource),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const ProjectMetaUpdatedPayload = Schema.Struct({
|
||||
const ProjectMetaUpdatedPayloadCanonical = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -821,13 +767,60 @@ export const ProjectMetaUpdatedPayload = Schema.Struct({
|
||||
scripts: Schema.optional(Schema.Array(ProjectScript)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ProjectMetaUpdatedPayloadCanonical = typeof ProjectMetaUpdatedPayloadCanonical.Type;
|
||||
const ProjectMetaUpdatedPayloadSource = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
|
||||
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
|
||||
...LegacyDefaultModelSelectionFields,
|
||||
scripts: Schema.optional(Schema.Array(ProjectScript)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ProjectMetaUpdatedPayloadSource = typeof ProjectMetaUpdatedPayloadSource.Type;
|
||||
export const ProjectMetaUpdatedPayload = ProjectMetaUpdatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ProjectMetaUpdatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input: ProjectMetaUpdatedPayloadSource) =>
|
||||
normalizeLegacyDefaultModelSelection(input).pipe(
|
||||
Effect.map((defaultModelSelection) => ({
|
||||
projectId: input.projectId,
|
||||
...(input.title !== undefined ? { title: input.title } : {}),
|
||||
...(input.workspaceRoot !== undefined ? { workspaceRoot: input.workspaceRoot } : {}),
|
||||
...(input.defaultModelSelection !== undefined ||
|
||||
input.defaultModel !== undefined ||
|
||||
input.defaultProvider !== undefined ||
|
||||
input.defaultModelOptions !== undefined
|
||||
? { defaultModelSelection }
|
||||
: {}),
|
||||
...(input.scripts !== undefined ? { scripts: input.scripts } : {}),
|
||||
updatedAt: input.updatedAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical: ProjectMetaUpdatedPayloadCanonical) =>
|
||||
Effect.succeed({
|
||||
projectId: canonical.projectId,
|
||||
...(canonical.title !== undefined ? { title: canonical.title } : {}),
|
||||
...(canonical.workspaceRoot !== undefined
|
||||
? { workspaceRoot: canonical.workspaceRoot }
|
||||
: {}),
|
||||
...(canonical.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: canonical.defaultModelSelection }
|
||||
: {}),
|
||||
...(canonical.scripts !== undefined ? { scripts: canonical.scripts } : {}),
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ProjectMetaUpdatedPayloadSource),
|
||||
} as any),
|
||||
),
|
||||
);
|
||||
|
||||
export const ProjectDeletedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
deletedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadCreatedPayload = Schema.Struct({
|
||||
const ThreadCreatedPayloadCanonical = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
@@ -841,13 +834,72 @@ export const ThreadCreatedPayload = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
const ThreadCreatedPayloadSource = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
...LegacyThreadModelSelectionFields,
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
),
|
||||
branch: Schema.NullOr(TrimmedNonEmptyString),
|
||||
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ThreadCreatedPayloadSource = typeof ThreadCreatedPayloadSource.Type;
|
||||
export const ThreadCreatedPayload = ThreadCreatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ThreadCreatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input) =>
|
||||
normalizeLegacyThreadModelSelection(input).pipe(
|
||||
Effect.flatMap((modelSelection) =>
|
||||
modelSelection === undefined
|
||||
? Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(input), {
|
||||
title: "Legacy thread.created payload is missing a model selection",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
branch: input.branch,
|
||||
worktreePath: input.worktreePath,
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.updatedAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
encode: (canonical) =>
|
||||
Effect.succeed({
|
||||
threadId: canonical.threadId,
|
||||
projectId: canonical.projectId,
|
||||
title: canonical.title,
|
||||
modelSelection: canonical.modelSelection,
|
||||
runtimeMode: canonical.runtimeMode,
|
||||
interactionMode: canonical.interactionMode,
|
||||
branch: canonical.branch,
|
||||
worktreePath: canonical.worktreePath,
|
||||
createdAt: canonical.createdAt,
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ThreadCreatedPayloadSource),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const ThreadDeletedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
deletedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadMetaUpdatedPayload = Schema.Struct({
|
||||
const ThreadMetaUpdatedPayloadCanonical = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
@@ -855,6 +907,46 @@ export const ThreadMetaUpdatedPayload = Schema.Struct({
|
||||
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ThreadMetaUpdatedPayloadCanonical = typeof ThreadMetaUpdatedPayloadCanonical.Type;
|
||||
const ThreadMetaUpdatedPayloadSource = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
...LegacyThreadModelSelectionFields,
|
||||
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ThreadMetaUpdatedPayloadSource = typeof ThreadMetaUpdatedPayloadSource.Type;
|
||||
export const ThreadMetaUpdatedPayload = ThreadMetaUpdatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ThreadMetaUpdatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input: ThreadMetaUpdatedPayloadSource) =>
|
||||
normalizeLegacyThreadModelSelection(input).pipe(
|
||||
Effect.map((modelSelection) => ({
|
||||
threadId: input.threadId,
|
||||
...(input.title !== undefined ? { title: input.title } : {}),
|
||||
...(modelSelection !== undefined ? { modelSelection } : {}),
|
||||
...(input.branch !== undefined ? { branch: input.branch } : {}),
|
||||
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
|
||||
updatedAt: input.updatedAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical: ThreadMetaUpdatedPayloadCanonical) =>
|
||||
Effect.succeed({
|
||||
threadId: canonical.threadId,
|
||||
...(canonical.title !== undefined ? { title: canonical.title } : {}),
|
||||
...(canonical.modelSelection !== undefined
|
||||
? { modelSelection: canonical.modelSelection }
|
||||
: {}),
|
||||
...(canonical.branch !== undefined ? { branch: canonical.branch } : {}),
|
||||
...(canonical.worktreePath !== undefined ? { worktreePath: canonical.worktreePath } : {}),
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ThreadMetaUpdatedPayloadSource),
|
||||
} as any),
|
||||
),
|
||||
);
|
||||
|
||||
export const ThreadRuntimeModeSetPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
@@ -882,7 +974,7 @@ export const ThreadMessageSentPayload = Schema.Struct({
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadTurnStartRequestedPayload = Schema.Struct({
|
||||
const ThreadTurnStartRequestedPayloadCanonical = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
@@ -895,6 +987,70 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
type ThreadTurnStartRequestedPayloadCanonical =
|
||||
typeof ThreadTurnStartRequestedPayloadCanonical.Type;
|
||||
const ThreadTurnStartRequestedPayloadSource = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
...LegacyThreadModelSelectionFields,
|
||||
providerOptions: Schema.optional(ProviderStartOptions),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
),
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
type ThreadTurnStartRequestedPayloadSource = typeof ThreadTurnStartRequestedPayloadSource.Type;
|
||||
export const ThreadTurnStartRequestedPayload = ThreadTurnStartRequestedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ThreadTurnStartRequestedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input: ThreadTurnStartRequestedPayloadSource) =>
|
||||
normalizeLegacyThreadModelSelection(input).pipe(
|
||||
Effect.map((modelSelection) => ({
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
...(modelSelection !== undefined ? { modelSelection } : {}),
|
||||
...(input.providerOptions !== undefined
|
||||
? { providerOptions: input.providerOptions }
|
||||
: {}),
|
||||
...(input.assistantDeliveryMode !== undefined
|
||||
? { assistantDeliveryMode: input.assistantDeliveryMode }
|
||||
: {}),
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
...(input.sourceProposedPlan !== undefined
|
||||
? { sourceProposedPlan: input.sourceProposedPlan }
|
||||
: {}),
|
||||
createdAt: input.createdAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical: ThreadTurnStartRequestedPayloadCanonical) =>
|
||||
Effect.succeed({
|
||||
threadId: canonical.threadId,
|
||||
messageId: canonical.messageId,
|
||||
...(canonical.modelSelection !== undefined
|
||||
? { modelSelection: canonical.modelSelection }
|
||||
: {}),
|
||||
...(canonical.providerOptions !== undefined
|
||||
? { providerOptions: canonical.providerOptions }
|
||||
: {}),
|
||||
...(canonical.assistantDeliveryMode !== undefined
|
||||
? { assistantDeliveryMode: canonical.assistantDeliveryMode }
|
||||
: {}),
|
||||
runtimeMode: canonical.runtimeMode,
|
||||
interactionMode: canonical.interactionMode,
|
||||
...(canonical.sourceProposedPlan !== undefined
|
||||
? { sourceProposedPlan: canonical.sourceProposedPlan }
|
||||
: {}),
|
||||
createdAt: canonical.createdAt,
|
||||
} as ThreadTurnStartRequestedPayloadSource),
|
||||
} as any),
|
||||
),
|
||||
);
|
||||
|
||||
export const ThreadTurnInterruptRequestedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Schema } from "effect";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { ProviderUserInputAnswers } from "./userInput";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
@@ -21,6 +20,7 @@ import {
|
||||
ProviderRequestKind,
|
||||
ProviderSandboxMode,
|
||||
ProviderStartOptions,
|
||||
ProviderUserInputAnswers,
|
||||
RuntimeMode,
|
||||
} from "./orchestration";
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Schema } from "effect";
|
||||
import { Option, Schema } from "effect";
|
||||
import {
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
ProviderItemId,
|
||||
PositiveInt,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
RuntimeTaskId,
|
||||
@@ -11,13 +13,9 @@ import {
|
||||
TurnId,
|
||||
} from "./baseSchemas";
|
||||
import { ProviderKind } from "./orchestration";
|
||||
import { CanonicalToolLifecycleData } from "./toolLifecycle";
|
||||
export { ThreadTokenUsageSnapshot } from "./threadUsage";
|
||||
import { ThreadTokenUsageSnapshot } from "./threadUsage";
|
||||
export { ProviderUserInputAnswers, UserInputQuestion } from "./userInput";
|
||||
import { ProviderUserInputAnswers, UserInputQuestion } from "./userInput";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
const UnknownRecordSchema = Schema.Record(Schema.String, Schema.Unknown);
|
||||
|
||||
const RuntimeEventRawSource = Schema.Literals([
|
||||
"codex.app-server.notification",
|
||||
@@ -145,14 +143,21 @@ export type CanonicalRequestType = typeof CanonicalRequestType.Type;
|
||||
|
||||
const ProviderRuntimeEventType = Schema.Literals([
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"session.exited",
|
||||
"thread.started",
|
||||
"thread.state.changed",
|
||||
"thread.metadata.updated",
|
||||
"thread.token-usage.updated",
|
||||
"thread.realtime.started",
|
||||
"thread.realtime.item-added",
|
||||
"thread.realtime.audio.delta",
|
||||
"thread.realtime.error",
|
||||
"thread.realtime.closed",
|
||||
"turn.started",
|
||||
"turn.completed",
|
||||
"turn.aborted",
|
||||
"turn.plan.updated",
|
||||
"turn.proposed.delta",
|
||||
"turn.proposed.completed",
|
||||
@@ -168,20 +173,41 @@ const ProviderRuntimeEventType = Schema.Literals([
|
||||
"task.started",
|
||||
"task.progress",
|
||||
"task.completed",
|
||||
"hook.started",
|
||||
"hook.progress",
|
||||
"hook.completed",
|
||||
"tool.progress",
|
||||
"tool.summary",
|
||||
"auth.status",
|
||||
"account.updated",
|
||||
"account.rate-limits.updated",
|
||||
"mcp.status.updated",
|
||||
"mcp.oauth.completed",
|
||||
"model.rerouted",
|
||||
"config.warning",
|
||||
"deprecation.notice",
|
||||
"files.persisted",
|
||||
"runtime.warning",
|
||||
"runtime.error",
|
||||
]);
|
||||
export type ProviderRuntimeEventType = typeof ProviderRuntimeEventType.Type;
|
||||
|
||||
const SessionStartedType = Schema.Literal("session.started");
|
||||
const SessionConfiguredType = Schema.Literal("session.configured");
|
||||
const SessionStateChangedType = Schema.Literal("session.state.changed");
|
||||
const SessionExitedType = Schema.Literal("session.exited");
|
||||
const ThreadStartedType = Schema.Literal("thread.started");
|
||||
const ThreadStateChangedType = Schema.Literal("thread.state.changed");
|
||||
const ThreadMetadataUpdatedType = Schema.Literal("thread.metadata.updated");
|
||||
const ThreadTokenUsageUpdatedType = Schema.Literal("thread.token-usage.updated");
|
||||
const ThreadRealtimeStartedType = Schema.Literal("thread.realtime.started");
|
||||
const ThreadRealtimeItemAddedType = Schema.Literal("thread.realtime.item-added");
|
||||
const ThreadRealtimeAudioDeltaType = Schema.Literal("thread.realtime.audio.delta");
|
||||
const ThreadRealtimeErrorType = Schema.Literal("thread.realtime.error");
|
||||
const ThreadRealtimeClosedType = Schema.Literal("thread.realtime.closed");
|
||||
const TurnStartedType = Schema.Literal("turn.started");
|
||||
const TurnCompletedType = Schema.Literal("turn.completed");
|
||||
const TurnAbortedType = Schema.Literal("turn.aborted");
|
||||
const TurnPlanUpdatedType = Schema.Literal("turn.plan.updated");
|
||||
const TurnProposedDeltaType = Schema.Literal("turn.proposed.delta");
|
||||
const TurnProposedCompletedType = Schema.Literal("turn.proposed.completed");
|
||||
@@ -197,6 +223,20 @@ const UserInputResolvedType = Schema.Literal("user-input.resolved");
|
||||
const TaskStartedType = Schema.Literal("task.started");
|
||||
const TaskProgressType = Schema.Literal("task.progress");
|
||||
const TaskCompletedType = Schema.Literal("task.completed");
|
||||
const HookStartedType = Schema.Literal("hook.started");
|
||||
const HookProgressType = Schema.Literal("hook.progress");
|
||||
const HookCompletedType = Schema.Literal("hook.completed");
|
||||
const ToolProgressType = Schema.Literal("tool.progress");
|
||||
const ToolSummaryType = Schema.Literal("tool.summary");
|
||||
const AuthStatusType = Schema.Literal("auth.status");
|
||||
const AccountUpdatedType = Schema.Literal("account.updated");
|
||||
const AccountRateLimitsUpdatedType = Schema.Literal("account.rate-limits.updated");
|
||||
const McpStatusUpdatedType = Schema.Literal("mcp.status.updated");
|
||||
const McpOauthCompletedType = Schema.Literal("mcp.oauth.completed");
|
||||
const ModelReroutedType = Schema.Literal("model.rerouted");
|
||||
const ConfigWarningType = Schema.Literal("config.warning");
|
||||
const DeprecationNoticeType = Schema.Literal("deprecation.notice");
|
||||
const FilesPersistedType = Schema.Literal("files.persisted");
|
||||
const RuntimeWarningType = Schema.Literal("runtime.warning");
|
||||
const RuntimeErrorType = Schema.Literal("runtime.error");
|
||||
|
||||
@@ -219,6 +259,11 @@ const SessionStartedPayload = Schema.Struct({
|
||||
});
|
||||
export type SessionStartedPayload = typeof SessionStartedPayload.Type;
|
||||
|
||||
const SessionConfiguredPayload = Schema.Struct({
|
||||
config: UnknownRecordSchema,
|
||||
});
|
||||
export type SessionConfiguredPayload = typeof SessionConfiguredPayload.Type;
|
||||
|
||||
const SessionStateChangedPayload = Schema.Struct({
|
||||
state: RuntimeSessionState,
|
||||
reason: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
@@ -246,15 +291,59 @@ export type ThreadStateChangedPayload = typeof ThreadStateChangedPayload.Type;
|
||||
|
||||
const ThreadMetadataUpdatedPayload = Schema.Struct({
|
||||
name: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
metadata: Schema.optional(UnknownRecordSchema),
|
||||
});
|
||||
export type ThreadMetadataUpdatedPayload = typeof ThreadMetadataUpdatedPayload.Type;
|
||||
|
||||
export const ThreadTokenUsageSnapshot = Schema.Struct({
|
||||
usedTokens: NonNegativeInt,
|
||||
totalProcessedTokens: Schema.optional(NonNegativeInt),
|
||||
maxTokens: Schema.optional(PositiveInt),
|
||||
inputTokens: Schema.optional(NonNegativeInt),
|
||||
cachedInputTokens: Schema.optional(NonNegativeInt),
|
||||
outputTokens: Schema.optional(NonNegativeInt),
|
||||
reasoningOutputTokens: Schema.optional(NonNegativeInt),
|
||||
lastUsedTokens: Schema.optional(NonNegativeInt),
|
||||
lastInputTokens: Schema.optional(NonNegativeInt),
|
||||
lastCachedInputTokens: Schema.optional(NonNegativeInt),
|
||||
lastOutputTokens: Schema.optional(NonNegativeInt),
|
||||
lastReasoningOutputTokens: Schema.optional(NonNegativeInt),
|
||||
toolUses: Schema.optional(NonNegativeInt),
|
||||
durationMs: Schema.optional(NonNegativeInt),
|
||||
compactsAutomatically: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type ThreadTokenUsageSnapshot = typeof ThreadTokenUsageSnapshot.Type;
|
||||
|
||||
const ThreadTokenUsageUpdatedPayload = Schema.Struct({
|
||||
usage: ThreadTokenUsageSnapshot,
|
||||
});
|
||||
export type ThreadTokenUsageUpdatedPayload = typeof ThreadTokenUsageUpdatedPayload.Type;
|
||||
|
||||
const ThreadRealtimeStartedPayload = Schema.Struct({
|
||||
realtimeSessionId: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type ThreadRealtimeStartedPayload = typeof ThreadRealtimeStartedPayload.Type;
|
||||
|
||||
const ThreadRealtimeItemAddedPayload = Schema.Struct({
|
||||
item: Schema.Unknown,
|
||||
});
|
||||
export type ThreadRealtimeItemAddedPayload = typeof ThreadRealtimeItemAddedPayload.Type;
|
||||
|
||||
const ThreadRealtimeAudioDeltaPayload = Schema.Struct({
|
||||
audio: Schema.Unknown,
|
||||
});
|
||||
export type ThreadRealtimeAudioDeltaPayload = typeof ThreadRealtimeAudioDeltaPayload.Type;
|
||||
|
||||
const ThreadRealtimeErrorPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type ThreadRealtimeErrorPayload = typeof ThreadRealtimeErrorPayload.Type;
|
||||
|
||||
const ThreadRealtimeClosedPayload = Schema.Struct({
|
||||
reason: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type ThreadRealtimeClosedPayload = typeof ThreadRealtimeClosedPayload.Type;
|
||||
|
||||
const TurnStartedPayload = Schema.Struct({
|
||||
model: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
effort: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
@@ -264,12 +353,18 @@ export type TurnStartedPayload = typeof TurnStartedPayload.Type;
|
||||
const TurnCompletedPayload = Schema.Struct({
|
||||
state: RuntimeTurnState,
|
||||
stopReason: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),
|
||||
usage: Schema.optional(ThreadTokenUsageSnapshot),
|
||||
usage: Schema.optional(Schema.Unknown),
|
||||
modelUsage: Schema.optional(UnknownRecordSchema),
|
||||
totalCostUsd: Schema.optional(Schema.Number),
|
||||
errorMessage: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type TurnCompletedPayload = typeof TurnCompletedPayload.Type;
|
||||
|
||||
const TurnAbortedPayload = Schema.Struct({
|
||||
reason: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type TurnAbortedPayload = typeof TurnAbortedPayload.Type;
|
||||
|
||||
const RuntimePlanStep = Schema.Struct({
|
||||
step: TrimmedNonEmptyStringSchema,
|
||||
status: RuntimePlanStepStatus,
|
||||
@@ -302,7 +397,7 @@ export const ItemLifecyclePayload = Schema.Struct({
|
||||
status: Schema.optional(RuntimeItemStatus),
|
||||
title: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
detail: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
data: Schema.optional(CanonicalToolLifecycleData),
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type ItemLifecyclePayload = typeof ItemLifecyclePayload.Type;
|
||||
|
||||
@@ -328,13 +423,30 @@ const RequestResolvedPayload = Schema.Struct({
|
||||
});
|
||||
export type RequestResolvedPayload = typeof RequestResolvedPayload.Type;
|
||||
|
||||
const UserInputQuestionOption = Schema.Struct({
|
||||
label: TrimmedNonEmptyStringSchema,
|
||||
description: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type UserInputQuestionOption = typeof UserInputQuestionOption.Type;
|
||||
|
||||
export const UserInputQuestion = Schema.Struct({
|
||||
id: TrimmedNonEmptyStringSchema,
|
||||
header: TrimmedNonEmptyStringSchema,
|
||||
question: TrimmedNonEmptyStringSchema,
|
||||
options: Schema.Array(UserInputQuestionOption),
|
||||
multiSelect: Schema.optional(Schema.Boolean).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(false)),
|
||||
),
|
||||
});
|
||||
export type UserInputQuestion = typeof UserInputQuestion.Type;
|
||||
|
||||
const UserInputRequestedPayload = Schema.Struct({
|
||||
questions: Schema.Array(UserInputQuestion),
|
||||
});
|
||||
export type UserInputRequestedPayload = typeof UserInputRequestedPayload.Type;
|
||||
|
||||
const UserInputResolvedPayload = Schema.Struct({
|
||||
answers: ProviderUserInputAnswers,
|
||||
answers: UnknownRecordSchema,
|
||||
});
|
||||
export type UserInputResolvedPayload = typeof UserInputResolvedPayload.Type;
|
||||
|
||||
@@ -349,7 +461,7 @@ const TaskProgressPayload = Schema.Struct({
|
||||
taskId: RuntimeTaskId,
|
||||
description: TrimmedNonEmptyStringSchema,
|
||||
summary: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
usage: Schema.optional(ThreadTokenUsageSnapshot),
|
||||
usage: Schema.optional(Schema.Unknown),
|
||||
lastToolName: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type TaskProgressPayload = typeof TaskProgressPayload.Type;
|
||||
@@ -358,10 +470,117 @@ const TaskCompletedPayload = Schema.Struct({
|
||||
taskId: RuntimeTaskId,
|
||||
status: Schema.Literals(["completed", "failed", "stopped"]),
|
||||
summary: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
usage: Schema.optional(ThreadTokenUsageSnapshot),
|
||||
usage: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type TaskCompletedPayload = typeof TaskCompletedPayload.Type;
|
||||
|
||||
const HookStartedPayload = Schema.Struct({
|
||||
hookId: TrimmedNonEmptyStringSchema,
|
||||
hookName: TrimmedNonEmptyStringSchema,
|
||||
hookEvent: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type HookStartedPayload = typeof HookStartedPayload.Type;
|
||||
|
||||
const HookProgressPayload = Schema.Struct({
|
||||
hookId: TrimmedNonEmptyStringSchema,
|
||||
output: Schema.optional(Schema.String),
|
||||
stdout: Schema.optional(Schema.String),
|
||||
stderr: Schema.optional(Schema.String),
|
||||
});
|
||||
export type HookProgressPayload = typeof HookProgressPayload.Type;
|
||||
|
||||
const HookCompletedPayload = Schema.Struct({
|
||||
hookId: TrimmedNonEmptyStringSchema,
|
||||
outcome: Schema.Literals(["success", "error", "cancelled"]),
|
||||
output: Schema.optional(Schema.String),
|
||||
stdout: Schema.optional(Schema.String),
|
||||
stderr: Schema.optional(Schema.String),
|
||||
exitCode: Schema.optional(Schema.Int),
|
||||
});
|
||||
export type HookCompletedPayload = typeof HookCompletedPayload.Type;
|
||||
|
||||
const ToolProgressPayload = Schema.Struct({
|
||||
toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
toolName: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
summary: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
elapsedSeconds: Schema.optional(Schema.Number),
|
||||
});
|
||||
export type ToolProgressPayload = typeof ToolProgressPayload.Type;
|
||||
|
||||
const ToolSummaryPayload = Schema.Struct({
|
||||
summary: TrimmedNonEmptyStringSchema,
|
||||
precedingToolUseIds: Schema.optional(Schema.Array(TrimmedNonEmptyStringSchema)),
|
||||
});
|
||||
export type ToolSummaryPayload = typeof ToolSummaryPayload.Type;
|
||||
|
||||
const AuthStatusPayload = Schema.Struct({
|
||||
isAuthenticating: Schema.optional(Schema.Boolean),
|
||||
output: Schema.optional(Schema.Array(Schema.String)),
|
||||
error: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type AuthStatusPayload = typeof AuthStatusPayload.Type;
|
||||
|
||||
const AccountUpdatedPayload = Schema.Struct({
|
||||
account: Schema.Unknown,
|
||||
});
|
||||
export type AccountUpdatedPayload = typeof AccountUpdatedPayload.Type;
|
||||
|
||||
const AccountRateLimitsUpdatedPayload = Schema.Struct({
|
||||
rateLimits: Schema.Unknown,
|
||||
});
|
||||
export type AccountRateLimitsUpdatedPayload = typeof AccountRateLimitsUpdatedPayload.Type;
|
||||
|
||||
const McpStatusUpdatedPayload = Schema.Struct({
|
||||
status: Schema.Unknown,
|
||||
});
|
||||
export type McpStatusUpdatedPayload = typeof McpStatusUpdatedPayload.Type;
|
||||
|
||||
const McpOauthCompletedPayload = Schema.Struct({
|
||||
success: Schema.Boolean,
|
||||
name: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
error: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type McpOauthCompletedPayload = typeof McpOauthCompletedPayload.Type;
|
||||
|
||||
const ModelReroutedPayload = Schema.Struct({
|
||||
fromModel: TrimmedNonEmptyStringSchema,
|
||||
toModel: TrimmedNonEmptyStringSchema,
|
||||
reason: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type ModelReroutedPayload = typeof ModelReroutedPayload.Type;
|
||||
|
||||
const ConfigWarningPayload = Schema.Struct({
|
||||
summary: TrimmedNonEmptyStringSchema,
|
||||
details: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
path: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
range: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type ConfigWarningPayload = typeof ConfigWarningPayload.Type;
|
||||
|
||||
const DeprecationNoticePayload = Schema.Struct({
|
||||
summary: TrimmedNonEmptyStringSchema,
|
||||
details: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type DeprecationNoticePayload = typeof DeprecationNoticePayload.Type;
|
||||
|
||||
const FilesPersistedPayload = Schema.Struct({
|
||||
files: Schema.Array(
|
||||
Schema.Struct({
|
||||
filename: TrimmedNonEmptyStringSchema,
|
||||
fileId: TrimmedNonEmptyStringSchema,
|
||||
}),
|
||||
),
|
||||
failed: Schema.optional(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
filename: TrimmedNonEmptyStringSchema,
|
||||
error: TrimmedNonEmptyStringSchema,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
export type FilesPersistedPayload = typeof FilesPersistedPayload.Type;
|
||||
|
||||
const RuntimeWarningPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyStringSchema,
|
||||
detail: Schema.optional(Schema.Unknown),
|
||||
@@ -382,6 +601,14 @@ const ProviderRuntimeSessionStartedEvent = Schema.Struct({
|
||||
});
|
||||
export type ProviderRuntimeSessionStartedEvent = typeof ProviderRuntimeSessionStartedEvent.Type;
|
||||
|
||||
const ProviderRuntimeSessionConfiguredEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: SessionConfiguredType,
|
||||
payload: SessionConfiguredPayload,
|
||||
});
|
||||
export type ProviderRuntimeSessionConfiguredEvent =
|
||||
typeof ProviderRuntimeSessionConfiguredEvent.Type;
|
||||
|
||||
const ProviderRuntimeSessionStateChangedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: SessionStateChangedType,
|
||||
@@ -428,6 +655,46 @@ const ProviderRuntimeThreadTokenUsageUpdatedEvent = Schema.Struct({
|
||||
export type ProviderRuntimeThreadTokenUsageUpdatedEvent =
|
||||
typeof ProviderRuntimeThreadTokenUsageUpdatedEvent.Type;
|
||||
|
||||
const ProviderRuntimeThreadRealtimeStartedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ThreadRealtimeStartedType,
|
||||
payload: ThreadRealtimeStartedPayload,
|
||||
});
|
||||
export type ProviderRuntimeThreadRealtimeStartedEvent =
|
||||
typeof ProviderRuntimeThreadRealtimeStartedEvent.Type;
|
||||
|
||||
const ProviderRuntimeThreadRealtimeItemAddedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ThreadRealtimeItemAddedType,
|
||||
payload: ThreadRealtimeItemAddedPayload,
|
||||
});
|
||||
export type ProviderRuntimeThreadRealtimeItemAddedEvent =
|
||||
typeof ProviderRuntimeThreadRealtimeItemAddedEvent.Type;
|
||||
|
||||
const ProviderRuntimeThreadRealtimeAudioDeltaEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ThreadRealtimeAudioDeltaType,
|
||||
payload: ThreadRealtimeAudioDeltaPayload,
|
||||
});
|
||||
export type ProviderRuntimeThreadRealtimeAudioDeltaEvent =
|
||||
typeof ProviderRuntimeThreadRealtimeAudioDeltaEvent.Type;
|
||||
|
||||
const ProviderRuntimeThreadRealtimeErrorEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ThreadRealtimeErrorType,
|
||||
payload: ThreadRealtimeErrorPayload,
|
||||
});
|
||||
export type ProviderRuntimeThreadRealtimeErrorEvent =
|
||||
typeof ProviderRuntimeThreadRealtimeErrorEvent.Type;
|
||||
|
||||
const ProviderRuntimeThreadRealtimeClosedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ThreadRealtimeClosedType,
|
||||
payload: ThreadRealtimeClosedPayload,
|
||||
});
|
||||
export type ProviderRuntimeThreadRealtimeClosedEvent =
|
||||
typeof ProviderRuntimeThreadRealtimeClosedEvent.Type;
|
||||
|
||||
const ProviderRuntimeTurnStartedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: TurnStartedType,
|
||||
@@ -442,6 +709,13 @@ const ProviderRuntimeTurnCompletedEvent = Schema.Struct({
|
||||
});
|
||||
export type ProviderRuntimeTurnCompletedEvent = typeof ProviderRuntimeTurnCompletedEvent.Type;
|
||||
|
||||
const ProviderRuntimeTurnAbortedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: TurnAbortedType,
|
||||
payload: TurnAbortedPayload,
|
||||
});
|
||||
export type ProviderRuntimeTurnAbortedEvent = typeof ProviderRuntimeTurnAbortedEvent.Type;
|
||||
|
||||
const ProviderRuntimeTurnPlanUpdatedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: TurnPlanUpdatedType,
|
||||
@@ -551,6 +825,107 @@ const ProviderRuntimeTaskCompletedEvent = Schema.Struct({
|
||||
});
|
||||
export type ProviderRuntimeTaskCompletedEvent = typeof ProviderRuntimeTaskCompletedEvent.Type;
|
||||
|
||||
const ProviderRuntimeHookStartedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: HookStartedType,
|
||||
payload: HookStartedPayload,
|
||||
});
|
||||
export type ProviderRuntimeHookStartedEvent = typeof ProviderRuntimeHookStartedEvent.Type;
|
||||
|
||||
const ProviderRuntimeHookProgressEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: HookProgressType,
|
||||
payload: HookProgressPayload,
|
||||
});
|
||||
export type ProviderRuntimeHookProgressEvent = typeof ProviderRuntimeHookProgressEvent.Type;
|
||||
|
||||
const ProviderRuntimeHookCompletedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: HookCompletedType,
|
||||
payload: HookCompletedPayload,
|
||||
});
|
||||
export type ProviderRuntimeHookCompletedEvent = typeof ProviderRuntimeHookCompletedEvent.Type;
|
||||
|
||||
const ProviderRuntimeToolProgressEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ToolProgressType,
|
||||
payload: ToolProgressPayload,
|
||||
});
|
||||
export type ProviderRuntimeToolProgressEvent = typeof ProviderRuntimeToolProgressEvent.Type;
|
||||
|
||||
const ProviderRuntimeToolSummaryEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ToolSummaryType,
|
||||
payload: ToolSummaryPayload,
|
||||
});
|
||||
export type ProviderRuntimeToolSummaryEvent = typeof ProviderRuntimeToolSummaryEvent.Type;
|
||||
|
||||
const ProviderRuntimeAuthStatusEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: AuthStatusType,
|
||||
payload: AuthStatusPayload,
|
||||
});
|
||||
export type ProviderRuntimeAuthStatusEvent = typeof ProviderRuntimeAuthStatusEvent.Type;
|
||||
|
||||
const ProviderRuntimeAccountUpdatedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: AccountUpdatedType,
|
||||
payload: AccountUpdatedPayload,
|
||||
});
|
||||
export type ProviderRuntimeAccountUpdatedEvent = typeof ProviderRuntimeAccountUpdatedEvent.Type;
|
||||
|
||||
const ProviderRuntimeAccountRateLimitsUpdatedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: AccountRateLimitsUpdatedType,
|
||||
payload: AccountRateLimitsUpdatedPayload,
|
||||
});
|
||||
export type ProviderRuntimeAccountRateLimitsUpdatedEvent =
|
||||
typeof ProviderRuntimeAccountRateLimitsUpdatedEvent.Type;
|
||||
|
||||
const ProviderRuntimeMcpStatusUpdatedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: McpStatusUpdatedType,
|
||||
payload: McpStatusUpdatedPayload,
|
||||
});
|
||||
export type ProviderRuntimeMcpStatusUpdatedEvent = typeof ProviderRuntimeMcpStatusUpdatedEvent.Type;
|
||||
|
||||
const ProviderRuntimeMcpOauthCompletedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: McpOauthCompletedType,
|
||||
payload: McpOauthCompletedPayload,
|
||||
});
|
||||
export type ProviderRuntimeMcpOauthCompletedEvent =
|
||||
typeof ProviderRuntimeMcpOauthCompletedEvent.Type;
|
||||
|
||||
const ProviderRuntimeModelReroutedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ModelReroutedType,
|
||||
payload: ModelReroutedPayload,
|
||||
});
|
||||
export type ProviderRuntimeModelReroutedEvent = typeof ProviderRuntimeModelReroutedEvent.Type;
|
||||
|
||||
const ProviderRuntimeConfigWarningEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ConfigWarningType,
|
||||
payload: ConfigWarningPayload,
|
||||
});
|
||||
export type ProviderRuntimeConfigWarningEvent = typeof ProviderRuntimeConfigWarningEvent.Type;
|
||||
|
||||
const ProviderRuntimeDeprecationNoticeEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: DeprecationNoticeType,
|
||||
payload: DeprecationNoticePayload,
|
||||
});
|
||||
export type ProviderRuntimeDeprecationNoticeEvent =
|
||||
typeof ProviderRuntimeDeprecationNoticeEvent.Type;
|
||||
|
||||
const ProviderRuntimeFilesPersistedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: FilesPersistedType,
|
||||
payload: FilesPersistedPayload,
|
||||
});
|
||||
export type ProviderRuntimeFilesPersistedEvent = typeof ProviderRuntimeFilesPersistedEvent.Type;
|
||||
|
||||
const ProviderRuntimeWarningEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: RuntimeWarningType,
|
||||
@@ -567,14 +942,21 @@ export type ProviderRuntimeErrorEvent = typeof ProviderRuntimeErrorEvent.Type;
|
||||
|
||||
export const ProviderRuntimeEventV2 = Schema.Union([
|
||||
ProviderRuntimeSessionStartedEvent,
|
||||
ProviderRuntimeSessionConfiguredEvent,
|
||||
ProviderRuntimeSessionStateChangedEvent,
|
||||
ProviderRuntimeSessionExitedEvent,
|
||||
ProviderRuntimeThreadStartedEvent,
|
||||
ProviderRuntimeThreadStateChangedEvent,
|
||||
ProviderRuntimeThreadMetadataUpdatedEvent,
|
||||
ProviderRuntimeThreadTokenUsageUpdatedEvent,
|
||||
ProviderRuntimeThreadRealtimeStartedEvent,
|
||||
ProviderRuntimeThreadRealtimeItemAddedEvent,
|
||||
ProviderRuntimeThreadRealtimeAudioDeltaEvent,
|
||||
ProviderRuntimeThreadRealtimeErrorEvent,
|
||||
ProviderRuntimeThreadRealtimeClosedEvent,
|
||||
ProviderRuntimeTurnStartedEvent,
|
||||
ProviderRuntimeTurnCompletedEvent,
|
||||
ProviderRuntimeTurnAbortedEvent,
|
||||
ProviderRuntimeTurnPlanUpdatedEvent,
|
||||
ProviderRuntimeTurnProposedDeltaEvent,
|
||||
ProviderRuntimeTurnProposedCompletedEvent,
|
||||
@@ -590,6 +972,20 @@ export const ProviderRuntimeEventV2 = Schema.Union([
|
||||
ProviderRuntimeTaskStartedEvent,
|
||||
ProviderRuntimeTaskProgressEvent,
|
||||
ProviderRuntimeTaskCompletedEvent,
|
||||
ProviderRuntimeHookStartedEvent,
|
||||
ProviderRuntimeHookProgressEvent,
|
||||
ProviderRuntimeHookCompletedEvent,
|
||||
ProviderRuntimeToolProgressEvent,
|
||||
ProviderRuntimeToolSummaryEvent,
|
||||
ProviderRuntimeAuthStatusEvent,
|
||||
ProviderRuntimeAccountUpdatedEvent,
|
||||
ProviderRuntimeAccountRateLimitsUpdatedEvent,
|
||||
ProviderRuntimeMcpStatusUpdatedEvent,
|
||||
ProviderRuntimeMcpOauthCompletedEvent,
|
||||
ProviderRuntimeModelReroutedEvent,
|
||||
ProviderRuntimeConfigWarningEvent,
|
||||
ProviderRuntimeDeprecationNoticeEvent,
|
||||
ProviderRuntimeFilesPersistedEvent,
|
||||
ProviderRuntimeWarningEvent,
|
||||
ProviderRuntimeErrorEvent,
|
||||
]);
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { NonNegativeInt, PositiveInt } from "./baseSchemas";
|
||||
|
||||
export const ThreadTokenUsageSnapshot = Schema.Struct({
|
||||
usedTokens: NonNegativeInt,
|
||||
totalProcessedTokens: Schema.optional(NonNegativeInt),
|
||||
maxTokens: Schema.optional(PositiveInt),
|
||||
inputTokens: Schema.optional(NonNegativeInt),
|
||||
cachedInputTokens: Schema.optional(NonNegativeInt),
|
||||
outputTokens: Schema.optional(NonNegativeInt),
|
||||
reasoningOutputTokens: Schema.optional(NonNegativeInt),
|
||||
lastUsedTokens: Schema.optional(NonNegativeInt),
|
||||
lastInputTokens: Schema.optional(NonNegativeInt),
|
||||
lastCachedInputTokens: Schema.optional(NonNegativeInt),
|
||||
lastOutputTokens: Schema.optional(NonNegativeInt),
|
||||
lastReasoningOutputTokens: Schema.optional(NonNegativeInt),
|
||||
toolUses: Schema.optional(NonNegativeInt),
|
||||
durationMs: Schema.optional(NonNegativeInt),
|
||||
compactsAutomatically: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type ThreadTokenUsageSnapshot = typeof ThreadTokenUsageSnapshot.Type;
|
||||
@@ -1,39 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { CanonicalJsonObjectSchema, CanonicalJsonValueSchema } from "./jsonValue";
|
||||
|
||||
export const CommandExecutionToolLifecycleData = Schema.Struct({
|
||||
kind: Schema.Literal("command_execution"),
|
||||
command: TrimmedNonEmptyString,
|
||||
toolName: Schema.optional(TrimmedNonEmptyString),
|
||||
input: Schema.optional(CanonicalJsonObjectSchema),
|
||||
output: Schema.optional(Schema.String),
|
||||
exitCode: Schema.optional(NonNegativeInt),
|
||||
result: Schema.optional(CanonicalJsonValueSchema),
|
||||
});
|
||||
export type CommandExecutionToolLifecycleData = typeof CommandExecutionToolLifecycleData.Type;
|
||||
|
||||
export const FileChangeToolLifecycleData = Schema.Struct({
|
||||
kind: Schema.Literal("file_change"),
|
||||
changedFiles: Schema.Array(TrimmedNonEmptyString),
|
||||
toolName: Schema.optional(TrimmedNonEmptyString),
|
||||
input: Schema.optional(CanonicalJsonObjectSchema),
|
||||
result: Schema.optional(CanonicalJsonValueSchema),
|
||||
});
|
||||
export type FileChangeToolLifecycleData = typeof FileChangeToolLifecycleData.Type;
|
||||
|
||||
export const GenericToolLifecycleData = Schema.Struct({
|
||||
kind: Schema.Literal("generic"),
|
||||
toolName: Schema.optional(TrimmedNonEmptyString),
|
||||
input: Schema.optional(CanonicalJsonObjectSchema),
|
||||
result: Schema.optional(CanonicalJsonValueSchema),
|
||||
});
|
||||
export type GenericToolLifecycleData = typeof GenericToolLifecycleData.Type;
|
||||
|
||||
export const CanonicalToolLifecycleData = Schema.Union([
|
||||
CommandExecutionToolLifecycleData,
|
||||
FileChangeToolLifecycleData,
|
||||
GenericToolLifecycleData,
|
||||
]);
|
||||
export type CanonicalToolLifecycleData = typeof CanonicalToolLifecycleData.Type;
|
||||
@@ -1,29 +0,0 @@
|
||||
import { Option, Schema } from "effect";
|
||||
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
export const UserInputQuestionOption = Schema.Struct({
|
||||
label: TrimmedNonEmptyString,
|
||||
description: TrimmedNonEmptyString,
|
||||
});
|
||||
export type UserInputQuestionOption = typeof UserInputQuestionOption.Type;
|
||||
|
||||
export const UserInputQuestion = Schema.Struct({
|
||||
id: TrimmedNonEmptyString,
|
||||
header: TrimmedNonEmptyString,
|
||||
question: TrimmedNonEmptyString,
|
||||
options: Schema.Array(UserInputQuestionOption),
|
||||
multiSelect: Schema.optional(Schema.Boolean).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(false)),
|
||||
),
|
||||
});
|
||||
export type UserInputQuestion = typeof UserInputQuestion.Type;
|
||||
|
||||
export const ProviderUserInputAnswer = Schema.Union([
|
||||
TrimmedNonEmptyString,
|
||||
Schema.Array(TrimmedNonEmptyString),
|
||||
]);
|
||||
export type ProviderUserInputAnswer = typeof ProviderUserInputAnswer.Type;
|
||||
|
||||
export const ProviderUserInputAnswers = Schema.Record(Schema.String, ProviderUserInputAnswer);
|
||||
export type ProviderUserInputAnswers = typeof ProviderUserInputAnswers.Type;
|
||||
@@ -2,25 +2,32 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
MODEL_OPTIONS,
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getEffectiveClaudeCodeEffort,
|
||||
getDefaultModel,
|
||||
getModelCapabilities,
|
||||
getDefaultReasoningEffort,
|
||||
getModelOptions,
|
||||
getReasoningEffortOptions,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptions,
|
||||
normalizeCodexModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveReasoningEffortForProvider,
|
||||
resolveSelectableModel,
|
||||
resolveModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
supportsClaudeAdaptiveReasoning,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeMaxEffort,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
} from "./model";
|
||||
|
||||
describe("normalizeModelSlug", () => {
|
||||
@@ -151,16 +158,13 @@ describe("resolveSelectableModel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getModelCapabilities reasoningEffortLevels", () => {
|
||||
const values = (provider: "codex" | "claudeAgent", model: string | null) =>
|
||||
getModelCapabilities(provider, model).reasoningEffortLevels.map((l) => l.value);
|
||||
|
||||
describe("getReasoningEffortOptions", () => {
|
||||
it("returns codex reasoning options for codex", () => {
|
||||
expect(values("codex", "gpt-5.4")).toEqual([...CODEX_REASONING_EFFORT_OPTIONS]);
|
||||
expect(getReasoningEffortOptions("codex")).toEqual(REASONING_EFFORT_OPTIONS_BY_PROVIDER.codex);
|
||||
});
|
||||
|
||||
it("returns claude effort options for Opus 4.6", () => {
|
||||
expect(values("claudeAgent", "claude-opus-4-6")).toEqual([
|
||||
expect(getReasoningEffortOptions("claudeAgent", "claude-opus-4-6")).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
@@ -170,7 +174,7 @@ describe("getModelCapabilities reasoningEffortLevels", () => {
|
||||
});
|
||||
|
||||
it("returns claude effort options for Sonnet 4.6", () => {
|
||||
expect(values("claudeAgent", "claude-sonnet-4-6")).toEqual([
|
||||
expect(getReasoningEffortOptions("claudeAgent", "claude-sonnet-4-6")).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
@@ -179,37 +183,28 @@ describe("getModelCapabilities reasoningEffortLevels", () => {
|
||||
});
|
||||
|
||||
it("returns no claude effort options for Haiku 4.5", () => {
|
||||
expect(values("claudeAgent", "claude-haiku-4-5")).toEqual([]);
|
||||
expect(getReasoningEffortOptions("claudeAgent", "claude-haiku-4-5")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it("co-locates labels with effort values", () => {
|
||||
const levels = getModelCapabilities("claudeAgent", "claude-opus-4-6").reasoningEffortLevels;
|
||||
const high = levels.find((l) => l.value === "high");
|
||||
expect(high).toEqual({ value: "high", label: "High", isDefault: true });
|
||||
const xhigh = getModelCapabilities("codex", "gpt-5.4").reasoningEffortLevels.find(
|
||||
(l) => l.value === "xhigh",
|
||||
describe("getDefaultReasoningEffort", () => {
|
||||
it("returns provider-scoped defaults", () => {
|
||||
expect(getDefaultReasoningEffort("codex")).toBe(DEFAULT_REASONING_EFFORT_BY_PROVIDER.codex);
|
||||
expect(getDefaultReasoningEffort("claudeAgent")).toBe(
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER.claudeAgent,
|
||||
);
|
||||
expect(xhigh).toEqual({ value: "xhigh", label: "Extra High" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDefaultEffort", () => {
|
||||
it("returns the default effort from capabilities", () => {
|
||||
expect(getDefaultEffort(getModelCapabilities("codex", "gpt-5.4"))).toBe("high");
|
||||
expect(getDefaultEffort(getModelCapabilities("claudeAgent", "claude-opus-4-6"))).toBe("high");
|
||||
expect(getDefaultEffort(getModelCapabilities("claudeAgent", "claude-haiku-4-5"))).toBeNull();
|
||||
describe("resolveReasoningEffortForProvider", () => {
|
||||
it("accepts provider-scoped effort values", () => {
|
||||
expect(resolveReasoningEffortForProvider("codex", "xhigh")).toBe("xhigh");
|
||||
expect(resolveReasoningEffortForProvider("claudeAgent", "ultrathink")).toBe("ultrathink");
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasEffortLevel", () => {
|
||||
it("validates effort against model capabilities", () => {
|
||||
const opusCaps = getModelCapabilities("claudeAgent", "claude-opus-4-6");
|
||||
expect(hasEffortLevel(opusCaps, "max")).toBe(true);
|
||||
expect(hasEffortLevel(opusCaps, "xhigh")).toBe(false);
|
||||
|
||||
const codexCaps = getModelCapabilities("codex", "gpt-5.4");
|
||||
expect(hasEffortLevel(codexCaps, "xhigh")).toBe(true);
|
||||
expect(hasEffortLevel(codexCaps, "max")).toBe(false);
|
||||
it("rejects effort values from the wrong provider", () => {
|
||||
expect(resolveReasoningEffortForProvider("codex", "max")).toBeNull();
|
||||
expect(resolveReasoningEffortForProvider("claudeAgent", "xhigh")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -228,17 +223,27 @@ describe("applyClaudePromptEffortPrefix", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getEffectiveClaudeCodeEffort", () => {
|
||||
it("does not persist ultrathink into Claude runtime configuration", () => {
|
||||
expect(getEffectiveClaudeCodeEffort("ultrathink")).toBeNull();
|
||||
expect(getEffectiveClaudeCodeEffort("high")).toBe("high");
|
||||
});
|
||||
|
||||
it("returns null when no claude effort is selected", () => {
|
||||
expect(getEffectiveClaudeCodeEffort(null)).toBeNull();
|
||||
expect(getEffectiveClaudeCodeEffort(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeCodexModelOptions", () => {
|
||||
it("drops default-only codex options", () => {
|
||||
expect(
|
||||
normalizeCodexModelOptions("gpt-5.4", { reasoningEffort: "high", fastMode: false }),
|
||||
normalizeCodexModelOptions({ reasoningEffort: "high", fastMode: false }),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves non-default codex options", () => {
|
||||
expect(
|
||||
normalizeCodexModelOptions("gpt-5.4", { reasoningEffort: "xhigh", fastMode: true }),
|
||||
).toEqual({
|
||||
expect(normalizeCodexModelOptions({ reasoningEffort: "xhigh", fastMode: true })).toEqual({
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
});
|
||||
@@ -267,50 +272,49 @@ describe("normalizeClaudeModelOptions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getModelCapabilities Claude capability flags", () => {
|
||||
describe("supportsClaudeAdaptiveReasoning", () => {
|
||||
it("only enables adaptive reasoning for Opus 4.6 and Sonnet 4.6", () => {
|
||||
const has = (m: string | undefined) =>
|
||||
getModelCapabilities("claudeAgent", m).reasoningEffortLevels.length > 0;
|
||||
expect(has("claude-opus-4-6")).toBe(true);
|
||||
expect(has("claude-sonnet-4-6")).toBe(true);
|
||||
expect(has("claude-haiku-4-5")).toBe(false);
|
||||
expect(has(undefined)).toBe(false);
|
||||
expect(supportsClaudeAdaptiveReasoning("claude-opus-4-6")).toBe(true);
|
||||
expect(supportsClaudeAdaptiveReasoning("claude-sonnet-4-6")).toBe(true);
|
||||
expect(supportsClaudeAdaptiveReasoning("claude-haiku-4-5")).toBe(false);
|
||||
expect(supportsClaudeAdaptiveReasoning(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeMaxEffort", () => {
|
||||
it("only enables max effort for Opus 4.6", () => {
|
||||
const has = (m: string | undefined) =>
|
||||
getModelCapabilities("claudeAgent", m).reasoningEffortLevels.some((l) => l.value === "max");
|
||||
expect(has("claude-opus-4-6")).toBe(true);
|
||||
expect(has("claude-sonnet-4-6")).toBe(false);
|
||||
expect(has("claude-haiku-4-5")).toBe(false);
|
||||
expect(has(undefined)).toBe(false);
|
||||
expect(supportsClaudeMaxEffort("claude-opus-4-6")).toBe(true);
|
||||
expect(supportsClaudeMaxEffort("claude-sonnet-4-6")).toBe(false);
|
||||
expect(supportsClaudeMaxEffort("claude-haiku-4-5")).toBe(false);
|
||||
expect(supportsClaudeMaxEffort(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeFastMode", () => {
|
||||
it("only enables Claude fast mode for Opus 4.6", () => {
|
||||
const has = (m: string | undefined) => getModelCapabilities("claudeAgent", m).supportsFastMode;
|
||||
expect(has("claude-opus-4-6")).toBe(true);
|
||||
expect(has("opus")).toBe(true);
|
||||
expect(has("claude-sonnet-4-6")).toBe(false);
|
||||
expect(has("claude-haiku-4-5")).toBe(false);
|
||||
expect(has(undefined)).toBe(false);
|
||||
expect(supportsClaudeFastMode("claude-opus-4-6")).toBe(true);
|
||||
expect(supportsClaudeFastMode("opus")).toBe(true);
|
||||
expect(supportsClaudeFastMode("claude-sonnet-4-6")).toBe(false);
|
||||
expect(supportsClaudeFastMode("claude-haiku-4-5")).toBe(false);
|
||||
expect(supportsClaudeFastMode(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeUltrathinkKeyword", () => {
|
||||
it("only enables ultrathink keyword handling for Opus 4.6 and Sonnet 4.6", () => {
|
||||
const has = (m: string | undefined) =>
|
||||
getModelCapabilities("claudeAgent", m).reasoningEffortLevels.length > 0;
|
||||
expect(has("claude-opus-4-6")).toBe(true);
|
||||
expect(has("claude-sonnet-4-6")).toBe(true);
|
||||
expect(has("claude-haiku-4-5")).toBe(false);
|
||||
expect(supportsClaudeUltrathinkKeyword("claude-opus-4-6")).toBe(true);
|
||||
expect(supportsClaudeUltrathinkKeyword("claude-sonnet-4-6")).toBe(true);
|
||||
expect(supportsClaudeUltrathinkKeyword("claude-haiku-4-5")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeThinkingToggle", () => {
|
||||
it("only enables the Claude thinking toggle for Haiku 4.5", () => {
|
||||
const has = (m: string | undefined) =>
|
||||
getModelCapabilities("claudeAgent", m).supportsThinkingToggle;
|
||||
expect(has("claude-opus-4-6")).toBe(false);
|
||||
expect(has("claude-sonnet-4-6")).toBe(false);
|
||||
expect(has("claude-haiku-4-5")).toBe(true);
|
||||
expect(has("haiku")).toBe(true);
|
||||
expect(has(undefined)).toBe(false);
|
||||
expect(supportsClaudeThinkingToggle("claude-opus-4-6")).toBe(false);
|
||||
expect(supportsClaudeThinkingToggle("claude-sonnet-4-6")).toBe(false);
|
||||
expect(supportsClaudeThinkingToggle("claude-haiku-4-5")).toBe(true);
|
||||
expect(supportsClaudeThinkingToggle("haiku")).toBe(true);
|
||||
expect(supportsClaudeThinkingToggle(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+108
-43
@@ -1,15 +1,18 @@
|
||||
import {
|
||||
CLAUDE_CODE_EFFORT_OPTIONS,
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
MODEL_CAPABILITIES_INDEX,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
MODEL_SLUG_ALIASES_BY_PROVIDER,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
type ClaudeModelOptions,
|
||||
type ClaudeCodeEffort,
|
||||
type CodexModelOptions,
|
||||
type ModelCapabilities,
|
||||
type CodexReasoningEffort,
|
||||
type ModelSlug,
|
||||
type ProviderReasoningEffort,
|
||||
type ProviderKind,
|
||||
CodexReasoningEffort,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const MODEL_SLUG_SET_BY_PROVIDER: Record<ProviderKind, ReadonlySet<ModelSlug>> = {
|
||||
@@ -17,6 +20,10 @@ const MODEL_SLUG_SET_BY_PROVIDER: Record<ProviderKind, ReadonlySet<ModelSlug>> =
|
||||
codex: new Set(MODEL_OPTIONS_BY_PROVIDER.codex.map((option) => option.slug)),
|
||||
};
|
||||
|
||||
const CLAUDE_OPUS_4_6_MODEL = "claude-opus-4-6";
|
||||
const CLAUDE_SONNET_4_6_MODEL = "claude-sonnet-4-6";
|
||||
const CLAUDE_HAIKU_4_5_MODEL = "claude-haiku-4-5";
|
||||
|
||||
export interface SelectableModelOption {
|
||||
slug: string;
|
||||
name: string;
|
||||
@@ -30,34 +37,25 @@ export function getDefaultModel(provider: ProviderKind = "codex"): ModelSlug {
|
||||
return DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
// ── Effort helpers ────────────────────────────────────────────────────
|
||||
|
||||
/** Check whether a capabilities object includes a given effort value. */
|
||||
export function hasEffortLevel(caps: ModelCapabilities, value: string): boolean {
|
||||
return caps.reasoningEffortLevels.some((l) => l.value === value);
|
||||
export function supportsClaudeFastMode(model: string | null | undefined): boolean {
|
||||
return normalizeModelSlug(model, "claudeAgent") === CLAUDE_OPUS_4_6_MODEL;
|
||||
}
|
||||
|
||||
/** Return the default effort value for a capabilities object, or null if none. */
|
||||
export function getDefaultEffort(caps: ModelCapabilities): string | null {
|
||||
return caps.reasoningEffortLevels.find((l) => l.isDefault)?.value ?? null;
|
||||
export function supportsClaudeAdaptiveReasoning(model: string | null | undefined): boolean {
|
||||
const normalized = normalizeModelSlug(model, "claudeAgent");
|
||||
return normalized === CLAUDE_OPUS_4_6_MODEL || normalized === CLAUDE_SONNET_4_6_MODEL;
|
||||
}
|
||||
|
||||
// ── Data-driven capability resolver ───────────────────────────────────
|
||||
export function supportsClaudeMaxEffort(model: string | null | undefined): boolean {
|
||||
return normalizeModelSlug(model, "claudeAgent") === CLAUDE_OPUS_4_6_MODEL;
|
||||
}
|
||||
|
||||
export function getModelCapabilities(
|
||||
provider: ProviderKind,
|
||||
model: string | null | undefined,
|
||||
): ModelCapabilities {
|
||||
const slug = normalizeModelSlug(model, provider);
|
||||
if (slug && MODEL_CAPABILITIES_INDEX[provider]?.[slug]) {
|
||||
return MODEL_CAPABILITIES_INDEX[provider][slug];
|
||||
}
|
||||
return {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
export function supportsClaudeUltrathinkKeyword(model: string | null | undefined): boolean {
|
||||
return supportsClaudeAdaptiveReasoning(model);
|
||||
}
|
||||
|
||||
export function supportsClaudeThinkingToggle(model: string | null | undefined): boolean {
|
||||
return normalizeModelSlug(model, "claudeAgent") === CLAUDE_HAIKU_4_5_MODEL;
|
||||
}
|
||||
|
||||
export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
|
||||
@@ -138,20 +136,85 @@ export function resolveModelSlugForProvider(
|
||||
return resolveModelSlug(model, provider);
|
||||
}
|
||||
|
||||
/** Trim a string, returning null for empty/missing values. */
|
||||
export function trimOrNull<T extends string>(value: T | null | undefined): T | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim() as T;
|
||||
return trimmed || null;
|
||||
export function getReasoningEffortOptions(provider: "codex"): ReadonlyArray<CodexReasoningEffort>;
|
||||
export function getReasoningEffortOptions(
|
||||
provider: "claudeAgent",
|
||||
model?: string | null | undefined,
|
||||
): ReadonlyArray<ClaudeCodeEffort>;
|
||||
export function getReasoningEffortOptions(
|
||||
provider?: ProviderKind,
|
||||
model?: string | null | undefined,
|
||||
): ReadonlyArray<ProviderReasoningEffort>;
|
||||
export function getReasoningEffortOptions(
|
||||
provider: ProviderKind = "codex",
|
||||
model?: string | null | undefined,
|
||||
): ReadonlyArray<ProviderReasoningEffort> {
|
||||
if (provider === "claudeAgent") {
|
||||
if (supportsClaudeMaxEffort(model)) {
|
||||
return ["low", "medium", "high", "max", "ultrathink"];
|
||||
}
|
||||
if (supportsClaudeAdaptiveReasoning(model)) {
|
||||
return ["low", "medium", "high", "ultrathink"];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
return REASONING_EFFORT_OPTIONS_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function getDefaultReasoningEffort(provider: "codex"): CodexReasoningEffort;
|
||||
export function getDefaultReasoningEffort(provider: "claudeAgent"): ClaudeCodeEffort;
|
||||
export function getDefaultReasoningEffort(provider?: ProviderKind): ProviderReasoningEffort;
|
||||
export function getDefaultReasoningEffort(
|
||||
provider: ProviderKind = "codex",
|
||||
): ProviderReasoningEffort {
|
||||
return DEFAULT_REASONING_EFFORT_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function resolveReasoningEffortForProvider(
|
||||
provider: "codex",
|
||||
effort: string | null | undefined,
|
||||
): CodexReasoningEffort | null;
|
||||
export function resolveReasoningEffortForProvider(
|
||||
provider: "claudeAgent",
|
||||
effort: string | null | undefined,
|
||||
): ClaudeCodeEffort | null;
|
||||
export function resolveReasoningEffortForProvider(
|
||||
provider: ProviderKind,
|
||||
effort: string | null | undefined,
|
||||
): ProviderReasoningEffort | null;
|
||||
export function resolveReasoningEffortForProvider(
|
||||
provider: ProviderKind,
|
||||
effort: string | null | undefined,
|
||||
): ProviderReasoningEffort | null {
|
||||
if (typeof effort !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const trimmed = effort.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const options = REASONING_EFFORT_OPTIONS_BY_PROVIDER[provider] as ReadonlyArray<string>;
|
||||
return options.includes(trimmed) ? (trimmed as ProviderReasoningEffort) : null;
|
||||
}
|
||||
|
||||
export function getEffectiveClaudeCodeEffort(
|
||||
effort: ClaudeCodeEffort | null | undefined,
|
||||
): Exclude<ClaudeCodeEffort, "ultrathink"> | null {
|
||||
if (!effort) {
|
||||
return null;
|
||||
}
|
||||
return effort === "ultrathink" ? null : effort;
|
||||
}
|
||||
|
||||
export function normalizeCodexModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const caps = getModelCapabilities("codex", model);
|
||||
const defaultReasoningEffort = getDefaultEffort(caps) as CodexReasoningEffort;
|
||||
const reasoningEffort = trimOrNull(modelOptions?.reasoningEffort) ?? defaultReasoningEffort;
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("codex");
|
||||
const reasoningEffort =
|
||||
resolveReasoningEffortForProvider("codex", modelOptions?.reasoningEffort) ??
|
||||
defaultReasoningEffort;
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort !== defaultReasoningEffort ? { reasoningEffort } : {}),
|
||||
@@ -164,20 +227,20 @@ export function normalizeClaudeModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const caps = getModelCapabilities("claudeAgent", model);
|
||||
const defaultReasoningEffort = getDefaultEffort(caps);
|
||||
const resolvedEffort = trimOrNull(modelOptions?.effort);
|
||||
const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? "");
|
||||
const reasoningOptions = getReasoningEffortOptions("claudeAgent", model);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("claudeAgent");
|
||||
const resolvedEffort = resolveReasoningEffortForProvider("claudeAgent", modelOptions?.effort);
|
||||
const effort =
|
||||
resolvedEffort &&
|
||||
!isPromptInjected &&
|
||||
hasEffortLevel(caps, resolvedEffort) &&
|
||||
resolvedEffort !== "ultrathink" &&
|
||||
reasoningOptions.includes(resolvedEffort) &&
|
||||
resolvedEffort !== defaultReasoningEffort
|
||||
? resolvedEffort
|
||||
: undefined;
|
||||
const thinking =
|
||||
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
|
||||
supportsClaudeThinkingToggle(model) && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode =
|
||||
supportsClaudeFastMode(model) && modelOptions?.fastMode === true ? true : undefined;
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
@@ -202,3 +265,5 @@ export function applyClaudePromptEffortPrefix(
|
||||
}
|
||||
return `Ultrathink:\n${trimmed}`;
|
||||
}
|
||||
|
||||
export { CLAUDE_CODE_EFFORT_OPTIONS, CODEX_REASONING_EFFORT_OPTIONS };
|
||||
Reference in new issue
Block a user