Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63ff52e33a |
No files matched your search
@@ -308,31 +308,11 @@ jobs:
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ vars.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
persist-credentials: true
|
||||
|
||||
- id: app_bot
|
||||
name: Resolve GitHub App bot identity
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app_token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.app_token.outputs.app-slug }}
|
||||
run: |
|
||||
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
|
||||
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
|
||||
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -369,8 +349,8 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "${{ steps.app_bot.outputs.name }}"
|
||||
git config user.email "${{ steps.app_bot.outputs.email }}"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
|
||||
@@ -17,4 +17,3 @@ release/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
@@ -3,7 +3,6 @@ import { randomUUID } from "node:crypto";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
@@ -18,6 +17,7 @@ import {
|
||||
TextGeneration,
|
||||
} from "../Services/TextGeneration.ts";
|
||||
|
||||
const CODEX_MODEL = "gpt-5.3-codex";
|
||||
const CODEX_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
|
||||
@@ -187,7 +187,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
outputSchemaJson,
|
||||
imagePaths = [],
|
||||
cleanupPaths = [],
|
||||
model,
|
||||
}: {
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
cwd: string;
|
||||
@@ -195,7 +194,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
outputSchemaJson: S;
|
||||
imagePaths?: ReadonlyArray<string>;
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
model?: string;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
@@ -214,7 +212,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
model ?? DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
@@ -355,7 +353,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
@@ -401,7 +398,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
title: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
@@ -453,7 +449,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
branch: Schema.String,
|
||||
}),
|
||||
imagePaths,
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -639,7 +639,6 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
filePaths?: readonly string[];
|
||||
model?: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
|
||||
@@ -666,7 +665,6 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
...(input.includeBranch ? { includeBranch: true } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
|
||||
@@ -684,7 +682,6 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
commitMessage?: string,
|
||||
preResolvedSuggestion?: CommitAndBranchSuggestion,
|
||||
filePaths?: readonly string[],
|
||||
model?: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion =
|
||||
@@ -694,7 +691,6 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(model ? { model } : {}),
|
||||
}));
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
@@ -708,7 +704,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const runPrStep = (cwd: string, fallbackBranch: string | null, model?: string) =>
|
||||
const runPrStep = (cwd: string, fallbackBranch: string | null) =>
|
||||
Effect.gen(function* () {
|
||||
const details = yield* gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
@@ -752,7 +748,6 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
|
||||
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
|
||||
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
|
||||
...(model ? { model } : {}),
|
||||
});
|
||||
|
||||
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
|
||||
@@ -977,7 +972,6 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
filePaths?: readonly string[],
|
||||
model?: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion = yield* resolveCommitAndBranchSuggestion({
|
||||
@@ -986,7 +980,6 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
includeBranch: true,
|
||||
...(model ? { model } : {}),
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* gitManagerError(
|
||||
@@ -1035,7 +1028,6 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
@@ -1052,7 +1044,6 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
);
|
||||
|
||||
const push = wantsPush
|
||||
@@ -1060,7 +1051,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel)
|
||||
? yield* runPrStep(input.cwd, currentBranch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return {
|
||||
|
||||
@@ -19,8 +19,6 @@ export interface CommitMessageGenerationInput {
|
||||
stagedPatch: string;
|
||||
/** When true, the model also returns a semantic branch name for the change. */
|
||||
includeBranch?: boolean;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
}
|
||||
|
||||
export interface CommitMessageGenerationResult {
|
||||
@@ -37,8 +35,6 @@ export interface PrContentGenerationInput {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationResult {
|
||||
@@ -50,8 +46,6 @@ export interface BranchNameGenerationInput {
|
||||
cwd: string;
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
}
|
||||
|
||||
export interface BranchNameGenerationResult {
|
||||
|
||||
@@ -1729,8 +1729,6 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
const threadId = ThreadId.makeUnsafe("thread-restart");
|
||||
const turnId = TurnId.makeUnsafe("turn-restart");
|
||||
const messageId = MessageId.makeUnsafe("message-restart");
|
||||
const sourcePlanThreadId = ThreadId.makeUnsafe("thread-plan-source");
|
||||
const sourcePlanId = "plan-source";
|
||||
const turnStartedAt = "2026-02-26T14:00:00.000Z";
|
||||
const sessionSetAt = "2026-02-26T14:00:05.000Z";
|
||||
|
||||
@@ -1751,10 +1749,6 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
payload: {
|
||||
threadId,
|
||||
messageId,
|
||||
sourceProposedPlan: {
|
||||
threadId: sourcePlanThreadId,
|
||||
planId: sourcePlanId,
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: turnStartedAt,
|
||||
},
|
||||
@@ -1806,15 +1800,11 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
return yield* sql<{
|
||||
readonly turnId: string;
|
||||
readonly userMessageId: string | null;
|
||||
readonly sourceProposedPlanThreadId: string | null;
|
||||
readonly sourceProposedPlanId: string | null;
|
||||
readonly startedAt: string;
|
||||
}>`
|
||||
SELECT
|
||||
turn_id AS "turnId",
|
||||
pending_message_id AS "userMessageId",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId",
|
||||
started_at AS "startedAt"
|
||||
FROM projection_turns
|
||||
WHERE turn_id = ${turnId}
|
||||
@@ -1825,8 +1815,6 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
{
|
||||
turnId: "turn-restart",
|
||||
userMessageId: "message-restart",
|
||||
sourceProposedPlanThreadId: "thread-plan-source",
|
||||
sourceProposedPlanId: "plan-source",
|
||||
startedAt: turnStartedAt,
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -653,8 +653,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.proposedPlan.turnId,
|
||||
planMarkdown: event.payload.proposedPlan.planMarkdown,
|
||||
implementedAt: event.payload.proposedPlan.implementedAt,
|
||||
implementationThreadId: event.payload.proposedPlan.implementationThreadId,
|
||||
createdAt: event.payload.proposedPlan.createdAt,
|
||||
updatedAt: event.payload.proposedPlan.updatedAt,
|
||||
});
|
||||
@@ -777,8 +775,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
yield* projectionTurnRepository.replacePendingTurnStart({
|
||||
threadId: event.payload.threadId,
|
||||
messageId: event.payload.messageId,
|
||||
sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null,
|
||||
sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null,
|
||||
requestedAt: event.payload.createdAt,
|
||||
});
|
||||
return;
|
||||
@@ -808,16 +804,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
pendingMessageId:
|
||||
existingTurn.value.pendingMessageId ??
|
||||
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),
|
||||
sourceProposedPlanThreadId:
|
||||
existingTurn.value.sourceProposedPlanThreadId ??
|
||||
(Option.isSome(pendingTurnStart)
|
||||
? pendingTurnStart.value.sourceProposedPlanThreadId
|
||||
: null),
|
||||
sourceProposedPlanId:
|
||||
existingTurn.value.sourceProposedPlanId ??
|
||||
(Option.isSome(pendingTurnStart)
|
||||
? pendingTurnStart.value.sourceProposedPlanId
|
||||
: null),
|
||||
startedAt:
|
||||
existingTurn.value.startedAt ??
|
||||
(Option.isSome(pendingTurnStart)
|
||||
@@ -836,12 +822,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
pendingMessageId: Option.isSome(pendingTurnStart)
|
||||
? pendingTurnStart.value.messageId
|
||||
: null,
|
||||
sourceProposedPlanThreadId: Option.isSome(pendingTurnStart)
|
||||
? pendingTurnStart.value.sourceProposedPlanThreadId
|
||||
: null,
|
||||
sourceProposedPlanId: Option.isSome(pendingTurnStart)
|
||||
? pendingTurnStart.value.sourceProposedPlanId
|
||||
: null,
|
||||
assistantMessageId: null,
|
||||
state: "running",
|
||||
requestedAt: Option.isSome(pendingTurnStart)
|
||||
@@ -895,8 +875,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
turnId: event.payload.turnId,
|
||||
threadId: event.payload.threadId,
|
||||
pendingMessageId: null,
|
||||
sourceProposedPlanThreadId: null,
|
||||
sourceProposedPlanId: null,
|
||||
assistantMessageId: event.payload.messageId,
|
||||
state: event.payload.streaming ? "running" : "completed",
|
||||
requestedAt: event.payload.createdAt,
|
||||
@@ -932,8 +910,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
turnId: event.payload.turnId,
|
||||
threadId: event.payload.threadId,
|
||||
pendingMessageId: null,
|
||||
sourceProposedPlanThreadId: null,
|
||||
sourceProposedPlanId: null,
|
||||
assistantMessageId: null,
|
||||
state: "interrupted",
|
||||
requestedAt: event.payload.createdAt,
|
||||
@@ -978,8 +954,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
turnId: event.payload.turnId,
|
||||
threadId: event.payload.threadId,
|
||||
pendingMessageId: null,
|
||||
sourceProposedPlanThreadId: null,
|
||||
sourceProposedPlanId: null,
|
||||
assistantMessageId: event.payload.assistantMessageId,
|
||||
state: nextState,
|
||||
requestedAt: event.payload.completedAt,
|
||||
|
||||
@@ -26,7 +26,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
yield* sql`DELETE FROM projection_thread_proposed_plans`;
|
||||
yield* sql`DELETE FROM projection_turns`;
|
||||
|
||||
yield* sql`
|
||||
@@ -102,29 +101,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_proposed_plans (
|
||||
plan_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
plan_markdown,
|
||||
implemented_at,
|
||||
implementation_thread_id,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
'plan-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'# Ship it',
|
||||
'2026-02-24T00:00:05.500Z',
|
||||
'thread-2',
|
||||
'2026-02-24T00:00:05.000Z',
|
||||
'2026-02-24T00:00:05.500Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id,
|
||||
@@ -178,8 +154,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
thread_id,
|
||||
turn_id,
|
||||
pending_message_id,
|
||||
source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id,
|
||||
assistant_message_id,
|
||||
state,
|
||||
requested_at,
|
||||
@@ -194,8 +168,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'thread-1',
|
||||
'plan-1',
|
||||
'message-1',
|
||||
'completed',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
@@ -266,10 +238,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
startedAt: "2026-02-24T00:00:08.000Z",
|
||||
completedAt: "2026-02-24T00:00:08.000Z",
|
||||
assistantMessageId: asMessageId("message-1"),
|
||||
sourceProposedPlan: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
planId: "plan-1",
|
||||
},
|
||||
},
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
@@ -285,17 +253,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
updatedAt: "2026-02-24T00:00:05.000Z",
|
||||
},
|
||||
],
|
||||
proposedPlans: [
|
||||
{
|
||||
id: "plan-1",
|
||||
turnId: asTurnId("turn-1"),
|
||||
planMarkdown: "# Ship it",
|
||||
implementedAt: "2026-02-24T00:00:05.500Z",
|
||||
implementationThreadId: ThreadId.makeUnsafe("thread-2"),
|
||||
createdAt: "2026-02-24T00:00:05.000Z",
|
||||
updatedAt: "2026-02-24T00:00:05.500Z",
|
||||
},
|
||||
],
|
||||
proposedPlans: [],
|
||||
activities: [
|
||||
{
|
||||
id: asEventId("activity-1"),
|
||||
|
||||
@@ -4,10 +4,8 @@ import {
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationReadModel,
|
||||
ProjectScript,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationLatestTurn,
|
||||
@@ -76,8 +74,6 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
|
||||
startedAt: Schema.NullOr(IsoDateTime),
|
||||
completedAt: Schema.NullOr(IsoDateTime),
|
||||
assistantMessageId: Schema.NullOr(MessageId),
|
||||
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
|
||||
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
|
||||
});
|
||||
const ProjectionStateDbRowSchema = ProjectionState;
|
||||
|
||||
@@ -204,8 +200,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
plan_markdown AS "planMarkdown",
|
||||
implemented_at AS "implementedAt",
|
||||
implementation_thread_id AS "implementationThreadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_proposed_plans
|
||||
@@ -290,9 +284,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
requested_at AS "requestedAt",
|
||||
started_at AS "startedAt",
|
||||
completed_at AS "completedAt",
|
||||
assistant_message_id AS "assistantMessageId",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
assistant_message_id AS "assistantMessageId"
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NOT NULL
|
||||
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
||||
@@ -443,8 +435,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
id: row.planId,
|
||||
turnId: row.turnId,
|
||||
planMarkdown: row.planMarkdown,
|
||||
implementedAt: row.implementedAt,
|
||||
implementationThreadId: row.implementationThreadId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
});
|
||||
@@ -507,14 +497,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
startedAt: row.startedAt,
|
||||
completedAt: row.completedAt,
|
||||
assistantMessageId: row.assistantMessageId,
|
||||
...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
|
||||
? {
|
||||
sourceProposedPlan: {
|
||||
threadId: row.sourceProposedPlanThreadId,
|
||||
planId: row.sourceProposedPlanId,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
type ChatAttachment,
|
||||
CommandId,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderModelOptions,
|
||||
@@ -312,7 +311,7 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const resumeCursor =
|
||||
providerChanged || shouldRestartForModelChange || shouldRestartForModelOptionsChange
|
||||
providerChanged || shouldRestartForModelChange
|
||||
? undefined
|
||||
: (activeSession?.resumeCursor ?? undefined);
|
||||
yield* Effect.logInfo("provider command reactor restarting provider session", {
|
||||
@@ -434,7 +433,6 @@ const make = Effect.gen(function* () {
|
||||
cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
|
||||
@@ -6,7 +6,6 @@ import type {
|
||||
OrchestrationReadModel,
|
||||
ProviderKind,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSession,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -62,7 +61,6 @@ type LegacyProviderRuntimeEvent = {
|
||||
|
||||
function createProviderServiceHarness() {
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const runtimeSessions: ProviderSession[] = [];
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
const service: ProviderServiceShape = {
|
||||
@@ -72,21 +70,12 @@ function createProviderServiceHarness() {
|
||||
respondToRequest: () => unsupported(),
|
||||
respondToUserInput: () => unsupported(),
|
||||
stopSession: () => unsupported(),
|
||||
listSessions: () => Effect.succeed([...runtimeSessions]),
|
||||
listSessions: () => Effect.succeed([]),
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
const setSession = (session: ProviderSession): void => {
|
||||
const existingIndex = runtimeSessions.findIndex((entry) => entry.threadId === session.threadId);
|
||||
if (existingIndex >= 0) {
|
||||
runtimeSessions[existingIndex] = session;
|
||||
return;
|
||||
}
|
||||
runtimeSessions.push(session);
|
||||
};
|
||||
|
||||
const emit = (event: LegacyProviderRuntimeEvent): void => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
|
||||
};
|
||||
@@ -94,7 +83,6 @@ function createProviderServiceHarness() {
|
||||
return {
|
||||
service,
|
||||
emit,
|
||||
setSession,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -102,12 +90,11 @@ async function waitForThread(
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (thread: ProviderRuntimeTestThread) => boolean,
|
||||
timeoutMs = 2000,
|
||||
threadId: ThreadId = asThreadId("thread-1"),
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<ProviderRuntimeTestThread> => {
|
||||
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
@@ -167,7 +154,6 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
const layer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -223,19 +209,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
provider.setSession({
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
runtimeMode: "approval-required",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
});
|
||||
|
||||
return {
|
||||
engine,
|
||||
emit: provider.emit,
|
||||
setProviderSession: provider.setSession,
|
||||
drain,
|
||||
};
|
||||
}
|
||||
@@ -709,496 +686,6 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("marks the source proposed plan implemented only after the target turn starts", async () => {
|
||||
const harness = await createHarness();
|
||||
const sourceThreadId = asThreadId("thread-plan");
|
||||
const targetThreadId = asThreadId("thread-implement");
|
||||
const sourceTurnId = asTurnId("turn-plan-source");
|
||||
const targetTurnId = asTurnId("turn-plan-implement");
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source"),
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
threadId: sourceThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target"),
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target"),
|
||||
threadId: targetThreadId,
|
||||
session: {
|
||||
threadId: targetThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
harness.setProviderSession({
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
runtimeMode: "approval-required",
|
||||
threadId: targetThreadId,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
activeTurnId: targetTurnId,
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "turn.proposed.completed",
|
||||
eventId: asEventId("evt-plan-source-completed"),
|
||||
provider: "codex",
|
||||
createdAt,
|
||||
threadId: sourceThreadId,
|
||||
turnId: sourceTurnId,
|
||||
payload: {
|
||||
planMarkdown: "# Source plan",
|
||||
},
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
|
||||
proposedPlan.implementedAt === null,
|
||||
),
|
||||
2_000,
|
||||
sourceThreadId,
|
||||
);
|
||||
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
|
||||
(entry: ProviderRuntimeTestProposedPlan) =>
|
||||
entry.id === "plan:thread-plan:turn:turn-plan-source",
|
||||
);
|
||||
expect(sourcePlan).toBeDefined();
|
||||
if (!sourcePlan) {
|
||||
throw new Error("Expected source plan to exist.");
|
||||
}
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target"),
|
||||
threadId: targetThreadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-plan-target"),
|
||||
role: "user",
|
||||
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
|
||||
attachments: [],
|
||||
},
|
||||
sourceProposedPlan: {
|
||||
threadId: sourceThreadId,
|
||||
planId: sourcePlan.id,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
|
||||
const sourceThreadBeforeStart = await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === sourcePlan.id && proposedPlan.implementedAt === null,
|
||||
),
|
||||
2_000,
|
||||
sourceThreadId,
|
||||
);
|
||||
expect(
|
||||
sourceThreadBeforeStart.proposedPlans.find((entry) => entry.id === sourcePlan.id),
|
||||
).toMatchObject({
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-plan-target-started"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: targetThreadId,
|
||||
turnId: targetTurnId,
|
||||
});
|
||||
|
||||
const sourceThreadAfterStart = await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === sourcePlan.id &&
|
||||
proposedPlan.implementedAt !== null &&
|
||||
proposedPlan.implementationThreadId === targetThreadId,
|
||||
),
|
||||
2_000,
|
||||
sourceThreadId,
|
||||
);
|
||||
expect(
|
||||
sourceThreadAfterStart.proposedPlans.find((entry) => entry.id === sourcePlan.id),
|
||||
).toMatchObject({
|
||||
implementationThreadId: "thread-implement",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not mark the source proposed plan implemented for a rejected turn.started event", async () => {
|
||||
const harness = await createHarness();
|
||||
const sourceThreadId = asThreadId("thread-plan");
|
||||
const targetThreadId = asThreadId("thread-1");
|
||||
const sourceTurnId = asTurnId("turn-plan-source");
|
||||
const activeTurnId = asTurnId("turn-already-running");
|
||||
const staleTurnId = asTurnId("turn-stale-start");
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
threadId: sourceThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
harness.setProviderSession({
|
||||
provider: "codex",
|
||||
status: "running",
|
||||
runtimeMode: "approval-required",
|
||||
threadId: targetThreadId,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
activeTurnId,
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-already-running"),
|
||||
provider: "codex",
|
||||
createdAt,
|
||||
threadId: targetThreadId,
|
||||
turnId: activeTurnId,
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === activeTurnId,
|
||||
2_000,
|
||||
targetThreadId,
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.proposed.completed",
|
||||
eventId: asEventId("evt-plan-source-completed-guarded"),
|
||||
provider: "codex",
|
||||
createdAt,
|
||||
threadId: sourceThreadId,
|
||||
turnId: sourceTurnId,
|
||||
payload: {
|
||||
planMarkdown: "# Source plan",
|
||||
},
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
|
||||
proposedPlan.implementedAt === null,
|
||||
),
|
||||
2_000,
|
||||
sourceThreadId,
|
||||
);
|
||||
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
|
||||
(entry: ProviderRuntimeTestProposedPlan) =>
|
||||
entry.id === "plan:thread-plan:turn:turn-plan-source",
|
||||
);
|
||||
expect(sourcePlan).toBeDefined();
|
||||
if (!sourcePlan) {
|
||||
throw new Error("Expected source plan to exist.");
|
||||
}
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-guarded"),
|
||||
threadId: targetThreadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-plan-target-guarded"),
|
||||
role: "user",
|
||||
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
|
||||
attachments: [],
|
||||
},
|
||||
sourceProposedPlan: {
|
||||
threadId: sourceThreadId,
|
||||
planId: sourcePlan.id,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-stale-plan-implementation"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: targetThreadId,
|
||||
turnId: staleTurnId,
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const sourceThreadAfterRejectedStart = readModel.threads.find(
|
||||
(entry) => entry.id === sourceThreadId,
|
||||
);
|
||||
expect(
|
||||
sourceThreadAfterRejectedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id),
|
||||
).toMatchObject({
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
});
|
||||
|
||||
const targetThreadAfterRejectedStart = readModel.threads.find(
|
||||
(entry) => entry.id === targetThreadId,
|
||||
);
|
||||
expect(targetThreadAfterRejectedStart?.session?.status).toBe("running");
|
||||
expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId);
|
||||
});
|
||||
|
||||
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
|
||||
const harness = await createHarness();
|
||||
const sourceThreadId = asThreadId("thread-plan");
|
||||
const targetThreadId = asThreadId("thread-implement");
|
||||
const sourceTurnId = asTurnId("turn-plan-source");
|
||||
const expectedTurnId = asTurnId("turn-plan-implement");
|
||||
const replayedTurnId = asTurnId("turn-replayed");
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-unrelated"),
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-unrelated"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
threadId: sourceThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target-unrelated"),
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target-unrelated"),
|
||||
threadId: targetThreadId,
|
||||
session: {
|
||||
threadId: targetThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.proposed.completed",
|
||||
eventId: asEventId("evt-plan-source-completed-unrelated"),
|
||||
provider: "codex",
|
||||
createdAt,
|
||||
threadId: sourceThreadId,
|
||||
turnId: sourceTurnId,
|
||||
payload: {
|
||||
planMarkdown: "# Source plan",
|
||||
},
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
|
||||
proposedPlan.implementedAt === null,
|
||||
),
|
||||
2_000,
|
||||
sourceThreadId,
|
||||
);
|
||||
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
|
||||
(entry: ProviderRuntimeTestProposedPlan) =>
|
||||
entry.id === "plan:thread-plan:turn:turn-plan-source",
|
||||
);
|
||||
expect(sourcePlan).toBeDefined();
|
||||
if (!sourcePlan) {
|
||||
throw new Error("Expected source plan to exist.");
|
||||
}
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-unrelated"),
|
||||
threadId: targetThreadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-plan-target-unrelated"),
|
||||
role: "user",
|
||||
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
|
||||
attachments: [],
|
||||
},
|
||||
sourceProposedPlan: {
|
||||
threadId: sourceThreadId,
|
||||
planId: sourcePlan.id,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
|
||||
harness.setProviderSession({
|
||||
provider: "codex",
|
||||
status: "running",
|
||||
runtimeMode: "approval-required",
|
||||
threadId: targetThreadId,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
activeTurnId: expectedTurnId,
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-unrelated-plan-implementation"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: targetThreadId,
|
||||
turnId: replayedTurnId,
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const sourceThreadAfterUnrelatedStart = readModel.threads.find(
|
||||
(entry) => entry.id === sourceThreadId,
|
||||
);
|
||||
expect(
|
||||
sourceThreadAfterUnrelatedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id),
|
||||
).toMatchObject({
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("finalizes buffered proposed-plan deltas into a first-class proposed plan on turn completion", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationProposedPlanId,
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
ThreadId,
|
||||
@@ -16,8 +15,6 @@ import { Cache, Cause, Duration, Effect, Layer, Option, Ref, Stream } from "effe
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { isGitRepository } from "../../git/isRepo.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
@@ -484,7 +481,6 @@ function runtimeEventToActivities(
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
|
||||
const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
|
||||
DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
@@ -676,8 +672,6 @@ const make = Effect.gen(function* () {
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
@@ -700,8 +694,6 @@ const make = Effect.gen(function* () {
|
||||
id: input.planId,
|
||||
turnId: input.turnId ?? null,
|
||||
planMarkdown,
|
||||
implementedAt: existingPlan?.implementedAt ?? null,
|
||||
implementationThreadId: existingPlan?.implementationThreadId ?? null,
|
||||
createdAt: existingPlan?.createdAt ?? input.createdAt,
|
||||
updatedAt: input.updatedAt,
|
||||
},
|
||||
@@ -715,8 +707,6 @@ const make = Effect.gen(function* () {
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
@@ -783,79 +773,6 @@ const make = Effect.gen(function* () {
|
||||
).pipe(Effect.asVoid);
|
||||
});
|
||||
|
||||
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* (
|
||||
threadId: ThreadId,
|
||||
) {
|
||||
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
|
||||
threadId,
|
||||
});
|
||||
if (Option.isNone(pendingTurnStart)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sourceThreadId = pendingTurnStart.value.sourceProposedPlanThreadId;
|
||||
const sourcePlanId = pendingTurnStart.value.sourceProposedPlanId;
|
||||
if (sourceThreadId === null || sourcePlanId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
sourceThreadId,
|
||||
sourcePlanId,
|
||||
} as const;
|
||||
});
|
||||
|
||||
const getExpectedProviderTurnIdForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
|
||||
const sessions = yield* providerService.listSessions();
|
||||
const session = sessions.find((entry) => entry.threadId === threadId);
|
||||
return session?.activeTurnId;
|
||||
});
|
||||
|
||||
const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fnUntraced(function* (
|
||||
threadId: ThreadId,
|
||||
eventTurnId: TurnId | undefined,
|
||||
) {
|
||||
if (eventTurnId === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const expectedTurnId = yield* getExpectedProviderTurnIdForThread(threadId);
|
||||
if (!sameId(expectedTurnId, eventTurnId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId);
|
||||
});
|
||||
|
||||
const markSourceProposedPlanImplemented = Effect.fnUntraced(function* (
|
||||
sourceThreadId: ThreadId,
|
||||
sourcePlanId: OrchestrationProposedPlanId,
|
||||
implementationThreadId: ThreadId,
|
||||
implementedAt: string,
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
|
||||
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
|
||||
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.proposed-plan.upsert",
|
||||
commandId: CommandId.makeUnsafe(
|
||||
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
|
||||
),
|
||||
threadId: sourceThread.id,
|
||||
proposedPlan: {
|
||||
...sourcePlan,
|
||||
implementedAt,
|
||||
implementationThreadId,
|
||||
updatedAt: implementedAt,
|
||||
},
|
||||
createdAt: implementedAt,
|
||||
});
|
||||
});
|
||||
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -896,10 +813,6 @@ const make = Effect.gen(function* () {
|
||||
return true;
|
||||
}
|
||||
})();
|
||||
const acceptedTurnStartedSourcePlan =
|
||||
event.type === "turn.started" && shouldApplyThreadLifecycle
|
||||
? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)
|
||||
: null;
|
||||
|
||||
if (
|
||||
event.type === "session.started" ||
|
||||
@@ -942,26 +855,6 @@ const make = Effect.gen(function* () {
|
||||
: (thread.session?.lastError ?? null);
|
||||
|
||||
if (shouldApplyThreadLifecycle) {
|
||||
if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) {
|
||||
yield* markSourceProposedPlanImplemented(
|
||||
acceptedTurnStartedSourcePlan.sourceThreadId,
|
||||
acceptedTurnStartedSourcePlan.sourcePlanId,
|
||||
thread.id,
|
||||
now,
|
||||
).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning(
|
||||
"provider runtime ingestion failed to mark source proposed plan",
|
||||
{
|
||||
eventId: event.eventId,
|
||||
eventType: event.type,
|
||||
cause: Cause.pretty(cause),
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: providerCommandId(event, "thread-session-set"),
|
||||
@@ -1252,7 +1145,4 @@ const make = Effect.gen(function* () {
|
||||
} satisfies ProviderRuntimeIngestionShape;
|
||||
});
|
||||
|
||||
export const ProviderRuntimeIngestionLive = Layer.effect(
|
||||
ProviderRuntimeIngestionService,
|
||||
make,
|
||||
).pipe(Layer.provide(ProjectionTurnRepositoryLive));
|
||||
export const ProviderRuntimeIngestionLive = Layer.effect(ProviderRuntimeIngestionService, make);
|
||||
@@ -262,35 +262,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.turn.start": {
|
||||
const targetThread = yield* requireThread({
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const sourceProposedPlan = command.sourceProposedPlan;
|
||||
const sourceThread = sourceProposedPlan
|
||||
? yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: sourceProposedPlan.threadId,
|
||||
})
|
||||
: null;
|
||||
const sourcePlan =
|
||||
sourceProposedPlan && sourceThread
|
||||
? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
|
||||
: null;
|
||||
if (sourceProposedPlan && !sourcePlan) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
|
||||
});
|
||||
}
|
||||
if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
|
||||
});
|
||||
}
|
||||
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
@@ -330,9 +306,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
? { providerOptions: command.providerOptions }
|
||||
: {}),
|
||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
runtimeMode: targetThread.runtimeMode,
|
||||
interactionMode: targetThread.interactionMode,
|
||||
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
|
||||
runtimeMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
|
||||
command.runtimeMode,
|
||||
interactionMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
|
||||
command.interactionMode,
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -22,8 +22,6 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
turn_id,
|
||||
plan_markdown,
|
||||
implemented_at,
|
||||
implementation_thread_id,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
@@ -32,8 +30,6 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.planMarkdown},
|
||||
${row.implementedAt},
|
||||
${row.implementationThreadId},
|
||||
${row.createdAt},
|
||||
${row.updatedAt}
|
||||
)
|
||||
@@ -42,8 +38,6 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
thread_id = excluded.thread_id,
|
||||
turn_id = excluded.turn_id,
|
||||
plan_markdown = excluded.plan_markdown,
|
||||
implemented_at = excluded.implemented_at,
|
||||
implementation_thread_id = excluded.implementation_thread_id,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at
|
||||
`,
|
||||
@@ -58,8 +52,6 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
plan_markdown AS "planMarkdown",
|
||||
implemented_at AS "implementedAt",
|
||||
implementation_thread_id AS "implementationThreadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_proposed_plans
|
||||
|
||||
@@ -47,8 +47,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
turn_id,
|
||||
pending_message_id,
|
||||
source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id,
|
||||
assistant_message_id,
|
||||
state,
|
||||
requested_at,
|
||||
@@ -63,8 +61,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.pendingMessageId},
|
||||
${row.sourceProposedPlanThreadId},
|
||||
${row.sourceProposedPlanId},
|
||||
${row.assistantMessageId},
|
||||
${row.state},
|
||||
${row.requestedAt},
|
||||
@@ -78,8 +74,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
ON CONFLICT (thread_id, turn_id)
|
||||
DO UPDATE SET
|
||||
pending_message_id = excluded.pending_message_id,
|
||||
source_proposed_plan_thread_id = excluded.source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id = excluded.source_proposed_plan_id,
|
||||
assistant_message_id = excluded.assistant_message_id,
|
||||
state = excluded.state,
|
||||
requested_at = excluded.requested_at,
|
||||
@@ -112,8 +106,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
turn_id,
|
||||
pending_message_id,
|
||||
source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id,
|
||||
assistant_message_id,
|
||||
state,
|
||||
requested_at,
|
||||
@@ -128,8 +120,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
NULL,
|
||||
${row.messageId},
|
||||
${row.sourceProposedPlanThreadId},
|
||||
${row.sourceProposedPlanId},
|
||||
NULL,
|
||||
'pending',
|
||||
${row.requestedAt},
|
||||
@@ -151,8 +141,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
pending_message_id AS "messageId",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId",
|
||||
requested_at AS "requestedAt"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = ${threadId}
|
||||
@@ -174,8 +162,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
pending_message_id AS "pendingMessageId",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId",
|
||||
assistant_message_id AS "assistantMessageId",
|
||||
state,
|
||||
requested_at AS "requestedAt",
|
||||
@@ -207,8 +193,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
pending_message_id AS "pendingMessageId",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId",
|
||||
assistant_message_id AS "assistantMessageId",
|
||||
state,
|
||||
requested_at AS "requestedAt",
|
||||
|
||||
@@ -25,8 +25,6 @@ import Migration0010 from "./Migrations/010_ProjectionThreadsRuntimeMode.ts";
|
||||
import Migration0011 from "./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts";
|
||||
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 { Effect } from "effect";
|
||||
|
||||
/**
|
||||
@@ -53,8 +51,6 @@ const loader = Migrator.fromRecord({
|
||||
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
|
||||
"12_ProjectionThreadsInteractionMode": Migration0012,
|
||||
"13_ProjectionThreadProposedPlans": Migration0013,
|
||||
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
|
||||
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
-16
@@ -1,16 +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_thread_proposed_plans
|
||||
ADD COLUMN implemented_at TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_proposed_plans
|
||||
ADD COLUMN implementation_thread_id TEXT
|
||||
`;
|
||||
});
|
||||
@@ -1,16 +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_turns
|
||||
ADD COLUMN source_proposed_plan_thread_id TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_turns
|
||||
ADD COLUMN source_proposed_plan_id TEXT
|
||||
`;
|
||||
});
|
||||
@@ -15,8 +15,6 @@ export const ProjectionThreadProposedPlan = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
planMarkdown: TrimmedNonEmptyString,
|
||||
implementedAt: Schema.NullOr(IsoDateTime),
|
||||
implementationThreadId: Schema.NullOr(ThreadId),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationCheckpointStatus,
|
||||
ThreadId,
|
||||
@@ -35,8 +34,6 @@ export const ProjectionTurn = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
pendingMessageId: Schema.NullOr(MessageId),
|
||||
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
|
||||
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
|
||||
assistantMessageId: Schema.NullOr(MessageId),
|
||||
state: ProjectionTurnState,
|
||||
requestedAt: IsoDateTime,
|
||||
@@ -53,8 +50,6 @@ export const ProjectionTurnById = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
pendingMessageId: Schema.NullOr(MessageId),
|
||||
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
|
||||
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
|
||||
assistantMessageId: Schema.NullOr(MessageId),
|
||||
state: ProjectionTurnState,
|
||||
requestedAt: IsoDateTime,
|
||||
@@ -70,8 +65,6 @@ export type ProjectionTurnById = typeof ProjectionTurnById.Type;
|
||||
export const ProjectionPendingTurnStart = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
|
||||
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
|
||||
requestedAt: IsoDateTime,
|
||||
});
|
||||
export type ProjectionPendingTurnStart = typeof ProjectionPendingTurnStart.Type;
|
||||
|
||||
@@ -275,104 +275,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("ignores unsupported max effort for Sonnet 4.6", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("ignores adaptive effort for Haiku 4.5", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("forwards Claude thinking toggle into SDK settings for Haiku 4.5", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.deepEqual(createInput?.options.settings, {
|
||||
alwaysThinkingEnabled: false,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("ignores Claude thinking toggle for non-Haiku models", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.settings, undefined);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("forwards claude fast mode into SDK settings", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
@@ -423,14 +325,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("treats ultrathink as a prompt keyword instead of a session effort", () => {
|
||||
it.effect("maps ultrathink to max effort and prefixes the prompt", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
@@ -443,7 +344,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
threadId: session.threadId,
|
||||
input: "Investigate the edge cases",
|
||||
attachments: [],
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "ultrathink",
|
||||
@@ -452,7 +352,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
assert.equal(createInput?.options.effort, "max");
|
||||
const promptText = yield* Effect.promise(() => readFirstPromptText(createInput));
|
||||
assert.equal(promptText, "Ultrathink:\nInvestigate the edge cases");
|
||||
}).pipe(
|
||||
|
||||
@@ -40,11 +40,7 @@ import {
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getEffectiveClaudeCodeEffort,
|
||||
getReasoningEffortOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
} from "@t3tools/shared/model";
|
||||
import { Cause, DateTime, Deferred, Effect, Layer, Queue, Random, Ref, Stream } from "effect";
|
||||
|
||||
@@ -242,12 +238,7 @@ function classifyToolItemType(toolName: string): CanonicalItemType {
|
||||
if (normalized.includes("agent")) {
|
||||
return "collab_agent_tool_call";
|
||||
}
|
||||
if (
|
||||
normalized === "task" ||
|
||||
normalized === "agent" ||
|
||||
normalized.includes("subagent") ||
|
||||
normalized.includes("sub-agent")
|
||||
) {
|
||||
if (normalized === "task") {
|
||||
return "collab_agent_tool_call";
|
||||
}
|
||||
if (
|
||||
@@ -355,18 +346,10 @@ function buildUserMessage(input: ProviderSendTurnInput): SDKUserMessage {
|
||||
}
|
||||
}
|
||||
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
const text = applyClaudePromptEffortPrefix(
|
||||
fragments.join("\n\n"),
|
||||
input.modelOptions?.claudeAgent?.effort ?? null,
|
||||
);
|
||||
const supportedEffortOptions = getReasoningEffortOptions("claudeAgent", input.model);
|
||||
const promptEffort =
|
||||
requestedEffort === "ultrathink" && supportsClaudeUltrathinkKeyword(input.model)
|
||||
? "ultrathink"
|
||||
: requestedEffort && supportedEffortOptions.includes(requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
const text = applyClaudePromptEffortPrefix(fragments.join("\n\n"), promptEffort);
|
||||
|
||||
return {
|
||||
type: "user",
|
||||
@@ -2209,30 +2192,13 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
);
|
||||
|
||||
const providerOptions = input.providerOptions?.claudeAgent;
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
input.modelOptions?.claudeAgent?.effort ?? null,
|
||||
);
|
||||
const supportedEffortOptions = getReasoningEffortOptions("claudeAgent", input.model);
|
||||
const effort =
|
||||
requestedEffort && supportedEffortOptions.includes(requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
const effort = input.modelOptions?.claudeAgent?.effort;
|
||||
const fastMode =
|
||||
input.modelOptions?.claudeAgent?.fastMode === true && supportsClaudeFastMode(input.model);
|
||||
const thinking =
|
||||
typeof input.modelOptions?.claudeAgent?.thinking === "boolean" &&
|
||||
supportsClaudeThinkingToggle(input.model)
|
||||
? input.modelOptions.claudeAgent.thinking
|
||||
: undefined;
|
||||
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
|
||||
const permissionMode =
|
||||
toPermissionMode(providerOptions?.permissionMode) ??
|
||||
(input.runtimeMode === "full-access" ? "bypassPermissions" : undefined);
|
||||
const settings = {
|
||||
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
};
|
||||
|
||||
const queryOptions: ClaudeQueryOptions = {
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
@@ -2248,7 +2214,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
...(providerOptions?.maxThinkingTokens !== undefined
|
||||
? { maxThinkingTokens: providerOptions.maxThinkingTokens }
|
||||
: {}),
|
||||
...(Object.keys(settings).length > 0 ? { settings } : {}),
|
||||
...(fastMode ? { settings: { fastMode: true } } : {}),
|
||||
...(resumeState?.resume ? { resume: resumeState.resume } : {}),
|
||||
...(resumeState?.resumeSessionAt ? { resumeSessionAt: resumeState.resumeSessionAt } : {}),
|
||||
includePartialMessages: true,
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = '2.12.10'
|
||||
const PACKAGE_VERSION = '2.12.9'
|
||||
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||
const activeClientIds = new Set()
|
||||
|
||||
@@ -35,7 +35,6 @@ describe("getAppModelOptions", () => {
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual([
|
||||
"gpt-5.4",
|
||||
"gpt-5.4-mini",
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark",
|
||||
"gpt-5.2-codex",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { TrimmedNonEmptyString, type ProviderKind } from "@t3tools/contracts";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { useLocalStorage } from "./hooks/useLocalStorage";
|
||||
|
||||
@@ -38,7 +38,6 @@ const AppSettingsSchema = Schema.Struct({
|
||||
customClaudeModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
textGenerationModel: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||
export interface AppModelOption {
|
||||
|
||||
@@ -21,10 +21,6 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
} from "../lib/terminalContext";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
@@ -154,25 +150,6 @@ function createAssistantMessage(options: { id: MessageId; text: string; offsetSe
|
||||
};
|
||||
}
|
||||
|
||||
function createTerminalContext(input: {
|
||||
id: string;
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
text: string;
|
||||
}): TerminalContextDraft {
|
||||
return {
|
||||
id: input.id,
|
||||
threadId: THREAD_ID,
|
||||
terminalId: `terminal-${input.id}`,
|
||||
terminalLabel: input.terminalLabel,
|
||||
lineStart: input.lineStart,
|
||||
lineEnd: input.lineEnd,
|
||||
text: input.text,
|
||||
createdAt: NOW_ISO,
|
||||
};
|
||||
}
|
||||
|
||||
function createSnapshotForTargetUser(options: {
|
||||
targetMessageId: MessageId;
|
||||
targetText: string;
|
||||
@@ -368,8 +345,6 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
id: "plan-browser-test",
|
||||
turnId: null,
|
||||
planMarkdown,
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: isoAt(1_000),
|
||||
updatedAt: isoAt(1_001),
|
||||
},
|
||||
@@ -556,13 +531,6 @@ async function waitForComposerEditor(): Promise<HTMLElement> {
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForSendButton(): Promise<HTMLButtonElement> {
|
||||
return waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Send message"]'),
|
||||
"Unable to find send button.",
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForInteractionModeButton(
|
||||
expectedLabel: "Chat" | "Plan",
|
||||
): Promise<HTMLButtonElement> {
|
||||
@@ -1043,166 +1011,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps backspaced terminal context pills removed when a new one is added", async () => {
|
||||
const removedLabel = "Terminal 1 lines 1-2";
|
||||
const addedLabel = "Terminal 2 lines 9-10";
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-removed",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 1,
|
||||
lineEnd: 2,
|
||||
text: "bun i\nno changes",
|
||||
}),
|
||||
);
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-terminal-pill-backspace" as MessageId,
|
||||
targetText: "terminal pill backspace target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(removedLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
const composerEditor = await waitForComposerEditor();
|
||||
composerEditor.focus();
|
||||
composerEditor.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Backspace",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[THREAD_ID]).toBeUndefined();
|
||||
expect(document.body.textContent).not.toContain(removedLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-added",
|
||||
terminalLabel: "Terminal 2",
|
||||
lineStart: 9,
|
||||
lineEnd: 10,
|
||||
text: "git status\nOn branch main",
|
||||
}),
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[THREAD_ID];
|
||||
expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-added"]);
|
||||
expect(document.body.textContent).toContain(addedLabel);
|
||||
expect(document.body.textContent).not.toContain(removedLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("disables send when the composer only contains an expired terminal pill", async () => {
|
||||
const expiredLabel = "Terminal 1 line 4";
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-expired-only",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
}),
|
||||
);
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-expired-pill-disabled" as MessageId,
|
||||
targetText: "expired pill disabled target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(expiredLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
const sendButton = await waitForSendButton();
|
||||
expect(sendButton.disabled).toBe(true);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("warns when sending text while omitting expired terminal pills", async () => {
|
||||
const expiredLabel = "Terminal 1 line 4";
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-expired-send-warning",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
}),
|
||||
);
|
||||
useComposerDraftStore
|
||||
.getState()
|
||||
.setPrompt(THREAD_ID, `yoo${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}waddup`);
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-expired-pill-warning" as MessageId,
|
||||
targetText: "expired pill warning target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(expiredLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
const sendButton = await waitForSendButton();
|
||||
expect(sendButton.disabled).toBe(false);
|
||||
sendButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(
|
||||
"Expired terminal context omitted from message",
|
||||
);
|
||||
expect(document.body.textContent).not.toContain(expiredLabel);
|
||||
expect(document.body.textContent).toContain("yoowaddup");
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a pointer cursor for the running stop button", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildExpiredTerminalContextToastCopy, deriveComposerSendState } from "./ChatView.logic";
|
||||
|
||||
describe("deriveComposerSendState", () => {
|
||||
it("treats expired terminal pills as non-sendable content", () => {
|
||||
const state = deriveComposerSendState({
|
||||
prompt: "\uFFFC",
|
||||
imageCount: 0,
|
||||
terminalContexts: [
|
||||
{
|
||||
id: "ctx-expired",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
createdAt: "2026-03-17T12:52:29.000Z",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(state.trimmedPrompt).toBe("");
|
||||
expect(state.sendableTerminalContexts).toEqual([]);
|
||||
expect(state.expiredTerminalContextCount).toBe(1);
|
||||
expect(state.hasSendableContent).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps text sendable while excluding expired terminal pills", () => {
|
||||
const state = deriveComposerSendState({
|
||||
prompt: `yoo \uFFFC waddup`,
|
||||
imageCount: 0,
|
||||
terminalContexts: [
|
||||
{
|
||||
id: "ctx-expired",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
createdAt: "2026-03-17T12:52:29.000Z",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(state.trimmedPrompt).toBe("yoo waddup");
|
||||
expect(state.expiredTerminalContextCount).toBe(1);
|
||||
expect(state.hasSendableContent).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildExpiredTerminalContextToastCopy", () => {
|
||||
it("formats clear empty-state guidance", () => {
|
||||
expect(buildExpiredTerminalContextToastCopy(1, "empty")).toEqual({
|
||||
title: "Expired terminal context won't be sent",
|
||||
description: "Remove it or re-add it to include terminal output.",
|
||||
});
|
||||
});
|
||||
|
||||
it("formats omission guidance for sent messages", () => {
|
||||
expect(buildExpiredTerminalContextToastCopy(2, "omitted")).toEqual({
|
||||
title: "Expired terminal contexts omitted from message",
|
||||
description: "Re-add it if you want that terminal output included.",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,11 +4,6 @@ import { randomUUID } from "~/lib/utils";
|
||||
import { getAppModelOptions } from "../appSettings";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import { Schema } from "effect";
|
||||
import {
|
||||
filterTerminalContextsWithText,
|
||||
stripInlineTerminalContextPlaceholders,
|
||||
type TerminalContextDraft,
|
||||
} from "../lib/terminalContext";
|
||||
|
||||
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
@@ -130,44 +125,3 @@ export function getCustomModelOptionsByProvider(settings: {
|
||||
claudeAgent: getAppModelOptions("claudeAgent", settings.customClaudeModels),
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveComposerSendState(options: {
|
||||
prompt: string;
|
||||
imageCount: number;
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
}): {
|
||||
trimmedPrompt: string;
|
||||
sendableTerminalContexts: TerminalContextDraft[];
|
||||
expiredTerminalContextCount: number;
|
||||
hasSendableContent: boolean;
|
||||
} {
|
||||
const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
|
||||
const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
|
||||
const expiredTerminalContextCount =
|
||||
options.terminalContexts.length - sendableTerminalContexts.length;
|
||||
return {
|
||||
trimmedPrompt,
|
||||
sendableTerminalContexts,
|
||||
expiredTerminalContextCount,
|
||||
hasSendableContent:
|
||||
trimmedPrompt.length > 0 || options.imageCount > 0 || sendableTerminalContexts.length > 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildExpiredTerminalContextToastCopy(
|
||||
expiredTerminalContextCount: number,
|
||||
variant: "omitted" | "empty",
|
||||
): { title: string; description: string } {
|
||||
const count = Math.max(1, Math.floor(expiredTerminalContextCount));
|
||||
const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
|
||||
if (variant === "empty") {
|
||||
return {
|
||||
title: `${noun} won't be sent`,
|
||||
description: "Remove it or re-add it to include terminal output.",
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: `${noun} omitted from message`,
|
||||
description: "Re-add it if you want that terminal output included.",
|
||||
};
|
||||
}
|
||||
@@ -2,37 +2,35 @@ import {
|
||||
type ApprovalRequestId,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ClaudeCodeEffort,
|
||||
type EditorId,
|
||||
type KeybindingCommand,
|
||||
type MessageId,
|
||||
type ProjectId,
|
||||
type ProjectEntry,
|
||||
type ProjectScript,
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
type ProjectEntry,
|
||||
type ProjectId,
|
||||
type ProviderApprovalDecision,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ProviderApprovalDecision,
|
||||
type ServerProviderStatus,
|
||||
type ProviderKind,
|
||||
type ProviderReasoningEffort,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type EditorId,
|
||||
type KeybindingCommand,
|
||||
OrchestrationThreadActivity,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ProviderInteractionMode,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getDefaultModel,
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptions,
|
||||
normalizeCodexModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveReasoningEffortForProvider,
|
||||
resolveModelSlugForProvider,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
supportsClaudeFastMode,
|
||||
} from "@t3tools/shared/model";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
@@ -59,10 +57,8 @@ import {
|
||||
deriveTimelineEntries,
|
||||
deriveActiveWorkStartedAt,
|
||||
deriveActivePlanState,
|
||||
findSidebarProposedPlan,
|
||||
findLatestProposedPlan,
|
||||
deriveWorkLogEntries,
|
||||
hasActionableProposedPlan,
|
||||
hasToolActivityForTurn,
|
||||
isLatestTurnSettled,
|
||||
formatElapsed,
|
||||
@@ -135,14 +131,6 @@ import {
|
||||
useComposerDraftStore,
|
||||
useComposerThreadDraft,
|
||||
} from "../composerDraftStore";
|
||||
import {
|
||||
appendTerminalContextsToPrompt,
|
||||
formatTerminalContextLabel,
|
||||
insertInlineTerminalContextPlaceholder,
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
type TerminalContextDraft,
|
||||
type TerminalContextSelection,
|
||||
} from "../lib/terminalContext";
|
||||
import { shouldUseCompactComposerFooter } from "./composerFooterLayout";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
|
||||
@@ -153,8 +141,7 @@ import { buildExpandedImagePreview, ExpandedImagePreview } from "./chat/Expanded
|
||||
import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./chat/ProviderModelPicker";
|
||||
import { ComposerCommandItem, ComposerCommandMenu } from "./chat/ComposerCommandMenu";
|
||||
import { ComposerPendingApprovalActions } from "./chat/ComposerPendingApprovalActions";
|
||||
import { ClaudeTraitsMenuContent, ClaudeTraitsPicker } from "./chat/ClaudeTraitsPicker";
|
||||
import { CodexTraitsMenuContent, CodexTraitsPicker } from "./chat/CodexTraitsPicker";
|
||||
import { ProviderTraitsPicker } from "./chat/CodexTraitsPicker";
|
||||
import { CompactComposerControlsMenu } from "./chat/CompactComposerControlsMenu";
|
||||
import { ComposerPendingApprovalPanel } from "./chat/ComposerPendingApprovalPanel";
|
||||
import { ComposerPendingUserInputPanel } from "./chat/ComposerPendingUserInputPanel";
|
||||
@@ -162,12 +149,10 @@ import { ComposerPlanFollowUpBanner } from "./chat/ComposerPlanFollowUpBanner";
|
||||
import { ProviderHealthBanner } from "./chat/ProviderHealthBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import {
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildLocalDraftThread,
|
||||
buildTemporaryWorktreeBranchName,
|
||||
cloneComposerImageForRetry,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
deriveComposerSendState,
|
||||
getCustomModelOptionsByProvider,
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
LastInvokedScriptByProjectSchema,
|
||||
@@ -192,13 +177,13 @@ const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnsw
|
||||
|
||||
function formatOutgoingPrompt(params: {
|
||||
provider: ProviderKind;
|
||||
effort: string | null;
|
||||
effort: ProviderReasoningEffort | null;
|
||||
text: string;
|
||||
}): string {
|
||||
if (params.provider === "claudeAgent" && params.effort === "ultrathink") {
|
||||
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeCodeEffort | null);
|
||||
if (params.provider !== "claudeAgent") {
|
||||
return params.text;
|
||||
}
|
||||
return params.text;
|
||||
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeCodeEffort | null);
|
||||
}
|
||||
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||
const SCRIPT_TERMINAL_COLS = 120;
|
||||
@@ -215,23 +200,6 @@ const extendReplacementRangeForTrailingSpace = (
|
||||
return text[rangeEnd] === " " ? rangeEnd + 1 : rangeEnd;
|
||||
};
|
||||
|
||||
const syncTerminalContextsByIds = (
|
||||
contexts: ReadonlyArray<TerminalContextDraft>,
|
||||
ids: ReadonlyArray<string>,
|
||||
): TerminalContextDraft[] => {
|
||||
const contextsById = new Map(contexts.map((context) => [context.id, context]));
|
||||
return ids.flatMap((id) => {
|
||||
const context = contextsById.get(id);
|
||||
return context ? [context] : [];
|
||||
});
|
||||
};
|
||||
|
||||
const terminalContextIdListsEqual = (
|
||||
contexts: ReadonlyArray<TerminalContextDraft>,
|
||||
ids: ReadonlyArray<string>,
|
||||
): boolean =>
|
||||
contexts.length === ids.length && contexts.every((context, index) => context.id === ids[index]);
|
||||
|
||||
interface ChatViewProps {
|
||||
threadId: ThreadId;
|
||||
}
|
||||
@@ -256,16 +224,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const composerDraft = useComposerThreadDraft(threadId);
|
||||
const prompt = composerDraft.prompt;
|
||||
const composerImages = composerDraft.images;
|
||||
const composerTerminalContexts = composerDraft.terminalContexts;
|
||||
const composerSendState = useMemo(
|
||||
() =>
|
||||
deriveComposerSendState({
|
||||
prompt,
|
||||
imageCount: composerImages.length,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
}),
|
||||
[composerImages.length, composerTerminalContexts, prompt],
|
||||
);
|
||||
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
|
||||
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
const setComposerDraftProvider = useComposerDraftStore((store) => store.setProvider);
|
||||
@@ -274,21 +232,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setComposerDraftInteractionMode = useComposerDraftStore(
|
||||
(store) => store.setInteractionMode,
|
||||
);
|
||||
const setComposerDraftEffort = useComposerDraftStore((store) => store.setEffort);
|
||||
const setComposerDraftFastMode = useComposerDraftStore((store) => store.setFastMode);
|
||||
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
|
||||
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
|
||||
const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage);
|
||||
const insertComposerDraftTerminalContext = useComposerDraftStore(
|
||||
(store) => store.insertTerminalContext,
|
||||
);
|
||||
const addComposerDraftTerminalContexts = useComposerDraftStore(
|
||||
(store) => store.addTerminalContexts,
|
||||
);
|
||||
const removeComposerDraftTerminalContext = useComposerDraftStore(
|
||||
(store) => store.removeTerminalContext,
|
||||
);
|
||||
const setComposerDraftTerminalContexts = useComposerDraftStore(
|
||||
(store) => store.setTerminalContexts,
|
||||
);
|
||||
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
|
||||
(store) => store.clearPersistedAttachments,
|
||||
);
|
||||
@@ -315,7 +263,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
|
||||
const optimisticUserMessagesRef = useRef(optimisticUserMessages);
|
||||
optimisticUserMessagesRef.current = optimisticUserMessages;
|
||||
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>(composerTerminalContexts);
|
||||
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
|
||||
Record<ThreadId, string | null>
|
||||
>({});
|
||||
@@ -338,7 +285,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
|
||||
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
|
||||
// When set, the thread-change reset effect will open the sidebar instead of closing it.
|
||||
// Used by "Implement in a new thread" to carry the sidebar-open intent across navigation.
|
||||
// Used by "Implement in new thread" to carry the sidebar-open intent across navigation.
|
||||
const planSidebarOpenOnNextThreadRef = useRef(false);
|
||||
const [nowTick, setNowTick] = useState(() => Date.now());
|
||||
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
|
||||
@@ -418,40 +365,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
},
|
||||
[addComposerDraftImages, threadId],
|
||||
);
|
||||
const addComposerTerminalContextsToDraft = useCallback(
|
||||
(contexts: TerminalContextDraft[]) => {
|
||||
addComposerDraftTerminalContexts(threadId, contexts);
|
||||
},
|
||||
[addComposerDraftTerminalContexts, threadId],
|
||||
);
|
||||
const removeComposerImageFromDraft = useCallback(
|
||||
(imageId: string) => {
|
||||
removeComposerDraftImage(threadId, imageId);
|
||||
},
|
||||
[removeComposerDraftImage, threadId],
|
||||
);
|
||||
const removeComposerTerminalContextFromDraft = useCallback(
|
||||
(contextId: string) => {
|
||||
const contextIndex = composerTerminalContexts.findIndex(
|
||||
(context) => context.id === contextId,
|
||||
);
|
||||
if (contextIndex < 0) {
|
||||
return;
|
||||
}
|
||||
const nextPrompt = removeInlineTerminalContextPlaceholder(promptRef.current, contextIndex);
|
||||
promptRef.current = nextPrompt.prompt;
|
||||
setPrompt(nextPrompt.prompt);
|
||||
removeComposerDraftTerminalContext(threadId, contextId);
|
||||
setComposerCursor(nextPrompt.cursor);
|
||||
setComposerTrigger(
|
||||
detectComposerTrigger(
|
||||
nextPrompt.prompt,
|
||||
expandCollapsedComposerCursor(nextPrompt.prompt, nextPrompt.cursor),
|
||||
),
|
||||
);
|
||||
},
|
||||
[composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId],
|
||||
);
|
||||
|
||||
const serverThread = threads.find((t) => t.id === threadId);
|
||||
const fallbackDraftProject = projects.find((project) => project.id === draftThread?.projectId);
|
||||
@@ -615,53 +534,54 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
draftModel,
|
||||
) as ModelSlug;
|
||||
}, [baseThreadModel, composerDraft.model, customModelsForSelectedProvider, selectedProvider]);
|
||||
const draftModelOptions = composerDraft.modelOptions;
|
||||
const reasoningOptions = getReasoningEffortOptions(selectedProvider);
|
||||
const supportsReasoningEffort = reasoningOptions.length > 0;
|
||||
const selectedCodexEffort =
|
||||
selectedProvider === "codex"
|
||||
? (resolveReasoningEffortForProvider("codex", draftModelOptions?.codex?.reasoningEffort) ??
|
||||
? (resolveReasoningEffortForProvider("codex", composerDraft.effort) ??
|
||||
getDefaultReasoningEffort("codex"))
|
||||
: null;
|
||||
const selectedClaudeReasoningOptions =
|
||||
const selectedClaudeEffort =
|
||||
selectedProvider === "claudeAgent"
|
||||
? getReasoningEffortOptions("claudeAgent", selectedModel)
|
||||
: ([] as const);
|
||||
const selectedClaudeBaseEffort =
|
||||
selectedProvider === "claudeAgent" && selectedClaudeReasoningOptions.length > 0
|
||||
? (() => {
|
||||
const draftEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
draftModelOptions?.claudeAgent?.effort,
|
||||
);
|
||||
if (
|
||||
draftEffort &&
|
||||
draftEffort !== "ultrathink" &&
|
||||
selectedClaudeReasoningOptions.includes(draftEffort)
|
||||
) {
|
||||
return draftEffort;
|
||||
}
|
||||
const defaultEffort = getDefaultReasoningEffort("claudeAgent");
|
||||
return selectedClaudeReasoningOptions.includes(defaultEffort) ? defaultEffort : null;
|
||||
})()
|
||||
? (resolveReasoningEffortForProvider("claudeAgent", composerDraft.effort) ??
|
||||
getDefaultReasoningEffort("claudeAgent"))
|
||||
: null;
|
||||
const isClaudeUltrathink =
|
||||
selectedProvider === "claudeAgent" &&
|
||||
supportsClaudeUltrathinkKeyword(selectedModel) &&
|
||||
isClaudeUltrathinkPrompt(prompt);
|
||||
const selectedPromptEffort = selectedCodexEffort ?? selectedClaudeBaseEffort;
|
||||
const selectedEffort = selectedCodexEffort ?? selectedClaudeEffort;
|
||||
const selectedClaudeFastModeAvailable =
|
||||
selectedProvider === "claudeAgent" && supportsClaudeFastMode(selectedModel);
|
||||
const selectedFastModeAvailable = selectedProvider === "codex" || selectedClaudeFastModeAvailable;
|
||||
const selectedFastModeEnabled = selectedFastModeAvailable ? composerDraft.fastMode : false;
|
||||
const isClaudeUltrathink = selectedClaudeEffort === "ultrathink";
|
||||
const selectedModelOptionsForDispatch = useMemo(() => {
|
||||
if (selectedProvider === "codex") {
|
||||
const codexOptions = normalizeCodexModelOptions(draftModelOptions?.codex);
|
||||
return codexOptions ? { codex: codexOptions } : undefined;
|
||||
const codexOptions = {
|
||||
...(supportsReasoningEffort && selectedCodexEffort
|
||||
? { reasoningEffort: selectedCodexEffort }
|
||||
: {}),
|
||||
...(selectedFastModeEnabled ? { fastMode: true } : {}),
|
||||
};
|
||||
return Object.keys(codexOptions).length > 0 ? { codex: codexOptions } : undefined;
|
||||
}
|
||||
if (selectedProvider === "claudeAgent") {
|
||||
const claudeOptions = normalizeClaudeModelOptions(
|
||||
selectedModel,
|
||||
draftModelOptions?.claudeAgent,
|
||||
);
|
||||
return claudeOptions ? { claudeAgent: claudeOptions } : undefined;
|
||||
const claudeOptions = {
|
||||
...(selectedClaudeEffort ? { effort: selectedClaudeEffort } : {}),
|
||||
...(selectedFastModeEnabled ? { fastMode: true } : {}),
|
||||
};
|
||||
if (Object.keys(claudeOptions).length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
claudeAgent: claudeOptions,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}, [draftModelOptions, selectedModel, selectedProvider]);
|
||||
}, [
|
||||
selectedClaudeEffort,
|
||||
selectedCodexEffort,
|
||||
selectedFastModeEnabled,
|
||||
selectedProvider,
|
||||
supportsReasoningEffort,
|
||||
]);
|
||||
const providerOptionsForDispatch = useMemo(() => {
|
||||
if (!settings.codexBinaryPath && !settings.codexHomePath) {
|
||||
return undefined;
|
||||
@@ -770,16 +690,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeLatestTurn?.turnId ?? null,
|
||||
);
|
||||
}, [activeLatestTurn?.turnId, activeThread?.proposedPlans, latestTurnSettled]);
|
||||
const sidebarProposedPlan = useMemo(
|
||||
() =>
|
||||
findSidebarProposedPlan({
|
||||
threads,
|
||||
latestTurn: activeLatestTurn,
|
||||
latestTurnSettled,
|
||||
threadId: activeThread?.id ?? null,
|
||||
}),
|
||||
[activeLatestTurn, activeThread?.id, latestTurnSettled, threads],
|
||||
);
|
||||
const activePlan = useMemo(
|
||||
() => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined),
|
||||
[activeLatestTurn?.turnId, threadActivities],
|
||||
@@ -788,7 +698,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
pendingUserInputs.length === 0 &&
|
||||
interactionMode === "plan" &&
|
||||
latestTurnSettled &&
|
||||
hasActionableProposedPlan(activeProposedPlan);
|
||||
activeProposedPlan !== null;
|
||||
const activePendingApproval = pendingApprovals[0] ?? null;
|
||||
const isComposerApprovalState = activePendingApproval !== null;
|
||||
const hasComposerHeader =
|
||||
@@ -1238,48 +1148,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
focusComposer();
|
||||
});
|
||||
}, [focusComposer]);
|
||||
const addTerminalContextToDraft = useCallback(
|
||||
(selection: TerminalContextSelection) => {
|
||||
if (!activeThread) {
|
||||
return;
|
||||
}
|
||||
const snapshot = composerEditorRef.current?.readSnapshot() ?? {
|
||||
value: promptRef.current,
|
||||
cursor: composerCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(promptRef.current, composerCursor),
|
||||
terminalContextIds: composerTerminalContexts.map((context) => context.id),
|
||||
};
|
||||
const insertion = insertInlineTerminalContextPlaceholder(
|
||||
snapshot.value,
|
||||
snapshot.expandedCursor,
|
||||
);
|
||||
const nextCollapsedCursor = collapseExpandedComposerCursor(
|
||||
insertion.prompt,
|
||||
insertion.cursor,
|
||||
);
|
||||
const inserted = insertComposerDraftTerminalContext(
|
||||
activeThread.id,
|
||||
insertion.prompt,
|
||||
{
|
||||
id: randomUUID(),
|
||||
threadId: activeThread.id,
|
||||
createdAt: new Date().toISOString(),
|
||||
...selection,
|
||||
},
|
||||
insertion.contextIndex,
|
||||
);
|
||||
if (!inserted) {
|
||||
return;
|
||||
}
|
||||
promptRef.current = insertion.prompt;
|
||||
setComposerCursor(nextCollapsedCursor);
|
||||
setComposerTrigger(detectComposerTrigger(insertion.prompt, insertion.cursor));
|
||||
window.requestAnimationFrame(() => {
|
||||
composerEditorRef.current?.focusAt(nextCollapsedCursor);
|
||||
});
|
||||
},
|
||||
[activeThread, composerCursor, composerTerminalContexts, insertComposerDraftTerminalContext],
|
||||
);
|
||||
const setTerminalOpen = useCallback(
|
||||
(open: boolean) => {
|
||||
if (!activeThreadId) return;
|
||||
@@ -1620,7 +1488,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const togglePlanSidebar = useCallback(() => {
|
||||
setPlanSidebarOpen((open) => {
|
||||
if (open) {
|
||||
const turnKey = activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? null;
|
||||
const turnKey = activePlan?.turnId ?? activeProposedPlan?.turnId ?? null;
|
||||
if (turnKey) {
|
||||
planSidebarDismissedForTurnRef.current = turnKey;
|
||||
}
|
||||
@@ -1629,7 +1497,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
return !open;
|
||||
});
|
||||
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
|
||||
}, [activePlan?.turnId, activeProposedPlan?.turnId]);
|
||||
|
||||
const persistThreadSettingsForNextTurn = useCallback(
|
||||
async (input: {
|
||||
@@ -1917,10 +1785,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
composerImagesRef.current = composerImages;
|
||||
}, [composerImages]);
|
||||
|
||||
useEffect(() => {
|
||||
composerTerminalContextsRef.current = composerTerminalContexts;
|
||||
}, [composerTerminalContexts]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id) return;
|
||||
if (activeThread.messages.length === 0) {
|
||||
@@ -2395,17 +2259,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onAdvanceActivePendingUserInput();
|
||||
return;
|
||||
}
|
||||
const promptForSend = promptRef.current;
|
||||
const {
|
||||
trimmedPrompt: trimmed,
|
||||
sendableTerminalContexts: sendableComposerTerminalContexts,
|
||||
expiredTerminalContextCount,
|
||||
hasSendableContent,
|
||||
} = deriveComposerSendState({
|
||||
prompt: promptForSend,
|
||||
imageCount: composerImages.length,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
});
|
||||
const trimmed = prompt.trim();
|
||||
if (showPlanFollowUpPrompt && activeProposedPlan) {
|
||||
const followUp = resolvePlanFollowUpSubmission({
|
||||
draftText: trimmed,
|
||||
@@ -2423,11 +2277,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
const standaloneSlashCommand =
|
||||
composerImages.length === 0 && sendableComposerTerminalContexts.length === 0
|
||||
? parseStandaloneComposerSlashCommand(trimmed)
|
||||
: null;
|
||||
composerImages.length === 0 ? parseStandaloneComposerSlashCommand(trimmed) : null;
|
||||
if (standaloneSlashCommand) {
|
||||
handleInteractionModeChange(standaloneSlashCommand);
|
||||
await handleInteractionModeChange(standaloneSlashCommand);
|
||||
promptRef.current = "";
|
||||
clearComposerDraftContent(activeThread.id);
|
||||
setComposerHighlightedItemId(null);
|
||||
@@ -2435,20 +2287,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setComposerTrigger(null);
|
||||
return;
|
||||
}
|
||||
if (!hasSendableContent) {
|
||||
if (expiredTerminalContextCount > 0) {
|
||||
const toastCopy = buildExpiredTerminalContextToastCopy(
|
||||
expiredTerminalContextCount,
|
||||
"empty",
|
||||
);
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: toastCopy.title,
|
||||
description: toastCopy.description,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!trimmed && composerImages.length === 0) return;
|
||||
if (!activeProject) return;
|
||||
const threadIdForSend = activeThread.id;
|
||||
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
|
||||
@@ -2473,17 +2312,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
|
||||
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
|
||||
const messageTextForSend = appendTerminalContextsToPrompt(
|
||||
promptForSend,
|
||||
composerTerminalContextsSnapshot,
|
||||
);
|
||||
const messageIdForSend = newMessageId();
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
const outgoingMessageText = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
effort: selectedPromptEffort,
|
||||
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
effort: selectedEffort,
|
||||
text: trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
});
|
||||
const turnAttachmentsPromise = Promise.all(
|
||||
composerImagesSnapshot.map(async (image) => ({
|
||||
@@ -2518,17 +2352,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
forceStickToBottom();
|
||||
|
||||
setThreadError(threadIdForSend, null);
|
||||
if (expiredTerminalContextCount > 0) {
|
||||
const toastCopy = buildExpiredTerminalContextToastCopy(
|
||||
expiredTerminalContextCount,
|
||||
"omitted",
|
||||
);
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: toastCopy.title,
|
||||
description: toastCopy.description,
|
||||
});
|
||||
}
|
||||
promptRef.current = "";
|
||||
clearComposerDraftContent(threadIdForSend);
|
||||
setComposerHighlightedItemId(null);
|
||||
@@ -2576,8 +2399,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
if (!titleSeed) {
|
||||
if (firstComposerImageName) {
|
||||
titleSeed = `Image: ${firstComposerImageName}`;
|
||||
} else if (composerTerminalContextsSnapshot.length > 0) {
|
||||
titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);
|
||||
} else {
|
||||
titleSeed = "New thread";
|
||||
}
|
||||
@@ -2686,8 +2507,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
if (
|
||||
!turnStartSucceeded &&
|
||||
promptRef.current.length === 0 &&
|
||||
composerImagesRef.current.length === 0 &&
|
||||
composerTerminalContextsRef.current.length === 0
|
||||
composerImagesRef.current.length === 0
|
||||
) {
|
||||
setOptimisticUserMessages((existing) => {
|
||||
const removed = existing.filter((message) => message.id === messageIdForSend);
|
||||
@@ -2697,12 +2517,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const next = existing.filter((message) => message.id !== messageIdForSend);
|
||||
return next.length === existing.length ? existing : next;
|
||||
});
|
||||
promptRef.current = promptForSend;
|
||||
setPrompt(promptForSend);
|
||||
setComposerCursor(collapseExpandedComposerCursor(promptForSend, promptForSend.length));
|
||||
promptRef.current = trimmed;
|
||||
setPrompt(trimmed);
|
||||
setComposerCursor(collapseExpandedComposerCursor(trimmed, trimmed.length));
|
||||
addComposerImagesToDraft(composerImagesSnapshot.map(cloneComposerImageForRetry));
|
||||
addComposerTerminalContextsToDraft(composerTerminalContextsSnapshot);
|
||||
setComposerTrigger(detectComposerTrigger(promptForSend, promptForSend.length));
|
||||
setComposerTrigger(detectComposerTrigger(trimmed, trimmed.length));
|
||||
}
|
||||
setThreadError(
|
||||
threadIdForSend,
|
||||
@@ -2903,7 +2722,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
const outgoingMessageText = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
effort: selectedPromptEffort,
|
||||
effort: selectedEffort,
|
||||
text: trimmed,
|
||||
});
|
||||
|
||||
@@ -2955,14 +2774,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
runtimeMode,
|
||||
interactionMode: nextInteractionMode,
|
||||
...(nextInteractionMode === "default" && activeProposedPlan
|
||||
? {
|
||||
sourceProposedPlan: {
|
||||
threadId: activeThread.id,
|
||||
planId: activeProposedPlan.id,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
createdAt: messageCreatedAt,
|
||||
});
|
||||
// Optimistically open the plan sidebar when implementing (not refining).
|
||||
@@ -2987,7 +2798,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
activeProposedPlan,
|
||||
beginSendPhase,
|
||||
forceStickToBottom,
|
||||
isConnecting,
|
||||
@@ -2996,7 +2806,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
persistThreadSettingsForNextTurn,
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedEffort,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
providerOptionsForDispatch,
|
||||
@@ -3028,7 +2838,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const implementationPrompt = buildPlanImplementationPrompt(planMarkdown);
|
||||
const outgoingImplementationPrompt = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
effort: selectedPromptEffort,
|
||||
effort: selectedEffort,
|
||||
text: implementationPrompt,
|
||||
});
|
||||
const nextThreadTitle = truncateTitle(buildPlanImplementationThreadTitle(planMarkdown));
|
||||
@@ -3125,7 +2935,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
navigate,
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedEffort,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
providerOptionsForDispatch,
|
||||
@@ -3157,21 +2967,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setComposerDraftProvider,
|
||||
],
|
||||
);
|
||||
const setPromptFromTraits = useCallback(
|
||||
(nextPrompt: string) => {
|
||||
const currentPrompt = promptRef.current;
|
||||
if (nextPrompt === currentPrompt) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
promptRef.current = nextPrompt;
|
||||
setPrompt(nextPrompt);
|
||||
const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length);
|
||||
setComposerCursor(nextCursor);
|
||||
setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length));
|
||||
const onEffortSelect = useCallback(
|
||||
(effort: ProviderReasoningEffort) => {
|
||||
setComposerDraftEffort(threadId, effort);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[scheduleComposerFocus, setPrompt],
|
||||
[scheduleComposerFocus, setComposerDraftEffort, threadId],
|
||||
);
|
||||
const onFastModeChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
setComposerDraftFastMode(threadId, enabled);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[scheduleComposerFocus, setComposerDraftFastMode, threadId],
|
||||
);
|
||||
const onEnvModeChange = useCallback(
|
||||
(mode: DraftThreadEnvMode) => {
|
||||
@@ -3233,7 +3041,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
terminalContextIds: string[];
|
||||
} => {
|
||||
const editorSnapshot = composerEditorRef.current?.readSnapshot();
|
||||
if (editorSnapshot) {
|
||||
@@ -3243,9 +3050,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
value: promptRef.current,
|
||||
cursor: composerCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(promptRef.current, composerCursor),
|
||||
terminalContextIds: composerTerminalContexts.map((context) => context.id),
|
||||
};
|
||||
}, [composerCursor, composerTerminalContexts]);
|
||||
}, [composerCursor]);
|
||||
|
||||
const resolveActiveComposerTrigger = useCallback((): {
|
||||
snapshot: { value: string; cursor: number; expandedCursor: number };
|
||||
@@ -3361,7 +3167,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
nextCursor: number,
|
||||
expandedCursor: number,
|
||||
cursorAdjacentToMention: boolean,
|
||||
terminalContextIds: string[],
|
||||
) => {
|
||||
if (activePendingProgress?.activeQuestion && activePendingUserInput) {
|
||||
onChangeActivePendingUserInputCustomAnswer(
|
||||
@@ -3375,12 +3180,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
promptRef.current = nextPrompt;
|
||||
setPrompt(nextPrompt);
|
||||
if (!terminalContextIdListsEqual(composerTerminalContexts, terminalContextIds)) {
|
||||
setComposerDraftTerminalContexts(
|
||||
threadId,
|
||||
syncTerminalContextsByIds(composerTerminalContexts, terminalContextIds),
|
||||
);
|
||||
}
|
||||
setComposerCursor(nextCursor);
|
||||
setComposerTrigger(
|
||||
cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor),
|
||||
@@ -3389,11 +3188,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
[
|
||||
activePendingProgress?.activeQuestion,
|
||||
activePendingUserInput,
|
||||
composerTerminalContexts,
|
||||
onChangeActivePendingUserInputCustomAnswer,
|
||||
setPrompt,
|
||||
setComposerDraftTerminalContexts,
|
||||
threadId,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -3646,6 +3442,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Textarea area */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative px-3 pb-2 sm:px-4",
|
||||
@@ -3745,12 +3543,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
: prompt
|
||||
}
|
||||
cursor={composerCursor}
|
||||
terminalContexts={
|
||||
!isComposerApprovalState && pendingUserInputs.length === 0
|
||||
? composerTerminalContexts
|
||||
: []
|
||||
}
|
||||
onRemoveTerminalContext={removeComposerTerminalContextFromDraft}
|
||||
onChange={onPromptChange}
|
||||
onCommandKeyDown={onComposerCommandKey}
|
||||
onPaste={onComposerPaste}
|
||||
@@ -3813,46 +3605,42 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{isComposerFooterCompact ? (
|
||||
<CompactComposerControlsMenu
|
||||
activePlan={Boolean(
|
||||
activePlan || sidebarProposedPlan || planSidebarOpen,
|
||||
activePlan || activeProposedPlan || planSidebarOpen,
|
||||
)}
|
||||
interactionMode={interactionMode}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
traitsMenuContent={
|
||||
selectedProvider === "codex" ? (
|
||||
<CodexTraitsMenuContent threadId={threadId} />
|
||||
) : selectedProvider === "claudeAgent" ? (
|
||||
<ClaudeTraitsMenuContent
|
||||
threadId={threadId}
|
||||
model={selectedModel}
|
||||
onPromptChange={setPromptFromTraits}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
selectedEffort={selectedEffort}
|
||||
selectedProvider={selectedProvider}
|
||||
supportsFastMode={selectedFastModeAvailable}
|
||||
selectedFastModeEnabled={selectedFastModeEnabled}
|
||||
reasoningOptions={reasoningOptions}
|
||||
onEffortSelect={onEffortSelect}
|
||||
onFastModeChange={onFastModeChange}
|
||||
onToggleInteractionMode={toggleInteractionMode}
|
||||
onTogglePlanSidebar={togglePlanSidebar}
|
||||
onToggleRuntimeMode={toggleRuntimeMode}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{selectedProvider === "codex" ? (
|
||||
{selectedEffort != null ? (
|
||||
<>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="mx-0.5 hidden h-4 sm:block"
|
||||
/>
|
||||
<CodexTraitsPicker threadId={threadId} />
|
||||
</>
|
||||
) : selectedProvider === "claudeAgent" ? (
|
||||
<>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="mx-0.5 hidden h-4 sm:block"
|
||||
/>
|
||||
<ClaudeTraitsPicker
|
||||
threadId={threadId}
|
||||
model={selectedModel}
|
||||
onPromptChange={setPromptFromTraits}
|
||||
<ProviderTraitsPicker
|
||||
provider={selectedProvider}
|
||||
effort={selectedEffort}
|
||||
supportsFastMode={selectedFastModeAvailable}
|
||||
options={reasoningOptions}
|
||||
onEffortChange={onEffortSelect}
|
||||
{...(selectedFastModeAvailable
|
||||
? {
|
||||
fastModeEnabled: selectedFastModeEnabled,
|
||||
onFastModeChange,
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
@@ -3909,7 +3697,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</span>
|
||||
</Button>
|
||||
|
||||
{activePlan || sidebarProposedPlan || planSidebarOpen ? (
|
||||
{activePlan || activeProposedPlan || planSidebarOpen ? (
|
||||
<>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
@@ -4037,7 +3825,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
disabled={isSendBusy || isConnecting}
|
||||
onClick={() => void onImplementPlanInNewThread()}
|
||||
>
|
||||
Implement in a new thread
|
||||
Implement in new thread
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
@@ -4048,7 +3836,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
type="submit"
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
|
||||
disabled={
|
||||
isSendBusy || isConnecting || !composerSendState.hasSendableContent
|
||||
isSendBusy ||
|
||||
isConnecting ||
|
||||
(!prompt.trim() && composerImages.length === 0)
|
||||
}
|
||||
aria-label={
|
||||
isConnecting
|
||||
@@ -4139,14 +3929,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{planSidebarOpen ? (
|
||||
<PlanSidebar
|
||||
activePlan={activePlan}
|
||||
activeProposedPlan={sidebarProposedPlan}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
workspaceRoot={activeProject?.cwd ?? undefined}
|
||||
timestampFormat={timestampFormat}
|
||||
onClose={() => {
|
||||
setPlanSidebarOpen(false);
|
||||
// Track that the user explicitly dismissed for this turn so auto-open won't fight them.
|
||||
const turnKey = activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? null;
|
||||
const turnKey = activePlan?.turnId ?? activeProposedPlan?.turnId ?? null;
|
||||
if (turnKey) {
|
||||
planSidebarDismissedForTurnRef.current = turnKey;
|
||||
}
|
||||
@@ -4180,7 +3970,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onActiveTerminalChange={activateTerminal}
|
||||
onCloseTerminal={closeTerminal}
|
||||
onHeightChange={setTerminalHeight}
|
||||
onAddTerminalContext={addTerminalContextToDraft}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
|
||||
@@ -26,10 +26,8 @@ import {
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
KEY_BACKSPACE_COMMAND,
|
||||
$getRoot,
|
||||
DecoratorNode,
|
||||
type ElementNode,
|
||||
type LexicalNode,
|
||||
type SerializedLexicalNode,
|
||||
TextNode,
|
||||
type EditorConfig,
|
||||
type EditorState,
|
||||
@@ -38,17 +36,14 @@ import {
|
||||
type Spread,
|
||||
} from "lexical";
|
||||
import {
|
||||
createContext,
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ClipboardEventHandler,
|
||||
type ReactElement,
|
||||
type Ref,
|
||||
} from "react";
|
||||
|
||||
@@ -56,21 +51,11 @@ import {
|
||||
clampCollapsedComposerCursor,
|
||||
collapseExpandedComposerCursor,
|
||||
expandCollapsedComposerCursor,
|
||||
isCollapsedCursorAdjacentToInlineToken,
|
||||
isCollapsedCursorAdjacentToMention,
|
||||
} from "~/composer-logic";
|
||||
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
} from "~/lib/terminalContext";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry, inferEntryKindFromPath } from "~/vscode-icons";
|
||||
import {
|
||||
COMPOSER_INLINE_CHIP_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
} from "./composerInlineChip";
|
||||
import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
|
||||
|
||||
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
|
||||
|
||||
@@ -83,21 +68,6 @@ type SerializedComposerMentionNode = Spread<
|
||||
SerializedTextNode
|
||||
>;
|
||||
|
||||
type SerializedComposerTerminalContextNode = Spread<
|
||||
{
|
||||
context: TerminalContextDraft;
|
||||
type: "composer-terminal-context";
|
||||
version: 1;
|
||||
},
|
||||
SerializedLexicalNode
|
||||
>;
|
||||
|
||||
const ComposerTerminalContextActionsContext = createContext<{
|
||||
onRemoveTerminalContext: (contextId: string) => void;
|
||||
}>({
|
||||
onRemoveTerminalContext: () => {},
|
||||
});
|
||||
|
||||
class ComposerMentionNode extends TextNode {
|
||||
__path: string;
|
||||
|
||||
@@ -130,7 +100,8 @@ class ComposerMentionNode extends TextNode {
|
||||
|
||||
override createDOM(_config: EditorConfig): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className = COMPOSER_INLINE_CHIP_CLASS_NAME;
|
||||
dom.className =
|
||||
"inline-flex select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
|
||||
dom.contentEditable = "false";
|
||||
dom.setAttribute("spellcheck", "false");
|
||||
renderMentionChipDom(dom, this.__path);
|
||||
@@ -170,76 +141,15 @@ function $createComposerMentionNode(path: string): ComposerMentionNode {
|
||||
return $applyNodeReplacement(new ComposerMentionNode(path));
|
||||
}
|
||||
|
||||
function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft }) {
|
||||
return <ComposerPendingTerminalContextChip context={props.context} />;
|
||||
}
|
||||
|
||||
class ComposerTerminalContextNode extends DecoratorNode<ReactElement> {
|
||||
__context: TerminalContextDraft;
|
||||
|
||||
static override getType(): string {
|
||||
return "composer-terminal-context";
|
||||
function inferMentionPathKind(pathValue: string): "file" | "directory" {
|
||||
const base = basenameOfPath(pathValue);
|
||||
if (base.startsWith(".") && !base.slice(1).includes(".")) {
|
||||
return "directory";
|
||||
}
|
||||
|
||||
static override clone(node: ComposerTerminalContextNode): ComposerTerminalContextNode {
|
||||
return new ComposerTerminalContextNode(node.__context, node.__key);
|
||||
if (base.includes(".")) {
|
||||
return "file";
|
||||
}
|
||||
|
||||
static override importJSON(
|
||||
serializedNode: SerializedComposerTerminalContextNode,
|
||||
): ComposerTerminalContextNode {
|
||||
return $createComposerTerminalContextNode(serializedNode.context);
|
||||
}
|
||||
|
||||
constructor(context: TerminalContextDraft, key?: NodeKey) {
|
||||
super(key);
|
||||
this.__context = context;
|
||||
}
|
||||
|
||||
override exportJSON(): SerializedComposerTerminalContextNode {
|
||||
return {
|
||||
...super.exportJSON(),
|
||||
context: this.__context,
|
||||
type: "composer-terminal-context",
|
||||
version: 1,
|
||||
};
|
||||
}
|
||||
|
||||
override createDOM(): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className = "inline-flex align-middle leading-none";
|
||||
return dom;
|
||||
}
|
||||
|
||||
override updateDOM(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override getTextContent(): string {
|
||||
return INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
|
||||
}
|
||||
|
||||
override isInline(): true {
|
||||
return true;
|
||||
}
|
||||
|
||||
override decorate(): ReactElement {
|
||||
return <ComposerTerminalContextDecorator context={this.__context} />;
|
||||
}
|
||||
}
|
||||
|
||||
function $createComposerTerminalContextNode(
|
||||
context: TerminalContextDraft,
|
||||
): ComposerTerminalContextNode {
|
||||
return $applyNodeReplacement(new ComposerTerminalContextNode(context));
|
||||
}
|
||||
|
||||
type ComposerInlineTokenNode = ComposerMentionNode | ComposerTerminalContextNode;
|
||||
|
||||
function isComposerInlineTokenNode(candidate: unknown): candidate is ComposerInlineTokenNode {
|
||||
return (
|
||||
candidate instanceof ComposerMentionNode || candidate instanceof ComposerTerminalContextNode
|
||||
);
|
||||
return "directory";
|
||||
}
|
||||
|
||||
function resolvedThemeFromDocument(): "light" | "dark" {
|
||||
@@ -255,91 +165,25 @@ function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
|
||||
const icon = document.createElement("img");
|
||||
icon.alt = "";
|
||||
icon.ariaHidden = "true";
|
||||
icon.className = COMPOSER_INLINE_CHIP_ICON_CLASS_NAME;
|
||||
icon.className = "size-3.5 shrink-0 opacity-85";
|
||||
icon.loading = "lazy";
|
||||
icon.src = getVscodeIconUrlForEntry(pathValue, inferEntryKindFromPath(pathValue), theme);
|
||||
icon.src = getVscodeIconUrlForEntry(pathValue, inferMentionPathKind(pathValue), theme);
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.className = COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME;
|
||||
label.className = "truncate select-none leading-tight";
|
||||
label.textContent = basenameOfPath(pathValue);
|
||||
|
||||
container.append(icon, label);
|
||||
}
|
||||
|
||||
function terminalContextSignature(contexts: ReadonlyArray<TerminalContextDraft>): string {
|
||||
return contexts
|
||||
.map((context) =>
|
||||
[
|
||||
context.id,
|
||||
context.threadId,
|
||||
context.terminalId,
|
||||
context.terminalLabel,
|
||||
context.lineStart,
|
||||
context.lineEnd,
|
||||
context.createdAt,
|
||||
context.text,
|
||||
].join("\u001f"),
|
||||
)
|
||||
.join("\u001e");
|
||||
}
|
||||
|
||||
function clampExpandedCursor(value: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return value.length;
|
||||
return Math.max(0, Math.min(value.length, Math.floor(cursor)));
|
||||
}
|
||||
|
||||
function getComposerInlineTokenTextLength(_node: ComposerInlineTokenNode): 1 {
|
||||
return 1;
|
||||
}
|
||||
|
||||
function getComposerInlineTokenExpandedTextLength(node: ComposerInlineTokenNode): number {
|
||||
return node.getTextContentSize();
|
||||
}
|
||||
|
||||
function getAbsoluteOffsetForInlineTokenPoint(
|
||||
node: ComposerInlineTokenNode,
|
||||
absoluteOffset: number,
|
||||
pointOffset: number,
|
||||
): number {
|
||||
return absoluteOffset + (pointOffset > 0 ? getComposerInlineTokenTextLength(node) : 0);
|
||||
}
|
||||
|
||||
function getExpandedAbsoluteOffsetForInlineTokenPoint(
|
||||
node: ComposerInlineTokenNode,
|
||||
absoluteOffset: number,
|
||||
pointOffset: number,
|
||||
): number {
|
||||
return absoluteOffset + (pointOffset > 0 ? getComposerInlineTokenExpandedTextLength(node) : 0);
|
||||
}
|
||||
|
||||
function findSelectionPointForInlineToken(
|
||||
node: ComposerInlineTokenNode,
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "element" } | null {
|
||||
const parent = node.getParent();
|
||||
if (!parent || !$isElementNode(parent)) return null;
|
||||
const index = node.getIndexWithinParent();
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
if (remainingRef.value === getComposerInlineTokenTextLength(node)) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index + 1,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= getComposerInlineTokenTextLength(node);
|
||||
return null;
|
||||
}
|
||||
|
||||
function getComposerNodeTextLength(node: LexicalNode): number {
|
||||
if (isComposerInlineTokenNode(node)) {
|
||||
return getComposerInlineTokenTextLength(node);
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return 1;
|
||||
}
|
||||
if ($isTextNode(node)) {
|
||||
return node.getTextContentSize();
|
||||
@@ -354,9 +198,6 @@ function getComposerNodeTextLength(node: LexicalNode): number {
|
||||
}
|
||||
|
||||
function getComposerNodeExpandedTextLength(node: LexicalNode): number {
|
||||
if (isComposerInlineTokenNode(node)) {
|
||||
return getComposerInlineTokenExpandedTextLength(node);
|
||||
}
|
||||
if ($isTextNode(node)) {
|
||||
return node.getTextContentSize();
|
||||
}
|
||||
@@ -392,13 +233,10 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
return offset + (pointOffset > 0 ? 1 : 0);
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
if ($isLineBreakNode(node)) {
|
||||
return offset + Math.min(pointOffset, 1);
|
||||
@@ -439,13 +277,10 @@ function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: numbe
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
return offset + (pointOffset > 0 ? node.getTextContentSize() : 0);
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
if ($isLineBreakNode(node)) {
|
||||
return offset + Math.min(pointOffset, 1);
|
||||
@@ -470,10 +305,25 @@ function findSelectionPointAtOffset(
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "text" | "element" } | null {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
const parent = node.getParent();
|
||||
if (!parent || !$isElementNode(parent)) return null;
|
||||
const index = node.getIndexWithinParent();
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
if (remainingRef.value === 1) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index + 1,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= 1;
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
@@ -588,67 +438,40 @@ function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function $setComposerEditorPrompt(
|
||||
prompt: string,
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>,
|
||||
): void {
|
||||
function $setComposerEditorPrompt(prompt: string): void {
|
||||
const root = $getRoot();
|
||||
root.clear();
|
||||
const paragraph = $createParagraphNode();
|
||||
root.append(paragraph);
|
||||
|
||||
const segments = splitPromptIntoComposerSegments(prompt, terminalContexts);
|
||||
const segments = splitPromptIntoComposerSegments(prompt);
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
paragraph.append($createComposerMentionNode(segment.path));
|
||||
continue;
|
||||
}
|
||||
if (segment.type === "terminal-context") {
|
||||
if (segment.context) {
|
||||
paragraph.append($createComposerTerminalContextNode(segment.context));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$appendTextWithLineBreaks(paragraph, segment.text);
|
||||
}
|
||||
}
|
||||
|
||||
function collectTerminalContextIds(node: LexicalNode): string[] {
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return [node.__context.id];
|
||||
}
|
||||
if ($isElementNode(node)) {
|
||||
return node.getChildren().flatMap((child) => collectTerminalContextIds(child));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export interface ComposerPromptEditorHandle {
|
||||
focus: () => void;
|
||||
focusAt: (cursor: number) => void;
|
||||
focusAtEnd: () => void;
|
||||
readSnapshot: () => {
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
terminalContextIds: string[];
|
||||
};
|
||||
readSnapshot: () => { value: string; cursor: number; expandedCursor: number };
|
||||
}
|
||||
|
||||
interface ComposerPromptEditorProps {
|
||||
value: string;
|
||||
cursor: number;
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
disabled: boolean;
|
||||
placeholder: string;
|
||||
className?: string;
|
||||
onRemoveTerminalContext: (contextId: string) => void;
|
||||
onChange: (
|
||||
nextValue: string,
|
||||
nextCursor: number,
|
||||
expandedCursor: number,
|
||||
cursorAdjacentToMention: boolean,
|
||||
terminalContextIds: string[],
|
||||
) => void;
|
||||
onCommandKeyDown?: (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
@@ -717,7 +540,7 @@ function ComposerCommandKeyPlugin(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerInlineTokenArrowPlugin() {
|
||||
function ComposerMentionArrowPlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -731,7 +554,7 @@ function ComposerInlineTokenArrowPlugin() {
|
||||
const currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
if (currentOffset <= 0) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "left")) {
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "left")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset - 1;
|
||||
@@ -758,7 +581,7 @@ function ComposerInlineTokenArrowPlugin() {
|
||||
const composerLength = $getComposerRootLength();
|
||||
if (currentOffset >= composerLength) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "right")) {
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "right")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset + 1;
|
||||
@@ -783,7 +606,7 @@ function ComposerInlineTokenArrowPlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerInlineTokenSelectionNormalizePlugin() {
|
||||
function ComposerMentionSelectionNormalizePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -793,7 +616,7 @@ function ComposerInlineTokenSelectionNormalizePlugin() {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
if (!isComposerInlineTokenNode(anchorNode)) return;
|
||||
if (!(anchorNode instanceof ComposerMentionNode)) return;
|
||||
if (selection.anchor.offset === 0) return;
|
||||
const beforeOffset = getAbsoluteOffsetForPoint(anchorNode, 0);
|
||||
afterOffset = beforeOffset + 1;
|
||||
@@ -811,9 +634,8 @@ function ComposerInlineTokenSelectionNormalizePlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerInlineTokenBackspacePlugin() {
|
||||
function ComposerMentionBackspacePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const { onRemoveTerminalContext } = useContext(ComposerTerminalContextActionsContext);
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerCommand(
|
||||
@@ -825,23 +647,18 @@ function ComposerInlineTokenBackspacePlugin() {
|
||||
}
|
||||
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
const selectionOffset = $readSelectionOffsetFromEditorState(0);
|
||||
const removeInlineTokenNode = (candidate: unknown): boolean => {
|
||||
if (!isComposerInlineTokenNode(candidate)) {
|
||||
const removeMentionNode = (candidate: unknown): boolean => {
|
||||
if (!(candidate instanceof ComposerMentionNode)) {
|
||||
return false;
|
||||
}
|
||||
const tokenStart = getAbsoluteOffsetForPoint(candidate, 0);
|
||||
const mentionStart = getAbsoluteOffsetForPoint(candidate, 0);
|
||||
candidate.remove();
|
||||
if (candidate instanceof ComposerTerminalContextNode) {
|
||||
onRemoveTerminalContext(candidate.__context.id);
|
||||
$setSelectionAtComposerOffset(selectionOffset);
|
||||
} else {
|
||||
$setSelectionAtComposerOffset(tokenStart);
|
||||
}
|
||||
$setSelectionAtComposerOffset(mentionStart);
|
||||
event?.preventDefault();
|
||||
return true;
|
||||
};
|
||||
if (removeInlineTokenNode(anchorNode)) {
|
||||
|
||||
if (removeMentionNode(anchorNode)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -849,13 +666,13 @@ function ComposerInlineTokenBackspacePlugin() {
|
||||
if (selection.anchor.offset > 0) {
|
||||
return false;
|
||||
}
|
||||
if (removeInlineTokenNode(anchorNode.getPreviousSibling())) {
|
||||
if (removeMentionNode(anchorNode.getPreviousSibling())) {
|
||||
return true;
|
||||
}
|
||||
const parent = anchorNode.getParent();
|
||||
if ($isElementNode(parent)) {
|
||||
const index = anchorNode.getIndexWithinParent();
|
||||
if (index > 0 && removeInlineTokenNode(parent.getChildAtIndex(index - 1))) {
|
||||
if (index > 0 && removeMentionNode(parent.getChildAtIndex(index - 1))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -864,7 +681,7 @@ function ComposerInlineTokenBackspacePlugin() {
|
||||
|
||||
if ($isElementNode(anchorNode)) {
|
||||
const childIndex = selection.anchor.offset - 1;
|
||||
if (childIndex >= 0 && removeInlineTokenNode(anchorNode.getChildAtIndex(childIndex))) {
|
||||
if (childIndex >= 0 && removeMentionNode(anchorNode.getChildAtIndex(childIndex))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -873,7 +690,7 @@ function ComposerInlineTokenBackspacePlugin() {
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
}, [editor, onRemoveTerminalContext]);
|
||||
}, [editor]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -881,11 +698,9 @@ function ComposerInlineTokenBackspacePlugin() {
|
||||
function ComposerPromptEditorInner({
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onRemoveTerminalContext,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
@@ -894,19 +709,12 @@ function ComposerPromptEditorInner({
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const onChangeRef = useRef(onChange);
|
||||
const initialCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const terminalContextsSignature = terminalContextSignature(terminalContexts);
|
||||
const terminalContextsSignatureRef = useRef(terminalContextsSignature);
|
||||
const snapshotRef = useRef({
|
||||
value,
|
||||
cursor: initialCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(value, initialCursor),
|
||||
terminalContextIds: terminalContexts.map((context) => context.id),
|
||||
});
|
||||
const isApplyingControlledUpdateRef = useRef(false);
|
||||
const terminalContextActions = useMemo(
|
||||
() => ({ onRemoveTerminalContext }),
|
||||
[onRemoveTerminalContext],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange;
|
||||
@@ -919,12 +727,7 @@ function ComposerPromptEditorInner({
|
||||
useLayoutEffect(() => {
|
||||
const normalizedCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
const contextsChanged = terminalContextsSignatureRef.current !== terminalContextsSignature;
|
||||
if (
|
||||
previousSnapshot.value === value &&
|
||||
previousSnapshot.cursor === normalizedCursor &&
|
||||
!contextsChanged
|
||||
) {
|
||||
if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -932,30 +735,28 @@ function ComposerPromptEditorInner({
|
||||
value,
|
||||
cursor: normalizedCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(value, normalizedCursor),
|
||||
terminalContextIds: terminalContexts.map((context) => context.id),
|
||||
};
|
||||
terminalContextsSignatureRef.current = terminalContextsSignature;
|
||||
|
||||
const rootElement = editor.getRootElement();
|
||||
const isFocused = Boolean(rootElement && document.activeElement === rootElement);
|
||||
if (previousSnapshot.value === value && !contextsChanged && !isFocused) {
|
||||
if (previousSnapshot.value === value && !isFocused) {
|
||||
return;
|
||||
}
|
||||
|
||||
isApplyingControlledUpdateRef.current = true;
|
||||
editor.update(() => {
|
||||
const shouldRewriteEditorState = previousSnapshot.value !== value || contextsChanged;
|
||||
if (shouldRewriteEditorState) {
|
||||
$setComposerEditorPrompt(value, terminalContexts);
|
||||
const valueChanged = previousSnapshot.value !== value;
|
||||
if (previousSnapshot.value !== value) {
|
||||
$setComposerEditorPrompt(value);
|
||||
}
|
||||
if (shouldRewriteEditorState || isFocused) {
|
||||
if (valueChanged || isFocused) {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
}
|
||||
});
|
||||
queueMicrotask(() => {
|
||||
isApplyingControlledUpdateRef.current = false;
|
||||
});
|
||||
}, [cursor, editor, terminalContexts, terminalContextsSignature, value]);
|
||||
}, [cursor, editor, value]);
|
||||
|
||||
const focusAt = useCallback(
|
||||
(nextCursor: number) => {
|
||||
@@ -970,14 +771,12 @@ function ComposerPromptEditorInner({
|
||||
value: snapshotRef.current.value,
|
||||
cursor: boundedCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(snapshotRef.current.value, boundedCursor),
|
||||
terminalContextIds: snapshotRef.current.terminalContextIds,
|
||||
};
|
||||
onChangeRef.current(
|
||||
snapshotRef.current.value,
|
||||
boundedCursor,
|
||||
snapshotRef.current.expandedCursor,
|
||||
false,
|
||||
snapshotRef.current.terminalContextIds,
|
||||
);
|
||||
},
|
||||
[editor],
|
||||
@@ -987,7 +786,6 @@ function ComposerPromptEditorInner({
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
terminalContextIds: string[];
|
||||
} => {
|
||||
let snapshot = snapshotRef.current;
|
||||
editor.getEditorState().read(() => {
|
||||
@@ -1005,12 +803,10 @@ function ComposerPromptEditorInner({
|
||||
nextValue,
|
||||
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
|
||||
);
|
||||
const terminalContextIds = collectTerminalContextIds($getRoot());
|
||||
snapshot = {
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
expandedCursor: nextExpandedCursor,
|
||||
terminalContextIds,
|
||||
};
|
||||
});
|
||||
snapshotRef.current = snapshot;
|
||||
@@ -1053,14 +849,11 @@ function ComposerPromptEditorInner({
|
||||
nextValue,
|
||||
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
|
||||
);
|
||||
const terminalContextIds = collectTerminalContextIds($getRoot());
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
if (
|
||||
previousSnapshot.value === nextValue &&
|
||||
previousSnapshot.cursor === nextCursor &&
|
||||
previousSnapshot.expandedCursor === nextExpandedCursor &&
|
||||
previousSnapshot.terminalContextIds.length === terminalContextIds.length &&
|
||||
previousSnapshot.terminalContextIds.every((id, index) => id === terminalContextIds[index])
|
||||
previousSnapshot.expandedCursor === nextExpandedCursor
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -1071,54 +864,43 @@ function ComposerPromptEditorInner({
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
expandedCursor: nextExpandedCursor,
|
||||
terminalContextIds,
|
||||
};
|
||||
const cursorAdjacentToMention =
|
||||
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(
|
||||
nextValue,
|
||||
nextCursor,
|
||||
nextExpandedCursor,
|
||||
cursorAdjacentToMention,
|
||||
terminalContextIds,
|
||||
);
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, cursorAdjacentToMention);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ComposerTerminalContextActionsContext.Provider value={terminalContextActions}>
|
||||
<div className="relative">
|
||||
<PlainTextPlugin
|
||||
contentEditable={
|
||||
<ContentEditable
|
||||
className={cn(
|
||||
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
|
||||
className,
|
||||
)}
|
||||
data-testid="composer-editor"
|
||||
aria-placeholder={placeholder}
|
||||
placeholder={<span />}
|
||||
onPaste={onPaste}
|
||||
/>
|
||||
}
|
||||
placeholder={
|
||||
terminalContexts.length > 0 ? null : (
|
||||
<div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
|
||||
{placeholder}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
ErrorBoundary={LexicalErrorBoundary}
|
||||
/>
|
||||
<OnChangePlugin onChange={handleEditorChange} />
|
||||
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||
<ComposerInlineTokenArrowPlugin />
|
||||
<ComposerInlineTokenSelectionNormalizePlugin />
|
||||
<ComposerInlineTokenBackspacePlugin />
|
||||
<HistoryPlugin />
|
||||
</div>
|
||||
</ComposerTerminalContextActionsContext.Provider>
|
||||
<div className="relative">
|
||||
<PlainTextPlugin
|
||||
contentEditable={
|
||||
<ContentEditable
|
||||
className={cn(
|
||||
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
|
||||
className,
|
||||
)}
|
||||
data-testid="composer-editor"
|
||||
aria-placeholder={placeholder}
|
||||
placeholder={<span />}
|
||||
onPaste={onPaste}
|
||||
/>
|
||||
}
|
||||
placeholder={
|
||||
<div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
|
||||
{placeholder}
|
||||
</div>
|
||||
}
|
||||
ErrorBoundary={LexicalErrorBoundary}
|
||||
/>
|
||||
<OnChangePlugin onChange={handleEditorChange} />
|
||||
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||
<ComposerMentionArrowPlugin />
|
||||
<ComposerMentionSelectionNormalizePlugin />
|
||||
<ComposerMentionBackspacePlugin />
|
||||
<HistoryPlugin />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1126,29 +908,17 @@ export const ComposerPromptEditor = forwardRef<
|
||||
ComposerPromptEditorHandle,
|
||||
ComposerPromptEditorProps
|
||||
>(function ComposerPromptEditor(
|
||||
{
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onRemoveTerminalContext,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
},
|
||||
{ value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
|
||||
ref,
|
||||
) {
|
||||
const initialValueRef = useRef(value);
|
||||
const initialTerminalContextsRef = useRef(terminalContexts);
|
||||
const initialConfig = useMemo<InitialConfigType>(
|
||||
() => ({
|
||||
namespace: "t3tools-composer-editor",
|
||||
editable: true,
|
||||
nodes: [ComposerMentionNode, ComposerTerminalContextNode],
|
||||
nodes: [ComposerMentionNode],
|
||||
editorState: () => {
|
||||
$setComposerEditorPrompt(initialValueRef.current, initialTerminalContextsRef.current);
|
||||
$setComposerEditorPrompt(initialValueRef.current);
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
@@ -1162,10 +932,8 @@ export const ComposerPromptEditor = forwardRef<
|
||||
<ComposerPromptEditorInner
|
||||
value={value}
|
||||
cursor={cursor}
|
||||
terminalContexts={terminalContexts}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
onRemoveTerminalContext={onRemoveTerminalContext}
|
||||
onChange={onChange}
|
||||
onPaste={onPaste}
|
||||
editorRef={ref}
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
resolveQuickAction,
|
||||
summarizeGitResult,
|
||||
} from "./GitActionsControl.logic";
|
||||
import { useAppSettings } from "~/appSettings";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Checkbox } from "~/components/ui/checkbox";
|
||||
import {
|
||||
@@ -155,7 +154,6 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
|
||||
}
|
||||
|
||||
export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsControlProps) {
|
||||
const { settings } = useAppSettings();
|
||||
const threadToastData = useMemo(
|
||||
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
|
||||
[activeThreadId],
|
||||
@@ -193,11 +191,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const initMutation = useMutation(gitInitMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
const runImmediateGitActionMutation = useMutation(
|
||||
gitRunStackedActionMutationOptions({
|
||||
cwd: gitCwd,
|
||||
queryClient,
|
||||
model: settings.textGenerationModel ?? null,
|
||||
}),
|
||||
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
|
||||
);
|
||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
|
||||
@@ -141,8 +141,6 @@ describe("resolveThreadStatusPill", () => {
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
planMarkdown: "# Plan",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
},
|
||||
],
|
||||
session: {
|
||||
@@ -157,35 +155,6 @@ describe("resolveThreadStatusPill", () => {
|
||||
).toMatchObject({ label: "Plan Ready", pulse: false });
|
||||
});
|
||||
|
||||
it("does not show plan ready after the proposed plan was implemented elsewhere", () => {
|
||||
expect(
|
||||
resolveThreadStatusPill({
|
||||
thread: {
|
||||
...baseThread,
|
||||
latestTurn: makeLatestTurn(),
|
||||
proposedPlans: [
|
||||
{
|
||||
id: "plan-1" as never,
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
planMarkdown: "# Plan",
|
||||
implementedAt: "2026-03-09T10:06:00.000Z",
|
||||
implementationThreadId: "thread-implement" as never,
|
||||
},
|
||||
],
|
||||
session: {
|
||||
...baseThread.session,
|
||||
status: "ready",
|
||||
orchestrationStatus: "ready",
|
||||
},
|
||||
},
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
}),
|
||||
).toMatchObject({ label: "Completed", pulse: false });
|
||||
});
|
||||
|
||||
it("shows completed when there is an unseen completion and no active blocker", () => {
|
||||
expect(
|
||||
resolveThreadStatusPill({
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import type { Thread } from "../types";
|
||||
import { cn } from "../lib/utils";
|
||||
import {
|
||||
findLatestProposedPlan,
|
||||
hasActionableProposedPlan,
|
||||
isLatestTurnSettled,
|
||||
} from "../session-logic";
|
||||
import { findLatestProposedPlan, isLatestTurnSettled } from "../session-logic";
|
||||
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
@@ -55,7 +51,7 @@ export function resolveThreadRowClassName(input: {
|
||||
isSelected: boolean;
|
||||
}): string {
|
||||
const baseClassName =
|
||||
"h-7 w-full translate-x-0 cursor-pointer justify-start px-2 text-left select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring";
|
||||
"h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring";
|
||||
|
||||
if (input.isSelected && input.isActive) {
|
||||
return cn(
|
||||
@@ -128,9 +124,7 @@ export function resolveThreadStatusPill(input: {
|
||||
!hasPendingUserInput &&
|
||||
thread.interactionMode === "plan" &&
|
||||
isLatestTurnSettled(thread.latestTurn, thread.session) &&
|
||||
hasActionableProposedPlan(
|
||||
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null),
|
||||
);
|
||||
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null) !== null;
|
||||
if (hasPlanReadyPrompt) {
|
||||
return {
|
||||
label: "Plan Ready",
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
type DragEndEvent,
|
||||
} from "@dnd-kit/core";
|
||||
import { SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
|
||||
import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";
|
||||
import { restrictToParentElement, restrictToVerticalAxis } from "@dnd-kit/modifiers";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
@@ -561,6 +561,7 @@ export default function Sidebar() {
|
||||
if (!api) return;
|
||||
const thread = threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
|
||||
const threadProject = projects.find((project) => project.id === thread.projectId);
|
||||
// When bulk-deleting, exclude the other threads being deleted so
|
||||
// getOrphanedWorktreePathForThread correctly detects that no surviving
|
||||
@@ -664,7 +665,7 @@ export default function Sidebar() {
|
||||
],
|
||||
);
|
||||
|
||||
const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
|
||||
const { copyToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
|
||||
onCopy: (ctx) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
@@ -680,40 +681,21 @@ export default function Sidebar() {
|
||||
});
|
||||
},
|
||||
});
|
||||
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
|
||||
onCopy: (ctx) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Path copied",
|
||||
description: ctx.path,
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to copy path",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
},
|
||||
});
|
||||
const handleThreadContextMenu = useCallback(
|
||||
async (threadId: ThreadId, position: { x: number; y: number }) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const thread = threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
const threadWorkspacePath =
|
||||
thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "copy-path", label: "Copy Path" },
|
||||
{ id: "copy-thread-id", label: "Copy Thread ID" },
|
||||
{ id: "delete", label: "Delete", destructive: true },
|
||||
],
|
||||
position,
|
||||
);
|
||||
const thread = threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
|
||||
if (clicked === "rename") {
|
||||
setRenamingThreadId(threadId);
|
||||
@@ -726,20 +708,8 @@ export default function Sidebar() {
|
||||
markThreadUnread(threadId);
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-path") {
|
||||
if (!threadWorkspacePath) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Path unavailable",
|
||||
description: "This thread does not have a workspace path to copy.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath });
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-thread-id") {
|
||||
copyThreadIdToClipboard(threadId, { threadId });
|
||||
copyToClipboard(threadId, { threadId });
|
||||
return;
|
||||
}
|
||||
if (clicked !== "delete") return;
|
||||
@@ -756,15 +726,7 @@ export default function Sidebar() {
|
||||
}
|
||||
await deleteThread(threadId);
|
||||
},
|
||||
[
|
||||
appSettings.confirmThreadDelete,
|
||||
copyPathToClipboard,
|
||||
copyThreadIdToClipboard,
|
||||
deleteThread,
|
||||
markThreadUnread,
|
||||
projectCwdById,
|
||||
threads,
|
||||
],
|
||||
[appSettings.confirmThreadDelete, copyToClipboard, deleteThread, markThreadUnread, threads],
|
||||
);
|
||||
|
||||
const handleMultiSelectContextMenu = useCallback(
|
||||
@@ -1320,7 +1282,7 @@ export default function Sidebar() {
|
||||
<DndContext
|
||||
sensors={projectDnDSensors}
|
||||
collisionDetection={projectCollisionDetection}
|
||||
modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}
|
||||
modifiers={[restrictToVerticalAxis, restrictToParentElement]}
|
||||
onDragStart={handleProjectDragStart}
|
||||
onDragEnd={handleProjectDragEnd}
|
||||
onDragCancel={handleProjectDragCancel}
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveTerminalSelectionActionPosition,
|
||||
shouldHandleTerminalSelectionMouseUp,
|
||||
terminalSelectionActionDelayForClickCount,
|
||||
} from "./ThreadTerminalDrawer";
|
||||
|
||||
describe("resolveTerminalSelectionActionPosition", () => {
|
||||
it("prefers the selection rect over the last pointer position", () => {
|
||||
expect(
|
||||
resolveTerminalSelectionActionPosition({
|
||||
bounds: { left: 100, top: 50, width: 500, height: 220 },
|
||||
selectionRect: { right: 260, bottom: 140 },
|
||||
pointer: { x: 520, y: 200 },
|
||||
viewport: { width: 1024, height: 768 },
|
||||
}),
|
||||
).toEqual({
|
||||
x: 260,
|
||||
y: 144,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the pointer position when no selection rect is available", () => {
|
||||
expect(
|
||||
resolveTerminalSelectionActionPosition({
|
||||
bounds: { left: 100, top: 50, width: 500, height: 220 },
|
||||
selectionRect: null,
|
||||
pointer: { x: 180, y: 130 },
|
||||
viewport: { width: 1024, height: 768 },
|
||||
}),
|
||||
).toEqual({
|
||||
x: 180,
|
||||
y: 130,
|
||||
});
|
||||
});
|
||||
|
||||
it("clamps the pointer fallback into the terminal drawer bounds", () => {
|
||||
expect(
|
||||
resolveTerminalSelectionActionPosition({
|
||||
bounds: { left: 100, top: 50, width: 500, height: 220 },
|
||||
selectionRect: null,
|
||||
pointer: { x: 720, y: 340 },
|
||||
viewport: { width: 1024, height: 768 },
|
||||
}),
|
||||
).toEqual({
|
||||
x: 600,
|
||||
y: 270,
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveTerminalSelectionActionPosition({
|
||||
bounds: { left: 100, top: 50, width: 500, height: 220 },
|
||||
selectionRect: null,
|
||||
pointer: { x: 40, y: 20 },
|
||||
viewport: { width: 1024, height: 768 },
|
||||
}),
|
||||
).toEqual({
|
||||
x: 100,
|
||||
y: 50,
|
||||
});
|
||||
});
|
||||
|
||||
it("delays multi-click selection actions so triple-click selection can complete", () => {
|
||||
expect(terminalSelectionActionDelayForClickCount(1)).toBe(0);
|
||||
expect(terminalSelectionActionDelayForClickCount(2)).toBe(260);
|
||||
expect(terminalSelectionActionDelayForClickCount(3)).toBe(260);
|
||||
});
|
||||
|
||||
it("only handles mouseup when the selection gesture started in the terminal", () => {
|
||||
expect(shouldHandleTerminalSelectionMouseUp(true, 0)).toBe(true);
|
||||
expect(shouldHandleTerminalSelectionMouseUp(false, 0)).toBe(false);
|
||||
expect(shouldHandleTerminalSelectionMouseUp(true, 1)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { type TerminalContextSelection } from "~/lib/terminalContext";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import {
|
||||
extractTerminalLinks,
|
||||
@@ -30,7 +29,6 @@ import { readNativeApi } from "~/nativeApi";
|
||||
|
||||
const MIN_DRAWER_HEIGHT = 180;
|
||||
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
|
||||
const MULTI_CLICK_SELECTION_ACTION_DELAY_MS = 260;
|
||||
|
||||
function maxDrawerHeight(): number {
|
||||
if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
|
||||
@@ -109,85 +107,12 @@ function terminalThemeFromApp(): ITheme {
|
||||
};
|
||||
}
|
||||
|
||||
function getTerminalSelectionRect(mountElement: HTMLElement): DOMRect | null {
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const range = selection.getRangeAt(0);
|
||||
const commonAncestor = range.commonAncestorContainer;
|
||||
const selectionRoot =
|
||||
commonAncestor instanceof Element ? commonAncestor : commonAncestor.parentElement;
|
||||
if (!(selectionRoot instanceof Element) || !mountElement.contains(selectionRoot)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rects = Array.from(range.getClientRects()).filter(
|
||||
(rect) => rect.width > 0 || rect.height > 0,
|
||||
);
|
||||
if (rects.length > 0) {
|
||||
return rects[rects.length - 1] ?? null;
|
||||
}
|
||||
|
||||
const boundingRect = range.getBoundingClientRect();
|
||||
return boundingRect.width > 0 || boundingRect.height > 0 ? boundingRect : null;
|
||||
}
|
||||
|
||||
export function resolveTerminalSelectionActionPosition(options: {
|
||||
bounds: { left: number; top: number; width: number; height: number };
|
||||
selectionRect: { right: number; bottom: number } | null;
|
||||
pointer: { x: number; y: number } | null;
|
||||
viewport?: { width: number; height: number } | null;
|
||||
}): { x: number; y: number } {
|
||||
const { bounds, selectionRect, pointer, viewport } = options;
|
||||
const viewportWidth =
|
||||
viewport?.width ??
|
||||
(typeof window === "undefined" ? bounds.left + bounds.width + 8 : window.innerWidth);
|
||||
const viewportHeight =
|
||||
viewport?.height ??
|
||||
(typeof window === "undefined" ? bounds.top + bounds.height + 8 : window.innerHeight);
|
||||
const drawerLeft = Math.round(bounds.left);
|
||||
const drawerTop = Math.round(bounds.top);
|
||||
const drawerRight = Math.round(bounds.left + bounds.width);
|
||||
const drawerBottom = Math.round(bounds.top + bounds.height);
|
||||
const preferredX =
|
||||
selectionRect !== null
|
||||
? Math.round(selectionRect.right)
|
||||
: pointer === null
|
||||
? Math.round(bounds.left + bounds.width - 140)
|
||||
: Math.max(drawerLeft, Math.min(Math.round(pointer.x), drawerRight));
|
||||
const preferredY =
|
||||
selectionRect !== null
|
||||
? Math.round(selectionRect.bottom + 4)
|
||||
: pointer === null
|
||||
? Math.round(bounds.top + 12)
|
||||
: Math.max(drawerTop, Math.min(Math.round(pointer.y), drawerBottom));
|
||||
return {
|
||||
x: Math.max(8, Math.min(preferredX, Math.max(viewportWidth - 8, 8))),
|
||||
y: Math.max(8, Math.min(preferredY, Math.max(viewportHeight - 8, 8))),
|
||||
};
|
||||
}
|
||||
|
||||
export function terminalSelectionActionDelayForClickCount(clickCount: number): number {
|
||||
return clickCount >= 2 ? MULTI_CLICK_SELECTION_ACTION_DELAY_MS : 0;
|
||||
}
|
||||
|
||||
export function shouldHandleTerminalSelectionMouseUp(
|
||||
selectionGestureActive: boolean,
|
||||
button: number,
|
||||
): boolean {
|
||||
return selectionGestureActive && button === 0;
|
||||
}
|
||||
|
||||
interface TerminalViewportProps {
|
||||
threadId: ThreadId;
|
||||
terminalId: string;
|
||||
terminalLabel: string;
|
||||
cwd: string;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
onSessionExited: () => void;
|
||||
onAddTerminalContext: (selection: TerminalContextSelection) => void;
|
||||
focusRequestId: number;
|
||||
autoFocus: boolean;
|
||||
resizeEpoch: number;
|
||||
@@ -197,11 +122,9 @@ interface TerminalViewportProps {
|
||||
function TerminalViewport({
|
||||
threadId,
|
||||
terminalId,
|
||||
terminalLabel,
|
||||
cwd,
|
||||
runtimeEnv,
|
||||
onSessionExited,
|
||||
onAddTerminalContext,
|
||||
focusRequestId,
|
||||
autoFocus,
|
||||
resizeEpoch,
|
||||
@@ -211,27 +134,12 @@ function TerminalViewport({
|
||||
const terminalRef = useRef<Terminal | null>(null);
|
||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||
const onSessionExitedRef = useRef(onSessionExited);
|
||||
const onAddTerminalContextRef = useRef(onAddTerminalContext);
|
||||
const terminalLabelRef = useRef(terminalLabel);
|
||||
const hasHandledExitRef = useRef(false);
|
||||
const selectionPointerRef = useRef<{ x: number; y: number } | null>(null);
|
||||
const selectionGestureActiveRef = useRef(false);
|
||||
const selectionActionRequestIdRef = useRef(0);
|
||||
const selectionActionOpenRef = useRef(false);
|
||||
const selectionActionTimerRef = useRef<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
onSessionExitedRef.current = onSessionExited;
|
||||
}, [onSessionExited]);
|
||||
|
||||
useEffect(() => {
|
||||
onAddTerminalContextRef.current = onAddTerminalContext;
|
||||
}, [onAddTerminalContext]);
|
||||
|
||||
useEffect(() => {
|
||||
terminalLabelRef.current = terminalLabel;
|
||||
}, [terminalLabel]);
|
||||
|
||||
useEffect(() => {
|
||||
const mount = containerRef.current;
|
||||
if (!mount) return;
|
||||
@@ -257,81 +165,6 @@ function TerminalViewport({
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
|
||||
const clearSelectionAction = () => {
|
||||
selectionActionRequestIdRef.current += 1;
|
||||
if (selectionActionTimerRef.current !== null) {
|
||||
window.clearTimeout(selectionActionTimerRef.current);
|
||||
selectionActionTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const readSelectionAction = (): {
|
||||
position: { x: number; y: number };
|
||||
selection: TerminalContextSelection;
|
||||
} | null => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
const mountElement = containerRef.current;
|
||||
if (!activeTerminal || !mountElement || !activeTerminal.hasSelection()) {
|
||||
return null;
|
||||
}
|
||||
const selectionText = activeTerminal.getSelection();
|
||||
const selectionPosition = activeTerminal.getSelectionPosition();
|
||||
const normalizedText = selectionText.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
|
||||
if (!selectionPosition || normalizedText.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const lineStart = selectionPosition.start.y + 1;
|
||||
const lineCount = normalizedText.split("\n").length;
|
||||
const lineEnd = Math.max(lineStart, lineStart + lineCount - 1);
|
||||
const bounds = mountElement.getBoundingClientRect();
|
||||
const selectionRect = getTerminalSelectionRect(mountElement);
|
||||
const position = resolveTerminalSelectionActionPosition({
|
||||
bounds,
|
||||
selectionRect:
|
||||
selectionRect === null
|
||||
? null
|
||||
: { right: selectionRect.right, bottom: selectionRect.bottom },
|
||||
pointer: selectionPointerRef.current,
|
||||
});
|
||||
return {
|
||||
position,
|
||||
selection: {
|
||||
terminalId,
|
||||
terminalLabel: terminalLabelRef.current,
|
||||
lineStart,
|
||||
lineEnd,
|
||||
text: normalizedText,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const showSelectionAction = async () => {
|
||||
if (selectionActionOpenRef.current) {
|
||||
return;
|
||||
}
|
||||
const nextAction = readSelectionAction();
|
||||
if (!nextAction) {
|
||||
clearSelectionAction();
|
||||
return;
|
||||
}
|
||||
const requestId = ++selectionActionRequestIdRef.current;
|
||||
selectionActionOpenRef.current = true;
|
||||
try {
|
||||
const clicked = await api.contextMenu.show(
|
||||
[{ id: "add-to-chat", label: "Add to chat" }],
|
||||
nextAction.position,
|
||||
);
|
||||
if (requestId !== selectionActionRequestIdRef.current || clicked !== "add-to-chat") {
|
||||
return;
|
||||
}
|
||||
onAddTerminalContextRef.current(nextAction.selection);
|
||||
terminalRef.current?.clearSelection();
|
||||
terminalRef.current?.focus();
|
||||
} finally {
|
||||
selectionActionOpenRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
const sendTerminalInput = async (data: string, fallbackError: string) => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) return;
|
||||
@@ -426,38 +259,6 @@ function TerminalViewport({
|
||||
);
|
||||
});
|
||||
|
||||
const selectionDisposable = terminal.onSelectionChange(() => {
|
||||
if (terminalRef.current?.hasSelection()) {
|
||||
return;
|
||||
}
|
||||
clearSelectionAction();
|
||||
});
|
||||
|
||||
const handleMouseUp = (event: MouseEvent) => {
|
||||
const shouldHandle = shouldHandleTerminalSelectionMouseUp(
|
||||
selectionGestureActiveRef.current,
|
||||
event.button,
|
||||
);
|
||||
selectionGestureActiveRef.current = false;
|
||||
if (!shouldHandle) {
|
||||
return;
|
||||
}
|
||||
selectionPointerRef.current = { x: event.clientX, y: event.clientY };
|
||||
const delay = terminalSelectionActionDelayForClickCount(event.detail);
|
||||
selectionActionTimerRef.current = window.setTimeout(() => {
|
||||
selectionActionTimerRef.current = null;
|
||||
window.requestAnimationFrame(() => {
|
||||
void showSelectionAction();
|
||||
});
|
||||
}, delay);
|
||||
};
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
clearSelectionAction();
|
||||
selectionGestureActiveRef.current = event.button === 0;
|
||||
};
|
||||
window.addEventListener("mouseup", handleMouseUp);
|
||||
mount.addEventListener("pointerdown", handlePointerDown);
|
||||
|
||||
const themeObserver = new MutationObserver(() => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) return;
|
||||
@@ -509,13 +310,11 @@ function TerminalViewport({
|
||||
|
||||
if (event.type === "output") {
|
||||
activeTerminal.write(event.data);
|
||||
clearSelectionAction();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "started" || event.type === "restarted") {
|
||||
hasHandledExitRef.current = false;
|
||||
clearSelectionAction();
|
||||
activeTerminal.write("\u001bc");
|
||||
if (event.snapshot.history.length > 0) {
|
||||
activeTerminal.write(event.snapshot.history);
|
||||
@@ -524,7 +323,6 @@ function TerminalViewport({
|
||||
}
|
||||
|
||||
if (event.type === "cleared") {
|
||||
clearSelectionAction();
|
||||
activeTerminal.clear();
|
||||
activeTerminal.write("\u001bc");
|
||||
return;
|
||||
@@ -585,13 +383,7 @@ function TerminalViewport({
|
||||
window.clearTimeout(fitTimer);
|
||||
unsubscribe();
|
||||
inputDisposable.dispose();
|
||||
selectionDisposable.dispose();
|
||||
terminalLinksDisposable.dispose();
|
||||
if (selectionActionTimerRef.current !== null) {
|
||||
window.clearTimeout(selectionActionTimerRef.current);
|
||||
}
|
||||
window.removeEventListener("mouseup", handleMouseUp);
|
||||
mount.removeEventListener("pointerdown", handlePointerDown);
|
||||
themeObserver.disconnect();
|
||||
terminalRef.current = null;
|
||||
fitAddonRef.current = null;
|
||||
@@ -638,9 +430,7 @@ function TerminalViewport({
|
||||
window.cancelAnimationFrame(frame);
|
||||
};
|
||||
}, [drawerHeight, resizeEpoch, terminalId, threadId]);
|
||||
return (
|
||||
<div ref={containerRef} className="relative h-full w-full overflow-hidden rounded-[4px]" />
|
||||
);
|
||||
return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
|
||||
}
|
||||
|
||||
interface ThreadTerminalDrawerProps {
|
||||
@@ -661,7 +451,6 @@ interface ThreadTerminalDrawerProps {
|
||||
onActiveTerminalChange: (terminalId: string) => void;
|
||||
onCloseTerminal: (terminalId: string) => void;
|
||||
onHeightChange: (height: number) => void;
|
||||
onAddTerminalContext: (selection: TerminalContextSelection) => void;
|
||||
}
|
||||
|
||||
interface TerminalActionButtonProps {
|
||||
@@ -711,7 +500,6 @@ export default function ThreadTerminalDrawer({
|
||||
onActiveTerminalChange,
|
||||
onCloseTerminal,
|
||||
onHeightChange,
|
||||
onAddTerminalContext,
|
||||
}: ThreadTerminalDrawerProps) {
|
||||
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
|
||||
const [resizeEpoch, setResizeEpoch] = useState(0);
|
||||
@@ -1008,11 +796,9 @@ export default function ThreadTerminalDrawer({
|
||||
<TerminalViewport
|
||||
threadId={threadId}
|
||||
terminalId={terminalId}
|
||||
terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
onSessionExited={() => onCloseTerminal(terminalId)}
|
||||
onAddTerminalContext={onAddTerminalContext}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus={terminalId === resolvedActiveTerminalId}
|
||||
resizeEpoch={resizeEpoch}
|
||||
@@ -1028,11 +814,9 @@ export default function ThreadTerminalDrawer({
|
||||
key={resolvedActiveTerminalId}
|
||||
threadId={threadId}
|
||||
terminalId={resolvedActiveTerminalId}
|
||||
terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||
onAddTerminalContext={onAddTerminalContext}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus
|
||||
resizeEpoch={resizeEpoch}
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
import "../../index.css";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { ClaudeTraitsPicker } from "./ClaudeTraitsPicker";
|
||||
import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
|
||||
async function mountPicker(props?: {
|
||||
model?: string;
|
||||
prompt?: string;
|
||||
effort?: "low" | "medium" | "high" | "max" | "ultrathink" | null;
|
||||
thinkingEnabled?: boolean | null;
|
||||
fastModeEnabled?: boolean;
|
||||
}) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-claude-traits");
|
||||
const draftsByThreadId = {} as ReturnType<
|
||||
typeof useComposerDraftStore.getState
|
||||
>["draftsByThreadId"];
|
||||
draftsByThreadId[threadId] = {
|
||||
prompt: props?.prompt ?? "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider: "claudeAgent",
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
...(props?.effort ? { effort: props.effort } : {}),
|
||||
...(props?.thinkingEnabled === false ? { thinking: false } : {}),
|
||||
...(props?.fastModeEnabled ? { fastMode: true } : {}),
|
||||
},
|
||||
},
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const onPromptChange = vi.fn();
|
||||
const screen = await render(
|
||||
<ClaudeTraitsPicker
|
||||
threadId={threadId}
|
||||
model={props?.model ?? "claude-opus-4-6"}
|
||||
onPromptChange={onPromptChange}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
return {
|
||||
onPromptChange,
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("ClaudeTraitsPicker", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls for Opus", async () => {
|
||||
const mounted = await mountPicker();
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-Opus models", async () => {
|
||||
const mounted = await mountPicker({ model: "claude-sonnet-4-6" });
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
const mounted = await mountPicker({
|
||||
model: "claude-sonnet-4-6",
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Max");
|
||||
expect(text).toContain("Ultrathink");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a thinking on/off dropdown for Haiku", async () => {
|
||||
const mounted = await mountPicker({
|
||||
model: "claude-haiku-4-5",
|
||||
thinkingEnabled: true,
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Thinking On");
|
||||
});
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Thinking");
|
||||
expect(text).toContain("On (default)");
|
||||
expect(text).toContain("Off");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows prompt-controlled Ultrathink state with disabled effort controls", async () => {
|
||||
const mounted = await mountPicker({
|
||||
effort: "high",
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "Ultrathink:\nInvestigate this",
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Ultrathink");
|
||||
expect(document.body.textContent ?? "").not.toContain("Ultrathink · Prompt");
|
||||
});
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,257 +0,0 @@
|
||||
import {
|
||||
type ClaudeCodeEffort,
|
||||
type ClaudeModelOptions,
|
||||
type ProviderModelOptions,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
normalizeClaudeModelOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
isClaudeUltrathinkPrompt,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator as MenuDivider,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
|
||||
|
||||
const CLAUDE_EFFORT_LABELS: Record<ClaudeCodeEffort, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
max: "Max",
|
||||
ultrathink: "Ultrathink",
|
||||
};
|
||||
|
||||
const ULTRATHINK_PROMPT_PREFIX = "Ultrathink:\n";
|
||||
|
||||
function getSelectedClaudeTraits(
|
||||
model: string | null | undefined,
|
||||
prompt: string,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): {
|
||||
effort: Exclude<ClaudeCodeEffort, "ultrathink"> | null;
|
||||
thinkingEnabled: boolean | null;
|
||||
fastModeEnabled: boolean;
|
||||
options: ReadonlyArray<ClaudeCodeEffort>;
|
||||
ultrathinkPromptControlled: boolean;
|
||||
supportsFastMode: boolean;
|
||||
} {
|
||||
const options = getReasoningEffortOptions("claudeAgent", model);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("claudeAgent") as Exclude<
|
||||
ClaudeCodeEffort,
|
||||
"ultrathink"
|
||||
>;
|
||||
const resolvedEffort = resolveReasoningEffortForProvider("claudeAgent", modelOptions?.effort);
|
||||
const effort =
|
||||
resolvedEffort && resolvedEffort !== "ultrathink" && options.includes(resolvedEffort)
|
||||
? resolvedEffort
|
||||
: options.includes(defaultReasoningEffort)
|
||||
? defaultReasoningEffort
|
||||
: null;
|
||||
const thinkingEnabled = supportsClaudeThinkingToggle(model)
|
||||
? (modelOptions?.thinking ?? true)
|
||||
: null;
|
||||
const supportsFastMode = supportsClaudeFastMode(model);
|
||||
return {
|
||||
effort,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled: supportsFastMode && modelOptions?.fastMode === true,
|
||||
options,
|
||||
ultrathinkPromptControlled:
|
||||
supportsClaudeUltrathinkKeyword(model) && isClaudeUltrathinkPrompt(prompt),
|
||||
supportsFastMode,
|
||||
};
|
||||
}
|
||||
|
||||
function ClaudeTraitsMenuContentImpl(props: {
|
||||
threadId: ThreadId;
|
||||
model: string | null | undefined;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}) {
|
||||
const draft = useComposerThreadDraft(props.threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions = draft.modelOptions?.claudeAgent;
|
||||
const setModelOptions = useComposerDraftStore((store) => store.setModelOptions);
|
||||
const {
|
||||
effort,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
options,
|
||||
ultrathinkPromptControlled,
|
||||
supportsFastMode,
|
||||
} = getSelectedClaudeTraits(props.model, prompt, modelOptions);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("claudeAgent");
|
||||
|
||||
const setClaudeModelOptions = (nextClaudeModelOptions: ClaudeModelOptions | undefined) => {
|
||||
const { claudeAgent: _discardedClaude, ...otherProviderModelOptions } =
|
||||
draft.modelOptions ?? {};
|
||||
const nextProviderModelOptions: ProviderModelOptions | undefined = nextClaudeModelOptions
|
||||
? { ...otherProviderModelOptions, claudeAgent: nextClaudeModelOptions }
|
||||
: Object.keys(otherProviderModelOptions).length > 0
|
||||
? otherProviderModelOptions
|
||||
: undefined;
|
||||
setModelOptions(props.threadId, nextProviderModelOptions);
|
||||
};
|
||||
|
||||
if (effort === null && thinkingEnabled === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{effort ? (
|
||||
<>
|
||||
<MenuGroup>
|
||||
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">Effort</div>
|
||||
{ultrathinkPromptControlled ? (
|
||||
<div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
|
||||
Remove Ultrathink from the prompt to change effort.
|
||||
</div>
|
||||
) : null}
|
||||
<MenuRadioGroup
|
||||
value={effort}
|
||||
onValueChange={(value) => {
|
||||
if (ultrathinkPromptControlled) return;
|
||||
if (!value) return;
|
||||
const nextEffort = options.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
if (nextEffort === "ultrathink") {
|
||||
const nextPrompt =
|
||||
prompt.trim().length === 0
|
||||
? ULTRATHINK_PROMPT_PREFIX
|
||||
: applyClaudePromptEffortPrefix(prompt, "ultrathink");
|
||||
props.onPromptChange(nextPrompt);
|
||||
return;
|
||||
}
|
||||
setClaudeModelOptions(
|
||||
normalizeClaudeModelOptions(props.model, {
|
||||
...modelOptions,
|
||||
effort: nextEffort,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{options.map((option) => (
|
||||
<MenuRadioItem key={option} value={option} disabled={ultrathinkPromptControlled}>
|
||||
{CLAUDE_EFFORT_LABELS[option]}
|
||||
{option === defaultReasoningEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : thinkingEnabled !== null ? (
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Thinking</div>
|
||||
<MenuRadioGroup
|
||||
value={thinkingEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setClaudeModelOptions(
|
||||
normalizeClaudeModelOptions(props.model, {
|
||||
...modelOptions,
|
||||
thinking: value === "on",
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="on">On (default)</MenuRadioItem>
|
||||
<MenuRadioItem value="off">Off</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
) : null}
|
||||
{supportsFastMode ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setClaudeModelOptions(
|
||||
normalizeClaudeModelOptions(props.model, {
|
||||
...modelOptions,
|
||||
fastMode: value === "on",
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const ClaudeTraitsMenuContent = memo(ClaudeTraitsMenuContentImpl);
|
||||
|
||||
export const ClaudeTraitsPicker = memo(function ClaudeTraitsPicker(props: {
|
||||
threadId: ThreadId;
|
||||
model: string | null | undefined;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const draft = useComposerThreadDraft(props.threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions = draft.modelOptions?.claudeAgent;
|
||||
const { effort, thinkingEnabled, fastModeEnabled, ultrathinkPromptControlled, supportsFastMode } =
|
||||
getSelectedClaudeTraits(props.model, prompt, modelOptions);
|
||||
const triggerLabel = [
|
||||
ultrathinkPromptControlled
|
||||
? "Ultrathink"
|
||||
: effort
|
||||
? CLAUDE_EFFORT_LABELS[effort]
|
||||
: thinkingEnabled === null
|
||||
? null
|
||||
: `Thinking ${thinkingEnabled ? "On" : "Off"}`,
|
||||
...(supportsFastMode && fastModeEnabled ? ["Fast"] : []),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsMenuOpen(open);
|
||||
}}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
<ClaudeTraitsMenuContent
|
||||
threadId={props.threadId}
|
||||
model={props.model}
|
||||
onPromptChange={props.onPromptChange}
|
||||
/>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
@@ -1,50 +1,37 @@
|
||||
import "../../index.css";
|
||||
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import type { ProviderReasoningEffort } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { CodexTraitsPicker } from "./CodexTraitsPicker";
|
||||
import { COMPOSER_DRAFT_STORAGE_KEY, useComposerDraftStore } from "../../composerDraftStore";
|
||||
import { ProviderTraitsPicker } from "./CodexTraitsPicker";
|
||||
|
||||
async function mountPicker(props: {
|
||||
reasoningEffort?: "low" | "medium" | "high" | "xhigh";
|
||||
effort: ProviderReasoningEffort;
|
||||
supportsFastMode: boolean;
|
||||
fastModeEnabled: boolean;
|
||||
}) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-codex-traits");
|
||||
const draftsByThreadId = {} as ReturnType<
|
||||
typeof useComposerDraftStore.getState
|
||||
>["draftsByThreadId"];
|
||||
draftsByThreadId[threadId] = {
|
||||
prompt: "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider: "codex",
|
||||
model: null,
|
||||
modelOptions: {
|
||||
codex: {
|
||||
...(props.reasoningEffort ? { reasoningEffort: props.reasoningEffort } : {}),
|
||||
...(props.fastModeEnabled ? { fastMode: true } : {}),
|
||||
},
|
||||
},
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[ProjectId.makeUnsafe("project-codex-traits")]: threadId,
|
||||
},
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const screen = await render(<CodexTraitsPicker threadId={threadId} />, { container: host });
|
||||
const onEffortChange = vi.fn();
|
||||
const onFastModeChange = vi.fn();
|
||||
const screen = await render(
|
||||
<ProviderTraitsPicker
|
||||
provider="claudeAgent"
|
||||
effort={props.effort}
|
||||
supportsFastMode={props.supportsFastMode}
|
||||
fastModeEnabled={props.fastModeEnabled}
|
||||
options={["low", "medium", "high", "max", "ultrathink"]}
|
||||
onEffortChange={onEffortChange}
|
||||
onFastModeChange={onFastModeChange}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
return {
|
||||
onEffortChange,
|
||||
onFastModeChange,
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
@@ -52,19 +39,15 @@ async function mountPicker(props: {
|
||||
};
|
||||
}
|
||||
|
||||
describe("CodexTraitsPicker", () => {
|
||||
describe("ProviderTraitsPicker", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls", async () => {
|
||||
it("shows fast mode controls for claude", async () => {
|
||||
const mounted = await mountPicker({
|
||||
effort: "high",
|
||||
supportsFastMode: true,
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
@@ -82,8 +65,10 @@ describe("CodexTraitsPicker", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("shows Fast in the trigger label when fast mode is active", async () => {
|
||||
it("shows Fast in the trigger label when claude fast mode is active", async () => {
|
||||
const mounted = await mountPicker({
|
||||
effort: "high",
|
||||
supportsFastMode: true,
|
||||
fastModeEnabled: true,
|
||||
});
|
||||
|
||||
@@ -96,8 +81,10 @@ describe("CodexTraitsPicker", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
it("hides fast mode controls for non-opus claude models", async () => {
|
||||
const mounted = await mountPicker({
|
||||
effort: "high",
|
||||
supportsFastMode: false,
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
@@ -105,65 +92,10 @@ describe("CodexTraitsPicker", () => {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).toContain("Extra High");
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hydrates legacy codex persisted state into modelOptions through the picker", async () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-codex-legacy");
|
||||
localStorage.setItem(
|
||||
COMPOSER_DRAFT_STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
state: {
|
||||
draftsByThreadId: {
|
||||
[threadId]: {
|
||||
prompt: "",
|
||||
attachments: [],
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "xhigh",
|
||||
codexFastMode: true,
|
||||
serviceTier: "fast",
|
||||
},
|
||||
},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
},
|
||||
version: 1,
|
||||
}),
|
||||
);
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const screen = await render(<CodexTraitsPicker threadId={threadId} />, { container: host });
|
||||
|
||||
try {
|
||||
await useComposerDraftStore.persist.rehydrate();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Extra High · Fast");
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,7 @@
|
||||
import type {
|
||||
CodexModelOptions,
|
||||
CodexReasoningEffort,
|
||||
ProviderModelOptions,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
normalizeCodexModelOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import { type ProviderKind, type ProviderReasoningEffort } from "@t3tools/contracts";
|
||||
import { getDefaultReasoningEffort } from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
@@ -24,99 +13,42 @@ import {
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
|
||||
const CODEX_REASONING_LABELS: Record<CodexReasoningEffort, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
xhigh: "Extra High",
|
||||
};
|
||||
function effortLabel(provider: ProviderKind, effort: ProviderReasoningEffort): string {
|
||||
if (provider === "codex") {
|
||||
const codexLabels: Record<string, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
xhigh: "Extra High",
|
||||
};
|
||||
return codexLabels[effort] ?? effort;
|
||||
}
|
||||
|
||||
function getSelectedCodexTraits(modelOptions: CodexModelOptions | null | undefined): {
|
||||
effort: CodexReasoningEffort;
|
||||
fastModeEnabled: boolean;
|
||||
} {
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("codex");
|
||||
return {
|
||||
effort:
|
||||
resolveReasoningEffortForProvider("codex", modelOptions?.reasoningEffort) ??
|
||||
defaultReasoningEffort,
|
||||
fastModeEnabled: modelOptions?.fastMode === true,
|
||||
const claudeLabels: Record<string, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
max: "Max",
|
||||
ultrathink: "Ultrathink",
|
||||
};
|
||||
return claudeLabels[effort] ?? effort;
|
||||
}
|
||||
|
||||
function CodexTraitsMenuContentImpl(props: { threadId: ThreadId }) {
|
||||
const draft = useComposerThreadDraft(props.threadId);
|
||||
const modelOptions = draft.modelOptions?.codex;
|
||||
const setModelOptions = useComposerDraftStore((store) => store.setModelOptions);
|
||||
const options = getReasoningEffortOptions("codex");
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("codex");
|
||||
const { effort, fastModeEnabled } = getSelectedCodexTraits(modelOptions);
|
||||
|
||||
const setCodexModelOptions = (nextCodexModelOptions: CodexModelOptions | undefined) => {
|
||||
const { codex: _discardedCodex, ...otherProviderModelOptions } = draft.modelOptions ?? {};
|
||||
const nextProviderModelOptions: ProviderModelOptions | undefined = nextCodexModelOptions
|
||||
? { ...otherProviderModelOptions, codex: nextCodexModelOptions }
|
||||
: Object.keys(otherProviderModelOptions).length > 0
|
||||
? otherProviderModelOptions
|
||||
: undefined;
|
||||
setModelOptions(props.threadId, nextProviderModelOptions);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Reasoning</div>
|
||||
<MenuRadioGroup
|
||||
value={effort}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
const nextEffort = options.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
setCodexModelOptions(
|
||||
normalizeCodexModelOptions({
|
||||
...modelOptions,
|
||||
reasoningEffort: nextEffort,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{options.map((option) => (
|
||||
<MenuRadioItem key={option} value={option}>
|
||||
{CODEX_REASONING_LABELS[option]}
|
||||
{option === defaultReasoningEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setCodexModelOptions(
|
||||
normalizeCodexModelOptions({
|
||||
...modelOptions,
|
||||
fastMode: value === "on",
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const CodexTraitsMenuContent = memo(CodexTraitsMenuContentImpl);
|
||||
|
||||
export const CodexTraitsPicker = memo(function CodexTraitsPicker(props: { threadId: ThreadId }) {
|
||||
export const ProviderTraitsPicker = memo(function ProviderTraitsPicker(props: {
|
||||
provider: ProviderKind;
|
||||
effort: ProviderReasoningEffort;
|
||||
supportsFastMode?: boolean;
|
||||
fastModeEnabled?: boolean;
|
||||
options: ReadonlyArray<ProviderReasoningEffort>;
|
||||
onEffortChange: (effort: ProviderReasoningEffort) => void;
|
||||
onFastModeChange?: (enabled: boolean) => void;
|
||||
}) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const modelOptions = useComposerThreadDraft(props.threadId).modelOptions?.codex;
|
||||
const { effort, fastModeEnabled } = getSelectedCodexTraits(modelOptions);
|
||||
const triggerLabel = [CODEX_REASONING_LABELS[effort], ...(fastModeEnabled ? ["Fast"] : [])]
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(props.provider);
|
||||
const triggerLabel = [
|
||||
effortLabel(props.provider, props.effort),
|
||||
...(props.supportsFastMode && props.fastModeEnabled ? ["Fast"] : []),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
@@ -132,17 +64,52 @@ export const CodexTraitsPicker = memo(function CodexTraitsPicker(props: { thread
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:max-w-48 sm:px-3 [&_svg]:mx-0"
|
||||
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
|
||||
{triggerLabel}
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
<CodexTraitsMenuContent threadId={props.threadId} />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
{props.provider === "codex" ? "Reasoning" : "Effort"}
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={props.effort}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
const nextEffort = props.options.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
props.onEffortChange(nextEffort);
|
||||
}}
|
||||
>
|
||||
{props.options.map((effort) => (
|
||||
<MenuRadioItem key={effort} value={effort}>
|
||||
{effortLabel(props.provider, effort)}
|
||||
{effort === defaultReasoningEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
{props.supportsFastMode && props.onFastModeChange ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={props.fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
props.onFastModeChange?.(value === "on");
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { type ProviderModelOptions, ThreadId } from "@t3tools/contracts";
|
||||
import "../../index.css";
|
||||
|
||||
import { page } from "vitest/browser";
|
||||
@@ -6,58 +5,23 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
|
||||
import { ClaudeTraitsMenuContent } from "./ClaudeTraitsPicker";
|
||||
import { CodexTraitsMenuContent } from "./CodexTraitsPicker";
|
||||
import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
|
||||
async function mountMenu(props?: {
|
||||
model?: string;
|
||||
prompt?: string;
|
||||
provider?: "codex" | "claudeAgent";
|
||||
modelOptions?: ProviderModelOptions | null;
|
||||
}) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-compact-menu");
|
||||
const provider = props?.provider ?? "claudeAgent";
|
||||
const draftsByThreadId = {} as ReturnType<
|
||||
typeof useComposerDraftStore.getState
|
||||
>["draftsByThreadId"];
|
||||
draftsByThreadId[threadId] = {
|
||||
prompt: props?.prompt ?? "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider,
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
modelOptions: props?.modelOptions ?? null,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
async function mountMenu(supportsFastMode = true) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const onPromptChange = vi.fn();
|
||||
const screen = await render(
|
||||
<CompactComposerControlsMenu
|
||||
activePlan={false}
|
||||
interactionMode="default"
|
||||
planSidebarOpen={false}
|
||||
runtimeMode="approval-required"
|
||||
traitsMenuContent={
|
||||
provider === "codex" ? (
|
||||
<CodexTraitsMenuContent threadId={threadId} />
|
||||
) : (
|
||||
<ClaudeTraitsMenuContent
|
||||
threadId={threadId}
|
||||
model={props?.model ?? "claude-opus-4-6"}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
)
|
||||
}
|
||||
selectedEffort="high"
|
||||
selectedProvider="claudeAgent"
|
||||
supportsFastMode={supportsFastMode}
|
||||
selectedFastModeEnabled={false}
|
||||
reasoningOptions={["low", "medium", "high", "max", "ultrathink"]}
|
||||
onEffortSelect={vi.fn()}
|
||||
onFastModeChange={vi.fn()}
|
||||
onToggleInteractionMode={vi.fn()}
|
||||
onTogglePlanSidebar={vi.fn()}
|
||||
onToggleRuntimeMode={vi.fn()}
|
||||
@@ -76,14 +40,9 @@ async function mountMenu(props?: {
|
||||
describe("CompactComposerControlsMenu", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls for Opus", async () => {
|
||||
it("shows fast mode controls for claude", async () => {
|
||||
const mounted = await mountMenu();
|
||||
|
||||
try {
|
||||
@@ -100,8 +59,8 @@ describe("CompactComposerControlsMenu", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-Opus Claude models", async () => {
|
||||
const mounted = await mountMenu({ model: "claude-sonnet-4-6" });
|
||||
it("hides fast mode controls for non-opus claude models", async () => {
|
||||
const mounted = await mountMenu(false);
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
@@ -113,74 +72,4 @@ describe("CompactComposerControlsMenu", () => {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
const mounted = await mountMenu({
|
||||
model: "claude-sonnet-4-6",
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Max");
|
||||
expect(text).toContain("Ultrathink");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a Claude thinking on/off section for Haiku", async () => {
|
||||
const mounted = await mountMenu({
|
||||
model: "claude-haiku-4-5",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
thinking: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Thinking");
|
||||
expect(text).toContain("On (default)");
|
||||
expect(text).toContain("Off");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows prompt-controlled Ultrathink messaging with disabled effort controls", async () => {
|
||||
const mounted = await mountMenu({
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "Ultrathink:\nInvestigate this",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,16 @@
|
||||
import { ProviderInteractionMode, RuntimeMode } from "@t3tools/contracts";
|
||||
import { memo, type ReactNode } from "react";
|
||||
import {
|
||||
type ProviderKind,
|
||||
RuntimeMode,
|
||||
ProviderInteractionMode,
|
||||
type ProviderReasoningEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import { getDefaultReasoningEffort } from "@t3tools/shared/model";
|
||||
import { memo } from "react";
|
||||
import { EllipsisIcon, ListTodoIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
@@ -17,11 +24,27 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
|
||||
interactionMode: ProviderInteractionMode;
|
||||
planSidebarOpen: boolean;
|
||||
runtimeMode: RuntimeMode;
|
||||
traitsMenuContent?: ReactNode;
|
||||
selectedEffort: ProviderReasoningEffort | null;
|
||||
selectedProvider: ProviderKind;
|
||||
supportsFastMode: boolean;
|
||||
selectedFastModeEnabled: boolean;
|
||||
reasoningOptions: ReadonlyArray<ProviderReasoningEffort>;
|
||||
onEffortSelect: (effort: ProviderReasoningEffort) => void;
|
||||
onFastModeChange: (enabled: boolean) => void;
|
||||
onToggleInteractionMode: () => void;
|
||||
onTogglePlanSidebar: () => void;
|
||||
onToggleRuntimeMode: () => void;
|
||||
}) {
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(props.selectedProvider);
|
||||
const reasoningLabelByOption: Record<ProviderReasoningEffort, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
xhigh: "Extra High",
|
||||
max: "Max",
|
||||
ultrathink: "Ultrathink",
|
||||
};
|
||||
|
||||
return (
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
@@ -37,35 +60,80 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
|
||||
<EllipsisIcon aria-hidden="true" className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
{props.traitsMenuContent ? (
|
||||
{props.selectedEffort != null ? (
|
||||
<>
|
||||
{props.traitsMenuContent}
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
{props.selectedProvider === "codex" ? "Reasoning" : "Effort"}
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={props.selectedEffort}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
const nextEffort = props.reasoningOptions.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
props.onEffortSelect(nextEffort);
|
||||
}}
|
||||
>
|
||||
{props.reasoningOptions.map((effort) => (
|
||||
<MenuRadioItem key={effort} value={effort}>
|
||||
{reasoningLabelByOption[effort]}
|
||||
{effort === defaultReasoningEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
{props.supportsFastMode ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
Fast Mode
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={props.selectedFastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
props.onFastModeChange(value === "on");
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
<MenuDivider />
|
||||
</>
|
||||
) : (
|
||||
<MenuDivider />
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={props.interactionMode}
|
||||
onValueChange={(value) => {
|
||||
if (!value || value === props.interactionMode) return;
|
||||
props.onToggleInteractionMode();
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="default">Chat</MenuRadioItem>
|
||||
<MenuRadioItem value="plan">Plan</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={props.interactionMode}
|
||||
onValueChange={(value) => {
|
||||
if (!value || value === props.interactionMode) return;
|
||||
props.onToggleInteractionMode();
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="default">Chat</MenuRadioItem>
|
||||
<MenuRadioItem value="plan">Plan</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
<MenuDivider />
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Access</div>
|
||||
<MenuRadioGroup
|
||||
value={props.runtimeMode}
|
||||
onValueChange={(value) => {
|
||||
if (!value || value === props.runtimeMode) return;
|
||||
props.onToggleRuntimeMode();
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="approval-required">Supervised</MenuRadioItem>
|
||||
<MenuRadioItem value="full-access">Full access</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Access</div>
|
||||
<MenuRadioGroup
|
||||
value={props.runtimeMode}
|
||||
onValueChange={(value) => {
|
||||
if (!value || value === props.runtimeMode) return;
|
||||
props.onToggleRuntimeMode();
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="approval-required">Supervised</MenuRadioItem>
|
||||
<MenuRadioItem value="full-access">Full access</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
{props.activePlan ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ComposerPendingTerminalContextChip } from "./ComposerPendingTerminalContexts";
|
||||
|
||||
describe("ComposerPendingTerminalContextChip", () => {
|
||||
it("renders expired terminal contexts with error styling", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ComposerPendingTerminalContextChip
|
||||
context={{
|
||||
id: "ctx-expired",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 2,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
createdAt: "2026-03-17T18:42:05.449Z",
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-terminal-context-expired="true"');
|
||||
expect(markup).toContain("border-destructive/35");
|
||||
expect(markup).toContain("Terminal 1 lines 2-4");
|
||||
});
|
||||
});
|
||||
@@ -1,44 +0,0 @@
|
||||
import { cn } from "~/lib/utils";
|
||||
import {
|
||||
type TerminalContextDraft,
|
||||
formatTerminalContextLabel,
|
||||
isTerminalContextExpired,
|
||||
} from "~/lib/terminalContext";
|
||||
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
|
||||
|
||||
interface ComposerPendingTerminalContextsProps {
|
||||
contexts: ReadonlyArray<TerminalContextDraft>;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
interface ComposerPendingTerminalContextChipProps {
|
||||
context: TerminalContextDraft;
|
||||
}
|
||||
|
||||
export function ComposerPendingTerminalContextChip({
|
||||
context,
|
||||
}: ComposerPendingTerminalContextChipProps) {
|
||||
const label = formatTerminalContextLabel(context);
|
||||
const expired = isTerminalContextExpired(context);
|
||||
const tooltipText = expired
|
||||
? `Terminal context expired. Remove and re-add ${label} to include it in your message.`
|
||||
: context.text;
|
||||
|
||||
return <TerminalContextInlineChip label={label} tooltipText={tooltipText} expired={expired} />;
|
||||
}
|
||||
|
||||
export function ComposerPendingTerminalContexts(props: ComposerPendingTerminalContextsProps) {
|
||||
const { contexts, className } = props;
|
||||
|
||||
if (contexts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-wrap gap-1.5", className)}>
|
||||
{contexts.map((context) => (
|
||||
<ComposerPendingTerminalContextChip key={context.id} context={context} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
import { MessageId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
function matchMedia() {
|
||||
return {
|
||||
matches: false,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
const classList = {
|
||||
add: () => {},
|
||||
remove: () => {},
|
||||
toggle: () => {},
|
||||
contains: () => false,
|
||||
};
|
||||
|
||||
vi.stubGlobal("localStorage", {
|
||||
getItem: () => null,
|
||||
setItem: () => {},
|
||||
removeItem: () => {},
|
||||
clear: () => {},
|
||||
});
|
||||
vi.stubGlobal("window", {
|
||||
matchMedia,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
desktopBridge: undefined,
|
||||
});
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: {
|
||||
classList,
|
||||
offsetHeight: 0,
|
||||
},
|
||||
});
|
||||
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
|
||||
callback(0);
|
||||
return 0;
|
||||
});
|
||||
});
|
||||
|
||||
describe("MessagesTimeline", () => {
|
||||
it("renders inline terminal labels with the composer chip UI", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
hasMessages
|
||||
isWorking={false}
|
||||
activeTurnInProgress={false}
|
||||
activeTurnStartedAt={null}
|
||||
scrollContainer={null}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-1",
|
||||
kind: "message",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
message: {
|
||||
id: MessageId.makeUnsafe("message-2"),
|
||||
role: "user",
|
||||
text: [
|
||||
"yoo what's @terminal-1:1-5 mean",
|
||||
"",
|
||||
"<terminal_context>",
|
||||
"- Terminal 1 lines 1-5:",
|
||||
" 1 | julius@mac effect-http-ws-cli % bun i",
|
||||
" 2 | bun install v1.3.9 (cf6cdbbb)",
|
||||
"</terminal_context>",
|
||||
].join("\n"),
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
]}
|
||||
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("Terminal 1 lines 1-5");
|
||||
expect(markup).toContain("lucide-terminal");
|
||||
expect(markup).toContain("yoo what's ");
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,5 @@
|
||||
import { type MessageId, type TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
measureElement as measureVirtualElement,
|
||||
type VirtualItem,
|
||||
@@ -42,19 +33,9 @@ import { ChangedFilesTree } from "./ChangedFilesTree";
|
||||
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { MessageCopyButton } from "./MessageCopyButton";
|
||||
import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
|
||||
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
|
||||
import {
|
||||
deriveDisplayedUserMessageState,
|
||||
type ParsedTerminalContextEntry,
|
||||
} from "~/lib/terminalContext";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { type TimestampFormat } from "../../appSettings";
|
||||
import { formatTimestamp } from "../../timestampFormat";
|
||||
import {
|
||||
buildInlineTerminalContextText,
|
||||
formatInlineTerminalContextLabel,
|
||||
textContainsInlineTerminalContextLabels,
|
||||
} from "./userMessageTerminalContexts";
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
|
||||
@@ -356,8 +337,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
row.message.role === "user" &&
|
||||
(() => {
|
||||
const userImages = row.message.attachments ?? [];
|
||||
const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
|
||||
const terminalContexts = displayedUserMessage.contexts;
|
||||
const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
|
||||
return (
|
||||
<div className="flex justify-end">
|
||||
@@ -399,18 +378,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{(displayedUserMessage.visibleText.trim().length > 0 ||
|
||||
terminalContexts.length > 0) && (
|
||||
<UserMessageBody
|
||||
text={displayedUserMessage.visibleText}
|
||||
terminalContexts={terminalContexts}
|
||||
/>
|
||||
{row.message.text && (
|
||||
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
|
||||
{row.message.text}
|
||||
</pre>
|
||||
)}
|
||||
<div className="mt-1.5 flex items-center justify-end gap-2">
|
||||
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
|
||||
{displayedUserMessage.copyText && (
|
||||
<MessageCopyButton text={displayedUserMessage.copyText} />
|
||||
)}
|
||||
{row.message.text && <MessageCopyButton text={row.message.text} />}
|
||||
{canRevertAgentWork && (
|
||||
<Button
|
||||
type="button"
|
||||
@@ -661,110 +636,6 @@ function formatMessageMeta(
|
||||
return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
|
||||
}
|
||||
|
||||
const UserMessageTerminalContextInlineLabel = memo(
|
||||
function UserMessageTerminalContextInlineLabel(props: { context: ParsedTerminalContextEntry }) {
|
||||
const tooltipText =
|
||||
props.context.body.length > 0
|
||||
? `${props.context.header}\n${props.context.body}`
|
||||
: props.context.header;
|
||||
|
||||
return <TerminalContextInlineChip label={props.context.header} tooltipText={tooltipText} />;
|
||||
},
|
||||
);
|
||||
|
||||
const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
text: string;
|
||||
terminalContexts: ParsedTerminalContextEntry[];
|
||||
}) {
|
||||
if (props.terminalContexts.length > 0) {
|
||||
const hasEmbeddedInlineLabels = textContainsInlineTerminalContextLabels(
|
||||
props.text,
|
||||
props.terminalContexts,
|
||||
);
|
||||
const inlinePrefix = buildInlineTerminalContextText(props.terminalContexts);
|
||||
const inlineNodes: ReactNode[] = [];
|
||||
|
||||
if (hasEmbeddedInlineLabels) {
|
||||
let cursor = 0;
|
||||
|
||||
for (const context of props.terminalContexts) {
|
||||
const label = formatInlineTerminalContextLabel(context.header);
|
||||
const matchIndex = props.text.indexOf(label, cursor);
|
||||
if (matchIndex === -1) {
|
||||
inlineNodes.length = 0;
|
||||
break;
|
||||
}
|
||||
if (matchIndex > cursor) {
|
||||
inlineNodes.push(
|
||||
<span key={`user-terminal-context-inline-before:${context.header}:${cursor}`}>
|
||||
{props.text.slice(cursor, matchIndex)}
|
||||
</span>,
|
||||
);
|
||||
}
|
||||
inlineNodes.push(
|
||||
<UserMessageTerminalContextInlineLabel
|
||||
key={`user-terminal-context-inline:${context.header}`}
|
||||
context={context}
|
||||
/>,
|
||||
);
|
||||
cursor = matchIndex + label.length;
|
||||
}
|
||||
|
||||
if (inlineNodes.length > 0) {
|
||||
if (cursor < props.text.length) {
|
||||
inlineNodes.push(
|
||||
<span key={`user-message-terminal-context-inline-rest:${cursor}`}>
|
||||
{props.text.slice(cursor)}
|
||||
</span>,
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
|
||||
{inlineNodes}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (const context of props.terminalContexts) {
|
||||
inlineNodes.push(
|
||||
<UserMessageTerminalContextInlineLabel
|
||||
key={`user-terminal-context-inline:${context.header}`}
|
||||
context={context}
|
||||
/>,
|
||||
);
|
||||
inlineNodes.push(
|
||||
<span key={`user-terminal-context-inline-space:${context.header}`} aria-hidden="true">
|
||||
{" "}
|
||||
</span>,
|
||||
);
|
||||
}
|
||||
|
||||
if (props.text.length > 0) {
|
||||
inlineNodes.push(<span key="user-message-terminal-context-inline-text">{props.text}</span>);
|
||||
} else if (inlinePrefix.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
|
||||
{inlineNodes}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.text.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
|
||||
{props.text}
|
||||
</pre>
|
||||
);
|
||||
});
|
||||
|
||||
function workToneIcon(tone: TimelineWorkEntry["tone"]): {
|
||||
icon: LucideIcon;
|
||||
className: string;
|
||||
|
||||
@@ -74,13 +74,6 @@ const COMING_SOON_PROVIDER_OPTIONS = [
|
||||
{ id: "gemini", label: "Gemini", icon: Gemini },
|
||||
] as const;
|
||||
|
||||
function providerIconClassName(
|
||||
provider: ProviderKind | ProviderPickerKind,
|
||||
fallbackClassName: string,
|
||||
): string {
|
||||
return provider === "claudeAgent" ? "text-[#d97757]" : fallbackClassName;
|
||||
}
|
||||
|
||||
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
@@ -127,31 +120,28 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"min-w-0 justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 [&_svg]:mx-0",
|
||||
props.compact ? "max-w-42 shrink-0" : "max-w-48 shrink sm:max-w-56 sm:px-3",
|
||||
"min-w-0 shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80",
|
||||
props.compact ? "max-w-42" : "sm:px-3",
|
||||
)}
|
||||
disabled={props.disabled}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"flex min-w-0 w-full items-center gap-2 overflow-hidden",
|
||||
props.compact ? "max-w-36" : undefined,
|
||||
)}
|
||||
className={cn("flex min-w-0 items-center gap-2", props.compact ? "max-w-36" : undefined)}
|
||||
>
|
||||
<ProviderIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
providerIconClassName(activeProvider, "text-muted-foreground/70"),
|
||||
activeProvider === "claudeAgent" && props.ultrathinkActive
|
||||
props.provider === "claudeAgent" ? "text-[#d97757]" : "text-muted-foreground/70",
|
||||
props.provider === "claudeAgent" && props.ultrathinkActive
|
||||
? "ultrathink-chroma"
|
||||
: undefined,
|
||||
)}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate">{selectedModelLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
<span className="truncate">{selectedModelLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</span>
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
@@ -181,10 +171,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
<MenuSubTrigger>
|
||||
<OptionIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
providerIconClassName(option.value, "text-muted-foreground/85"),
|
||||
)}
|
||||
className="size-4 shrink-0 text-muted-foreground/85"
|
||||
/>
|
||||
{option.label}
|
||||
</MenuSubTrigger>
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
import { TerminalIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import {
|
||||
COMPOSER_INLINE_CHIP_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
} from "../composerInlineChip";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
interface TerminalContextInlineChipProps {
|
||||
label: string;
|
||||
tooltipText: string;
|
||||
expired?: boolean;
|
||||
}
|
||||
|
||||
export function TerminalContextInlineChip(props: TerminalContextInlineChipProps) {
|
||||
const { label, tooltipText, expired = false } = props;
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
className={cn(
|
||||
COMPOSER_INLINE_CHIP_CLASS_NAME,
|
||||
expired && "border-destructive/35 bg-destructive/8 text-destructive",
|
||||
)}
|
||||
data-terminal-context-expired={expired ? "true" : undefined}
|
||||
>
|
||||
<TerminalIcon
|
||||
className={cn(
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
"size-3.5",
|
||||
expired && "opacity-100",
|
||||
)}
|
||||
/>
|
||||
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{label}</span>
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
|
||||
{tooltipText}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildInlineTerminalContextText,
|
||||
formatInlineTerminalContextLabel,
|
||||
textContainsInlineTerminalContextLabels,
|
||||
} from "./userMessageTerminalContexts";
|
||||
|
||||
describe("userMessageTerminalContexts", () => {
|
||||
it("builds plain inline terminal text labels", () => {
|
||||
expect(
|
||||
buildInlineTerminalContextText([
|
||||
{ header: "Terminal 1 lines 12-13" },
|
||||
{ header: "Terminal 2 line 4" },
|
||||
]),
|
||||
).toBe("@terminal-1:12-13 @terminal-2:4");
|
||||
});
|
||||
|
||||
it("formats individual inline terminal labels compactly", () => {
|
||||
expect(formatInlineTerminalContextLabel("Terminal 1 lines 12-13")).toBe("@terminal-1:12-13");
|
||||
expect(formatInlineTerminalContextLabel("Terminal 2 line 4")).toBe("@terminal-2:4");
|
||||
});
|
||||
|
||||
it("detects inline terminal labels embedded in user message text", () => {
|
||||
expect(
|
||||
textContainsInlineTerminalContextLabels("yo @terminal-1:12-13 whats up", [
|
||||
{ header: "Terminal 1 lines 12-13" },
|
||||
]),
|
||||
).toBe(true);
|
||||
expect(
|
||||
textContainsInlineTerminalContextLabels("yo whats up", [
|
||||
{ header: "Terminal 1 lines 12-13" },
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import { formatInlineTerminalContextLabel as formatInlineTerminalContextSelectionLabel } from "~/lib/terminalContext";
|
||||
|
||||
const TERMINAL_CONTEXT_HEADER_PATTERN = /^(.*?)\s+line(?:s)?\s+(\d+)(?:-(\d+))?$/i;
|
||||
|
||||
export function buildInlineTerminalContextText(
|
||||
contexts: ReadonlyArray<{
|
||||
header: string;
|
||||
}>,
|
||||
): string {
|
||||
return contexts
|
||||
.map((context) => context.header.trim())
|
||||
.filter((header) => header.length > 0)
|
||||
.map(formatInlineTerminalContextLabel)
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
export function formatInlineTerminalContextLabel(header: string): string {
|
||||
const trimmedHeader = header.trim();
|
||||
const match = TERMINAL_CONTEXT_HEADER_PATTERN.exec(trimmedHeader);
|
||||
if (!match) {
|
||||
return `@${trimmedHeader.toLowerCase().replace(/\s+/g, "-")}`;
|
||||
}
|
||||
|
||||
const lineStart = Number.parseInt(match[2] ?? "", 10);
|
||||
const lineEnd = Number.parseInt(match[3] ?? match[2] ?? "", 10);
|
||||
if (!Number.isFinite(lineStart) || !Number.isFinite(lineEnd)) {
|
||||
return `@${trimmedHeader.toLowerCase().replace(/\s+/g, "-")}`;
|
||||
}
|
||||
|
||||
return formatInlineTerminalContextSelectionLabel({
|
||||
terminalLabel: match[1]?.trim() || "terminal",
|
||||
lineStart,
|
||||
lineEnd,
|
||||
});
|
||||
}
|
||||
|
||||
export function textContainsInlineTerminalContextLabels(
|
||||
text: string,
|
||||
contexts: ReadonlyArray<{
|
||||
header: string;
|
||||
}>,
|
||||
): boolean {
|
||||
let searchStartIndex = 0;
|
||||
|
||||
for (const context of contexts) {
|
||||
const label = formatInlineTerminalContextLabel(context.header);
|
||||
const matchIndex = text.indexOf(label, searchStartIndex);
|
||||
if (matchIndex === -1) {
|
||||
return false;
|
||||
}
|
||||
searchStartIndex = matchIndex + label.length;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
export const COMPOSER_INLINE_CHIP_CLASS_NAME =
|
||||
"inline-flex max-w-full select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_ICON_CLASS_NAME = "size-3.5 shrink-0 opacity-85";
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME = "truncate select-none leading-tight";
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME =
|
||||
"ml-0.5 inline-flex size-3.5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground/72 transition-colors hover:bg-foreground/6 hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring";
|
||||
@@ -1,7 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { appendTerminalContextsToPrompt } from "../lib/terminalContext";
|
||||
import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
describe("estimateTimelineMessageHeight", () => {
|
||||
@@ -77,35 +75,6 @@ describe("estimateTimelineMessageHeight", () => {
|
||||
).toBe(162);
|
||||
});
|
||||
|
||||
it("adds terminal context chrome without counting the hidden block as message text", () => {
|
||||
const prompt = appendTerminalContextsToPrompt("Investigate this", [
|
||||
{
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 40,
|
||||
lineEnd: 43,
|
||||
text: [
|
||||
"git status",
|
||||
"M apps/web/src/components/chat/MessagesTimeline.tsx",
|
||||
"?? tmp",
|
||||
"",
|
||||
].join("\n"),
|
||||
},
|
||||
]);
|
||||
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: prompt,
|
||||
}),
|
||||
).toBe(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: `${buildInlineTerminalContextText([{ header: "Terminal 1 lines 40-43" }])} Investigate this`,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("uses narrower width to increase user line wrapping", () => {
|
||||
const message = {
|
||||
role: "user" as const,
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import { deriveDisplayedUserMessageState } from "../lib/terminalContext";
|
||||
import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
|
||||
|
||||
const ASSISTANT_CHARS_PER_LINE_FALLBACK = 72;
|
||||
const USER_CHARS_PER_LINE_FALLBACK = 56;
|
||||
const LINE_HEIGHT_PX = 22;
|
||||
@@ -78,17 +75,7 @@ export function estimateTimelineMessageHeight(
|
||||
|
||||
if (message.role === "user") {
|
||||
const charsPerLine = estimateCharsPerLineForUser(layout.timelineWidthPx);
|
||||
const displayedUserMessage = deriveDisplayedUserMessageState(message.text);
|
||||
const renderedText =
|
||||
displayedUserMessage.contexts.length > 0
|
||||
? [
|
||||
buildInlineTerminalContextText(displayedUserMessage.contexts),
|
||||
displayedUserMessage.visibleText,
|
||||
]
|
||||
.filter((part) => part.length > 0)
|
||||
.join(" ")
|
||||
: displayedUserMessage.visibleText;
|
||||
const estimatedLines = estimateWrappedLineCount(renderedText, charsPerLine);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
const attachmentCount = message.attachments?.length ?? 0;
|
||||
const attachmentRows = Math.ceil(attachmentCount / ATTACHMENTS_PER_ROW);
|
||||
const attachmentHeight = attachmentRows * USER_ATTACHMENT_ROW_HEIGHT_PX;
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
SidebarMenuAction,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuSubButton,
|
||||
SidebarProvider,
|
||||
} from "./sidebar";
|
||||
|
||||
function renderSidebarButton(className?: string) {
|
||||
return renderToStaticMarkup(
|
||||
<SidebarProvider>
|
||||
<SidebarMenuButton className={className}>Projects</SidebarMenuButton>
|
||||
</SidebarProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("sidebar interactive cursors", () => {
|
||||
it("uses a pointer cursor for menu buttons by default", () => {
|
||||
const html = renderSidebarButton();
|
||||
|
||||
expect(html).toContain('data-slot="sidebar-menu-button"');
|
||||
expect(html).toContain("cursor-pointer");
|
||||
});
|
||||
|
||||
it("lets project drag handles override the default pointer cursor", () => {
|
||||
const html = renderSidebarButton("cursor-grab");
|
||||
|
||||
expect(html).toContain("cursor-grab");
|
||||
expect(html).not.toContain("cursor-pointer");
|
||||
});
|
||||
|
||||
it("uses a pointer cursor for menu actions", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SidebarMenuAction aria-label="Create thread">
|
||||
<span>+</span>
|
||||
</SidebarMenuAction>,
|
||||
);
|
||||
|
||||
expect(html).toContain('data-slot="sidebar-menu-action"');
|
||||
expect(html).toContain("cursor-pointer");
|
||||
});
|
||||
|
||||
it("uses a pointer cursor for submenu buttons", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SidebarMenuSubButton render={<button type="button" />}>Show more</SidebarMenuSubButton>,
|
||||
);
|
||||
|
||||
expect(html).toContain('data-slot="sidebar-menu-sub-button"');
|
||||
expect(html).toContain("cursor-pointer");
|
||||
});
|
||||
});
|
||||
@@ -750,7 +750,7 @@ function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full cursor-pointer items-center gap-2 overflow-hidden rounded-lg p-2 text-left text-sm outline-hidden ring-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-lg p-2 text-left text-sm outline-hidden ring-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
@@ -834,7 +834,7 @@ function SidebarMenuAction({
|
||||
}) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"absolute top-1.5 right-1 flex aspect-square w-5 cursor-pointer items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
"absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:-inset-2 after:absolute md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
@@ -946,7 +946,7 @@ function SidebarMenuSubButton({
|
||||
}) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"-translate-x-px flex h-7 min-w-0 cursor-pointer items-center gap-2 overflow-hidden rounded-lg px-2 text-sidebar-foreground outline-hidden ring-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||
"-translate-x-px flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-lg px-2 text-sidebar-foreground outline-hidden ring-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
|
||||
|
||||
describe("splitPromptIntoComposerSegments", () => {
|
||||
it("splits mention tokens followed by whitespace into mention segments", () => {
|
||||
@@ -25,17 +24,4 @@ describe("splitPromptIntoComposerSegments", () => {
|
||||
{ type: "text", text: " \ntwo" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps inline terminal context placeholders at their prompt positions", () => {
|
||||
expect(
|
||||
splitPromptIntoComposerSegments(
|
||||
`Inspect ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}@AGENTS.md please`,
|
||||
),
|
||||
).toEqual([
|
||||
{ type: "text", text: "Inspect " },
|
||||
{ type: "terminal-context", context: null },
|
||||
{ type: "mention", path: "AGENTS.md" },
|
||||
{ type: "text", text: " please" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,3 @@
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
} from "./lib/terminalContext";
|
||||
|
||||
export type ComposerPromptSegment =
|
||||
| {
|
||||
type: "text";
|
||||
@@ -11,10 +6,6 @@ export type ComposerPromptSegment =
|
||||
| {
|
||||
type: "mention";
|
||||
path: string;
|
||||
}
|
||||
| {
|
||||
type: "terminal-context";
|
||||
context: TerminalContextDraft | null;
|
||||
};
|
||||
|
||||
const MENTION_TOKEN_REGEX = /(^|\s)@([^\s@]+)(?=\s)/g;
|
||||
@@ -29,14 +20,14 @@ function pushTextSegment(segments: ComposerPromptSegment[], text: string): void
|
||||
segments.push({ type: "text", text });
|
||||
}
|
||||
|
||||
function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegment[] {
|
||||
export function splitPromptIntoComposerSegments(prompt: string): ComposerPromptSegment[] {
|
||||
const segments: ComposerPromptSegment[] = [];
|
||||
if (!text) {
|
||||
if (!prompt) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
let cursor = 0;
|
||||
for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
|
||||
for (const match of prompt.matchAll(MENTION_TOKEN_REGEX)) {
|
||||
const fullMatch = match[0];
|
||||
const prefix = match[1] ?? "";
|
||||
const path = match[2] ?? "";
|
||||
@@ -45,55 +36,20 @@ function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegmen
|
||||
const mentionEnd = mentionStart + fullMatch.length - prefix.length;
|
||||
|
||||
if (mentionStart > cursor) {
|
||||
pushTextSegment(segments, text.slice(cursor, mentionStart));
|
||||
pushTextSegment(segments, prompt.slice(cursor, mentionStart));
|
||||
}
|
||||
|
||||
if (path.length > 0) {
|
||||
segments.push({ type: "mention", path });
|
||||
} else {
|
||||
pushTextSegment(segments, text.slice(mentionStart, mentionEnd));
|
||||
pushTextSegment(segments, prompt.slice(mentionStart, mentionEnd));
|
||||
}
|
||||
|
||||
cursor = mentionEnd;
|
||||
}
|
||||
|
||||
if (cursor < text.length) {
|
||||
pushTextSegment(segments, text.slice(cursor));
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
export function splitPromptIntoComposerSegments(
|
||||
prompt: string,
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft> = [],
|
||||
): ComposerPromptSegment[] {
|
||||
if (!prompt) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const segments: ComposerPromptSegment[] = [];
|
||||
let textCursor = 0;
|
||||
let terminalContextIndex = 0;
|
||||
|
||||
for (let index = 0; index < prompt.length; index += 1) {
|
||||
if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (index > textCursor) {
|
||||
segments.push(...splitPromptTextIntoComposerSegments(prompt.slice(textCursor, index)));
|
||||
}
|
||||
segments.push({
|
||||
type: "terminal-context",
|
||||
context: terminalContexts[terminalContextIndex] ?? null,
|
||||
});
|
||||
terminalContextIndex += 1;
|
||||
textCursor = index + 1;
|
||||
}
|
||||
|
||||
if (textCursor < prompt.length) {
|
||||
segments.push(...splitPromptTextIntoComposerSegments(prompt.slice(textCursor)));
|
||||
if (cursor < prompt.length) {
|
||||
pushTextSegment(segments, prompt.slice(cursor));
|
||||
}
|
||||
|
||||
return segments;
|
||||
|
||||
@@ -5,11 +5,10 @@ import {
|
||||
collapseExpandedComposerCursor,
|
||||
detectComposerTrigger,
|
||||
expandCollapsedComposerCursor,
|
||||
isCollapsedCursorAdjacentToInlineToken,
|
||||
isCollapsedCursorAdjacentToMention,
|
||||
parseStandaloneComposerSlashCommand,
|
||||
replaceTextRange,
|
||||
} from "./composer-logic";
|
||||
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
|
||||
|
||||
describe("detectComposerTrigger", () => {
|
||||
it("detects @path trigger at cursor", () => {
|
||||
@@ -193,16 +192,16 @@ describe("replaceTextRange trailing space consumption", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isCollapsedCursorAdjacentToInlineToken", () => {
|
||||
describe("isCollapsedCursorAdjacentToMention", () => {
|
||||
it("returns false when no mention exists", () => {
|
||||
expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps @query typing non-adjacent while no mention pill exists", () => {
|
||||
const text = "hello @pac";
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects left adjacency only when cursor is directly after a mention", () => {
|
||||
@@ -210,9 +209,9 @@ describe("isCollapsedCursorAdjacentToInlineToken", () => {
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "left")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd + 1, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "left")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd + 1, "left")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects right adjacency only when cursor is directly before a mention", () => {
|
||||
@@ -220,18 +219,9 @@ describe("isCollapsedCursorAdjacentToInlineToken", () => {
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "right")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart - 1, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("treats terminal pills as inline tokens for adjacency checks", () => {
|
||||
const text = `open ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} next`;
|
||||
const tokenStart = "open ".length;
|
||||
const tokenEnd = tokenStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, tokenEnd, "left")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, tokenStart, "right")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "right")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart - 1, "right")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
|
||||
|
||||
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
|
||||
export type ComposerSlashCommand = "model" | "plan" | "default";
|
||||
@@ -12,9 +11,6 @@ export interface ComposerTrigger {
|
||||
}
|
||||
|
||||
const SLASH_COMMANDS: readonly ComposerSlashCommand[] = ["model", "plan", "default"];
|
||||
const isInlineTokenSegment = (
|
||||
segment: { type: "text"; text: string } | { type: "mention" } | { type: "terminal-context" },
|
||||
): boolean => segment.type !== "text";
|
||||
|
||||
function clampCursor(text: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return text.length;
|
||||
@@ -22,13 +18,7 @@ function clampCursor(text: string, cursor: number): number {
|
||||
}
|
||||
|
||||
function isWhitespace(char: string): boolean {
|
||||
return (
|
||||
char === " " ||
|
||||
char === "\n" ||
|
||||
char === "\t" ||
|
||||
char === "\r" ||
|
||||
char === INLINE_TERMINAL_CONTEXT_PLACEHOLDER
|
||||
);
|
||||
return char === " " || char === "\n" || char === "\t" || char === "\r";
|
||||
}
|
||||
|
||||
function tokenStartForCursor(text: string, cursor: number): number {
|
||||
@@ -59,14 +49,6 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
|
||||
expandedCursor += expandedLength;
|
||||
continue;
|
||||
}
|
||||
if (segment.type === "terminal-context") {
|
||||
if (remaining <= 1) {
|
||||
return expandedCursor + remaining;
|
||||
}
|
||||
remaining -= 1;
|
||||
expandedCursor += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const segmentLength = segment.text.length;
|
||||
if (remaining <= segmentLength) {
|
||||
@@ -80,18 +62,13 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
|
||||
}
|
||||
|
||||
function collapsedSegmentLength(
|
||||
segment: { type: "text"; text: string } | { type: "mention" } | { type: "terminal-context" },
|
||||
segment: { type: "text"; text: string } | { type: "mention" },
|
||||
): number {
|
||||
if (segment.type === "text") {
|
||||
return segment.text.length;
|
||||
}
|
||||
return 1;
|
||||
return segment.type === "mention" ? 1 : segment.text.length;
|
||||
}
|
||||
|
||||
function clampCollapsedComposerCursorForSegments(
|
||||
segments: ReadonlyArray<
|
||||
{ type: "text"; text: string } | { type: "mention" } | { type: "terminal-context" }
|
||||
>,
|
||||
segments: ReadonlyArray<{ type: "text"; text: string } | { type: "mention" }>,
|
||||
cursorInput: number,
|
||||
): number {
|
||||
const collapsedLength = segments.reduce(
|
||||
@@ -134,14 +111,6 @@ export function collapseExpandedComposerCursor(text: string, cursorInput: number
|
||||
collapsedCursor += 1;
|
||||
continue;
|
||||
}
|
||||
if (segment.type === "terminal-context") {
|
||||
if (remaining <= 1) {
|
||||
return collapsedCursor + remaining;
|
||||
}
|
||||
remaining -= 1;
|
||||
collapsedCursor += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const segmentLength = segment.text.length;
|
||||
if (remaining <= segmentLength) {
|
||||
@@ -154,13 +123,13 @@ export function collapseExpandedComposerCursor(text: string, cursorInput: number
|
||||
return collapsedCursor;
|
||||
}
|
||||
|
||||
export function isCollapsedCursorAdjacentToInlineToken(
|
||||
export function isCollapsedCursorAdjacentToMention(
|
||||
text: string,
|
||||
cursorInput: number,
|
||||
direction: "left" | "right",
|
||||
): boolean {
|
||||
const segments = splitPromptIntoComposerSegments(text);
|
||||
if (!segments.some(isInlineTokenSegment)) {
|
||||
if (!segments.some((segment) => segment.type === "mention")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -168,7 +137,7 @@ export function isCollapsedCursorAdjacentToInlineToken(
|
||||
let collapsedOffset = 0;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (isInlineTokenSegment(segment)) {
|
||||
if (segment.type === "mention") {
|
||||
if (direction === "left" && cursor === collapsedOffset + 1) {
|
||||
return true;
|
||||
}
|
||||
@@ -182,8 +151,6 @@ export function isCollapsedCursorAdjacentToInlineToken(
|
||||
return false;
|
||||
}
|
||||
|
||||
export const isCollapsedCursorAdjacentToMention = isCollapsedCursorAdjacentToInlineToken;
|
||||
|
||||
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
||||
const cursor = clampCursor(text, cursorInput);
|
||||
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
||||
|
||||
@@ -1,19 +1,11 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
COMPOSER_DRAFT_STORAGE_KEY,
|
||||
type ComposerImageAttachment,
|
||||
createDebouncedStorage,
|
||||
useComposerDraftStore,
|
||||
} from "./composerDraftStore";
|
||||
import { removeLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
insertInlineTerminalContextPlaceholder,
|
||||
type TerminalContextDraft,
|
||||
} from "./lib/terminalContext";
|
||||
import { createDebouncedStorage } from "./lib/storage";
|
||||
|
||||
function makeImage(input: {
|
||||
id: string;
|
||||
@@ -42,26 +34,6 @@ function makeImage(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function makeTerminalContext(input: {
|
||||
id: string;
|
||||
text?: string;
|
||||
terminalId?: string;
|
||||
terminalLabel?: string;
|
||||
lineStart?: number;
|
||||
lineEnd?: number;
|
||||
}): TerminalContextDraft {
|
||||
return {
|
||||
id: input.id,
|
||||
threadId: ThreadId.makeUnsafe("thread-dedupe"),
|
||||
terminalId: input.terminalId ?? "default",
|
||||
terminalLabel: input.terminalLabel ?? "Terminal 1",
|
||||
lineStart: input.lineStart ?? 4,
|
||||
lineEnd: input.lineEnd ?? 5,
|
||||
text: input.text ?? "git status\nOn branch main",
|
||||
createdAt: "2026-03-13T12:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("composerDraftStore addImages", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-dedupe");
|
||||
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
|
||||
@@ -186,236 +158,6 @@ describe("composerDraftStore clearComposerContent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore syncPersistedAttachments", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-sync-persisted");
|
||||
|
||||
beforeEach(() => {
|
||||
removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
removeLocalStorageItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
});
|
||||
|
||||
it("treats malformed persisted draft storage as empty", async () => {
|
||||
const image = makeImage({
|
||||
id: "img-persisted",
|
||||
previewUrl: "blob:persisted",
|
||||
});
|
||||
useComposerDraftStore.getState().addImage(threadId, image);
|
||||
setLocalStorageItem(
|
||||
COMPOSER_DRAFT_STORAGE_KEY,
|
||||
{
|
||||
version: 2,
|
||||
state: {
|
||||
draftsByThreadId: {
|
||||
[threadId]: {
|
||||
attachments: "not-an-array",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Schema.Unknown,
|
||||
);
|
||||
|
||||
useComposerDraftStore.getState().syncPersistedAttachments(threadId, [
|
||||
{
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
dataUrl: image.previewUrl,
|
||||
},
|
||||
]);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.persistedAttachments,
|
||||
).toEqual([]);
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.nonPersistedImageIds,
|
||||
).toEqual([image.id]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore terminal contexts", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-dedupe");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("deduplicates identical terminal contexts by selection signature", () => {
|
||||
const first = makeTerminalContext({ id: "ctx-1" });
|
||||
const duplicate = makeTerminalContext({ id: "ctx-2" });
|
||||
|
||||
useComposerDraftStore.getState().addTerminalContexts(threadId, [first, duplicate]);
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-1"]);
|
||||
});
|
||||
|
||||
it("clears terminal contexts when clearing composer content", () => {
|
||||
useComposerDraftStore
|
||||
.getState()
|
||||
.addTerminalContext(threadId, makeTerminalContext({ id: "ctx-1" }));
|
||||
|
||||
useComposerDraftStore.getState().clearComposerContent(threadId);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("inserts terminal contexts at the requested inline prompt position", () => {
|
||||
const firstInsertion = insertInlineTerminalContextPlaceholder("alpha beta", 6);
|
||||
const secondInsertion = insertInlineTerminalContextPlaceholder(firstInsertion.prompt, 0);
|
||||
|
||||
expect(
|
||||
useComposerDraftStore
|
||||
.getState()
|
||||
.insertTerminalContext(
|
||||
threadId,
|
||||
firstInsertion.prompt,
|
||||
makeTerminalContext({ id: "ctx-1" }),
|
||||
firstInsertion.contextIndex,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
useComposerDraftStore.getState().insertTerminalContext(
|
||||
threadId,
|
||||
secondInsertion.prompt,
|
||||
makeTerminalContext({
|
||||
id: "ctx-2",
|
||||
terminalLabel: "Terminal 2",
|
||||
lineStart: 9,
|
||||
lineEnd: 10,
|
||||
}),
|
||||
secondInsertion.contextIndex,
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.prompt).toBe(
|
||||
`${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} alpha ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} beta`,
|
||||
);
|
||||
expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-2", "ctx-1"]);
|
||||
});
|
||||
|
||||
it("omits terminal context text from persisted drafts", () => {
|
||||
useComposerDraftStore
|
||||
.getState()
|
||||
.addTerminalContext(threadId, makeTerminalContext({ id: "ctx-persist" }));
|
||||
|
||||
const persistApi = useComposerDraftStore.persist as unknown as {
|
||||
getOptions: () => {
|
||||
partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
|
||||
};
|
||||
};
|
||||
const persistedState = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
|
||||
draftsByThreadId?: Record<string, { terminalContexts?: Array<Record<string, unknown>> }>;
|
||||
};
|
||||
|
||||
expect(
|
||||
persistedState.draftsByThreadId?.[threadId]?.terminalContexts?.[0],
|
||||
"Expected terminal context metadata to be persisted.",
|
||||
).toMatchObject({
|
||||
id: "ctx-persist",
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 5,
|
||||
});
|
||||
expect(
|
||||
persistedState.draftsByThreadId?.[threadId]?.terminalContexts?.[0]?.text,
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("hydrates persisted terminal contexts without in-memory snapshot text", () => {
|
||||
const persistApi = useComposerDraftStore.persist as unknown as {
|
||||
getOptions: () => {
|
||||
merge: (
|
||||
persistedState: unknown,
|
||||
currentState: ReturnType<typeof useComposerDraftStore.getState>,
|
||||
) => ReturnType<typeof useComposerDraftStore.getState>;
|
||||
};
|
||||
};
|
||||
const mergedState = persistApi.getOptions().merge(
|
||||
{
|
||||
draftsByThreadId: {
|
||||
[threadId]: {
|
||||
prompt: INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
attachments: [],
|
||||
terminalContexts: [
|
||||
{
|
||||
id: "ctx-rehydrated",
|
||||
threadId,
|
||||
createdAt: "2026-03-13T12:00:00.000Z",
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
},
|
||||
useComposerDraftStore.getInitialState(),
|
||||
);
|
||||
|
||||
expect(mergedState.draftsByThreadId[threadId]?.terminalContexts).toMatchObject([
|
||||
{
|
||||
id: "ctx-rehydrated",
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 5,
|
||||
text: "",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("sanitizes malformed persisted drafts during merge", () => {
|
||||
const persistApi = useComposerDraftStore.persist as unknown as {
|
||||
getOptions: () => {
|
||||
merge: (
|
||||
persistedState: unknown,
|
||||
currentState: ReturnType<typeof useComposerDraftStore.getState>,
|
||||
) => ReturnType<typeof useComposerDraftStore.getState>;
|
||||
};
|
||||
};
|
||||
const mergedState = persistApi.getOptions().merge(
|
||||
{
|
||||
draftsByThreadId: {
|
||||
[threadId]: {
|
||||
prompt: "",
|
||||
attachments: "not-an-array",
|
||||
terminalContexts: "not-an-array",
|
||||
provider: "bogus-provider",
|
||||
modelOptions: "not-an-object",
|
||||
},
|
||||
},
|
||||
draftThreadsByThreadId: "not-an-object",
|
||||
projectDraftThreadIdByProjectId: "not-an-object",
|
||||
},
|
||||
useComposerDraftStore.getInitialState(),
|
||||
);
|
||||
|
||||
expect(mergedState.draftsByThreadId[threadId]).toBeUndefined();
|
||||
expect(mergedState.draftThreadsByThreadId).toEqual({});
|
||||
expect(mergedState.projectDraftThreadIdByProjectId).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore project draft thread mapping", () => {
|
||||
const projectId = ProjectId.makeUnsafe("project-a");
|
||||
const otherProjectId = ProjectId.makeUnsafe("project-b");
|
||||
@@ -595,8 +337,8 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore modelOptions", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model-options");
|
||||
describe("composerDraftStore fast mode", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-service-tier");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
@@ -606,39 +348,17 @@ describe("composerDraftStore modelOptions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("stores provider-scoped model options in the draft", () => {
|
||||
it("stores fast mode in the draft", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
store.setFastMode(threadId, true);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.fastMode).toBe(true);
|
||||
});
|
||||
|
||||
it("drops default-only model options from the draft", () => {
|
||||
it("clears fast mode when reset to the default", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: true,
|
||||
},
|
||||
});
|
||||
store.setFastMode(threadId, true);
|
||||
store.setFastMode(threadId, false);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
+255
-621
File diff suppressed because it is too large.
Load diff
@@ -112,7 +112,6 @@ export function gitCheckoutMutationOptions(input: {
|
||||
export function gitRunStackedActionMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
model?: string | null;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
|
||||
@@ -135,7 +134,6 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
});
|
||||
},
|
||||
onSettled: async () => {
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
|
||||
export interface StateStorage<R = unknown> {
|
||||
getItem: (name: string) => string | null | Promise<string | null>;
|
||||
setItem: (name: string, value: string) => R;
|
||||
removeItem: (name: string) => R;
|
||||
}
|
||||
|
||||
export interface DebouncedStorage<R = unknown> extends StateStorage<R> {
|
||||
flush: () => void;
|
||||
}
|
||||
|
||||
export function createMemoryStorage(): StateStorage {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
getItem: (name) => store.get(name) ?? null,
|
||||
setItem: (name, value) => {
|
||||
store.set(name, value);
|
||||
},
|
||||
removeItem: (name) => {
|
||||
store.delete(name);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createDebouncedStorage(
|
||||
baseStorage: StateStorage,
|
||||
debounceMs: number = 300,
|
||||
): DebouncedStorage {
|
||||
const debouncedSetItem = new Debouncer(
|
||||
(name: string, value: string) => {
|
||||
baseStorage.setItem(name, value);
|
||||
},
|
||||
{ wait: debounceMs },
|
||||
);
|
||||
|
||||
return {
|
||||
getItem: (name) => baseStorage.getItem(name),
|
||||
setItem: (name, value) => {
|
||||
debouncedSetItem.maybeExecute(name, value);
|
||||
},
|
||||
removeItem: (name) => {
|
||||
debouncedSetItem.cancel();
|
||||
baseStorage.removeItem(name);
|
||||
},
|
||||
flush: () => {
|
||||
debouncedSetItem.flush();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
appendTerminalContextsToPrompt,
|
||||
buildTerminalContextPreviewTitle,
|
||||
buildTerminalContextBlock,
|
||||
countInlineTerminalContextPlaceholders,
|
||||
deriveDisplayedUserMessageState,
|
||||
ensureInlineTerminalContextPlaceholders,
|
||||
extractTrailingTerminalContexts,
|
||||
filterTerminalContextsWithText,
|
||||
formatInlineTerminalContextLabel,
|
||||
formatTerminalContextLabel,
|
||||
hasTerminalContextText,
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
insertInlineTerminalContextPlaceholder,
|
||||
isTerminalContextExpired,
|
||||
materializeInlineTerminalContextPrompt,
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
stripInlineTerminalContextPlaceholders,
|
||||
type TerminalContextDraft,
|
||||
} from "./terminalContext";
|
||||
|
||||
function makeContext(overrides?: Partial<TerminalContextDraft>): TerminalContextDraft {
|
||||
return {
|
||||
id: "context-1",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 12,
|
||||
lineEnd: 13,
|
||||
text: "git status\nOn branch main",
|
||||
createdAt: "2026-03-13T12:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("terminalContext", () => {
|
||||
it("formats terminal labels with line ranges", () => {
|
||||
expect(formatTerminalContextLabel(makeContext())).toBe("Terminal 1 lines 12-13");
|
||||
expect(
|
||||
formatTerminalContextLabel(
|
||||
makeContext({
|
||||
lineStart: 9,
|
||||
lineEnd: 9,
|
||||
}),
|
||||
),
|
||||
).toBe("Terminal 1 line 9");
|
||||
});
|
||||
|
||||
it("builds a numbered terminal context block", () => {
|
||||
expect(buildTerminalContextBlock([makeContext()])).toBe(
|
||||
[
|
||||
"<terminal_context>",
|
||||
"- Terminal 1 lines 12-13:",
|
||||
" 12 | git status",
|
||||
" 13 | On branch main",
|
||||
"</terminal_context>",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("appends terminal context blocks after prompt text", () => {
|
||||
expect(appendTerminalContextsToPrompt("Investigate this", [makeContext()])).toBe(
|
||||
[
|
||||
"Investigate this",
|
||||
"",
|
||||
"<terminal_context>",
|
||||
"- Terminal 1 lines 12-13:",
|
||||
" 12 | git status",
|
||||
" 13 | On branch main",
|
||||
"</terminal_context>",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("replaces inline placeholders with inline terminal labels before appending context blocks", () => {
|
||||
expect(
|
||||
appendTerminalContextsToPrompt(
|
||||
`Investigate ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} carefully`,
|
||||
[makeContext()],
|
||||
),
|
||||
).toBe(
|
||||
[
|
||||
"Investigate @terminal-1:12-13 carefully",
|
||||
"",
|
||||
"<terminal_context>",
|
||||
"- Terminal 1 lines 12-13:",
|
||||
" 12 | git status",
|
||||
" 13 | On branch main",
|
||||
"</terminal_context>",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("extracts terminal context blocks from message text", () => {
|
||||
const prompt = appendTerminalContextsToPrompt("Investigate this", [makeContext()]);
|
||||
expect(extractTrailingTerminalContexts(prompt)).toEqual({
|
||||
promptText: "Investigate this",
|
||||
contextCount: 1,
|
||||
previewTitle: "Terminal 1 lines 12-13\n12 | git status\n13 | On branch main",
|
||||
contexts: [
|
||||
{
|
||||
header: "Terminal 1 lines 12-13",
|
||||
body: "12 | git status\n13 | On branch main",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("derives displayed user message state from terminal context prompts", () => {
|
||||
const prompt = appendTerminalContextsToPrompt("Investigate this", [makeContext()]);
|
||||
expect(deriveDisplayedUserMessageState(prompt)).toEqual({
|
||||
visibleText: "Investigate this",
|
||||
copyText: prompt,
|
||||
contextCount: 1,
|
||||
previewTitle: "Terminal 1 lines 12-13\n12 | git status\n13 | On branch main",
|
||||
contexts: [
|
||||
{
|
||||
header: "Terminal 1 lines 12-13",
|
||||
body: "12 | git status\n13 | On branch main",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves prompt text when no trailing terminal context block exists", () => {
|
||||
expect(extractTrailingTerminalContexts("No attached context")).toEqual({
|
||||
promptText: "No attached context",
|
||||
contextCount: 0,
|
||||
previewTitle: null,
|
||||
contexts: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null preview title when every context is invalid", () => {
|
||||
expect(
|
||||
buildTerminalContextPreviewTitle([
|
||||
makeContext({
|
||||
terminalId: " ",
|
||||
}),
|
||||
makeContext({
|
||||
id: "context-2",
|
||||
text: "\n\n",
|
||||
}),
|
||||
]),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("tracks inline terminal context placeholders in prompt text", () => {
|
||||
const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
|
||||
expect(countInlineTerminalContextPlaceholders(`a${placeholder}b${placeholder}`)).toBe(2);
|
||||
expect(ensureInlineTerminalContextPlaceholders("Investigate this", 2)).toBe(
|
||||
`${placeholder}${placeholder}Investigate this`,
|
||||
);
|
||||
expect(insertInlineTerminalContextPlaceholder("abc", 1)).toEqual({
|
||||
prompt: `a ${placeholder} bc`,
|
||||
cursor: 4,
|
||||
contextIndex: 0,
|
||||
});
|
||||
expect(removeInlineTerminalContextPlaceholder(`a${placeholder}b${placeholder}c`, 1)).toEqual({
|
||||
prompt: `a${placeholder}bc`,
|
||||
cursor: 3,
|
||||
});
|
||||
expect(stripInlineTerminalContextPlaceholders(`a${placeholder}b`)).toBe("ab");
|
||||
});
|
||||
|
||||
it("inserts a placeholder after a file mention when given the expanded prompt cursor", () => {
|
||||
const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
|
||||
expect(insertInlineTerminalContextPlaceholder("Inspect @package.json ", 22)).toEqual({
|
||||
prompt: `Inspect @package.json ${placeholder} `,
|
||||
cursor: 24,
|
||||
contextIndex: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("adds a trailing space and consumes an existing trailing space at the insertion point", () => {
|
||||
const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
|
||||
expect(insertInlineTerminalContextPlaceholder("yo whats", 3)).toEqual({
|
||||
prompt: `yo ${placeholder} whats`,
|
||||
cursor: 5,
|
||||
contextIndex: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("marks contexts without snapshot text as expired and filters them from sendable contexts", () => {
|
||||
const liveContext = makeContext();
|
||||
const expiredContext = makeContext({
|
||||
id: "context-2",
|
||||
text: "",
|
||||
});
|
||||
|
||||
expect(hasTerminalContextText(liveContext)).toBe(true);
|
||||
expect(isTerminalContextExpired(liveContext)).toBe(false);
|
||||
expect(hasTerminalContextText(expiredContext)).toBe(false);
|
||||
expect(isTerminalContextExpired(expiredContext)).toBe(true);
|
||||
expect(filterTerminalContextsWithText([expiredContext, liveContext])).toEqual([liveContext]);
|
||||
});
|
||||
|
||||
it("formats and materializes inline terminal labels from placeholder positions", () => {
|
||||
expect(formatInlineTerminalContextLabel(makeContext())).toBe("@terminal-1:12-13");
|
||||
expect(
|
||||
materializeInlineTerminalContextPrompt(
|
||||
`Investigate ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} carefully`,
|
||||
[makeContext()],
|
||||
),
|
||||
).toBe("Investigate @terminal-1:12-13 carefully");
|
||||
});
|
||||
});
|
||||
@@ -1,356 +0,0 @@
|
||||
import { type ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export interface TerminalContextSelection {
|
||||
terminalId: string;
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface TerminalContextDraft extends TerminalContextSelection {
|
||||
id: string;
|
||||
threadId: ThreadId;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface ExtractedTerminalContexts {
|
||||
promptText: string;
|
||||
contextCount: number;
|
||||
previewTitle: string | null;
|
||||
contexts: ParsedTerminalContextEntry[];
|
||||
}
|
||||
|
||||
export interface DisplayedUserMessageState {
|
||||
visibleText: string;
|
||||
copyText: string;
|
||||
contextCount: number;
|
||||
previewTitle: string | null;
|
||||
contexts: ParsedTerminalContextEntry[];
|
||||
}
|
||||
|
||||
export interface ParsedTerminalContextEntry {
|
||||
header: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export const INLINE_TERMINAL_CONTEXT_PLACEHOLDER = "\uFFFC";
|
||||
|
||||
const TRAILING_TERMINAL_CONTEXT_BLOCK_PATTERN =
|
||||
/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/;
|
||||
|
||||
export function normalizeTerminalContextText(text: string): string {
|
||||
return text.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
|
||||
}
|
||||
|
||||
export function hasTerminalContextText(context: { text: string }): boolean {
|
||||
return normalizeTerminalContextText(context.text).length > 0;
|
||||
}
|
||||
|
||||
export function isTerminalContextExpired(context: { text: string }): boolean {
|
||||
return !hasTerminalContextText(context);
|
||||
}
|
||||
|
||||
export function filterTerminalContextsWithText<T extends { text: string }>(
|
||||
contexts: ReadonlyArray<T>,
|
||||
): T[] {
|
||||
return contexts.filter((context) => hasTerminalContextText(context));
|
||||
}
|
||||
|
||||
function previewTerminalContextText(text: string): string {
|
||||
const normalized = normalizeTerminalContextText(text);
|
||||
if (normalized.length === 0) {
|
||||
return "";
|
||||
}
|
||||
const lines = normalized.split("\n");
|
||||
const visibleLines = lines.slice(0, 3);
|
||||
if (lines.length > 3) {
|
||||
visibleLines.push("...");
|
||||
}
|
||||
const preview = visibleLines.join("\n");
|
||||
return preview.length > 180 ? `${preview.slice(0, 177)}...` : preview;
|
||||
}
|
||||
|
||||
export function normalizeTerminalContextSelection(
|
||||
selection: TerminalContextSelection,
|
||||
): TerminalContextSelection | null {
|
||||
const text = normalizeTerminalContextText(selection.text);
|
||||
const terminalId = selection.terminalId.trim();
|
||||
const terminalLabel = selection.terminalLabel.trim();
|
||||
if (text.length === 0 || terminalId.length === 0 || terminalLabel.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const lineStart = Math.max(1, Math.floor(selection.lineStart));
|
||||
const lineEnd = Math.max(lineStart, Math.floor(selection.lineEnd));
|
||||
return {
|
||||
terminalId,
|
||||
terminalLabel,
|
||||
lineStart,
|
||||
lineEnd,
|
||||
text,
|
||||
};
|
||||
}
|
||||
|
||||
export function formatTerminalContextRange(selection: {
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
}): string {
|
||||
return selection.lineStart === selection.lineEnd
|
||||
? `line ${selection.lineStart}`
|
||||
: `lines ${selection.lineStart}-${selection.lineEnd}`;
|
||||
}
|
||||
|
||||
export function formatTerminalContextLabel(selection: {
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
}): string {
|
||||
return `${selection.terminalLabel} ${formatTerminalContextRange(selection)}`;
|
||||
}
|
||||
|
||||
export function formatInlineTerminalContextLabel(selection: {
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
}): string {
|
||||
const terminalLabel = selection.terminalLabel.trim().toLowerCase().replace(/\s+/g, "-");
|
||||
const range =
|
||||
selection.lineStart === selection.lineEnd
|
||||
? `${selection.lineStart}`
|
||||
: `${selection.lineStart}-${selection.lineEnd}`;
|
||||
return `@${terminalLabel}:${range}`;
|
||||
}
|
||||
|
||||
export function buildTerminalContextPreviewTitle(
|
||||
contexts: ReadonlyArray<TerminalContextSelection>,
|
||||
): string | null {
|
||||
if (contexts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const previews = contexts
|
||||
.map((context) => {
|
||||
const normalized = normalizeTerminalContextSelection(context);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
const preview = previewTerminalContextText(normalized.text);
|
||||
return preview.length > 0
|
||||
? `${formatTerminalContextLabel(normalized)}\n${preview}`
|
||||
: formatTerminalContextLabel(normalized);
|
||||
})
|
||||
.filter((value): value is string => value !== null)
|
||||
.join("\n\n");
|
||||
return previews.length > 0 ? previews : null;
|
||||
}
|
||||
|
||||
function buildTerminalContextBodyLines(selection: TerminalContextSelection): string[] {
|
||||
return normalizeTerminalContextText(selection.text)
|
||||
.split("\n")
|
||||
.map((line, index) => ` ${selection.lineStart + index} | ${line}`);
|
||||
}
|
||||
|
||||
export function buildTerminalContextBlock(
|
||||
contexts: ReadonlyArray<TerminalContextSelection>,
|
||||
): string {
|
||||
const normalizedContexts = contexts
|
||||
.map((context) => normalizeTerminalContextSelection(context))
|
||||
.filter((context): context is TerminalContextSelection => context !== null);
|
||||
if (normalizedContexts.length === 0) {
|
||||
return "";
|
||||
}
|
||||
const lines: string[] = [];
|
||||
for (let index = 0; index < normalizedContexts.length; index += 1) {
|
||||
const context = normalizedContexts[index]!;
|
||||
lines.push(`- ${formatTerminalContextLabel(context)}:`);
|
||||
lines.push(...buildTerminalContextBodyLines(context));
|
||||
if (index < normalizedContexts.length - 1) {
|
||||
lines.push("");
|
||||
}
|
||||
}
|
||||
return ["<terminal_context>", ...lines, "</terminal_context>"].join("\n");
|
||||
}
|
||||
|
||||
export function materializeInlineTerminalContextPrompt(
|
||||
prompt: string,
|
||||
contexts: ReadonlyArray<{
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
}>,
|
||||
): string {
|
||||
let nextContextIndex = 0;
|
||||
let result = "";
|
||||
|
||||
for (const char of prompt) {
|
||||
if (char !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
|
||||
result += char;
|
||||
continue;
|
||||
}
|
||||
const context = contexts[nextContextIndex] ?? null;
|
||||
nextContextIndex += 1;
|
||||
if (!context) {
|
||||
continue;
|
||||
}
|
||||
result += formatInlineTerminalContextLabel(context);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function appendTerminalContextsToPrompt(
|
||||
prompt: string,
|
||||
contexts: ReadonlyArray<TerminalContextSelection>,
|
||||
): string {
|
||||
const trimmedPrompt = materializeInlineTerminalContextPrompt(prompt, contexts).trim();
|
||||
const contextBlock = buildTerminalContextBlock(contexts);
|
||||
if (contextBlock.length === 0) {
|
||||
return trimmedPrompt;
|
||||
}
|
||||
return trimmedPrompt.length > 0 ? `${trimmedPrompt}\n\n${contextBlock}` : contextBlock;
|
||||
}
|
||||
|
||||
export function extractTrailingTerminalContexts(prompt: string): ExtractedTerminalContexts {
|
||||
const match = TRAILING_TERMINAL_CONTEXT_BLOCK_PATTERN.exec(prompt);
|
||||
if (!match) {
|
||||
return {
|
||||
promptText: prompt,
|
||||
contextCount: 0,
|
||||
previewTitle: null,
|
||||
contexts: [],
|
||||
};
|
||||
}
|
||||
const promptText = prompt.slice(0, match.index).replace(/\n+$/, "");
|
||||
const parsedContexts = parseTerminalContextEntries(match[1] ?? "");
|
||||
return {
|
||||
promptText,
|
||||
contextCount: parsedContexts.length,
|
||||
previewTitle:
|
||||
parsedContexts.length > 0
|
||||
? parsedContexts
|
||||
.map(({ header, body }) => (body.length > 0 ? `${header}\n${body}` : header))
|
||||
.join("\n\n")
|
||||
: null,
|
||||
contexts: parsedContexts,
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveDisplayedUserMessageState(prompt: string): DisplayedUserMessageState {
|
||||
const extractedContexts = extractTrailingTerminalContexts(prompt);
|
||||
return {
|
||||
visibleText: extractedContexts.promptText,
|
||||
copyText: prompt,
|
||||
contextCount: extractedContexts.contextCount,
|
||||
previewTitle: extractedContexts.previewTitle,
|
||||
contexts: extractedContexts.contexts,
|
||||
};
|
||||
}
|
||||
|
||||
function parseTerminalContextEntries(block: string): ParsedTerminalContextEntry[] {
|
||||
const entries: ParsedTerminalContextEntry[] = [];
|
||||
let current: { header: string; bodyLines: string[] } | null = null;
|
||||
|
||||
const commitCurrent = () => {
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
entries.push({
|
||||
header: current.header,
|
||||
body: current.bodyLines.join("\n").trimEnd(),
|
||||
});
|
||||
current = null;
|
||||
};
|
||||
|
||||
for (const rawLine of block.split("\n")) {
|
||||
const headerMatch = /^- (.+):$/.exec(rawLine);
|
||||
if (headerMatch) {
|
||||
commitCurrent();
|
||||
current = {
|
||||
header: headerMatch[1]!,
|
||||
bodyLines: [],
|
||||
};
|
||||
continue;
|
||||
}
|
||||
if (!current) {
|
||||
continue;
|
||||
}
|
||||
if (rawLine.startsWith(" ")) {
|
||||
current.bodyLines.push(rawLine.slice(2));
|
||||
continue;
|
||||
}
|
||||
if (rawLine.length === 0) {
|
||||
current.bodyLines.push("");
|
||||
}
|
||||
}
|
||||
|
||||
commitCurrent();
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function countInlineTerminalContextPlaceholders(prompt: string): number {
|
||||
let count = 0;
|
||||
for (const char of prompt) {
|
||||
if (char === INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
export function ensureInlineTerminalContextPlaceholders(
|
||||
prompt: string,
|
||||
terminalContextCount: number,
|
||||
): string {
|
||||
const missingCount = terminalContextCount - countInlineTerminalContextPlaceholders(prompt);
|
||||
if (missingCount <= 0) {
|
||||
return prompt;
|
||||
}
|
||||
return `${INLINE_TERMINAL_CONTEXT_PLACEHOLDER.repeat(missingCount)}${prompt}`;
|
||||
}
|
||||
|
||||
function isInlineTerminalContextBoundaryWhitespace(char: string | undefined): boolean {
|
||||
return char === undefined || char === " " || char === "\n" || char === "\t" || char === "\r";
|
||||
}
|
||||
|
||||
export function insertInlineTerminalContextPlaceholder(
|
||||
prompt: string,
|
||||
cursorInput: number,
|
||||
): { prompt: string; cursor: number; contextIndex: number } {
|
||||
const cursor = Math.max(0, Math.min(prompt.length, Math.floor(cursorInput)));
|
||||
const needsLeadingSpace = !isInlineTerminalContextBoundaryWhitespace(prompt[cursor - 1]);
|
||||
const replacement = `${needsLeadingSpace ? " " : ""}${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} `;
|
||||
const rangeEnd = prompt[cursor] === " " ? cursor + 1 : cursor;
|
||||
return {
|
||||
prompt: `${prompt.slice(0, cursor)}${replacement}${prompt.slice(rangeEnd)}`,
|
||||
cursor: cursor + replacement.length,
|
||||
contextIndex: countInlineTerminalContextPlaceholders(prompt.slice(0, cursor)),
|
||||
};
|
||||
}
|
||||
|
||||
export function stripInlineTerminalContextPlaceholders(prompt: string): string {
|
||||
return prompt.replaceAll(INLINE_TERMINAL_CONTEXT_PLACEHOLDER, "");
|
||||
}
|
||||
|
||||
export function removeInlineTerminalContextPlaceholder(
|
||||
prompt: string,
|
||||
contextIndex: number,
|
||||
): { prompt: string; cursor: number } {
|
||||
if (contextIndex < 0) {
|
||||
return { prompt, cursor: prompt.length };
|
||||
}
|
||||
|
||||
let placeholderIndex = 0;
|
||||
for (let index = 0; index < prompt.length; index += 1) {
|
||||
if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
|
||||
continue;
|
||||
}
|
||||
if (placeholderIndex === contextIndex) {
|
||||
return {
|
||||
prompt: prompt.slice(0, index) + prompt.slice(index + 1),
|
||||
cursor: index,
|
||||
};
|
||||
}
|
||||
placeholderIndex += 1;
|
||||
}
|
||||
|
||||
return { prompt, cursor: prompt.length };
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useCallback, useState } from "react";
|
||||
import { type ProviderKind, DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { getAppModelOptions, MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
@@ -126,17 +126,6 @@ function SettingsRouteView() {
|
||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||
const availableEditors = serverConfigQuery.data?.availableEditors;
|
||||
|
||||
const gitTextGenerationModelOptions = getAppModelOptions(
|
||||
"codex",
|
||||
settings.customCodexModels,
|
||||
settings.textGenerationModel,
|
||||
);
|
||||
const selectedGitTextGenerationModelLabel =
|
||||
gitTextGenerationModelOptions.find(
|
||||
(option) =>
|
||||
option.slug === (settings.textGenerationModel ?? DEFAULT_GIT_TEXT_GENERATION_MODEL),
|
||||
)?.name ?? settings.textGenerationModel;
|
||||
|
||||
const openKeybindingsFile = useCallback(() => {
|
||||
if (!keybindingsConfigPath) return;
|
||||
setOpenKeybindingsError(null);
|
||||
@@ -527,65 +516,6 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Git</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Configure the model used for generating commit messages, PR titles, and branch
|
||||
names.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 rounded-lg border border-border bg-background px-3 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-foreground">Text generation model</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Model used for auto-generated git content.
|
||||
</p>
|
||||
</div>
|
||||
<Select
|
||||
value={settings.textGenerationModel ?? DEFAULT_GIT_TEXT_GENERATION_MODEL}
|
||||
onValueChange={(value) => {
|
||||
if (value) {
|
||||
updateSettings({
|
||||
textGenerationModel: value,
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
className="w-full shrink-0 sm:w-48"
|
||||
aria-label="Git text generation model"
|
||||
>
|
||||
<SelectValue>{selectedGitTextGenerationModelLabel}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end">
|
||||
{gitTextGenerationModelOptions.map((option) => (
|
||||
<SelectItem key={option.slug} value={option.slug}>
|
||||
{option.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{settings.textGenerationModel !== defaults.textGenerationModel ? (
|
||||
<div className="mt-3 flex justify-end">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
textGenerationModel: defaults.textGenerationModel,
|
||||
})
|
||||
}
|
||||
>
|
||||
Restore default
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Threads</h2>
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
import { EventId, MessageId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -16,8 +10,6 @@ import {
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
findLatestProposedPlan,
|
||||
findSidebarProposedPlan,
|
||||
hasActionableProposedPlan,
|
||||
hasToolActivityForTurn,
|
||||
isLatestTurnSettled,
|
||||
} from "./session-logic";
|
||||
@@ -277,8 +269,6 @@ describe("findLatestProposedPlan", () => {
|
||||
id: "plan:thread-1:turn:turn-1",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
planMarkdown: "# Older",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
updatedAt: "2026-02-23T00:00:01.000Z",
|
||||
},
|
||||
@@ -286,8 +276,6 @@ describe("findLatestProposedPlan", () => {
|
||||
id: "plan:thread-1:turn:turn-1",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
planMarkdown: "# Latest",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
updatedAt: "2026-02-23T00:00:02.000Z",
|
||||
},
|
||||
@@ -295,8 +283,6 @@ describe("findLatestProposedPlan", () => {
|
||||
id: "plan:thread-1:turn:turn-2",
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
planMarkdown: "# Different turn",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-23T00:00:03.000Z",
|
||||
updatedAt: "2026-02-23T00:00:03.000Z",
|
||||
},
|
||||
@@ -307,8 +293,6 @@ describe("findLatestProposedPlan", () => {
|
||||
id: "plan:thread-1:turn:turn-1",
|
||||
turnId: "turn-1",
|
||||
planMarkdown: "# Latest",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
updatedAt: "2026-02-23T00:00:02.000Z",
|
||||
});
|
||||
@@ -321,8 +305,6 @@ describe("findLatestProposedPlan", () => {
|
||||
id: "plan:thread-1:turn:turn-1",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
planMarkdown: "# First",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
updatedAt: "2026-02-23T00:00:01.000Z",
|
||||
},
|
||||
@@ -330,8 +312,6 @@ describe("findLatestProposedPlan", () => {
|
||||
id: "plan:thread-1:turn:turn-2",
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
planMarkdown: "# Latest",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-23T00:00:02.000Z",
|
||||
updatedAt: "2026-02-23T00:00:03.000Z",
|
||||
},
|
||||
@@ -343,133 +323,6 @@ describe("findLatestProposedPlan", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasActionableProposedPlan", () => {
|
||||
it("returns true for an unimplemented proposed plan", () => {
|
||||
expect(
|
||||
hasActionableProposedPlan({
|
||||
id: "plan-1",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
planMarkdown: "# Plan",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-23T00:00:00.000Z",
|
||||
updatedAt: "2026-02-23T00:00:01.000Z",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false for a proposed plan already implemented elsewhere", () => {
|
||||
expect(
|
||||
hasActionableProposedPlan({
|
||||
id: "plan-1",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
planMarkdown: "# Plan",
|
||||
implementedAt: "2026-02-23T00:00:02.000Z",
|
||||
implementationThreadId: ThreadId.makeUnsafe("thread-implement"),
|
||||
createdAt: "2026-02-23T00:00:00.000Z",
|
||||
updatedAt: "2026-02-23T00:00:02.000Z",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findSidebarProposedPlan", () => {
|
||||
it("prefers the running turn source proposed plan when available on the same thread", () => {
|
||||
expect(
|
||||
findSidebarProposedPlan({
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
proposedPlans: [
|
||||
{
|
||||
id: "plan-1",
|
||||
turnId: TurnId.makeUnsafe("turn-plan"),
|
||||
planMarkdown: "# Source plan",
|
||||
implementedAt: "2026-02-23T00:00:03.000Z",
|
||||
implementationThreadId: ThreadId.makeUnsafe("thread-2"),
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
updatedAt: "2026-02-23T00:00:02.000Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: ThreadId.makeUnsafe("thread-2"),
|
||||
proposedPlans: [
|
||||
{
|
||||
id: "plan-2",
|
||||
turnId: TurnId.makeUnsafe("turn-other"),
|
||||
planMarkdown: "# Latest elsewhere",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-23T00:00:04.000Z",
|
||||
updatedAt: "2026-02-23T00:00:05.000Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-implementation"),
|
||||
sourceProposedPlan: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
planId: "plan-1",
|
||||
},
|
||||
},
|
||||
latestTurnSettled: false,
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
}),
|
||||
).toEqual({
|
||||
id: "plan-1",
|
||||
turnId: "turn-plan",
|
||||
planMarkdown: "# Source plan",
|
||||
implementedAt: "2026-02-23T00:00:03.000Z",
|
||||
implementationThreadId: "thread-2",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
updatedAt: "2026-02-23T00:00:02.000Z",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the latest proposed plan once the turn is settled", () => {
|
||||
expect(
|
||||
findSidebarProposedPlan({
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
proposedPlans: [
|
||||
{
|
||||
id: "plan-1",
|
||||
turnId: TurnId.makeUnsafe("turn-plan"),
|
||||
planMarkdown: "# Older",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
updatedAt: "2026-02-23T00:00:02.000Z",
|
||||
},
|
||||
{
|
||||
id: "plan-2",
|
||||
turnId: TurnId.makeUnsafe("turn-latest"),
|
||||
planMarkdown: "# Latest",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-23T00:00:03.000Z",
|
||||
updatedAt: "2026-02-23T00:00:04.000Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-implementation"),
|
||||
sourceProposedPlan: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
planId: "plan-1",
|
||||
},
|
||||
},
|
||||
latestTurnSettled: true,
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
})?.planMarkdown,
|
||||
).toBe("# Latest");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveWorkLogEntries", () => {
|
||||
it("omits tool started entries and keeps completed entries", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
@@ -557,42 +410,6 @@ describe("deriveWorkLogEntries", () => {
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
|
||||
});
|
||||
|
||||
it("omits ExitPlanMode lifecycle entries once the plan card is shown", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "exit-plan-updated",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
kind: "tool.updated",
|
||||
summary: "Tool call",
|
||||
payload: {
|
||||
detail: 'ExitPlanMode: {"allowedPrompts":[{"tool":"Bash","prompt":"run tests"}]}',
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "exit-plan-completed",
|
||||
createdAt: "2026-02-23T00:00:02.000Z",
|
||||
kind: "tool.completed",
|
||||
summary: "Tool call",
|
||||
payload: {
|
||||
detail: "ExitPlanMode: {}",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "real-work-log",
|
||||
createdAt: "2026-02-23T00:00:03.000Z",
|
||||
kind: "tool.completed",
|
||||
summary: "Ran command",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
detail: "Bash: bun test",
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["real-work-log"]);
|
||||
});
|
||||
|
||||
it("orders work log by activity sequence when present", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
@@ -714,8 +531,6 @@ describe("deriveTimelineEntries", () => {
|
||||
id: "plan:thread-1:turn:turn-1",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
planMarkdown: "# Ship it",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: "2026-02-23T00:00:02.000Z",
|
||||
updatedAt: "2026-02-23T00:00:02.000Z",
|
||||
},
|
||||
@@ -735,8 +550,6 @@ describe("deriveTimelineEntries", () => {
|
||||
kind: "proposed-plan",
|
||||
proposedPlan: {
|
||||
planMarkdown: "# Ship it",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
type ProviderKind,
|
||||
type ToolLifecycleItemType,
|
||||
type UserInputQuestion,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
@@ -15,7 +14,6 @@ import type {
|
||||
ChatMessage,
|
||||
ProposedPlan,
|
||||
SessionPhase,
|
||||
Thread,
|
||||
ThreadSession,
|
||||
TurnDiffSummary,
|
||||
} from "./types";
|
||||
@@ -74,8 +72,6 @@ export interface LatestProposedPlanState {
|
||||
updatedAt: string;
|
||||
turnId: TurnId | null;
|
||||
planMarkdown: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}
|
||||
|
||||
export type TimelineEntry =
|
||||
@@ -378,7 +374,13 @@ export function findLatestProposedPlan(
|
||||
)
|
||||
.at(-1);
|
||||
if (matchingTurnPlan) {
|
||||
return toLatestProposedPlanState(matchingTurnPlan);
|
||||
return {
|
||||
id: matchingTurnPlan.id,
|
||||
createdAt: matchingTurnPlan.createdAt,
|
||||
updatedAt: matchingTurnPlan.updatedAt,
|
||||
turnId: matchingTurnPlan.turnId,
|
||||
planMarkdown: matchingTurnPlan.planMarkdown,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,37 +394,13 @@ export function findLatestProposedPlan(
|
||||
return null;
|
||||
}
|
||||
|
||||
return toLatestProposedPlanState(latestPlan);
|
||||
}
|
||||
|
||||
export function findSidebarProposedPlan(input: {
|
||||
threads: ReadonlyArray<Pick<Thread, "id" | "proposedPlans">>;
|
||||
latestTurn: Pick<OrchestrationLatestTurn, "turnId" | "sourceProposedPlan"> | null;
|
||||
latestTurnSettled: boolean;
|
||||
threadId: ThreadId | string | null | undefined;
|
||||
}): LatestProposedPlanState | null {
|
||||
const activeThreadPlans =
|
||||
input.threads.find((thread) => thread.id === input.threadId)?.proposedPlans ?? [];
|
||||
|
||||
if (!input.latestTurnSettled) {
|
||||
const sourceProposedPlan = input.latestTurn?.sourceProposedPlan;
|
||||
if (sourceProposedPlan) {
|
||||
const sourcePlan = input.threads
|
||||
.find((thread) => thread.id === sourceProposedPlan.threadId)
|
||||
?.proposedPlans.find((plan) => plan.id === sourceProposedPlan.planId);
|
||||
if (sourcePlan) {
|
||||
return toLatestProposedPlanState(sourcePlan);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return findLatestProposedPlan(activeThreadPlans, input.latestTurn?.turnId ?? null);
|
||||
}
|
||||
|
||||
export function hasActionableProposedPlan(
|
||||
proposedPlan: LatestProposedPlanState | Pick<ProposedPlan, "implementedAt"> | null,
|
||||
): boolean {
|
||||
return proposedPlan !== null && proposedPlan.implementedAt === null;
|
||||
return {
|
||||
id: latestPlan.id,
|
||||
createdAt: latestPlan.createdAt,
|
||||
updatedAt: latestPlan.updatedAt,
|
||||
turnId: latestPlan.turnId,
|
||||
planMarkdown: latestPlan.planMarkdown,
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveWorkLogEntries(
|
||||
@@ -435,7 +413,6 @@ export function deriveWorkLogEntries(
|
||||
.filter((activity) => activity.kind !== "tool.started")
|
||||
.filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
|
||||
.filter((activity) => activity.summary !== "Checkpoint captured")
|
||||
.filter((activity) => !isPlanBoundaryToolActivity(activity))
|
||||
.map((activity) => {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
@@ -477,30 +454,6 @@ export function deriveWorkLogEntries(
|
||||
});
|
||||
}
|
||||
|
||||
function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
|
||||
if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
|
||||
}
|
||||
|
||||
function toLatestProposedPlanState(proposedPlan: ProposedPlan): LatestProposedPlanState {
|
||||
return {
|
||||
id: proposedPlan.id,
|
||||
createdAt: proposedPlan.createdAt,
|
||||
updatedAt: proposedPlan.updatedAt,
|
||||
turnId: proposedPlan.turnId,
|
||||
planMarkdown: proposedPlan.planMarkdown,
|
||||
implementedAt: proposedPlan.implementedAt,
|
||||
implementationThreadId: proposedPlan.implementationThreadId,
|
||||
};
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
|
||||
}
|
||||
|
||||
@@ -297,8 +297,6 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
|
||||
id: proposedPlan.id,
|
||||
turnId: proposedPlan.turnId,
|
||||
planMarkdown: proposedPlan.planMarkdown,
|
||||
implementedAt: proposedPlan.implementedAt,
|
||||
implementationThreadId: proposedPlan.implementationThreadId,
|
||||
createdAt: proposedPlan.createdAt,
|
||||
updatedAt: proposedPlan.updatedAt,
|
||||
})),
|
||||
|
||||
@@ -53,8 +53,6 @@ export interface ProposedPlan {
|
||||
id: OrchestrationProposedPlanId;
|
||||
turnId: TurnId | null;
|
||||
planMarkdown: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
@@ -75,17 +75,6 @@ export function basenameOfPath(pathValue: string): string {
|
||||
return pathValue.slice(slashIndex + 1);
|
||||
}
|
||||
|
||||
export function inferEntryKindFromPath(pathValue: string): "file" | "directory" {
|
||||
const base = basenameOfPath(pathValue);
|
||||
if (base.startsWith(".") && !base.slice(1).includes(".")) {
|
||||
return "directory";
|
||||
}
|
||||
if (base.includes(".")) {
|
||||
return "file";
|
||||
}
|
||||
return "directory";
|
||||
}
|
||||
|
||||
function extensionCandidates(fileName: string): string[] {
|
||||
const candidates = new Set<string>();
|
||||
if (fileName.includes(".")) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Option, Schema } from "effect";
|
||||
import { Schema } from "effect";
|
||||
import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "./model";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
|
||||
@@ -65,9 +64,6 @@ export const GitRunStackedActionInput = Schema.Struct({
|
||||
filePaths: Schema.optional(
|
||||
Schema.Array(TrimmedNonEmptyStringSchema).check(Schema.isMinLength(1)),
|
||||
),
|
||||
textGenerationModel: Schema.optional(TrimmedNonEmptyStringSchema).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(DEFAULT_GIT_TEXT_GENERATION_MODEL)),
|
||||
),
|
||||
});
|
||||
export type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;
|
||||
|
||||
|
||||
@@ -34,7 +34,6 @@ type ModelOption = {
|
||||
export const MODEL_OPTIONS_BY_PROVIDER = {
|
||||
codex: [
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ slug: "gpt-5.4-mini", name: "GPT-5.4 Mini" },
|
||||
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
|
||||
{ slug: "gpt-5.3-codex-spark", name: "GPT-5.3 Codex Spark" },
|
||||
{ slug: "gpt-5.2-codex", name: "GPT-5.2 Codex" },
|
||||
@@ -59,7 +58,6 @@ export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, ModelSlug> = {
|
||||
// Backward compatibility for existing Codex-only call sites.
|
||||
export const MODEL_OPTIONS = MODEL_OPTIONS_BY_PROVIDER.codex;
|
||||
export const DEFAULT_MODEL = DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini" as const;
|
||||
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string, ModelSlug>> = {
|
||||
codex: {
|
||||
|
||||
@@ -6,8 +6,6 @@ import {
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationProposedPlan,
|
||||
OrchestrationSession,
|
||||
ProjectCreateCommand,
|
||||
ThreadTurnStartCommand,
|
||||
@@ -23,8 +21,6 @@ const decodeThreadTurnStartCommand = Schema.decodeUnknownEffect(ThreadTurnStartC
|
||||
const decodeThreadTurnStartRequestedPayload = Schema.decodeUnknownEffect(
|
||||
ThreadTurnStartRequestedPayload,
|
||||
);
|
||||
const decodeOrchestrationLatestTurn = Schema.decodeUnknownEffect(OrchestrationLatestTurn);
|
||||
const decodeOrchestrationProposedPlan = Schema.decodeUnknownEffect(OrchestrationProposedPlan);
|
||||
const decodeOrchestrationSession = Schema.decodeUnknownEffect(OrchestrationSession);
|
||||
const decodeThreadCreatedPayload = Schema.decodeUnknownEffect(ThreadCreatedPayload);
|
||||
|
||||
@@ -190,31 +186,6 @@ it.effect("accepts provider-scoped model options in thread.turn.start", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts a source proposed plan reference in thread.turn.start", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadTurnStartCommand({
|
||||
type: "thread.turn.start",
|
||||
commandId: "cmd-turn-source-plan",
|
||||
threadId: "thread-2",
|
||||
message: {
|
||||
messageId: "msg-source-plan",
|
||||
role: "user",
|
||||
text: "implement this",
|
||||
attachments: [],
|
||||
},
|
||||
sourceProposedPlan: {
|
||||
threadId: "thread-1",
|
||||
planId: "plan-1",
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.sourceProposedPlan, {
|
||||
threadId: "thread-1",
|
||||
planId: "plan-1",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"decodes thread.turn-start-requested defaults for provider, runtime mode, and interaction mode",
|
||||
() =>
|
||||
@@ -227,49 +198,9 @@ it.effect(
|
||||
assert.strictEqual(parsed.provider, undefined);
|
||||
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
|
||||
assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
assert.strictEqual(parsed.sourceProposedPlan, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes thread.turn-start-requested source proposed plan metadata when present", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadTurnStartRequestedPayload({
|
||||
threadId: "thread-2",
|
||||
messageId: "msg-2",
|
||||
sourceProposedPlan: {
|
||||
threadId: "thread-1",
|
||||
planId: "plan-1",
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.sourceProposedPlan, {
|
||||
threadId: "thread-1",
|
||||
planId: "plan-1",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes latest turn source proposed plan metadata when present", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeOrchestrationLatestTurn({
|
||||
turnId: "turn-2",
|
||||
state: "running",
|
||||
requestedAt: "2026-01-01T00:00:00.000Z",
|
||||
startedAt: "2026-01-01T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
sourceProposedPlan: {
|
||||
threadId: "thread-1",
|
||||
planId: "plan-1",
|
||||
},
|
||||
});
|
||||
assert.deepStrictEqual(parsed.sourceProposedPlan, {
|
||||
threadId: "thread-1",
|
||||
planId: "plan-1",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes orchestration session runtime mode defaults", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeOrchestrationSession({
|
||||
@@ -285,33 +216,3 @@ it.effect("decodes orchestration session runtime mode defaults", () =>
|
||||
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("defaults proposed plan implementation metadata for historical rows", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeOrchestrationProposedPlan({
|
||||
id: "plan-1",
|
||||
turnId: "turn-1",
|
||||
planMarkdown: "# Plan",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.implementedAt, null);
|
||||
assert.strictEqual(parsed.implementationThreadId, null);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves proposed plan implementation metadata when present", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeOrchestrationProposedPlan({
|
||||
id: "plan-2",
|
||||
turnId: "turn-2",
|
||||
planMarkdown: "# Plan",
|
||||
implementedAt: "2026-01-02T00:00:00.000Z",
|
||||
implementationThreadId: "thread-2",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-02T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.implementedAt, "2026-01-02T00:00:00.000Z");
|
||||
assert.strictEqual(parsed.implementationThreadId, "thread-2");
|
||||
}),
|
||||
);
|
||||
@@ -174,18 +174,11 @@ export const OrchestrationProposedPlan = Schema.Struct({
|
||||
id: OrchestrationProposedPlanId,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
planMarkdown: TrimmedNonEmptyString,
|
||||
implementedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)),
|
||||
implementationThreadId: Schema.NullOr(ThreadId).pipe(Schema.withDecodingDefault(() => null)),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type OrchestrationProposedPlan = typeof OrchestrationProposedPlan.Type;
|
||||
|
||||
const SourceProposedPlanReference = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
planId: OrchestrationProposedPlanId,
|
||||
});
|
||||
|
||||
export const OrchestrationSessionStatus = Schema.Literals([
|
||||
"idle",
|
||||
"starting",
|
||||
@@ -265,7 +258,6 @@ export const OrchestrationLatestTurn = Schema.Struct({
|
||||
startedAt: Schema.NullOr(IsoDateTime),
|
||||
completedAt: Schema.NullOr(IsoDateTime),
|
||||
assistantMessageId: Schema.NullOr(MessageId),
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
});
|
||||
export type OrchestrationLatestTurn = typeof OrchestrationLatestTurn.Type;
|
||||
|
||||
@@ -393,7 +385,6 @@ export const ThreadTurnStartCommand = Schema.Struct({
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
),
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -414,7 +405,6 @@ const ClientThreadTurnStartCommand = Schema.Struct({
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -697,7 +687,6 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
),
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
|
||||
@@ -16,18 +16,11 @@ import {
|
||||
getModelOptions,
|
||||
getReasoningEffortOptions,
|
||||
inferProviderForModel,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptions,
|
||||
normalizeCodexModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveReasoningEffortForProvider,
|
||||
resolveModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
supportsClaudeAdaptiveReasoning,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeMaxEffort,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
} from "./model";
|
||||
|
||||
describe("normalizeModelSlug", () => {
|
||||
@@ -99,8 +92,8 @@ describe("getReasoningEffortOptions", () => {
|
||||
expect(getReasoningEffortOptions("codex")).toEqual(REASONING_EFFORT_OPTIONS_BY_PROVIDER.codex);
|
||||
});
|
||||
|
||||
it("returns claude effort options for Opus 4.6", () => {
|
||||
expect(getReasoningEffortOptions("claudeAgent", "claude-opus-4-6")).toEqual([
|
||||
it("returns claude effort options for claudeAgent", () => {
|
||||
expect(getReasoningEffortOptions("claudeAgent")).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
@@ -108,19 +101,6 @@ describe("getReasoningEffortOptions", () => {
|
||||
"ultrathink",
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns claude effort options for Sonnet 4.6", () => {
|
||||
expect(getReasoningEffortOptions("claudeAgent", "claude-sonnet-4-6")).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"ultrathink",
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns no claude effort options for Haiku 4.5", () => {
|
||||
expect(getReasoningEffortOptions("claudeAgent", "claude-haiku-4-5")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("inferProviderForModel", () => {
|
||||
@@ -177,8 +157,8 @@ describe("applyClaudePromptEffortPrefix", () => {
|
||||
});
|
||||
|
||||
describe("getEffectiveClaudeCodeEffort", () => {
|
||||
it("does not persist ultrathink into Claude runtime configuration", () => {
|
||||
expect(getEffectiveClaudeCodeEffort("ultrathink")).toBeNull();
|
||||
it("maps ultrathink to max for Claude runtime configuration", () => {
|
||||
expect(getEffectiveClaudeCodeEffort("ultrathink")).toBe("max");
|
||||
expect(getEffectiveClaudeCodeEffort("high")).toBe("high");
|
||||
});
|
||||
|
||||
@@ -188,61 +168,6 @@ describe("getEffectiveClaudeCodeEffort", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeCodexModelOptions", () => {
|
||||
it("drops default-only codex options", () => {
|
||||
expect(
|
||||
normalizeCodexModelOptions({ reasoningEffort: "high", fastMode: false }),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves non-default codex options", () => {
|
||||
expect(normalizeCodexModelOptions({ reasoningEffort: "xhigh", fastMode: true })).toEqual({
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeClaudeModelOptions", () => {
|
||||
it("drops unsupported fast mode and max effort for Sonnet", () => {
|
||||
expect(
|
||||
normalizeClaudeModelOptions("claude-sonnet-4-6", {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps the Haiku thinking toggle and removes unsupported effort", () => {
|
||||
expect(
|
||||
normalizeClaudeModelOptions("claude-haiku-4-5", {
|
||||
thinking: false,
|
||||
effort: "high",
|
||||
}),
|
||||
).toEqual({
|
||||
thinking: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeAdaptiveReasoning", () => {
|
||||
it("only enables adaptive reasoning for Opus 4.6 and Sonnet 4.6", () => {
|
||||
expect(supportsClaudeAdaptiveReasoning("claude-opus-4-6")).toBe(true);
|
||||
expect(supportsClaudeAdaptiveReasoning("claude-sonnet-4-6")).toBe(true);
|
||||
expect(supportsClaudeAdaptiveReasoning("claude-haiku-4-5")).toBe(false);
|
||||
expect(supportsClaudeAdaptiveReasoning(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeMaxEffort", () => {
|
||||
it("only enables max effort for Opus 4.6", () => {
|
||||
expect(supportsClaudeMaxEffort("claude-opus-4-6")).toBe(true);
|
||||
expect(supportsClaudeMaxEffort("claude-sonnet-4-6")).toBe(false);
|
||||
expect(supportsClaudeMaxEffort("claude-haiku-4-5")).toBe(false);
|
||||
expect(supportsClaudeMaxEffort(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeFastMode", () => {
|
||||
it("only enables Claude fast mode for Opus 4.6", () => {
|
||||
expect(supportsClaudeFastMode("claude-opus-4-6")).toBe(true);
|
||||
@@ -252,30 +177,3 @@ describe("supportsClaudeFastMode", () => {
|
||||
expect(supportsClaudeFastMode(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeUltrathinkKeyword", () => {
|
||||
it("only enables ultrathink keyword handling for Opus 4.6 and Sonnet 4.6", () => {
|
||||
expect(supportsClaudeUltrathinkKeyword("claude-opus-4-6")).toBe(true);
|
||||
expect(supportsClaudeUltrathinkKeyword("claude-sonnet-4-6")).toBe(true);
|
||||
expect(supportsClaudeUltrathinkKeyword("claude-haiku-4-5")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeThinkingToggle", () => {
|
||||
it("only enables the Claude thinking toggle for Haiku 4.5", () => {
|
||||
expect(supportsClaudeThinkingToggle("claude-opus-4-6")).toBe(false);
|
||||
expect(supportsClaudeThinkingToggle("claude-sonnet-4-6")).toBe(false);
|
||||
expect(supportsClaudeThinkingToggle("claude-haiku-4-5")).toBe(true);
|
||||
expect(supportsClaudeThinkingToggle("haiku")).toBe(true);
|
||||
expect(supportsClaudeThinkingToggle(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isClaudeUltrathinkPrompt", () => {
|
||||
it("detects ultrathink prompts case-insensitively", () => {
|
||||
expect(isClaudeUltrathinkPrompt("Please ultrathink about this")).toBe(true);
|
||||
expect(isClaudeUltrathinkPrompt("Ultrathink:\nInvestigate")).toBe(true);
|
||||
expect(isClaudeUltrathinkPrompt("Think hard about this")).toBe(false);
|
||||
expect(isClaudeUltrathinkPrompt(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -6,9 +6,7 @@ import {
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
MODEL_SLUG_ALIASES_BY_PROVIDER,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
type ClaudeModelOptions,
|
||||
type ClaudeCodeEffort,
|
||||
type CodexModelOptions,
|
||||
type CodexReasoningEffort,
|
||||
type ModelSlug,
|
||||
type ProviderReasoningEffort,
|
||||
@@ -20,10 +18,6 @@ const MODEL_SLUG_SET_BY_PROVIDER: Record<ProviderKind, ReadonlySet<ModelSlug>> =
|
||||
codex: new Set(MODEL_OPTIONS_BY_PROVIDER.codex.map((option) => option.slug)),
|
||||
};
|
||||
|
||||
const CLAUDE_OPUS_4_6_MODEL = "claude-opus-4-6";
|
||||
const CLAUDE_SONNET_4_6_MODEL = "claude-sonnet-4-6";
|
||||
const CLAUDE_HAIKU_4_5_MODEL = "claude-haiku-4-5";
|
||||
|
||||
export function getModelOptions(provider: ProviderKind = "codex") {
|
||||
return MODEL_OPTIONS_BY_PROVIDER[provider];
|
||||
}
|
||||
@@ -33,28 +27,7 @@ export function getDefaultModel(provider: ProviderKind = "codex"): ModelSlug {
|
||||
}
|
||||
|
||||
export function supportsClaudeFastMode(model: string | null | undefined): boolean {
|
||||
return normalizeModelSlug(model, "claudeAgent") === CLAUDE_OPUS_4_6_MODEL;
|
||||
}
|
||||
|
||||
export function supportsClaudeAdaptiveReasoning(model: string | null | undefined): boolean {
|
||||
const normalized = normalizeModelSlug(model, "claudeAgent");
|
||||
return normalized === CLAUDE_OPUS_4_6_MODEL || normalized === CLAUDE_SONNET_4_6_MODEL;
|
||||
}
|
||||
|
||||
export function supportsClaudeMaxEffort(model: string | null | undefined): boolean {
|
||||
return normalizeModelSlug(model, "claudeAgent") === CLAUDE_OPUS_4_6_MODEL;
|
||||
}
|
||||
|
||||
export function supportsClaudeUltrathinkKeyword(model: string | null | undefined): boolean {
|
||||
return supportsClaudeAdaptiveReasoning(model);
|
||||
}
|
||||
|
||||
export function supportsClaudeThinkingToggle(model: string | null | undefined): boolean {
|
||||
return normalizeModelSlug(model, "claudeAgent") === CLAUDE_HAIKU_4_5_MODEL;
|
||||
}
|
||||
|
||||
export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
|
||||
return typeof text === "string" && /\bultrathink\b/i.test(text);
|
||||
return normalizeModelSlug(model, "claudeAgent") === "claude-opus-4-6";
|
||||
}
|
||||
|
||||
export function normalizeModelSlug(
|
||||
@@ -116,27 +89,13 @@ export function inferProviderForModel(
|
||||
}
|
||||
|
||||
export function getReasoningEffortOptions(provider: "codex"): ReadonlyArray<CodexReasoningEffort>;
|
||||
export function getReasoningEffortOptions(
|
||||
provider: "claudeAgent",
|
||||
model?: string | null | undefined,
|
||||
): ReadonlyArray<ClaudeCodeEffort>;
|
||||
export function getReasoningEffortOptions(provider: "claudeAgent"): ReadonlyArray<ClaudeCodeEffort>;
|
||||
export function getReasoningEffortOptions(
|
||||
provider?: ProviderKind,
|
||||
model?: string | null | undefined,
|
||||
): ReadonlyArray<ProviderReasoningEffort>;
|
||||
export function getReasoningEffortOptions(
|
||||
provider: ProviderKind = "codex",
|
||||
model?: string | null | undefined,
|
||||
): ReadonlyArray<ProviderReasoningEffort> {
|
||||
if (provider === "claudeAgent") {
|
||||
if (supportsClaudeMaxEffort(model)) {
|
||||
return ["low", "medium", "high", "max", "ultrathink"];
|
||||
}
|
||||
if (supportsClaudeAdaptiveReasoning(model)) {
|
||||
return ["low", "medium", "high", "ultrathink"];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
return REASONING_EFFORT_OPTIONS_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
@@ -184,48 +143,7 @@ export function getEffectiveClaudeCodeEffort(
|
||||
if (!effort) {
|
||||
return null;
|
||||
}
|
||||
return effort === "ultrathink" ? null : effort;
|
||||
}
|
||||
|
||||
export function normalizeCodexModelOptions(
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("codex");
|
||||
const reasoningEffort =
|
||||
resolveReasoningEffortForProvider("codex", modelOptions?.reasoningEffort) ??
|
||||
defaultReasoningEffort;
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort !== defaultReasoningEffort ? { reasoningEffort } : {}),
|
||||
...(fastModeEnabled ? { fastMode: true } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function normalizeClaudeModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const reasoningOptions = getReasoningEffortOptions("claudeAgent", model);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("claudeAgent");
|
||||
const resolvedEffort = resolveReasoningEffortForProvider("claudeAgent", modelOptions?.effort);
|
||||
const effort =
|
||||
resolvedEffort &&
|
||||
resolvedEffort !== "ultrathink" &&
|
||||
reasoningOptions.includes(resolvedEffort) &&
|
||||
resolvedEffort !== defaultReasoningEffort
|
||||
? resolvedEffort
|
||||
: undefined;
|
||||
const thinking =
|
||||
supportsClaudeThinkingToggle(model) && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode =
|
||||
supportsClaudeFastMode(model) && modelOptions?.fastMode === true ? true : undefined;
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
return effort === "ultrathink" ? "max" : effort;
|
||||
}
|
||||
|
||||
export function applyClaudePromptEffortPrefix(
|
||||
|
||||
@@ -1,261 +0,0 @@
|
||||
import { query, type SDKMessage, type ThinkingConfig } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
type ProbeCase =
|
||||
| "default"
|
||||
| "effort-low"
|
||||
| "effort-high"
|
||||
| "settings-off"
|
||||
| "settings-on"
|
||||
| "thinking-disabled"
|
||||
| "thinking-enabled";
|
||||
|
||||
function parseArgs(argv: ReadonlyArray<string>): {
|
||||
readonly model: string;
|
||||
readonly cwd?: string;
|
||||
readonly prompt: string;
|
||||
readonly cases: ReadonlyArray<ProbeCase>;
|
||||
} {
|
||||
let model = "claude-haiku-4-5";
|
||||
let cwd: string | undefined;
|
||||
let prompt =
|
||||
"Think step by step about this before answering: what is 27 multiplied by 43? Return the final number only.";
|
||||
let cases: ReadonlyArray<ProbeCase> = [
|
||||
"default",
|
||||
"effort-low",
|
||||
"effort-high",
|
||||
"settings-off",
|
||||
"settings-on",
|
||||
"thinking-disabled",
|
||||
"thinking-enabled",
|
||||
];
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const value = argv[index];
|
||||
if (!value) {
|
||||
continue;
|
||||
}
|
||||
if (value === "--model") {
|
||||
model = argv[index + 1] ?? model;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (value === "--cwd") {
|
||||
cwd = argv[index + 1] ?? cwd;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (value === "--prompt") {
|
||||
prompt = argv[index + 1] ?? prompt;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (value === "--cases") {
|
||||
const next = argv[index + 1];
|
||||
if (next) {
|
||||
const requested = next
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter(
|
||||
(entry): entry is ProbeCase =>
|
||||
entry === "default" ||
|
||||
entry === "effort-low" ||
|
||||
entry === "effort-high" ||
|
||||
entry === "settings-off" ||
|
||||
entry === "settings-on" ||
|
||||
entry === "thinking-disabled" ||
|
||||
entry === "thinking-enabled",
|
||||
);
|
||||
if (requested.length > 0) {
|
||||
cases = requested;
|
||||
}
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
model,
|
||||
prompt,
|
||||
...(cwd ? { cwd } : {}),
|
||||
cases,
|
||||
};
|
||||
}
|
||||
|
||||
function caseOptions(caseName: ProbeCase): {
|
||||
readonly label: ProbeCase;
|
||||
readonly effort?: "low" | "high";
|
||||
readonly settings?: { alwaysThinkingEnabled: boolean };
|
||||
readonly thinking?: ThinkingConfig;
|
||||
} {
|
||||
switch (caseName) {
|
||||
case "effort-low":
|
||||
return {
|
||||
label: caseName,
|
||||
effort: "low",
|
||||
};
|
||||
case "effort-high":
|
||||
return {
|
||||
label: caseName,
|
||||
effort: "high",
|
||||
};
|
||||
case "settings-off":
|
||||
return {
|
||||
label: caseName,
|
||||
settings: {
|
||||
alwaysThinkingEnabled: false,
|
||||
},
|
||||
};
|
||||
case "settings-on":
|
||||
return {
|
||||
label: caseName,
|
||||
settings: {
|
||||
alwaysThinkingEnabled: true,
|
||||
},
|
||||
};
|
||||
case "thinking-disabled":
|
||||
return {
|
||||
label: caseName,
|
||||
thinking: {
|
||||
type: "disabled",
|
||||
},
|
||||
};
|
||||
case "thinking-enabled":
|
||||
return {
|
||||
label: caseName,
|
||||
thinking: {
|
||||
type: "enabled",
|
||||
budgetTokens: 1024,
|
||||
},
|
||||
};
|
||||
default:
|
||||
return {
|
||||
label: caseName,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
type ProbeSummary = {
|
||||
readonly case: ProbeCase;
|
||||
readonly model: string;
|
||||
initModelInfo: {
|
||||
value: string | null;
|
||||
supportsEffort: boolean | null;
|
||||
supportsAdaptiveThinking: boolean | null;
|
||||
supportedEffortLevels: ReadonlyArray<string> | null;
|
||||
} | null;
|
||||
resultSubtype: string | null;
|
||||
resultText: string | null;
|
||||
assistantThinkingBlockCount: number;
|
||||
streamThinkingEventTypes: Record<string, number>;
|
||||
error: string | null;
|
||||
};
|
||||
|
||||
async function runCase(input: {
|
||||
readonly caseName: ProbeCase;
|
||||
readonly model: string;
|
||||
readonly cwd?: string;
|
||||
readonly prompt: string;
|
||||
}): Promise<ProbeSummary> {
|
||||
const caseConfig = caseOptions(input.caseName);
|
||||
const summary: ProbeSummary = {
|
||||
case: input.caseName,
|
||||
model: input.model,
|
||||
initModelInfo: null,
|
||||
resultSubtype: null,
|
||||
resultText: null,
|
||||
assistantThinkingBlockCount: 0,
|
||||
streamThinkingEventTypes: {},
|
||||
error: null,
|
||||
};
|
||||
|
||||
try {
|
||||
const messages = query({
|
||||
prompt: input.prompt,
|
||||
options: {
|
||||
model: input.model,
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
persistSession: false,
|
||||
tools: [],
|
||||
permissionMode: "bypassPermissions",
|
||||
includePartialMessages: true,
|
||||
maxTurns: 1,
|
||||
...(caseConfig.effort ? { effort: caseConfig.effort } : {}),
|
||||
...(caseConfig.settings ? { settings: caseConfig.settings } : {}),
|
||||
...(caseConfig.thinking ? { thinking: caseConfig.thinking } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
const initialization = await messages.initializationResult();
|
||||
const initModel =
|
||||
initialization.models.find((candidate) => candidate.value === input.model) ??
|
||||
initialization.models.find((candidate) => candidate.value.includes("haiku")) ??
|
||||
null;
|
||||
summary.initModelInfo = initModel
|
||||
? {
|
||||
value: initModel.value,
|
||||
supportsEffort: initModel.supportsEffort ?? null,
|
||||
supportsAdaptiveThinking: initModel.supportsAdaptiveThinking ?? null,
|
||||
supportedEffortLevels: initModel.supportedEffortLevels ?? null,
|
||||
}
|
||||
: null;
|
||||
|
||||
for await (const message of messages) {
|
||||
handleMessage(summary, message);
|
||||
}
|
||||
} catch (error) {
|
||||
summary.error = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
function handleMessage(summary: ProbeSummary, message: SDKMessage): void {
|
||||
if (message.type === "stream_event") {
|
||||
const event = message.event as {
|
||||
type?: string;
|
||||
delta?: {
|
||||
type?: string;
|
||||
};
|
||||
};
|
||||
const eventType = event.delta?.type ?? event.type;
|
||||
if (typeof eventType === "string" && eventType.includes("thinking")) {
|
||||
summary.streamThinkingEventTypes[eventType] =
|
||||
(summary.streamThinkingEventTypes[eventType] ?? 0) + 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "assistant") {
|
||||
for (const block of message.message.content) {
|
||||
if (typeof block?.type === "string" && block.type.includes("thinking")) {
|
||||
summary.assistantThinkingBlockCount += 1;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "result") {
|
||||
summary.resultSubtype = message.subtype;
|
||||
summary.resultText = message.subtype === "success" ? message.result : message.errors.join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const results: ProbeSummary[] = [];
|
||||
|
||||
for (const caseName of args.cases) {
|
||||
results.push(
|
||||
await runCase({
|
||||
caseName,
|
||||
model: args.model,
|
||||
...(args.cwd ? { cwd: args.cwd } : {}),
|
||||
prompt: args.prompt,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(results, null, 2));
|
||||
}
|
||||
|
||||
await main();
|
||||
@@ -5,7 +5,6 @@
|
||||
"scripts": {
|
||||
"prepare": "effect-language-service patch",
|
||||
"claude-fast-mode-probe": "bun run claude-fast-mode-probe.ts",
|
||||
"claude-haiku-thinking-probe": "bun run claude-haiku-thinking-probe.ts",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user