Compare commits

...
Author SHA1 Message Date
Cursor Agent 919971ae24 Fix migration log message showing 'undefined' when no toMigrationInclusive is provided 2026-03-24 22:57:33 +00:00
Julius Marminge 3003850f37 migration test harness 2026-03-24 15:51:59 -07:00
Julius Marminge c44d17f174 simplify migrations 2026-03-24 15:42:54 -07:00
Julius Marminge e12d2903f2 Update sidebar test fixtures for provider-aware model selection
- Switch project and thread fixtures to provider-scoped model selection
- Keep sidebar logic tests aligned with the new Codex provider model shape
2026-03-24 15:28:10 -07:00
Julius Marminge 8cb3995a9c Merge branch 'main' into t3code/provider-kind-model 2026-03-24 15:24:52 -07:00
Julius Marminge 96d6160ea5 Unify provider model selection across orchestration and UI
- Replace provider-specific model options with typed modelSelection
- Persist and replay selected provider, model, and options end to end
- Update adapter, service, and chat composer tests for the new shape
2026-03-24 14:35:29 -07:00
Julius Marminge 97ff0ac4a9 Canonicalize legacy model selections
- Add migration for legacy provider/model payloads
- Cover project, thread, and orchestration event records
2026-03-24 14:09:22 -07:00
Julius Marminge 07e86e938b Preserve null model options in projections and restarts
- Store missing model options as SQL NULL in project and thread projections
- Stop rehydrating derived model options when restarting provider sessions
- Share model option conversion logic in `packages/shared`
2026-03-24 13:27:25 -07:00
t3-code[bot] 2a435aef66 chore(release): prepare v0.0.14 2026-03-24 19:56:02 +00:00
Julius Marminge 28afb14004 Sort sidebar projects and threads by recency (#1372) 2026-03-24 12:40:42 -07:00
Julius Marminge 8f3515572d Surface context window usage in the UI (#1351) 2026-03-24 12:36:51 -07:00
Julius Marminge 71ff626e3e Persist first sticky model snapshot from provider options
- Keep sticky selection in sync when provider options change
- Add regression test for creating the initial sticky snapshot
2026-03-24 12:08:58 -07:00
49 changed files with 3122 additions and 818 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.13",
"version": "0.0.14",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.13",
"version": "0.0.14",
"license": "MIT",
"repository": {
"type": "git",
@@ -43,7 +43,7 @@ import {
type ProjectionSnapshotQueryShape,
} from "../Services/ProjectionSnapshotQuery.ts";
const decodeReadModelSync = Schema.decodeUnknownSync(OrchestrationReadModel);
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
const ProjectionProjectDbRowSchema = Schema.Struct({
projectId: ProjectionProject.fields.projectId,
title: ProjectionProject.fields.title,
@@ -103,7 +103,7 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
});
const ProjectionStateDbRowSchema = ProjectionState;
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
const decodeModelSelectionSchema = Schema.decodeUnknownEffect(ModelSelection);
const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.projects,
@@ -158,20 +158,13 @@ const decodeModelSelection = (input: {
readonly model: string;
readonly options: unknown;
}) =>
Effect.try({
try: () =>
decodeModelSelectionSync({
provider: input.provider,
model: input.model,
...(input.options !== null && input.options !== undefined
? { options: input.options }
: {}),
}),
catch: (error) =>
Schema.isSchemaError(error)
? toPersistenceDecodeError("ProjectionSnapshotQuery.decodeModelSelection")(error)
: toPersistenceSqlError("ProjectionSnapshotQuery.decodeModelSelection")(error),
});
decodeModelSelectionSchema({
provider: input.provider,
model: input.model,
...(input.options !== null && input.options !== undefined ? { options: input.options } : {}),
}).pipe(
Effect.mapError(toPersistenceDecodeError("ProjectionSnapshotQuery.decodeModelSelection")),
);
const makeProjectionSnapshotQuery = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -646,13 +639,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
updatedAt: updatedAt ?? new Date(0).toISOString(),
};
return yield* Effect.try({
try: () => decodeReadModelSync(snapshot),
catch: (error) =>
toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel")(
error as Schema.SchemaError,
),
});
return yield* decodeReadModel(snapshot).pipe(
Effect.mapError(
toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"),
),
);
}),
)
.pipe(
@@ -313,7 +313,10 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1"));
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
model: "gpt-5-codex",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
});
@@ -355,9 +358,10 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
model: "gpt-5.3-codex",
modelOptions: {
codex: {
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "high",
fastMode: true,
},
@@ -365,9 +369,10 @@ describe("ProviderCommandReactor", () => {
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "gpt-5.3-codex",
modelOptions: {
codex: {
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "high",
fastMode: true,
},
@@ -406,19 +411,20 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
@@ -456,19 +462,20 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeAgent",
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
fastMode: true,
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
fastMode: true,
},
},
@@ -594,12 +601,17 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "codex",
model: "claude-sonnet-4-6",
modelSelection: {
provider: "codex",
model: "claude-sonnet-4-6",
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-sonnet-4-6",
modelSelection: {
provider: "codex",
model: "claude-sonnet-4-6",
},
});
});
@@ -707,10 +719,11 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
provider: "claudeAgent",
resumeCursor: { opaque: "resume-1" },
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
@@ -804,6 +817,51 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
const harness = await createHarness({
threadModel: "claude-opus-4-6",
});
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-runtime-mode-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-claude-no-options"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
runtimeMode: "approval-required",
});
});
it("rejects provider changes after a thread is already bound to a session provider", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -5,7 +5,6 @@ import {
EventId,
type ModelSelection,
type OrchestrationEvent,
type ProviderModelOptions,
ProviderKind,
type ProviderStartOptions,
type OrchestrationSession,
@@ -76,22 +75,11 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const WORKTREE_BRANCH_PREFIX = "t3code";
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
const sameModelOptions = (
left: ProviderModelOptions | undefined,
right: ProviderModelOptions | undefined,
const sameModelSelectionOptions = (
left: ModelSelection | undefined,
right: ModelSelection | undefined,
): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
function toProviderModelOptions(
modelSelection: ModelSelection | undefined,
): ProviderModelOptions | undefined {
if (!modelSelection?.options) {
return undefined;
}
return modelSelection.provider === "codex"
? { codex: modelSelection.options }
: { claudeAgent: modelSelection.options };
}
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
@@ -169,7 +157,7 @@ const make = Effect.gen(function* () {
);
const threadProviderOptions = new Map<string, ProviderStartOptions>();
const threadModelOptions = new Map<string, ProviderModelOptions>();
const threadModelSelections = new Map<string, ModelSelection>();
const appendProviderFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -227,7 +215,6 @@ const make = Effect.gen(function* () {
createdAt: string,
options?: {
readonly modelSelection?: ModelSelection;
readonly modelOptions?: ProviderModelOptions;
readonly providerOptions?: ProviderStartOptions;
},
) {
@@ -257,9 +244,6 @@ const make = Effect.gen(function* () {
}
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const desiredModel = desiredModelSelection.model;
const desiredModelOptions =
options?.modelOptions ?? toProviderModelOptions(desiredModelSelection);
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
@@ -278,8 +262,7 @@ const make = Effect.gen(function* () {
threadId,
...(preferredProvider ? { provider: preferredProvider } : {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(desiredModel ? { model: desiredModel } : {}),
...(desiredModelOptions !== undefined ? { modelOptions: desiredModelOptions } : {}),
modelSelection: desiredModelSelection,
...(options?.providerOptions !== undefined
? { providerOptions: options.providerOptions }
: {}),
@@ -319,17 +302,17 @@ const make = Effect.gen(function* () {
requestedModelSelection !== undefined &&
requestedModelSelection.model !== activeSession?.model;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
const previousModelOptions = threadModelOptions.get(threadId);
const shouldRestartForModelOptionsChange =
const previousModelSelection = threadModelSelections.get(threadId);
const shouldRestartForModelSelectionChange =
currentProvider === "claudeAgent" &&
options?.modelOptions !== undefined &&
!sameModelOptions(previousModelOptions, options.modelOptions);
requestedModelSelection !== undefined &&
!sameModelSelectionOptions(previousModelSelection, requestedModelSelection);
if (
!runtimeModeChanged &&
!providerChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelOptionsChange
!shouldRestartForModelSelectionChange
) {
return existingSessionThreadId;
}
@@ -349,7 +332,7 @@ const make = Effect.gen(function* () {
providerChanged,
modelChanged,
shouldRestartForModelChange,
shouldRestartForModelOptionsChange,
shouldRestartForModelSelectionChange,
hasResumeCursor: resumeCursor !== undefined,
});
const restartedSession = yield* startProviderSession(
@@ -376,7 +359,6 @@ const make = Effect.gen(function* () {
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly modelSelection?: ModelSelection;
readonly modelOptions?: ProviderModelOptions;
readonly providerOptions?: ProviderStartOptions;
readonly interactionMode?: "default" | "plan";
readonly createdAt: string;
@@ -387,14 +369,13 @@ const make = Effect.gen(function* () {
}
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
if (input.providerOptions !== undefined) {
threadProviderOptions.set(input.threadId, input.providerOptions);
}
if (input.modelOptions !== undefined) {
threadModelOptions.set(input.threadId, input.modelOptions);
if (input.modelSelection !== undefined) {
threadModelSelections.set(input.threadId, input.modelSelection);
}
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
@@ -408,14 +389,20 @@ const make = Effect.gen(function* () {
? "in-session"
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
const modelForTurn =
sessionModelSwitch === "unsupported" ? activeSession?.model : input.modelSelection?.model;
sessionModelSwitch === "unsupported"
? input.modelSelection
? {
...input.modelSelection,
model: activeSession?.model ?? input.modelSelection.model,
}
: undefined
: input.modelSelection;
yield* providerService.sendTurn({
threadId: input.threadId,
...(normalizedInput ? { input: normalizedInput } : {}),
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
});
});
@@ -524,10 +511,6 @@ const make = Effect.gen(function* () {
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
}).pipe(Effect.forkScoped);
const requestedModelOptions = event.payload.modelSelection
? toProviderModelOptions(event.payload.modelSelection)
: undefined;
yield* sendTurnForThread({
threadId: event.payload.threadId,
messageText: message.text,
@@ -535,7 +518,6 @@ const make = Effect.gen(function* () {
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
: {}),
...(requestedModelOptions !== undefined ? { modelOptions: requestedModelOptions } : {}),
...(event.payload.providerOptions !== undefined
? { providerOptions: event.payload.providerOptions }
: {}),
@@ -705,14 +687,12 @@ const make = Effect.gen(function* () {
return;
}
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
const cachedModelOptions =
threadModelOptions.get(event.payload.threadId) ??
toProviderModelOptions(thread.modelSelection);
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
...(cachedProviderOptions !== undefined
? { providerOptions: cachedProviderOptions }
: {}),
...(cachedModelOptions !== undefined ? { modelOptions: cachedModelOptions } : {}),
...(cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {}),
});
return;
}
@@ -1919,6 +1919,185 @@ describe("ProviderRuntimeIngestion", () => {
expect(checkpoint?.checkpointRef).toBe("provider-diff:evt-turn-diff-updated");
});
it("projects context window updates into normalized thread activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
usage: {
usedTokens: 1075,
totalProcessedTokens: 10_200,
maxTokens: 128_000,
inputTokens: 1000,
cachedInputTokens: 500,
outputTokens: 50,
reasoningOutputTokens: 25,
lastUsedTokens: 1075,
lastInputTokens: 1000,
lastCachedInputTokens: 500,
lastOutputTokens: 50,
lastReasoningOutputTokens: 25,
compactsAutomatically: true,
},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
),
);
const usageActivity = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
);
expect(usageActivity).toBeDefined();
expect(usageActivity?.payload).toMatchObject({
usedTokens: 1075,
totalProcessedTokens: 10_200,
maxTokens: 128_000,
inputTokens: 1000,
cachedInputTokens: 500,
outputTokens: 50,
reasoningOutputTokens: 25,
lastUsedTokens: 1075,
compactsAutomatically: true,
});
});
it("projects Codex camelCase token usage payloads into normalized thread activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated-camel"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
usage: {
usedTokens: 126,
totalProcessedTokens: 11_839,
maxTokens: 258_400,
inputTokens: 120,
cachedInputTokens: 0,
outputTokens: 6,
reasoningOutputTokens: 0,
lastUsedTokens: 126,
lastInputTokens: 120,
lastCachedInputTokens: 0,
lastOutputTokens: 6,
lastReasoningOutputTokens: 0,
compactsAutomatically: true,
},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
),
);
const usageActivity = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
);
expect(usageActivity?.payload).toMatchObject({
usedTokens: 126,
totalProcessedTokens: 11_839,
maxTokens: 258_400,
inputTokens: 120,
cachedInputTokens: 0,
outputTokens: 6,
reasoningOutputTokens: 0,
lastUsedTokens: 126,
lastInputTokens: 120,
lastOutputTokens: 6,
compactsAutomatically: true,
});
});
it("projects Claude usage snapshots with context window into normalized thread activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated-claude-window"),
provider: "claudeAgent",
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
usage: {
usedTokens: 31_251,
lastUsedTokens: 31_251,
maxTokens: 200_000,
toolUses: 25,
durationMs: 43_567,
},
},
raw: {
source: "claude.sdk.message",
method: "claude/result/success",
payload: {},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
),
);
const usageActivity = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
);
expect(usageActivity?.payload).toMatchObject({
usedTokens: 31_251,
lastUsedTokens: 31_251,
maxTokens: 200_000,
toolUses: 25,
durationMs: 43_567,
});
});
it("projects compacted thread state into context compaction activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "thread.state.changed",
eventId: asEventId("evt-thread-compacted"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
payload: {
state: "compacted",
detail: { source: "provider" },
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-compaction",
),
);
const activity = thread.activities.find(
(candidate: ProviderRuntimeTestActivity) => candidate.kind === "context-compaction",
);
expect(activity?.summary).toBe("Context compacted");
expect(activity?.tone).toBe("info");
});
it("projects Codex task lifecycle chunks into thread activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -8,6 +8,7 @@ import {
CheckpointRef,
isToolLifecycleItemType,
ThreadId,
type ThreadTokenUsageSnapshot,
TurnId,
type OrchestrationThreadActivity,
type ProviderRuntimeEvent,
@@ -101,6 +102,15 @@ function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function buildContextWindowActivityPayload(
event: ProviderRuntimeEvent,
): ThreadTokenUsageSnapshot | undefined {
if (event.type !== "thread.token-usage.updated" || event.payload.usage.usedTokens <= 0) {
return undefined;
}
return event.payload.usage;
}
function runtimePayloadRecord(event: ProviderRuntimeEvent): Record<string, unknown> | undefined {
const payload = (event as { payload?: unknown }).payload;
if (!payload || typeof payload !== "object") {
@@ -409,6 +419,48 @@ function runtimeEventToActivities(
];
}
case "thread.state.changed": {
if (event.payload.state !== "compacted") {
return [];
}
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "info",
kind: "context-compaction",
summary: "Context compacted",
payload: {
state: event.payload.state,
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "thread.token-usage.updated": {
const payload = buildContextWindowActivityPayload(event);
if (!payload) {
return [];
}
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "info",
kind: "context-window.updated",
summary: "Context window updated",
payload,
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "item.updated": {
if (!isToolLifecycleItemType(event.payload.itemType)) {
return [];
@@ -77,7 +77,11 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
${row.workspaceRoot},
${row.defaultModelSelection?.provider ?? null},
${row.defaultModelSelection?.model ?? null},
${JSON.stringify(row.defaultModelSelection?.options ?? null)},
${
row.defaultModelSelection?.options != null
? JSON.stringify(row.defaultModelSelection.options)
: null
},
${JSON.stringify(row.scripts)},
${row.createdAt},
${row.updatedAt},
@@ -0,0 +1,110 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { SqlitePersistenceMemory } from "./Sqlite.ts";
import { ProjectionProjectRepositoryLive } from "./ProjectionProjects.ts";
import { ProjectionThreadRepositoryLive } from "./ProjectionThreads.ts";
import { ProjectionProjectRepository } from "../Services/ProjectionProjects.ts";
import { ProjectionThreadRepository } from "../Services/ProjectionThreads.ts";
const projectionRepositoriesLayer = it.layer(
Layer.mergeAll(
ProjectionProjectRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
ProjectionThreadRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
SqlitePersistenceMemory,
),
);
projectionRepositoriesLayer("Projection repositories", (it) => {
it.effect("stores SQL NULL for missing project model options", () =>
Effect.gen(function* () {
const projects = yield* ProjectionProjectRepository;
const sql = yield* SqlClient.SqlClient;
yield* projects.upsert({
projectId: ProjectId.makeUnsafe("project-null-options"),
title: "Null options project",
workspaceRoot: "/tmp/project-null-options",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.4",
},
scripts: [],
createdAt: "2026-03-24T00:00:00.000Z",
updatedAt: "2026-03-24T00:00:00.000Z",
deletedAt: null,
});
const rows = yield* sql<{
readonly defaultModelOptions: string | null;
}>`
SELECT default_model_options_json AS "defaultModelOptions"
FROM projection_projects
WHERE project_id = 'project-null-options'
`;
const row = rows[0];
if (!row) {
return yield* Effect.fail(new Error("Expected projection_projects row to exist."));
}
assert.strictEqual(row.defaultModelOptions, null);
const persisted = yield* projects.getById({
projectId: ProjectId.makeUnsafe("project-null-options"),
});
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
provider: "codex",
model: "gpt-5.4",
});
}),
);
it.effect("stores SQL NULL for missing thread model options", () =>
Effect.gen(function* () {
const threads = yield* ProjectionThreadRepository;
const sql = yield* SqlClient.SqlClient;
yield* threads.upsert({
threadId: ThreadId.makeUnsafe("thread-null-options"),
projectId: ProjectId.makeUnsafe("project-null-options"),
title: "Null options thread",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurnId: null,
createdAt: "2026-03-24T00:00:00.000Z",
updatedAt: "2026-03-24T00:00:00.000Z",
deletedAt: null,
});
const rows = yield* sql<{
readonly modelOptions: string | null;
}>`
SELECT model_options_json AS "modelOptions"
FROM projection_threads
WHERE thread_id = 'thread-null-options'
`;
const row = rows[0];
if (!row) {
return yield* Effect.fail(new Error("Expected projection_threads row to exist."));
}
assert.strictEqual(row.modelOptions, null);
const persisted = yield* threads.getById({
threadId: ThreadId.makeUnsafe("thread-null-options"),
});
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
});
}),
);
});
@@ -89,7 +89,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.title},
${row.modelSelection.provider},
${row.modelSelection.model},
${JSON.stringify(row.modelSelection.options ?? null)},
${row.modelSelection.options != null ? JSON.stringify(row.modelSelection.options) : null},
${row.runtimeMode},
${row.interactionMode},
${row.branch},
+1 -1
View File
@@ -31,7 +31,7 @@ const setup = Layer.effectDiscard(
const sql = yield* SqlClient.SqlClient;
yield* sql`PRAGMA journal_mode = WAL;`;
yield* sql`PRAGMA foreign_keys = ON;`;
yield* runMigrations;
yield* runMigrations();
}),
);
+45 -28
View File
@@ -10,6 +10,7 @@
import * as Migrator from "effect/unstable/sql/Migrator";
import * as Layer from "effect/Layer";
import * as Effect from "effect/Effect";
// Import all migrations statically
import Migration0001 from "./Migrations/001_OrchestrationEvents.ts";
@@ -27,9 +28,7 @@ import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts"
import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
import Migration0016 from "./Migrations/016_ProjectionProviders.ts";
import Migration0017 from "./Migrations/017_ProjectionModelSelectionOptions.ts";
import { Effect } from "effect";
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
/**
* Migration loader with all migrations defined inline.
@@ -41,25 +40,33 @@ import { Effect } from "effect";
* Uses Migrator.fromRecord which parses the key format and
* returns migrations sorted by ID.
*/
const loader = Migrator.fromRecord({
"1_OrchestrationEvents": Migration0001,
"2_OrchestrationCommandReceipts": Migration0002,
"3_CheckpointDiffBlobs": Migration0003,
"4_ProviderSessionRuntime": Migration0004,
"5_Projections": Migration0005,
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
"7_ProjectionThreadMessageAttachments": Migration0007,
"8_ProjectionThreadActivitySequence": Migration0008,
"9_ProviderSessionRuntimeMode": Migration0009,
"10_ProjectionThreadsRuntimeMode": Migration0010,
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
"12_ProjectionThreadsInteractionMode": Migration0012,
"13_ProjectionThreadProposedPlans": Migration0013,
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
"16_ProjectionProviders": Migration0016,
"17_ProjectionModelSelectionOptions": Migration0017,
});
export const migrationEntries = [
[1, "OrchestrationEvents", Migration0001],
[2, "OrchestrationCommandReceipts", Migration0002],
[3, "CheckpointDiffBlobs", Migration0003],
[4, "ProviderSessionRuntime", Migration0004],
[5, "Projections", Migration0005],
[6, "ProjectionThreadSessionRuntimeModeColumns", Migration0006],
[7, "ProjectionThreadMessageAttachments", Migration0007],
[8, "ProjectionThreadActivitySequence", Migration0008],
[9, "ProviderSessionRuntimeMode", Migration0009],
[10, "ProjectionThreadsRuntimeMode", Migration0010],
[11, "OrchestrationThreadCreatedRuntimeMode", Migration0011],
[12, "ProjectionThreadsInteractionMode", Migration0012],
[13, "ProjectionThreadProposedPlans", Migration0013],
[14, "ProjectionThreadProposedPlanImplementation", Migration0014],
[15, "ProjectionTurnsSourceProposedPlan", Migration0015],
[16, "CanonicalizeModelSelections", Migration0016],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
Migrator.fromRecord(
Object.fromEntries(
migrationEntries
.filter(([id]) => throughId === undefined || id <= throughId)
.map(([id, name, migration]) => [`${id}_${name}`, migration]),
),
);
/**
* Migrator run function - no schema dumping needed
@@ -67,6 +74,10 @@ const loader = Migrator.fromRecord({
*/
const run = Migrator.make({});
export interface RunMigrationsOptions {
readonly toMigrationInclusive?: number | undefined;
}
/**
* Run all pending migrations.
*
@@ -77,11 +88,17 @@ const run = Migrator.make({});
*
* @returns Effect containing array of executed migrations
*/
export const runMigrations = Effect.gen(function* () {
yield* Effect.log("Running migrations...");
yield* run({ loader });
yield* Effect.log("Migrations ran successfully");
});
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
Effect.gen(function* () {
yield* Effect.log(
toMigrationInclusive !== undefined
? `Running migrations 1 through ${toMigrationInclusive}...`
: "Running migrations...",
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully");
return executedMigrations;
});
/**
* Layer that runs migrations when the layer is built.
@@ -100,4 +117,4 @@ export const runMigrations = Effect.gen(function* () {
* )
* ```
*/
export const MigrationsLive = Layer.effectDiscard(runMigrations);
export const MigrationsLive = Layer.effectDiscard(runMigrations());
@@ -0,0 +1,248 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("016_CanonicalizeModelSelections", (it) => {
it.effect(
"migrates legacy projection rows and event payloads to the canonical model-selection shape",
() =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
// Setup base state
{
yield* runMigrations({ toMigrationInclusive: 15 });
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES
('project-codex', 'Codex project', '/tmp/project-codex', 'gpt-5.4', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL),
('project-claude', 'Claude project', '/tmp/project-claude', 'claude-sonnet-4-6', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL),
('project-null', 'Null project', '/tmp/project-null', NULL, '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL)
`;
yield* sql`
UPDATE projection_projects
SET default_model = 'claude-opus-4-6'
WHERE project_id = 'project-claude'
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
deleted_at,
runtime_mode,
interaction_mode
)
VALUES
('thread-session', 'project-codex', 'Session thread', 'gpt-5.4', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
('thread-claude', 'project-claude', 'Claude thread', 'claude-opus-4-6', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
('thread-codex', 'project-codex', 'Codex thread', 'gpt-5.4', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
('thread-legacy-options', 'project-claude', 'Legacy options thread', 'claude-opus-4-6', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default')
`;
yield* sql`
INSERT INTO projection_thread_sessions (
thread_id,
status,
provider_name,
provider_session_id,
provider_thread_id,
active_turn_id,
last_error,
updated_at,
runtime_mode
)
VALUES (
'thread-session',
'running',
'claudeAgent',
'provider-session-1',
'provider-thread-1',
NULL,
NULL,
'2026-01-01T00:00:00.000Z',
'full-access'
)
`;
yield* sql`
INSERT INTO orchestration_events (
event_id,
aggregate_kind,
stream_id,
stream_version,
event_type,
occurred_at,
command_id,
causation_event_id,
correlation_id,
actor_kind,
payload_json,
metadata_json
)
VALUES
(
'event-project-created',
'project',
'project-1',
1,
'project.created',
'2026-01-01T00:00:00.000Z',
'command-project-created',
NULL,
'correlation-project-created',
'user',
'{"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-thread-created',
'thread',
'thread-1',
1,
'thread.created',
'2026-01-01T00:00:00.000Z',
'command-thread-created',
NULL,
'correlation-thread-created',
'user',
'{"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-turn-start-requested',
'thread',
'thread-1',
2,
'thread.turn-start-requested',
'2026-01-01T00:00:00.000Z',
'command-turn-start-requested',
NULL,
'correlation-turn-start-requested',
'user',
'{"threadId":"thread-1","turnId":"turn-1","input":"hi","model":"gpt-5.4","modelOptions":{"codex":{"fastMode":true},"claudeAgent":{"effort":"max"}},"deliveryMode":"buffered"}',
'{}'
)
`;
}
// Execute migration under test
yield* runMigrations({ toMigrationInclusive: 16 });
// Assert expected state
{
const projectRows = yield* sql<{
readonly projectId: string;
readonly defaultProvider: string | null;
}>`
SELECT
project_id AS "projectId",
default_provider AS "defaultProvider"
FROM projection_projects
ORDER BY project_id
`;
assert.deepStrictEqual(projectRows, [
{ projectId: "project-claude", defaultProvider: "claudeAgent" },
{ projectId: "project-codex", defaultProvider: "codex" },
{ projectId: "project-null", defaultProvider: null },
]);
const threadRows = yield* sql<{
readonly threadId: string;
readonly provider: string | null;
readonly modelOptions: string | null;
}>`
SELECT
thread_id AS "threadId",
provider,
model_options_json AS "modelOptions"
FROM projection_threads
ORDER BY thread_id
`;
assert.deepStrictEqual(threadRows, [
{ threadId: "thread-claude", provider: "claudeAgent", modelOptions: null },
{ threadId: "thread-codex", provider: "codex", modelOptions: null },
{ threadId: "thread-legacy-options", provider: "claudeAgent", modelOptions: null },
{ threadId: "thread-session", provider: "claudeAgent", modelOptions: null },
]);
const eventRows = yield* sql<{
readonly payloadJson: string;
}>`
SELECT payload_json AS "payloadJson"
FROM orchestration_events
ORDER BY rowid ASC
`;
assert.deepStrictEqual(JSON.parse(eventRows[0]!.payloadJson), {
projectId: "project-1",
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
},
},
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.deepStrictEqual(JSON.parse(eventRows[1]!.payloadJson), {
threadId: "thread-1",
projectId: "project-1",
title: "Thread",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
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",
});
assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), {
threadId: "thread-1",
turnId: "turn-1",
input: "hi",
modelSelection: {
provider: "codex",
model: "gpt-5.4",
options: {
fastMode: true,
},
},
deliveryMode: "buffered",
});
}
}),
);
});
@@ -0,0 +1,209 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN default_provider TEXT
`;
yield* sql`
UPDATE projection_projects
SET default_provider = CASE
WHEN default_model IS NULL THEN NULL
WHEN lower(default_model) LIKE '%claude%' THEN 'claudeAgent'
ELSE 'codex'
END
WHERE default_provider IS NULL
`;
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN provider TEXT
`;
yield* sql`
UPDATE projection_threads
SET provider = COALESCE(
(
SELECT provider_name
FROM projection_thread_sessions
WHERE projection_thread_sessions.thread_id = projection_threads.thread_id
),
CASE
WHEN lower(model) LIKE '%claude%' THEN 'claudeAgent'
ELSE 'codex'
END,
'codex'
)
WHERE provider IS NULL
`;
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN default_model_options_json TEXT
`;
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN model_options_json TEXT
`;
yield* sql`
UPDATE projection_projects
SET
default_model_options_json = CASE
WHEN default_model_options_json IS NULL THEN NULL
WHEN json_valid(default_model_options_json) = 0 THEN default_model_options_json
WHEN json_type(default_model_options_json, '$.codex') IS NOT NULL
OR json_type(default_model_options_json, '$.claudeAgent') IS NOT NULL
THEN CASE
WHEN default_provider = 'claudeAgent'
THEN json_extract(default_model_options_json, '$.claudeAgent')
ELSE json_extract(default_model_options_json, '$.codex')
END
ELSE default_model_options_json
END
WHERE default_model IS NOT NULL
`;
yield* sql`
UPDATE projection_threads
SET
model_options_json = CASE
WHEN model_options_json IS NULL THEN NULL
WHEN json_valid(model_options_json) = 0 THEN model_options_json
WHEN json_type(model_options_json, '$.codex') IS NOT NULL
OR json_type(model_options_json, '$.claudeAgent') IS NOT NULL
THEN CASE
WHEN provider = 'claudeAgent'
THEN json_extract(model_options_json, '$.claudeAgent')
ELSE json_extract(model_options_json, '$.codex')
END
ELSE model_options_json
END
`;
yield* sql`
UPDATE orchestration_events
SET payload_json = CASE
WHEN json_type(payload_json, '$.defaultModel') = 'null' THEN json_remove(
json_set(payload_json, '$.defaultModelSelection', json('null')),
'$.defaultProvider',
'$.defaultModel',
'$.defaultModelOptions'
)
ELSE json_remove(
json_set(
payload_json,
'$.defaultModelSelection',
json_patch(
json_object(
'provider',
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,
'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_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 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'))
)
END
)
),
'$.defaultProvider',
'$.defaultModel',
'$.defaultModelOptions'
)
END
WHERE event_type IN ('project.created', 'project.meta-updated')
AND json_type(payload_json, '$.defaultModelSelection') IS NULL
AND json_type(payload_json, '$.defaultModel') IS NOT NULL
`;
yield* sql`
UPDATE orchestration_events
SET payload_json = json_remove(
json_set(
payload_json,
'$.modelSelection',
json_patch(
json_object(
'provider',
CASE
WHEN json_extract(payload_json, '$.provider') IS NOT NULL
THEN json_extract(payload_json, '$.provider')
WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'
THEN 'claudeAgent'
ELSE 'codex'
END,
'model',
json_extract(payload_json, '$.model')
),
CASE
WHEN json_type(payload_json, '$.modelOptions') IS NULL THEN '{}'
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
OR json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
THEN CASE
WHEN (
CASE
WHEN json_extract(payload_json, '$.provider') IS NOT NULL
THEN json_extract(payload_json, '$.provider')
WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'
THEN 'claudeAgent'
ELSE 'codex'
END
) = 'claudeAgent'
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
)
),
'$.provider',
'$.model',
'$.modelOptions'
)
WHERE event_type IN ('thread.created', 'thread.meta-updated', 'thread.turn-start-requested')
AND json_type(payload_json, '$.modelSelection') IS NULL
AND json_type(payload_json, '$.model') IS NOT NULL
`;
});
@@ -1,38 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN default_provider TEXT
`;
yield* sql`
UPDATE projection_projects
SET default_provider = CASE
WHEN default_model IS NULL THEN NULL
ELSE 'codex'
END
WHERE default_provider IS NULL
`;
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN provider TEXT
`;
yield* sql`
UPDATE projection_threads
SET provider = COALESCE(
(
SELECT provider_name
FROM projection_thread_sessions
WHERE projection_thread_sessions.thread_id = projection_threads.thread_id
),
'codex'
)
WHERE provider IS NULL
`;
});
@@ -1,28 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN default_model_options_json TEXT
`;
yield* sql`
UPDATE projection_projects
SET default_model_options_json = NULL
WHERE default_model_options_json IS NULL
`;
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN model_options_json TEXT
`;
yield* sql`
UPDATE projection_threads
SET model_options_json = NULL
WHERE model_options_json IS NULL
`;
});
@@ -332,13 +332,14 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
model: "claude-opus-4-6",
runtimeMode: "full-access",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
},
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
@@ -356,13 +357,14 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
model: "claude-sonnet-4-6",
runtimeMode: "full-access",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
@@ -380,13 +382,14 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
model: "claude-haiku-4-5",
runtimeMode: "full-access",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
effort: "high",
},
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
@@ -404,13 +407,14 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
model: "claude-haiku-4-5",
runtimeMode: "full-access",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
thinking: false,
},
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
@@ -430,13 +434,14 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
model: "claude-sonnet-4-6",
runtimeMode: "full-access",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
thinking: false,
},
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
@@ -454,13 +459,14 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
model: "claude-opus-4-6",
runtimeMode: "full-access",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
fastMode: true,
},
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
@@ -480,13 +486,14 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
model: "claude-sonnet-4-6",
runtimeMode: "full-access",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
fastMode: true,
},
},
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
@@ -504,22 +511,24 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
model: "claude-sonnet-4-6",
runtimeMode: "full-access",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "ultrathink",
},
},
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "Investigate the edge cases",
attachments: [],
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "ultrathink",
},
},
@@ -613,7 +622,10 @@ describe("ClaudeAdapterLive", () => {
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
model: "claude-sonnet-4-5",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-5",
},
runtimeMode: "full-access",
});
@@ -1225,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,
);
@@ -1267,6 +1279,127 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("emits thread token usage updates from Claude task progress", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
harness.query.emit({
type: "system",
subtype: "task_progress",
task_id: "task-usage-1",
description: "Thinking through the patch",
usage: {
total_tokens: 321,
tool_uses: 2,
duration_ms: 654,
},
session_id: "sdk-session-task-usage",
uuid: "task-usage-progress-1",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated");
const progressEvent = runtimeEvents.find((event) => event.type === "task.progress");
assert.equal(usageEvent?.type, "thread.token-usage.updated");
if (usageEvent?.type === "thread.token-usage.updated") {
assert.deepEqual(usageEvent.payload, {
usage: {
usedTokens: 321,
lastUsedTokens: 321,
toolUses: 2,
durationMs: 654,
},
});
}
assert.equal(progressEvent?.type, "task.progress");
if (usageEvent && progressEvent) {
assert.notStrictEqual(usageEvent.eventId, progressEvent.eventId);
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("emits Claude context window on result completion usage snapshots", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: THREAD_ID,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
duration_ms: 1234,
duration_api_ms: 1200,
num_turns: 1,
result: "done",
stop_reason: "end_turn",
session_id: "sdk-session-result-usage",
usage: {
input_tokens: 4,
cache_creation_input_tokens: 2715,
cache_read_input_tokens: 21144,
output_tokens: 679,
},
modelUsage: {
"claude-opus-4-6": {
contextWindow: 200000,
maxOutputTokens: 64000,
},
},
} as unknown as SDKMessage);
harness.query.finish();
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated");
assert.equal(usageEvent?.type, "thread.token-usage.updated");
if (usageEvent?.type === "thread.token-usage.updated") {
assert.deepEqual(usageEvent.payload, {
usage: {
usedTokens: 24542,
lastUsedTokens: 24542,
inputTokens: 23863,
outputTokens: 679,
maxTokens: 200000,
},
});
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect(
"emits completion only after turn result when assistant frames arrive before deltas",
() => {
@@ -2239,7 +2372,10 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
model: "claude-opus-4-6",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
attachments: [],
});
+186 -15
View File
@@ -29,6 +29,7 @@ import {
type ProviderRuntimeTurnStatus,
type ProviderSendTurnInput,
type ProviderSession,
type ThreadTokenUsageSnapshot,
type ProviderUserInputAnswers,
type RuntimeContentStreamKind,
RuntimeItemId,
@@ -156,6 +157,7 @@ interface ClaudeSessionContext {
}>;
readonly inFlightTools: Map<number, ToolInFlight>;
turnState: ClaudeTurnState | undefined;
lastKnownContextWindow: number | undefined;
lastAssistantUuid: string | undefined;
lastThreadStartedId: string | undefined;
stopped: boolean;
@@ -259,6 +261,82 @@ function asRuntimeItemId(value: string): RuntimeItemId {
return RuntimeItemId.makeUnsafe(value);
}
function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | undefined {
if (!modelUsage || typeof modelUsage !== "object") {
return undefined;
}
let maxContextWindow: number | undefined;
for (const value of Object.values(modelUsage as Record<string, unknown>)) {
if (!value || typeof value !== "object") {
continue;
}
const contextWindow = (value as { contextWindow?: unknown }).contextWindow;
if (
typeof contextWindow !== "number" ||
!Number.isFinite(contextWindow) ||
contextWindow <= 0
) {
continue;
}
maxContextWindow = Math.max(maxContextWindow ?? 0, contextWindow);
}
return maxContextWindow;
}
function normalizeClaudeTokenUsage(
usage: unknown,
contextWindow?: number,
): ThreadTokenUsageSnapshot | undefined {
if (!usage || typeof usage !== "object") {
return undefined;
}
const record = usage as Record<string, unknown>;
const directUsedTokens =
typeof record.total_tokens === "number" && Number.isFinite(record.total_tokens)
? record.total_tokens
: undefined;
const inputTokens =
(typeof record.input_tokens === "number" && Number.isFinite(record.input_tokens)
? record.input_tokens
: 0) +
(typeof record.cache_creation_input_tokens === "number" &&
Number.isFinite(record.cache_creation_input_tokens)
? record.cache_creation_input_tokens
: 0) +
(typeof record.cache_read_input_tokens === "number" &&
Number.isFinite(record.cache_read_input_tokens)
? record.cache_read_input_tokens
: 0);
const outputTokens =
typeof record.output_tokens === "number" && Number.isFinite(record.output_tokens)
? record.output_tokens
: 0;
const derivedUsedTokens = inputTokens + outputTokens;
const usedTokens = directUsedTokens ?? (derivedUsedTokens > 0 ? derivedUsedTokens : undefined);
if (usedTokens === undefined || usedTokens <= 0) {
return undefined;
}
return {
usedTokens,
lastUsedTokens: usedTokens,
...(inputTokens > 0 ? { inputTokens } : {}),
...(outputTokens > 0 ? { outputTokens } : {}),
...(typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
? { maxTokens: contextWindow }
: {}),
...(typeof record.tool_uses === "number" && Number.isFinite(record.tool_uses)
? { toolUses: record.tool_uses }
: {}),
...(typeof record.duration_ms === "number" && Number.isFinite(record.duration_ms)
? { durationMs: record.duration_ms }
: {}),
};
}
function asCanonicalTurnId(value: TurnId): TurnId {
return value;
}
@@ -436,11 +514,17 @@ const CLAUDE_SETTING_SOURCES = [
function buildPromptText(input: ProviderSendTurnInput): string {
const requestedEffort = resolveReasoningEffortForProvider(
"claudeAgent",
input.modelOptions?.claudeAgent?.effort ?? null,
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null,
);
const supportedEffortOptions = getReasoningEffortOptions(
"claudeAgent",
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined,
);
const supportedEffortOptions = getReasoningEffortOptions("claudeAgent", input.model);
const promptEffort =
requestedEffort === "ultrathink" && supportsClaudeUltrathinkKeyword(input.model)
requestedEffort === "ultrathink" &&
supportsClaudeUltrathinkKeyword(
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined,
)
? "ultrathink"
: requestedEffort && supportedEffortOptions.includes(requestedEffort)
? requestedEffort
@@ -1287,8 +1371,34 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
result?: SDKResultMessage,
): Effect.Effect<void> =>
Effect.gen(function* () {
const resultUsage =
result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined;
const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);
const usageSnapshot = normalizeClaudeTokenUsage(
resultUsage,
resultContextWindow ?? context.lastKnownContextWindow,
);
if (resultContextWindow !== undefined) {
context.lastKnownContextWindow = resultContextWindow;
}
const turnState = context.turnState;
if (!turnState) {
if (usageSnapshot) {
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "thread.token-usage.updated",
eventId: usageStamp.eventId,
provider: PROVIDER,
createdAt: usageStamp.createdAt,
threadId: context.session.threadId,
payload: {
usage: usageSnapshot,
},
providerRefs: {},
});
}
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.completed",
@@ -1356,6 +1466,22 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
items: [...turnState.items],
});
if (usageSnapshot) {
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "thread.token-usage.updated",
eventId: usageStamp.eventId,
provider: PROVIDER,
createdAt: usageStamp.createdAt,
threadId: context.session.threadId,
turnId: turnState.turnId,
payload: {
usage: usageSnapshot,
},
providerRefs: nativeProviderRefs(context),
});
}
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.completed",
@@ -1925,6 +2051,24 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
});
return;
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,
type: "task.progress",
@@ -1938,6 +2082,24 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
});
return;
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,
type: "task.completed",
@@ -2542,21 +2704,27 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
);
const providerOptions = input.providerOptions?.claudeAgent;
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
const requestedEffort = resolveReasoningEffortForProvider(
"claudeAgent",
input.modelOptions?.claudeAgent?.effort ?? null,
modelSelection?.options?.effort ?? null,
);
const supportedEffortOptions = getReasoningEffortOptions(
"claudeAgent",
modelSelection?.model,
);
const supportedEffortOptions = getReasoningEffortOptions("claudeAgent", input.model);
const effort =
requestedEffort && supportedEffortOptions.includes(requestedEffort)
? requestedEffort
: null;
const fastMode =
input.modelOptions?.claudeAgent?.fastMode === true && supportsClaudeFastMode(input.model);
modelSelection?.options?.fastMode === true &&
supportsClaudeFastMode(modelSelection?.model);
const thinking =
typeof input.modelOptions?.claudeAgent?.thinking === "boolean" &&
supportsClaudeThinkingToggle(input.model)
? input.modelOptions.claudeAgent.thinking
typeof modelSelection?.options?.thinking === "boolean" &&
supportsClaudeThinkingToggle(modelSelection?.model)
? modelSelection.options.thinking
: undefined;
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
const permissionMode =
@@ -2569,7 +2737,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const queryOptions: ClaudeQueryOptions = {
...(input.cwd ? { cwd: input.cwd } : {}),
...(input.model ? { model: input.model } : {}),
...(modelSelection?.model ? { model: modelSelection.model } : {}),
pathToClaudeCodeExecutable: providerOptions?.binaryPath ?? "claude",
settingSources: [...CLAUDE_SETTING_SOURCES],
...(effectiveEffort ? { effort: effectiveEffort } : {}),
@@ -2610,7 +2778,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
status: "ready",
runtimeMode: input.runtimeMode,
...(input.cwd ? { cwd: input.cwd } : {}),
...(input.model ? { model: input.model } : {}),
...(modelSelection?.model ? { model: modelSelection.model } : {}),
...(threadId ? { threadId } : {}),
resumeCursor: {
...(threadId ? { threadId } : {}),
@@ -2637,6 +2805,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
turns: [],
inFlightTools,
turnState: undefined,
lastKnownContextWindow: undefined,
lastAssistantUuid: resumeState?.resumeSessionAt,
lastThreadStartedId: undefined,
stopped: false,
@@ -2664,7 +2833,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
threadId,
payload: {
config: {
...(input.model ? { model: input.model } : {}),
...(modelSelection?.model ? { model: modelSelection.model } : {}),
...(input.cwd ? { cwd: input.cwd } : {}),
...(effectiveEffort ? { effort: effectiveEffort } : {}),
...(permissionMode ? { permissionMode } : {}),
@@ -2710,6 +2879,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const sendTurn: ClaudeAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
const context = yield* requireSession(input.threadId);
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
if (context.turnState) {
// Auto-close a stale synthetic turn (from background agent responses
@@ -2717,9 +2888,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
yield* completeTurn(context, "completed");
}
if (input.model) {
if (modelSelection?.model) {
yield* Effect.tryPromise({
try: () => context.query.setModel(input.model),
try: () => context.query.setModel(modelSelection.model),
catch: (cause) => toRequestError(input.threadId, "turn/setModel", cause),
});
}
@@ -2769,7 +2940,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
createdAt: turnStartedStamp.createdAt,
threadId: context.session.threadId,
turnId,
payload: input.model ? { model: input.model } : {},
payload: modelSelection?.model ? { model: modelSelection.model } : {},
providerRefs: {},
});
@@ -188,9 +188,10 @@ validationLayer("CodexAdapterLive validation", (it) => {
yield* adapter.startSession({
provider: "codex",
threadId: asThreadId("thread-1"),
model: "gpt-5.3-codex",
modelOptions: {
codex: {
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
fastMode: true,
},
},
@@ -256,9 +257,10 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
adapter.sendTurn({
threadId: asThreadId("sess-missing"),
input: "hello",
model: "gpt-5.3-codex",
modelOptions: {
codex: {
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "high",
fastMode: true,
},
@@ -839,6 +841,70 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
assert.equal(firstEvent.value.payload.taskId, "turn-child");
}),
);
it.effect("unwraps Codex token usage payloads for context window events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-thread-token-usage-updated"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
createdAt: new Date().toISOString(),
method: "thread/tokenUsage/updated",
payload: {
threadId: "thread-1",
turnId: "turn-1",
tokenUsage: {
total: {
inputTokens: 11_833,
cachedInputTokens: 3456,
outputTokens: 6,
reasoningOutputTokens: 0,
totalTokens: 11_839,
},
last: {
inputTokens: 120,
cachedInputTokens: 0,
outputTokens: 6,
reasoningOutputTokens: 0,
totalTokens: 126,
},
modelContextWindow: 258_400,
},
},
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "thread.token-usage.updated");
if (firstEvent.value.type !== "thread.token-usage.updated") {
return;
}
assert.deepEqual(firstEvent.value.payload.usage, {
usedTokens: 126,
totalProcessedTokens: 11_839,
maxTokens: 258_400,
inputTokens: 120,
cachedInputTokens: 0,
outputTokens: 6,
reasoningOutputTokens: 0,
lastUsedTokens: 126,
lastInputTokens: 120,
lastCachedInputTokens: 0,
lastOutputTokens: 6,
lastReasoningOutputTokens: 0,
compactsAutomatically: true,
});
}),
);
});
afterAll(() => {
@@ -11,6 +11,7 @@ import {
type CanonicalRequestType,
type ProviderEvent,
type ProviderRuntimeEvent,
type ThreadTokenUsageSnapshot,
type ProviderUserInputAnswers,
RuntimeItemId,
RuntimeRequestId,
@@ -109,6 +110,48 @@ function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined {
const usage = asObject(value);
const totalUsage = asObject(usage?.total_token_usage ?? usage?.total);
const lastUsage = asObject(usage?.last_token_usage ?? usage?.last);
const totalProcessedTokens =
asNumber(totalUsage?.total_tokens) ?? asNumber(totalUsage?.totalTokens);
const usedTokens =
asNumber(lastUsage?.total_tokens) ?? asNumber(lastUsage?.totalTokens) ?? totalProcessedTokens;
if (usedTokens === undefined || usedTokens <= 0) {
return undefined;
}
const maxTokens = asNumber(usage?.model_context_window) ?? asNumber(usage?.modelContextWindow);
const inputTokens = asNumber(lastUsage?.input_tokens) ?? asNumber(lastUsage?.inputTokens);
const cachedInputTokens =
asNumber(lastUsage?.cached_input_tokens) ?? asNumber(lastUsage?.cachedInputTokens);
const outputTokens = asNumber(lastUsage?.output_tokens) ?? asNumber(lastUsage?.outputTokens);
const reasoningOutputTokens =
asNumber(lastUsage?.reasoning_output_tokens) ?? asNumber(lastUsage?.reasoningOutputTokens);
return {
usedTokens,
...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens
? { totalProcessedTokens }
: {}),
...(maxTokens !== undefined ? { maxTokens } : {}),
...(inputTokens !== undefined ? { inputTokens } : {}),
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
...(outputTokens !== undefined ? { outputTokens } : {}),
...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
...(usedTokens !== undefined ? { lastUsedTokens: usedTokens } : {}),
...(inputTokens !== undefined ? { lastInputTokens: inputTokens } : {}),
...(cachedInputTokens !== undefined ? { lastCachedInputTokens: cachedInputTokens } : {}),
...(outputTokens !== undefined ? { lastOutputTokens: outputTokens } : {}),
...(reasoningOutputTokens !== undefined
? { lastReasoningOutputTokens: reasoningOutputTokens }
: {}),
compactsAutomatically: true,
};
}
function toTurnId(value: string | undefined): TurnId | undefined {
return value?.trim() ? TurnId.makeUnsafe(value) : undefined;
}
@@ -708,12 +751,17 @@ function mapToRuntimeEvents(
}
if (event.method === "thread/tokenUsage/updated") {
const tokenUsage = asObject(payload?.tokenUsage);
const normalizedUsage = normalizeCodexTokenUsage(tokenUsage ?? event.payload);
if (!normalizedUsage) {
return [];
}
return [
{
type: "thread.token-usage.updated",
...runtimeEventBase(event, canonicalThreadId),
payload: {
usage: event.payload ?? {},
usage: normalizedUsage,
},
},
];
@@ -1313,8 +1361,12 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
...(input.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
runtimeMode: input.runtimeMode,
...(input.model !== undefined ? { model: input.model } : {}),
...(input.modelOptions?.codex?.fastMode ? { serviceTier: "fast" } : {}),
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
? { serviceTier: "fast" }
: {}),
};
return Effect.tryPromise({
@@ -1370,11 +1422,17 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
const managerInput = {
threadId: input.threadId,
...(input.input !== undefined ? { input: input.input } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.modelOptions?.codex?.reasoningEffort !== undefined
? { effort: input.modelOptions.codex.reasoningEffort }
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.provider === "codex" &&
input.modelSelection.options?.reasoningEffort !== undefined
? { effort: input.modelSelection.options.reasoningEffort }
: {}),
...(input.modelSelection?.provider === "codex" &&
input.modelSelection.options?.fastMode
? { serviceTier: "fast" }
: {}),
...(input.modelOptions?.codex?.fastMode ? { serviceTier: "fast" } : {}),
...(input.interactionMode !== undefined
? { interactionMode: input.interactionMode }
: {}),
@@ -633,8 +633,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
provider: "claudeAgent",
threadId: asThreadId("thread-claude-send-turn"),
cwd: "/tmp/project-claude-send-turn",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
},
},
@@ -658,14 +660,16 @@ routing.layer("ProviderServiceLive routing", (it) => {
const startPayload = resumedStartInput as {
provider?: string;
cwd?: string;
modelOptions?: unknown;
modelSelection?: unknown;
resumeCursor?: unknown;
threadId?: string;
};
assert.equal(startPayload.provider, "claudeAgent");
assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn");
assert.deepEqual(startPayload.modelOptions, {
claudeAgent: {
assert.deepEqual(startPayload.modelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
},
});
@@ -10,6 +10,7 @@
* @module ProviderServiceLive
*/
import {
ModelSelection,
NonNegativeInt,
ThreadId,
ProviderInterruptTurnInput,
@@ -89,7 +90,7 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
function toRuntimePayloadFromSession(
session: ProviderSession,
extra?: {
readonly modelOptions?: unknown;
readonly modelSelection?: unknown;
readonly providerOptions?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
@@ -100,7 +101,7 @@ function toRuntimePayloadFromSession(
model: session.model ?? null,
activeTurnId: session.activeTurnId ?? null,
lastError: session.lastError ?? null,
...(extra?.modelOptions !== undefined ? { modelOptions: extra.modelOptions } : {}),
...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}),
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
...(extra?.lastRuntimeEventAt !== undefined
@@ -109,15 +110,14 @@ function toRuntimePayloadFromSession(
};
}
function readPersistedModelOptions(
function readPersistedModelSelection(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): Record<string, unknown> | undefined {
): ModelSelection | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const raw = "modelOptions" in runtimePayload ? runtimePayload.modelOptions : undefined;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
return raw as Record<string, unknown>;
const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined;
return Schema.is(ModelSelection)(raw) ? raw : undefined;
}
function readPersistedProviderOptions(
@@ -172,7 +172,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
session: ProviderSession,
threadId: ThreadId,
extra?: {
readonly modelOptions?: unknown;
readonly modelSelection?: unknown;
readonly providerOptions?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
@@ -238,14 +238,14 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelOptions = readPersistedModelOptions(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelOptions ? { modelOptions: persistedModelOptions } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
@@ -328,7 +328,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
yield* upsertSessionBinding(session, threadId, {
modelOptions: input.modelOptions,
modelSelection: input.modelSelection,
providerOptions: input.providerOptions,
});
yield* analytics.record("provider.session.started", {
@@ -336,7 +336,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
runtimeMode: input.runtimeMode,
hasResumeCursor: session.resumeCursor !== undefined,
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
hasModel: typeof input.model === "string" && input.model.trim().length > 0,
hasModel:
typeof input.modelSelection?.model === "string" &&
input.modelSelection.model.trim().length > 0,
});
return session;
@@ -372,6 +374,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
activeTurnId: turn.turnId,
lastRuntimeEvent: "provider.sendTurn",
lastRuntimeEventAt: new Date().toISOString(),
@@ -379,7 +382,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.model,
model: input.modelSelection?.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.13",
"version": "0.0.14",
"private": true,
"type": "module",
"scripts": {
@@ -19,6 +19,7 @@
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@formkit/auto-animate": "^0.9.0",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
+14
View File
@@ -3,6 +3,8 @@ import { describe, expect, it } from "vitest";
import {
AppSettingsSchema,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
DEFAULT_TIMESTAMP_FORMAT,
getAppModelOptions,
getCustomModelOptionsByProvider,
@@ -111,6 +113,16 @@ describe("timestamp format defaults", () => {
});
});
describe("sidebar sort defaults", () => {
it("defaults project sorting to updated_at", () => {
expect(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER).toBe("updated_at");
});
it("defaults thread sorting to updated_at", () => {
expect(DEFAULT_SIDEBAR_THREAD_SORT_ORDER).toBe("updated_at");
});
});
describe("provider-specific custom models", () => {
it("includes provider-specific custom slugs in non-codex model lists", () => {
const claudeOptions = getAppModelOptions("claudeAgent", ["claude/custom-opus"]);
@@ -245,6 +257,8 @@ describe("AppSettingsSchema", () => {
defaultThreadEnvMode: "local",
confirmThreadDelete: false,
enableAssistantStreaming: false,
sidebarProjectSortOrder: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
sidebarThreadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
timestampFormat: DEFAULT_TIMESTAMP_FORMAT,
customCodexModels: [],
customClaudeModels: [],
+12
View File
@@ -21,6 +21,12 @@ export const MAX_CUSTOM_MODEL_LENGTH = 256;
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
export type TimestampFormat = typeof TimestampFormat.Type;
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);
export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;
export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";
export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);
export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
type CustomModelSettingsKey = "customCodexModels" | "customClaudeModels";
export type ProviderCustomModelConfig = {
provider: ProviderKind;
@@ -58,6 +64,12 @@ export const AppSettingsSchema = Schema.Struct({
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
diffWordWrap: Schema.Boolean.pipe(withDefaults(() => false)),
enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
withDefaults(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),
),
sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
withDefaults(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),
),
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
+13 -35
View File
@@ -7,7 +7,6 @@ import {
type ProjectScript,
type ModelSlug,
type ProviderKind,
type ProviderModelOptions,
type ProjectEntry,
type ProjectId,
type ProviderApprovalDecision,
@@ -145,12 +144,14 @@ import {
type TerminalContextDraft,
type TerminalContextSelection,
} from "../lib/terminalContext";
import { deriveLatestContextWindowSnapshot } from "../lib/contextWindow";
import { shouldUseCompactComposerFooter } from "./composerFooterLayout";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
import { MessagesTimeline } from "./chat/MessagesTimeline";
import { ChatHeader } from "./chat/ChatHeader";
import { ContextWindowMeter } from "./chat/ContextWindowMeter";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./chat/ExpandedImagePreview";
import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./chat/ProviderModelPicker";
import { ComposerCommandItem, ComposerCommandMenu } from "./chat/ComposerCommandMenu";
@@ -204,23 +205,6 @@ function formatOutgoingPrompt(params: {
}
return params.text;
}
function extractModelSelectionOptions(
provider: ProviderKind,
modelOptions: ProviderModelOptions | undefined,
): ModelSelection["options"] | undefined {
return provider === "codex" ? modelOptions?.codex : modelOptions?.claudeAgent;
}
function toProviderModelOptions(
modelSelection: ModelSelection | null | undefined,
): ProviderModelOptions | undefined {
if (!modelSelection?.options) {
return undefined;
}
return modelSelection.provider === "codex"
? { codex: modelSelection.options }
: { claudeAgent: modelSelection.options };
}
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
const SCRIPT_TERMINAL_COLS = 120;
const SCRIPT_TERMINAL_ROWS = 30;
@@ -505,6 +489,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
const diffOpen = rawSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const activeLatestTurn = activeThread?.latestTurn ?? null;
const activeContextWindow = useMemo(
() => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []),
[activeThread?.activities],
);
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = projects.find((p) => p.id === activeThread?.projectId);
@@ -640,16 +628,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
customModelsByProvider,
selectedProvider,
]);
const draftModelOptions = toProviderModelOptions(composerDraft.modelSelection);
const composerProviderState = useMemo(
() =>
getComposerProviderState({
provider: selectedProvider,
model: selectedModel,
prompt,
modelOptions: draftModelOptions,
modelOptions: composerDraft.modelSelection?.options,
}),
[draftModelOptions, prompt, selectedModel, selectedProvider],
[composerDraft.modelSelection?.options, prompt, selectedModel, selectedProvider],
);
const selectedPromptEffort = composerProviderState.promptEffort;
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
@@ -657,14 +644,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => ({
provider: selectedProvider,
model: selectedModel,
...(extractModelSelectionOptions(selectedProvider, selectedModelOptionsForDispatch)
? {
options: extractModelSelectionOptions(
selectedProvider,
selectedModelOptionsForDispatch,
),
}
: {}),
...(selectedModelOptionsForDispatch ? { options: selectedModelOptionsForDispatch } : {}),
}),
[selectedModel, selectedModelOptionsForDispatch, selectedProvider],
);
@@ -3035,12 +3015,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
text: implementationPrompt,
});
const nextThreadTitle = truncateTitle(buildPlanImplementationThreadTitle(planMarkdown));
const nextThreadModelSelection: ModelSelection = selectedModelSelection ??
activeThread.modelSelection ??
activeProject.defaultModelSelection ?? {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
};
const nextThreadModelSelection: ModelSelection = selectedModelSelection;
sendInFlightRef.current = true;
beginSendPhase("sending-turn");
@@ -3950,6 +3925,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
data-chat-composer-actions="right"
className="flex shrink-0 items-center gap-2"
>
{activeContextWindow ? (
<ContextWindowMeter usage={activeContextWindow} />
) : null}
{isPreparingWorktree ? (
<span className="text-muted-foreground/70 text-xs">
Preparing worktree...
@@ -1,13 +1,24 @@
import { describe, expect, it } from "vitest";
import {
getVisibleThreadsForProject,
getProjectSortTimestamp,
hasUnseenCompletion,
resolveProjectStatusIndicator,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
resolveThreadStatusPill,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortThreadsForSidebar,
} from "./Sidebar.logic";
import { ProjectId, ThreadId } from "@t3tools/contracts";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type Project,
type Thread,
} from "../types";
function makeLatestTurn(overrides?: {
completedAt?: string | null;
@@ -281,3 +292,346 @@ describe("resolveProjectStatusIndicator", () => {
).toMatchObject({ label: "Plan Ready", dotClass: "bg-violet-500" });
});
});
describe("getVisibleThreadsForProject", () => {
it("includes the active thread even when it falls below the folded preview", () => {
const threads = Array.from({ length: 8 }, (_, index) =>
makeThread({
id: ThreadId.makeUnsafe(`thread-${index + 1}`),
title: `Thread ${index + 1}`,
}),
);
const result = getVisibleThreadsForProject({
threads,
activeThreadId: ThreadId.makeUnsafe("thread-8"),
isThreadListExpanded: false,
previewLimit: 6,
});
expect(result.hasHiddenThreads).toBe(true);
expect(result.visibleThreads.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-3"),
ThreadId.makeUnsafe("thread-4"),
ThreadId.makeUnsafe("thread-5"),
ThreadId.makeUnsafe("thread-6"),
ThreadId.makeUnsafe("thread-8"),
]);
});
it("returns all threads when the list is expanded", () => {
const threads = Array.from({ length: 8 }, (_, index) =>
makeThread({
id: ThreadId.makeUnsafe(`thread-${index + 1}`),
}),
);
const result = getVisibleThreadsForProject({
threads,
activeThreadId: ThreadId.makeUnsafe("thread-8"),
isThreadListExpanded: true,
previewLimit: 6,
});
expect(result.hasHiddenThreads).toBe(true);
expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
threads.map((thread) => thread.id),
);
});
});
function makeProject(overrides: Partial<Project> = {}): Project {
return {
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.4",
...overrides?.defaultModelSelection,
},
expanded: true,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:00:00.000Z",
scripts: [],
...overrides,
};
}
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5.4",
...overrides?.modelSelection,
},
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_INTERACTION_MODE,
session: null,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:00:00.000Z",
latestTurn: null,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
...overrides,
};
}
describe("sortThreadsForSidebar", () => {
it("sorts threads by the latest user message in recency mode", () => {
const sorted = sortThreadsForSidebar(
[
makeThread({
id: ThreadId.makeUnsafe("thread-1"),
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:10:00.000Z",
messages: [
{
id: "message-1" as never,
role: "user",
text: "older",
createdAt: "2026-03-09T10:01:00.000Z",
streaming: false,
completedAt: "2026-03-09T10:01:00.000Z",
},
],
}),
makeThread({
id: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-03-09T10:05:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
messages: [
{
id: "message-2" as never,
role: "user",
text: "newer",
createdAt: "2026-03-09T10:06:00.000Z",
streaming: false,
completedAt: "2026-03-09T10:06:00.000Z",
},
],
}),
],
"updated_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-1"),
]);
});
it("falls back to thread timestamps when there is no user message", () => {
const sorted = sortThreadsForSidebar(
[
makeThread({
id: ThreadId.makeUnsafe("thread-1"),
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:01:00.000Z",
messages: [
{
id: "message-1" as never,
role: "assistant",
text: "assistant only",
createdAt: "2026-03-09T10:02:00.000Z",
streaming: false,
completedAt: "2026-03-09T10:02:00.000Z",
},
],
}),
makeThread({
id: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-03-09T10:05:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
messages: [],
}),
],
"updated_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-1"),
]);
});
it("falls back to id ordering when threads have no sortable timestamps", () => {
const sorted = sortThreadsForSidebar(
[
makeThread({
id: ThreadId.makeUnsafe("thread-1"),
createdAt: "" as never,
updatedAt: undefined,
messages: [],
}),
makeThread({
id: ThreadId.makeUnsafe("thread-2"),
createdAt: "" as never,
updatedAt: undefined,
messages: [],
}),
],
"updated_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-1"),
]);
});
it("can sort threads by createdAt when configured", () => {
const sorted = sortThreadsForSidebar(
[
makeThread({
id: ThreadId.makeUnsafe("thread-1"),
createdAt: "2026-03-09T10:05:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
}),
makeThread({
id: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:10:00.000Z",
}),
],
"created_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-2"),
]);
});
});
describe("sortProjectsForSidebar", () => {
it("sorts projects by the most recent user message across their threads", () => {
const projects = [
makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "Older project" }),
makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Newer project" }),
];
const threads = [
makeThread({
projectId: ProjectId.makeUnsafe("project-1"),
updatedAt: "2026-03-09T10:20:00.000Z",
messages: [
{
id: "message-1" as never,
role: "user",
text: "older project user message",
createdAt: "2026-03-09T10:01:00.000Z",
streaming: false,
completedAt: "2026-03-09T10:01:00.000Z",
},
],
}),
makeThread({
id: ThreadId.makeUnsafe("thread-2"),
projectId: ProjectId.makeUnsafe("project-2"),
updatedAt: "2026-03-09T10:05:00.000Z",
messages: [
{
id: "message-2" as never,
role: "user",
text: "newer project user message",
createdAt: "2026-03-09T10:05:00.000Z",
streaming: false,
completedAt: "2026-03-09T10:05:00.000Z",
},
],
}),
];
const sorted = sortProjectsForSidebar(projects, threads, "updated_at");
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
]);
});
it("falls back to project timestamps when a project has no threads", () => {
const sorted = sortProjectsForSidebar(
[
makeProject({
id: ProjectId.makeUnsafe("project-1"),
name: "Older project",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
makeProject({
id: ProjectId.makeUnsafe("project-2"),
name: "Newer project",
updatedAt: "2026-03-09T10:05:00.000Z",
}),
],
[],
"updated_at",
);
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
]);
});
it("falls back to name and id ordering when projects have no sortable timestamps", () => {
const sorted = sortProjectsForSidebar(
[
makeProject({
id: ProjectId.makeUnsafe("project-2"),
name: "Beta",
createdAt: undefined,
updatedAt: undefined,
}),
makeProject({
id: ProjectId.makeUnsafe("project-1"),
name: "Alpha",
createdAt: undefined,
updatedAt: undefined,
}),
],
[],
"updated_at",
);
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
]);
});
it("preserves manual project ordering", () => {
const projects = [
makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Second" }),
makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "First" }),
];
const sorted = sortProjectsForSidebar(projects, [], "manual");
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
]);
});
it("returns the project timestamp when no threads are present", () => {
const timestamp = getProjectSortTimestamp(
makeProject({ updatedAt: "2026-03-09T10:10:00.000Z" }),
[],
"updated_at",
);
expect(timestamp).toBe(Date.parse("2026-03-09T10:10:00.000Z"));
});
});
+152
View File
@@ -1,3 +1,4 @@
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "../appSettings";
import type { Thread } from "../types";
import { cn } from "../lib/utils";
import {
@@ -8,6 +9,13 @@ import {
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export type SidebarNewThreadEnvMode = "local" | "worktree";
type SidebarProject = {
id: string;
name: string;
createdAt?: string | undefined;
updatedAt?: string | undefined;
};
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt" | "messages">;
export interface ThreadStatusPill {
label:
@@ -178,3 +186,147 @@ export function resolveProjectStatusIndicator(
return highestPriorityStatus;
}
export function getVisibleThreadsForProject(input: {
threads: readonly Thread[];
activeThreadId: Thread["id"] | undefined;
isThreadListExpanded: boolean;
previewLimit: number;
}): {
hasHiddenThreads: boolean;
visibleThreads: Thread[];
} {
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
const hasHiddenThreads = threads.length > previewLimit;
if (!hasHiddenThreads || isThreadListExpanded) {
return {
hasHiddenThreads,
visibleThreads: [...threads],
};
}
const previewThreads = threads.slice(0, previewLimit);
if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
return {
hasHiddenThreads: true,
visibleThreads: previewThreads,
};
}
const activeThread = threads.find((thread) => thread.id === activeThreadId);
if (!activeThread) {
return {
hasHiddenThreads: true,
visibleThreads: previewThreads,
};
}
const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
return {
hasHiddenThreads: true,
visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
};
}
function toSortableTimestamp(iso: string | undefined): number | null {
if (!iso) return null;
const ms = Date.parse(iso);
return Number.isFinite(ms) ? ms : null;
}
function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
let latestUserMessageTimestamp: number | null = null;
for (const message of thread.messages) {
if (message.role !== "user") continue;
const messageTimestamp = toSortableTimestamp(message.createdAt);
if (messageTimestamp === null) continue;
latestUserMessageTimestamp =
latestUserMessageTimestamp === null
? messageTimestamp
: Math.max(latestUserMessageTimestamp, messageTimestamp);
}
if (latestUserMessageTimestamp !== null) {
return latestUserMessageTimestamp;
}
return toSortableTimestamp(thread.updatedAt ?? thread.createdAt) ?? Number.NEGATIVE_INFINITY;
}
function getThreadSortTimestamp(
thread: SidebarThreadSortInput,
sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
): number {
if (sortOrder === "created_at") {
return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY;
}
return getLatestUserMessageTimestamp(thread);
}
export function sortThreadsForSidebar<
T extends Pick<Thread, "id" | "createdAt" | "updatedAt" | "messages">,
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
return threads.toSorted((left, right) => {
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
const leftTimestamp = getThreadSortTimestamp(left, sortOrder);
const byTimestamp =
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
if (byTimestamp !== 0) return byTimestamp;
return right.id.localeCompare(left.id);
});
}
export function getProjectSortTimestamp(
project: SidebarProject,
projectThreads: readonly SidebarThreadSortInput[],
sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
): number {
if (projectThreads.length > 0) {
return projectThreads.reduce(
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
Number.NEGATIVE_INFINITY,
);
}
if (sortOrder === "created_at") {
return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
}
return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
}
export function sortProjectsForSidebar<TProject extends SidebarProject, TThread extends Thread>(
projects: readonly TProject[],
threads: readonly TThread[],
sortOrder: SidebarProjectSortOrder,
): TProject[] {
if (sortOrder === "manual") {
return [...projects];
}
const threadsByProjectId = new Map<string, TThread[]>();
for (const thread of threads) {
const existing = threadsByProjectId.get(thread.projectId) ?? [];
existing.push(thread);
threadsByProjectId.set(thread.projectId, existing);
}
return [...projects].toSorted((left, right) => {
const rightTimestamp = getProjectSortTimestamp(
right,
threadsByProjectId.get(right.id) ?? [],
sortOrder,
);
const leftTimestamp = getProjectSortTimestamp(
left,
threadsByProjectId.get(left.id) ?? [],
sortOrder,
);
const byTimestamp =
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
if (byTimestamp !== 0) return byTimestamp;
return left.name.localeCompare(right.name) || left.id.localeCompare(right.id);
});
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,114 @@
import { cn } from "~/lib/utils";
import { type ContextWindowSnapshot, formatContextWindowTokens } from "~/lib/contextWindow";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
function formatPercentage(value: number | null): string | null {
if (value === null || !Number.isFinite(value)) {
return null;
}
if (value < 10) {
return `${value.toFixed(1).replace(/\.0$/, "")}%`;
}
return `${Math.round(value)}%`;
}
export function ContextWindowMeter(props: { usage: ContextWindowSnapshot }) {
const { usage } = props;
const usedPercentage = formatPercentage(usage.usedPercentage);
const normalizedPercentage = Math.max(0, Math.min(100, usage.usedPercentage ?? 0));
const radius = 9.75;
const circumference = 2 * Math.PI * radius;
const dashOffset = circumference - (normalizedPercentage / 100) * circumference;
return (
<Popover>
<PopoverTrigger
openOnHover
delay={150}
closeDelay={0}
render={
<button
type="button"
className="group inline-flex items-center justify-center rounded-full transition-opacity hover:opacity-85"
aria-label={
usage.maxTokens !== null && usedPercentage
? `Context window ${usedPercentage} used`
: `Context window ${formatContextWindowTokens(usage.usedTokens)} tokens used`
}
>
<span className="relative flex h-6 w-6 items-center justify-center">
<svg
viewBox="0 0 24 24"
className="-rotate-90 absolute inset-0 h-full w-full transform-gpu"
aria-hidden="true"
>
<circle
cx="12"
cy="12"
r={radius}
fill="none"
stroke="color-mix(in oklab, var(--color-muted) 70%, transparent)"
strokeWidth="3"
/>
<circle
cx="12"
cy="12"
r={radius}
fill="none"
stroke="var(--color-muted-foreground)"
strokeWidth="3"
strokeLinecap="round"
strokeDasharray={circumference}
strokeDashoffset={dashOffset}
className="transition-[stroke-dashoffset] duration-500 ease-out motion-reduce:transition-none"
/>
</svg>
<span
className={cn(
"relative flex h-[15px] w-[15px] items-center justify-center rounded-full bg-background text-[8px] font-medium",
"text-muted-foreground",
)}
>
{usage.usedPercentage !== null
? Math.round(usage.usedPercentage)
: formatContextWindowTokens(usage.usedTokens)}
</span>
</span>
</button>
}
/>
<PopoverPopup tooltipStyle side="top" align="end" className="w-max max-w-none px-3 py-2">
<div className="space-y-1.5 leading-tight">
<div className="text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground">
Context window
</div>
{usage.maxTokens !== null && usedPercentage ? (
<div className="whitespace-nowrap text-xs font-medium text-foreground">
<span>{usedPercentage}</span>
<span className="mx-1">⋅</span>
<span>{formatContextWindowTokens(usage.usedTokens)}</span>
<span>/</span>
<span>{formatContextWindowTokens(usage.maxTokens ?? null)} context used</span>
</div>
) : (
<div className="text-sm text-foreground">
{formatContextWindowTokens(usage.usedTokens)} tokens used so far
</div>
)}
{(usage.totalProcessedTokens ?? null) !== null &&
(usage.totalProcessedTokens ?? 0) > usage.usedTokens ? (
<div className="text-xs text-muted-foreground">
Total processed: {formatContextWindowTokens(usage.totalProcessedTokens ?? null)}{" "}
tokens
</div>
) : null}
{usage.compactsAutomatically ? (
<div className="text-xs text-muted-foreground">
Automatically compacts its context when needed.
</div>
) : null}
</div>
</PopoverPopup>
</Popover>
);
}
@@ -96,4 +96,48 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("lucide-terminal");
expect(markup).toContain("yoo what&#x27;s ");
});
it("renders context compaction entries in the normal work log", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
hasMessages
isWorking={false}
activeTurnInProgress={false}
activeTurnStartedAt={null}
scrollContainer={null}
timelineEntries={[
{
id: "entry-1",
kind: "work",
createdAt: "2026-03-17T19:12:28.000Z",
entry: {
id: "work-1",
createdAt: "2026-03-17T19:12:28.000Z",
label: "Context compacted",
tone: "info",
},
},
]}
completionDividerBeforeEntryId={null}
completionSummary={null}
turnDiffSummaryByAssistantMessageId={new Map()}
nowIso="2026-03-17T19:12:30.000Z"
expandedWorkGroups={{}}
onToggleWorkGroup={() => {}}
onOpenTurnDiff={() => {}}
revertTurnCountByUserMessageId={new Map()}
onRevertUserMessage={() => {}}
isRevertingCheckpoint={false}
onImageExpand={() => {}}
markdownCwd={undefined}
resolvedTheme="light"
timestampFormat="locale"
workspaceRoot={undefined}
/>,
);
expect(markup).toContain("Context compacted");
expect(markup).toContain("Work log");
});
});
@@ -23,10 +23,8 @@ describe("getComposerProviderState", () => {
model: "gpt-5.4",
prompt: "",
modelOptions: {
codex: {
reasoningEffort: "low",
fastMode: true,
},
reasoningEffort: "low",
fastMode: true,
},
});
@@ -34,10 +32,8 @@ describe("getComposerProviderState", () => {
provider: "codex",
promptEffort: "low",
modelOptionsForDispatch: {
codex: {
reasoningEffort: "low",
fastMode: true,
},
reasoningEffort: "low",
fastMode: true,
},
});
});
@@ -63,9 +59,7 @@ describe("getComposerProviderState", () => {
model: "claude-sonnet-4-6",
prompt: "Ultrathink:\nInvestigate this failure",
modelOptions: {
claudeAgent: {
effort: "medium",
},
effort: "medium",
},
});
@@ -73,9 +67,7 @@ describe("getComposerProviderState", () => {
provider: "claudeAgent",
promptEffort: "medium",
modelOptionsForDispatch: {
claudeAgent: {
effort: "medium",
},
effort: "medium",
},
composerFrameClassName: "ultrathink-frame",
composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]",
@@ -89,10 +81,8 @@ describe("getComposerProviderState", () => {
model: "claude-haiku-4-5",
prompt: "",
modelOptions: {
claudeAgent: {
effort: "max",
thinking: false,
},
effort: "max",
thinking: false,
},
});
@@ -100,50 +90,8 @@ describe("getComposerProviderState", () => {
provider: "claudeAgent",
promptEffort: null,
modelOptionsForDispatch: {
claudeAgent: {
thinking: false,
},
thinking: false,
},
});
});
it("ignores codex options while resolving Claude state", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
prompt: "",
modelOptions: {
codex: {
reasoningEffort: "low",
fastMode: true,
},
},
});
expect(state).toEqual({
provider: "claudeAgent",
promptEffort: "high",
modelOptionsForDispatch: undefined,
});
});
it("ignores Claude options while resolving codex state", () => {
const state = getComposerProviderState({
provider: "codex",
model: "gpt-5.4",
prompt: "Ultrathink:\nThis should not matter",
modelOptions: {
claudeAgent: {
effort: "max",
fastMode: true,
},
},
});
expect(state).toEqual({
provider: "codex",
promptEffort: "high",
modelOptionsForDispatch: undefined,
});
});
});
@@ -1,7 +1,9 @@
import {
type ClaudeModelOptions,
type CodexModelOptions,
type ModelSlug,
type ModelSelection,
type ProviderKind,
type ProviderModelOptions,
type ThreadId,
} from "@t3tools/contracts";
import {
@@ -21,13 +23,13 @@ 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 | undefined;
modelOptionsForDispatch: ModelSelection["options"] | undefined;
composerFrameClassName?: string;
composerSurfaceClassName?: string;
modelPickerIconClassName?: string;
@@ -47,20 +49,33 @@ type ProviderRegistryEntry = {
}) => ReactNode;
};
function asCodexModelOptions(
modelOptions: ModelSelection["options"] | null | undefined,
): CodexModelOptions | undefined {
return modelOptions && "reasoningEffort" in modelOptions ? modelOptions : undefined;
}
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: ({ modelOptions }) => {
const codexModelOptions = asCodexModelOptions(modelOptions);
const promptEffort =
resolveReasoningEffortForProvider("codex", modelOptions?.codex?.reasoningEffort) ??
resolveReasoningEffortForProvider("codex", codexModelOptions?.reasoningEffort) ??
getDefaultReasoningEffort("codex");
const normalizedCodexOptions = normalizeCodexModelOptions(modelOptions?.codex);
const normalizedCodexOptions = normalizeCodexModelOptions(codexModelOptions);
return {
provider: "codex",
promptEffort,
modelOptionsForDispatch: normalizedCodexOptions
? { codex: normalizedCodexOptions }
: undefined,
modelOptionsForDispatch: normalizedCodexOptions,
};
},
renderTraitsMenuContent: ({ threadId }) => <CodexTraitsMenuContent threadId={threadId} />,
@@ -68,10 +83,11 @@ const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
},
claudeAgent: {
getState: ({ model, prompt, modelOptions }) => {
const claudeModelOptions = asClaudeModelOptions(modelOptions);
const reasoningOptions = getReasoningEffortOptions("claudeAgent", model);
const draftEffort = resolveReasoningEffortForProvider(
"claudeAgent",
modelOptions?.claudeAgent?.effort,
claudeModelOptions?.effort,
);
const defaultEffort = getDefaultReasoningEffort("claudeAgent");
const promptEffort =
@@ -80,16 +96,14 @@ const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
: reasoningOptions.includes(defaultEffort)
? defaultEffort
: null;
const normalizedClaudeOptions = normalizeClaudeModelOptions(model, modelOptions?.claudeAgent);
const normalizedClaudeOptions = normalizeClaudeModelOptions(model, claudeModelOptions);
const ultrathinkActive =
supportsClaudeUltrathinkKeyword(model) && isClaudeUltrathinkPrompt(prompt);
return {
provider: "claudeAgent",
promptEffort,
modelOptionsForDispatch: normalizedClaudeOptions
? { claudeAgent: normalizedClaudeOptions }
: undefined,
modelOptionsForDispatch: normalizedClaudeOptions,
...(ultrathinkActive ? { composerFrameClassName: "ultrathink-frame" } : {}),
...(ultrathinkActive
? { composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]" }
+21
View File
@@ -738,6 +738,27 @@ describe("composerDraftStore modelSelection", () => {
);
});
it("creates the first sticky snapshot from provider option changes", () => {
const store = useComposerDraftStore.getState();
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.4"));
store.setProviderModelOptions(
threadId,
"codex",
{
fastMode: true,
},
{ persistSticky: true },
);
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
modelSelection("codex", "gpt-5.4", {
fastMode: true,
}),
);
});
it("updates only the draft when sticky persistence is disabled", () => {
const store = useComposerDraftStore.getState();
+1 -3
View File
@@ -1327,9 +1327,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
...(nextOptions ? { options: nextOptions } : {}),
};
const nextStickyModelSelection =
options?.persistSticky === true &&
state.stickyModelSelection?.provider === normalizedProvider &&
nextModelSelection !== null
options?.persistSticky === true && nextModelSelection !== null
? nextModelSelection
: state.stickyModelSelection;
+67
View File
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import { EventId, type OrchestrationThreadActivity, TurnId } from "@t3tools/contracts";
import { deriveLatestContextWindowSnapshot, formatContextWindowTokens } from "./contextWindow";
function makeActivity(id: string, kind: string, payload: unknown): OrchestrationThreadActivity {
return {
id: EventId.makeUnsafe(id),
tone: "info",
kind,
summary: kind,
payload,
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-03-23T00:00:00.000Z",
};
}
describe("contextWindow", () => {
it("derives the latest valid context window snapshot", () => {
const snapshot = deriveLatestContextWindowSnapshot([
makeActivity("activity-1", "context-window.updated", {
usedTokens: 1000,
}),
makeActivity("activity-2", "tool.started", {}),
makeActivity("activity-3", "context-window.updated", {
usedTokens: 14_000,
maxTokens: 258_000,
compactsAutomatically: true,
}),
]);
expect(snapshot).not.toBeNull();
expect(snapshot?.usedTokens).toBe(14_000);
expect(snapshot?.totalProcessedTokens).toBeNull();
expect(snapshot?.maxTokens).toBe(258_000);
expect(snapshot?.compactsAutomatically).toBe(true);
});
it("ignores malformed payloads", () => {
const snapshot = deriveLatestContextWindowSnapshot([
makeActivity("activity-1", "context-window.updated", {}),
]);
expect(snapshot).toBeNull();
});
it("formats compact token counts", () => {
expect(formatContextWindowTokens(999)).toBe("999");
expect(formatContextWindowTokens(1400)).toBe("1.4k");
expect(formatContextWindowTokens(14_000)).toBe("14k");
expect(formatContextWindowTokens(258_000)).toBe("258k");
});
it("includes total processed tokens when available", () => {
const snapshot = deriveLatestContextWindowSnapshot([
makeActivity("activity-1", "context-window.updated", {
usedTokens: 81_659,
totalProcessedTokens: 748_126,
maxTokens: 258_400,
lastUsedTokens: 81_659,
}),
]);
expect(snapshot?.usedTokens).toBe(81_659);
expect(snapshot?.totalProcessedTokens).toBe(748_126);
});
});
+90
View File
@@ -0,0 +1,90 @@
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
: ThreadTokenUsageSnapshot[Key];
};
export type ContextWindowSnapshot = NullableContextWindowUsage & {
readonly remainingTokens: number | null;
readonly usedPercentage: number | null;
readonly remainingPercentage: number | null;
readonly updatedAt: string;
};
export function deriveLatestContextWindowSnapshot(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ContextWindowSnapshot | null {
for (let index = activities.length - 1; index >= 0; index -= 1) {
const activity = activities[index];
if (!activity || activity.kind !== "context-window.updated") {
continue;
}
const payload = asRecord(activity.payload);
const usedTokens = asFiniteNumber(payload?.usedTokens);
if (usedTokens === null || usedTokens <= 0) {
continue;
}
const maxTokens = asFiniteNumber(payload?.maxTokens);
const usedPercentage =
maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null;
const remainingTokens =
maxTokens !== null ? Math.max(0, Math.round(maxTokens - usedTokens)) : null;
const remainingPercentage = usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null;
return {
usedTokens,
totalProcessedTokens: asFiniteNumber(payload?.totalProcessedTokens),
maxTokens,
remainingTokens,
usedPercentage,
remainingPercentage,
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,
};
}
return null;
}
export function formatContextWindowTokens(value: number | null): string {
if (value === null || !Number.isFinite(value)) {
return "0";
}
if (value < 1_000) {
return `${Math.round(value)}`;
}
if (value < 10_000) {
return `${(value / 1_000).toFixed(1).replace(/\.0$/, "")}k`;
}
if (value < 1_000_000) {
return `${Math.round(value / 1_000)}k`;
}
return `${(value / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
}
+45
View File
@@ -966,6 +966,51 @@ describe("deriveTimelineEntries", () => {
});
});
describe("deriveWorkLogEntries context window handling", () => {
it("excludes context window updates from the work log", () => {
const entries = deriveWorkLogEntries(
[
makeActivity({
id: "context-1",
turnId: "turn-1",
kind: "context-window.updated",
summary: "Context window updated",
tone: "info",
}),
makeActivity({
id: "tool-1",
turnId: "turn-1",
kind: "tool.completed",
summary: "Ran command",
tone: "tool",
}),
],
TurnId.makeUnsafe("turn-1"),
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Ran command");
});
it("keeps context compaction activities as normal work log entries", () => {
const entries = deriveWorkLogEntries(
[
makeActivity({
id: "compaction-1",
turnId: "turn-1",
kind: "context-compaction",
summary: "Context compacted",
tone: "info",
}),
],
TurnId.makeUnsafe("turn-1"),
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Context compacted");
});
});
describe("hasToolActivityForTurn", () => {
it("returns false when turn id is missing", () => {
const activities: OrchestrationThreadActivity[] = [
+1
View File
@@ -463,6 +463,7 @@ export function deriveWorkLogEntries(
.filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
.filter((activity) => activity.kind !== "tool.started")
.filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
.filter((activity) => activity.kind !== "context-window.updated")
.filter((activity) => activity.summary !== "Checkpoint captured")
.filter((activity) => !isPlanBoundaryToolActivity(activity))
.map(toDerivedWorkLogEntry);
+14
View File
@@ -256,6 +256,20 @@ describe("store read model sync", () => {
expect(next.threads[0]?.modelSelection.model).toBe("claude-sonnet-4-6");
});
it("preserves project and thread updatedAt timestamps from the read model", () => {
const initialState = makeState(makeThread());
const readModel = makeReadModel(
makeReadModelThread({
updatedAt: "2026-02-27T00:05:00.000Z",
}),
);
const next = syncServerReadModel(initialState, readModel);
expect(next.projects[0]?.updatedAt).toBe("2026-02-27T00:00:00.000Z");
expect(next.threads[0]?.updatedAt).toBe("2026-02-27T00:05:00.000Z");
});
it("preserves the current project order when syncing incoming read model updates", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
+3
View File
@@ -150,6 +150,8 @@ function mapProjectsFromReadModel(
(persistedExpandedProjectCwds.size > 0
? persistedExpandedProjectCwds.has(project.workspaceRoot)
: true),
createdAt: project.createdAt,
updatedAt: project.updatedAt,
scripts: project.scripts.map((script) => ({ ...script })),
} satisfies Project;
});
@@ -299,6 +301,7 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
})),
error: thread.session?.lastError ?? null,
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
latestTurn: thread.latestTurn,
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
branch: thread.branch,
+3
View File
@@ -83,6 +83,8 @@ export interface Project {
cwd: string;
defaultModelSelection: ModelSelection | null;
expanded: boolean;
createdAt?: string | undefined;
updatedAt?: string | undefined;
scripts: ProjectScript[];
}
@@ -99,6 +101,7 @@ export interface Thread {
proposedPlans: ProposedPlan[];
error: string | null;
createdAt: string;
updatedAt?: string | undefined;
latestTurn: OrchestrationLatestTurn | null;
lastVisitedAt?: string | undefined;
branch: string | null;
+7 -4
View File
@@ -14,7 +14,7 @@
},
"apps/desktop": {
"name": "@t3tools/desktop",
"version": "0.0.13",
"version": "0.0.14",
"dependencies": {
"effect": "catalog:",
"electron": "40.6.0",
@@ -43,7 +43,7 @@
},
"apps/server": {
"name": "t3",
"version": "0.0.13",
"version": "0.0.14",
"bin": {
"t3": "./dist/index.mjs",
},
@@ -73,13 +73,14 @@
},
"apps/web": {
"name": "@t3tools/web",
"version": "0.0.13",
"version": "0.0.14",
"dependencies": {
"@base-ui/react": "^1.2.0",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@formkit/auto-animate": "^0.9.0",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
@@ -123,7 +124,7 @@
},
"packages/contracts": {
"name": "@t3tools/contracts",
"version": "0.0.13",
"version": "0.0.14",
"dependencies": {
"effect": "catalog:",
},
@@ -358,6 +359,8 @@
"@floating-ui/utils": ["@floating-ui/[email protected]", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="],
"@formkit/auto-animate": ["@formkit/[email protected]", "", {}, "sha512-VhP4zEAacXS3dfTpJpJ88QdLqMTcabMg0jwpOSxZ/VzfQVfl3GkZSCZThhGC5uhq/TxPHPzW0dzr4H9Bb1OgKA=="],
"@hapi/address": ["@hapi/[email protected]", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-A+po2d/dVoY7cYajycYI43ZbYMXukuopIsqCjh5QzsBCipDtdofHntljDlpccMjIfTy6UOkg+5KPriwYch2bXA=="],
"@hapi/formula": ["@hapi/[email protected]", "", {}, "sha512-hY5YPNXzw1He7s0iqkRQi+uMGh383CGdyyIGYtB+W5N3KHPXoqychklvHhKCC9M3Xtv0OCs/IHw+r4dcHtBYWw=="],
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.13",
"version": "0.0.14",
"private": true,
"files": [
"dist"
+1 -1
View File
@@ -133,7 +133,7 @@ function normalizeLegacyThreadModelSelection(
return Effect.succeed(input.modelSelection);
}
if (input.model === undefined) {
return Effect.succeed(undefined);
return Effect.succeed<ModelSelection | undefined>(undefined);
}
return Effect.try({
try: () =>
+46 -24
View File
@@ -12,9 +12,10 @@ describe("ProviderSessionStartInput", () => {
threadId: "thread-1",
provider: "codex",
cwd: "/tmp/workspace",
model: "gpt-5.3-codex",
modelOptions: {
codex: {
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "high",
fastMode: true,
},
@@ -28,8 +29,13 @@ describe("ProviderSessionStartInput", () => {
},
});
expect(parsed.runtimeMode).toBe("full-access");
expect(parsed.modelOptions?.codex?.reasoningEffort).toBe("high");
expect(parsed.modelOptions?.codex?.fastMode).toBe(true);
expect(parsed.modelSelection?.provider).toBe("codex");
expect(parsed.modelSelection?.model).toBe("gpt-5.3-codex");
if (parsed.modelSelection?.provider !== "codex") {
throw new Error("Expected codex modelSelection");
}
expect(parsed.modelSelection.options?.reasoningEffort).toBe("high");
expect(parsed.modelSelection.options?.fastMode).toBe(true);
expect(parsed.providerOptions?.codex?.binaryPath).toBe("/usr/local/bin/codex");
expect(parsed.providerOptions?.codex?.homePath).toBe("/tmp/.codex");
});
@@ -48,9 +54,10 @@ describe("ProviderSessionStartInput", () => {
threadId: "thread-1",
provider: "claudeAgent",
cwd: "/tmp/workspace",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
thinking: true,
effort: "max",
fastMode: true,
@@ -66,9 +73,14 @@ describe("ProviderSessionStartInput", () => {
runtimeMode: "full-access",
});
expect(parsed.provider).toBe("claudeAgent");
expect(parsed.modelOptions?.claudeAgent?.thinking).toBe(true);
expect(parsed.modelOptions?.claudeAgent?.effort).toBe("max");
expect(parsed.modelOptions?.claudeAgent?.fastMode).toBe(true);
expect(parsed.modelSelection?.provider).toBe("claudeAgent");
expect(parsed.modelSelection?.model).toBe("claude-sonnet-4-6");
if (parsed.modelSelection?.provider !== "claudeAgent") {
throw new Error("Expected claude modelSelection");
}
expect(parsed.modelSelection.options?.thinking).toBe(true);
expect(parsed.modelSelection.options?.effort).toBe("max");
expect(parsed.modelSelection.options?.fastMode).toBe(true);
expect(parsed.providerOptions?.claudeAgent?.binaryPath).toBe("/usr/local/bin/claude");
expect(parsed.providerOptions?.claudeAgent?.permissionMode).toBe("plan");
expect(parsed.providerOptions?.claudeAgent?.maxThinkingTokens).toBe(12_000);
@@ -77,36 +89,46 @@ describe("ProviderSessionStartInput", () => {
});
describe("ProviderSendTurnInput", () => {
it("accepts provider-scoped model options", () => {
it("accepts codex modelSelection", () => {
const parsed = decodeProviderSendTurnInput({
threadId: "thread-1",
model: "gpt-5.3-codex",
modelOptions: {
codex: {
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "xhigh",
fastMode: true,
},
},
});
expect(parsed.model).toBe("gpt-5.3-codex");
expect(parsed.modelOptions?.codex?.reasoningEffort).toBe("xhigh");
expect(parsed.modelOptions?.codex?.fastMode).toBe(true);
expect(parsed.modelSelection?.provider).toBe("codex");
expect(parsed.modelSelection?.model).toBe("gpt-5.3-codex");
if (parsed.modelSelection?.provider !== "codex") {
throw new Error("Expected codex modelSelection");
}
expect(parsed.modelSelection.options?.reasoningEffort).toBe("xhigh");
expect(parsed.modelSelection.options?.fastMode).toBe(true);
});
it("accepts claude provider effort options including ultrathink", () => {
it("accepts claude modelSelection including ultrathink", () => {
const parsed = decodeProviderSendTurnInput({
threadId: "thread-1",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "ultrathink",
fastMode: true,
},
},
});
expect(parsed.modelOptions?.claudeAgent?.effort).toBe("ultrathink");
expect(parsed.modelOptions?.claudeAgent?.fastMode).toBe(true);
expect(parsed.modelSelection?.provider).toBe("claudeAgent");
if (parsed.modelSelection?.provider !== "claudeAgent") {
throw new Error("Expected claude modelSelection");
}
expect(parsed.modelSelection.options?.effort).toBe("ultrathink");
expect(parsed.modelSelection.options?.fastMode).toBe(true);
});
});
+3 -5
View File
@@ -1,6 +1,5 @@
import { Schema } from "effect";
import { TrimmedNonEmptyString } from "./baseSchemas";
import { ProviderModelOptions } from "./model";
import {
ApprovalRequestId,
EventId,
@@ -11,6 +10,7 @@ import {
} from "./baseSchemas";
import {
ChatAttachment,
ModelSelection,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
ProviderApprovalDecision,
@@ -51,8 +51,7 @@ export const ProviderSessionStartInput = Schema.Struct({
threadId: ThreadId,
provider: Schema.optional(ProviderKind),
cwd: Schema.optional(TrimmedNonEmptyString),
model: Schema.optional(TrimmedNonEmptyString),
modelOptions: Schema.optional(ProviderModelOptions),
modelSelection: Schema.optional(ModelSelection),
resumeCursor: Schema.optional(Schema.Unknown),
approvalPolicy: Schema.optional(ProviderApprovalPolicy),
sandboxMode: Schema.optional(ProviderSandboxMode),
@@ -69,8 +68,7 @@ export const ProviderSendTurnInput = Schema.Struct({
attachments: Schema.optional(
Schema.Array(ChatAttachment).check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS)),
),
model: Schema.optional(TrimmedNonEmptyString),
modelOptions: Schema.optional(ProviderModelOptions),
modelSelection: Schema.optional(ModelSelection),
interactionMode: Schema.optional(ProviderInteractionMode),
});
export type ProviderSendTurnInput = typeof ProviderSendTurnInput.Type;
@@ -139,4 +139,29 @@ describe("ProviderRuntimeEvent", () => {
}),
).toThrow();
});
it("decodes normalized thread token usage snapshots", () => {
const parsed = decodeRuntimeEvent({
type: "thread.token-usage.updated",
eventId: "event-token-usage-1",
provider: "claudeAgent",
createdAt: "2026-02-28T00:00:04.000Z",
threadId: "thread-1",
payload: {
usage: {
usedTokens: 31251,
maxTokens: 200000,
toolUses: 25,
durationMs: 43567,
},
},
});
expect(parsed.type).toBe("thread.token-usage.updated");
if (parsed.type !== "thread.token-usage.updated") {
throw new Error("expected thread.token-usage.updated");
}
expect(parsed.payload.usage.maxTokens).toBe(200000);
expect(parsed.payload.usage.usedTokens).toBe(31251);
});
});
+22 -1
View File
@@ -2,7 +2,9 @@ import { Option, Schema } from "effect";
import {
EventId,
IsoDateTime,
NonNegativeInt,
ProviderItemId,
PositiveInt,
RuntimeItemId,
RuntimeRequestId,
RuntimeTaskId,
@@ -293,8 +295,27 @@ const ThreadMetadataUpdatedPayload = Schema.Struct({
});
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: Schema.Unknown,
usage: ThreadTokenUsageSnapshot,
});
export type ThreadTokenUsageUpdatedPayload = typeof ThreadTokenUsageUpdatedPayload.Type;